]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiWorkArea.cpp
Revert "Do not display caret when we're not ready"
[lyx.git] / src / frontends / qt / GuiWorkArea.cpp
1 /**
2  * \file GuiWorkArea.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  * \author Abdelrazak Younes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "GuiWorkArea.h"
15 #include "GuiWorkArea_Private.h"
16
17 #include "ColorCache.h"
18 #include "FontLoader.h"
19 #include "GuiApplication.h"
20 #include "GuiCompleter.h"
21 #include "GuiKeySymbol.h"
22 #include "GuiPainter.h"
23 #include "GuiView.h"
24 #include "Menus.h"
25 #include "qt_helpers.h"
26
27 #include "Buffer.h"
28 #include "BufferList.h"
29 #include "BufferParams.h"
30 #include "BufferView.h"
31 #include "CoordCache.h"
32 #include "Cursor.h"
33 #include "Font.h"
34 #include "FuncRequest.h"
35 #include "KeySymbol.h"
36 #include "Language.h"
37 #include "LyX.h"
38 #include "LyXRC.h"
39 #include "LyXVC.h"
40 #include "Text.h"
41 #include "TextMetrics.h"
42 #include "Undo.h"
43 #include "version.h"
44
45 #include "graphics/GraphicsImage.h"
46 #include "graphics/GraphicsLoader.h"
47
48 #include "support/convert.h"
49 #include "support/debug.h"
50 #include "support/lassert.h"
51 #include "support/TempFile.h"
52
53 #include "frontends/Application.h"
54 #include "frontends/FontMetrics.h"
55 #include "frontends/WorkAreaManager.h"
56
57 #include <QContextMenuEvent>
58 #if (QT_VERSION < 0x050000)
59 #include <QInputContext>
60 #endif
61 #include <QDrag>
62 #include <QHelpEvent>
63 #ifdef Q_OS_MAC
64 #include <QProxyStyle>
65 #endif
66 #include <QMainWindow>
67 #include <QMimeData>
68 #include <QMenu>
69 #include <QPainter>
70 #include <QPalette>
71 #include <QScrollBar>
72 #include <QStyleOption>
73 #include <QStylePainter>
74 #include <QTimer>
75 #include <QToolButton>
76 #include <QToolTip>
77 #include <QMenuBar>
78
79 #include <cmath>
80 #include <iostream>
81
82 int const TabIndicatorWidth = 3;
83
84 #undef KeyPress
85 #undef NoModifier
86
87 using namespace std;
88 using namespace lyx::support;
89
90 namespace lyx {
91
92
93 /// return the LyX mouse button state from Qt's
94 static mouse_button::state q_button_state(Qt::MouseButton button)
95 {
96         mouse_button::state b = mouse_button::none;
97         switch (button) {
98                 case Qt::LeftButton:
99                         b = mouse_button::button1;
100                         break;
101                 case Qt::MidButton:
102                         b = mouse_button::button2;
103                         break;
104                 case Qt::RightButton:
105                         b = mouse_button::button3;
106                         break;
107                 default:
108                         break;
109         }
110         return b;
111 }
112
113
114 /// return the LyX mouse button state from Qt's
115 mouse_button::state q_motion_state(Qt::MouseButtons state)
116 {
117         mouse_button::state b = mouse_button::none;
118         if (state & Qt::LeftButton)
119                 b |= mouse_button::button1;
120         if (state & Qt::MidButton)
121                 b |= mouse_button::button2;
122         if (state & Qt::RightButton)
123                 b |= mouse_button::button3;
124         return b;
125 }
126
127
128 namespace frontend {
129
130 class CaretWidget {
131 public:
132         CaretWidget() : rtl_(false), l_shape_(false), completable_(false),
133                 x_(0), caret_width_(0)
134         {}
135
136         /* Draw the caret. Parameter \c horiz_offset is not 0 when there
137          * has been horizontal scrolling in current row
138          */
139         void draw(QPainter & painter, int horiz_offset)
140         {
141                 if (!rect_.isValid())
142                         return;
143
144                 int const x = x_ - horiz_offset;
145                 int const y = rect_.top();
146                 int const l = x_ - rect_.left();
147                 int const r = rect_.right() - x_;
148                 int const bot = rect_.bottom();
149
150                 // draw vertical line
151                 painter.fillRect(x, y, caret_width_, rect_.height(), color_);
152
153                 // draw RTL/LTR indication
154                 painter.setPen(color_);
155                 if (l_shape_) {
156                         if (rtl_)
157                                 painter.drawLine(x, bot, x - l + 1, bot);
158                         else
159                                 painter.drawLine(x, bot, x + caret_width_ + r - 1, bot);
160                 }
161
162                 // draw completion triangle
163                 if (completable_) {
164                         int m = y + rect_.height() / 2;
165                         int d = TabIndicatorWidth - 1;
166                         if (rtl_) {
167                                 painter.drawLine(x - 1, m - d, x - 1 - d, m);
168                                 painter.drawLine(x - 1, m + d, x - 1 - d, m);
169                         } else {
170                                 painter.drawLine(x + caret_width_, m - d, x + caret_width_ + d, m);
171                                 painter.drawLine(x + caret_width_, m + d, x + caret_width_ + d, m);
172                         }
173                 }
174         }
175
176         void update(int x, int y, int h, bool l_shape,
177                 bool rtl, bool completable)
178         {
179                 color_ = guiApp->colorCache().get(Color_cursor);
180                 l_shape_ = l_shape;
181                 rtl_ = rtl;
182                 completable_ = completable;
183                 x_ = x;
184
185                 // extension to left and right
186                 int l = 0;
187                 int r = 0;
188
189                 // RTL/LTR indication
190                 if (l_shape_) {
191                         if (rtl)
192                                 l += h / 3;
193                         else
194                                 r += h / 3;
195                 }
196
197                 // completion triangle
198                 if (completable_) {
199                         if (rtl)
200                                 l = max(l, TabIndicatorWidth);
201                         else
202                                 r = max(r, TabIndicatorWidth);
203                 }
204
205                 //FIXME: LyXRC::cursor_width should be caret_width
206                 caret_width_ = lyxrc.cursor_width
207                         ? lyxrc.cursor_width
208                         : 1 + int((lyxrc.currentZoom + 50) / 200.0);
209
210                 // compute overall rectangle
211                 rect_ = QRect(x - l, y, caret_width_ + r + l, h);
212         }
213
214         QRect const & rect() { return rect_; }
215
216 private:
217         /// caret is in RTL or LTR text
218         bool rtl_;
219         /// indication for RTL or LTR
220         bool l_shape_;
221         /// triangle to show that a completion is available
222         bool completable_;
223         ///
224         QColor color_;
225         /// rectangle, possibly with l_shape and completion triangle
226         QRect rect_;
227         /// x position (were the vertical line is drawn)
228         int x_;
229         /// the width of the vertical blinking bar
230         int caret_width_;
231 };
232
233
234 // This is a 'heartbeat' generating synthetic mouse move events when the
235 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
236 SyntheticMouseEvent::SyntheticMouseEvent()
237         : timeout(200), restart_timeout(true)
238 {}
239
240
241 GuiWorkArea::Private::Private(GuiWorkArea * parent)
242 : p(parent), buffer_view_(0), lyx_view_(0), caret_(0),
243   caret_visible_(false), need_resize_(false), preedit_lines_(1),
244   last_pixel_ratio_(1.0), completer_(new GuiCompleter(p, p)),
245   dialog_mode_(false), shell_escape_(false), read_only_(false),
246   clean_(true), externally_modified_(false)
247 {
248 /* Qt on macOS and Wayland does not respect the
249  * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
250  * store at each update. Therefore, we use our own backing store in
251  * these two cases. */
252 #if QT_VERSION >= 0x050000
253         use_backingstore_ = guiApp->platformName() == "cocoa"
254                 || guiApp->platformName().contains("wayland");
255 #else
256 #  ifdef Q_OS_MAC
257         use_backingstore_ = true;
258 #  else
259         use_backingstore_ = false;
260 #  endif
261 #endif
262
263         int const time = QApplication::cursorFlashTime() / 2;
264         if (time > 0) {
265                 caret_timeout_.setInterval(time);
266                 caret_timeout_.start();
267         } else {
268                 // let's initialize this just to be safe
269                 caret_timeout_.setInterval(500);
270         }
271 }
272
273
274 GuiWorkArea::Private::~Private()
275 {
276         // If something is wrong with the buffer, we can ignore it safely
277         try {
278                 buffer_view_->buffer().workAreaManager().remove(p);
279         } catch(...) {}
280         delete buffer_view_;
281         delete caret_;
282         // Completer has a QObject parent and is thus automatically destroyed.
283         // See #4758.
284         // delete completer_;
285 }
286
287
288 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
289 : d(new Private(this))
290 {
291         new CompressorProxy(this); // not a leak
292 }
293
294
295 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
296 : d(new Private(this))
297 {
298         new CompressorProxy(this); // not a leak
299         setGuiView(gv);
300         buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
301         setBuffer(buffer);
302         init();
303 }
304
305
306 double GuiWorkArea::pixelRatio() const
307 {
308 #if QT_VERSION >= 0x050000
309         return qt_scale_factor * devicePixelRatio();
310 #else
311         return 1.0;
312 #endif
313 }
314
315
316 void GuiWorkArea::init()
317 {
318         // Setup the signals
319         connect(&d->caret_timeout_, SIGNAL(timeout()),
320                 this, SLOT(toggleCaret()));
321
322         // This connection is closed at the same time as this is destroyed.
323         d->synthetic_mouse_event_.timeout.timeout.connect([this](){
324                         generateSyntheticMouseEvent();
325                 });
326
327         d->resetScreen();
328         // With Qt4.5 a mouse event will happen before the first paint event
329         // so make sure that the buffer view has an up to date metrics.
330         d->buffer_view_->resize(viewport()->width(), viewport()->height());
331         d->caret_ = new frontend::CaretWidget();
332
333         setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
334         setAcceptDrops(true);
335         setMouseTracking(true);
336         setMinimumSize(100, 70);
337         setFrameStyle(QFrame::NoFrame);
338         updateWindowTitle();
339
340         d->updateCursorShape();
341
342         // we paint our own background
343         viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
344
345         setFocusPolicy(Qt::StrongFocus);
346
347         LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
348                 << "  viewport height: " << viewport()->height());
349
350         // Enables input methods for asian languages.
351         // Must be set when creating custom text editing widgets.
352         setAttribute(Qt::WA_InputMethodEnabled, true);
353 }
354
355
356 GuiWorkArea::~GuiWorkArea()
357 {
358         delete d;
359 }
360
361
362 void GuiWorkArea::Private::updateCursorShape()
363 {
364         bool const clickable = buffer_view_ && buffer_view_->clickableInset();
365         p->viewport()->setCursor(clickable ? Qt::PointingHandCursor
366                                            : Qt::IBeamCursor);
367 }
368
369
370 void GuiWorkArea::setGuiView(GuiView & gv)
371 {
372         d->lyx_view_ = &gv;
373 }
374
375
376 void GuiWorkArea::setBuffer(Buffer & buffer)
377 {
378         delete d->buffer_view_;
379         d->buffer_view_ = new BufferView(buffer);
380         buffer.workAreaManager().add(this);
381
382         // HACK: Prevents an additional redraw when the scrollbar pops up
383         // which regularily happens on documents with more than one page.
384         // The policy  should be set to "Qt::ScrollBarAsNeeded" soon.
385         // Since we have no geometry information yet, we assume that
386         // a document needs a scrollbar if there is more then four
387         // paragraph in the outermost text.
388         if (buffer.text().paragraphs().size() > 4)
389                 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
390         QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
391         Q_EMIT bufferViewChanged();
392 }
393
394
395 void GuiWorkArea::fixVerticalScrollBar()
396 {
397         if (!isFullScreen())
398                 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
399 }
400
401
402 void GuiWorkArea::close()
403 {
404         d->lyx_view_->removeWorkArea(this);
405 }
406
407
408 void GuiWorkArea::setFullScreen(bool full_screen)
409 {
410         d->buffer_view_->setFullScreen(full_screen);
411         setFrameStyle(QFrame::NoFrame);
412         if (full_screen) {
413                 setFrameStyle(QFrame::NoFrame);
414                 if (lyxrc.full_screen_scrollbar)
415                         setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
416         } else
417                 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
418 }
419
420
421 BufferView & GuiWorkArea::bufferView()
422 {
423         return *d->buffer_view_;
424 }
425
426
427 BufferView const & GuiWorkArea::bufferView() const
428 {
429         return *d->buffer_view_;
430 }
431
432
433 void GuiWorkArea::stopBlinkingCaret()
434 {
435         d->caret_timeout_.stop();
436         d->hideCaret();
437 }
438
439
440 void GuiWorkArea::startBlinkingCaret()
441 {
442         // do not show the cursor if the view is busy
443         if (view().busy())
444                 return;
445
446         // Don't start blinking if the cursor isn't on screen.
447         if (!d->buffer_view_->caretInView())
448                 return;
449
450         d->showCaret();
451
452         // Avoid blinking when debugging PAINTING, since it creates too much noise
453         if (!lyxerr.debugging(Debug::PAINTING)) {
454                 // we are not supposed to cache this value.
455                 int const time = QApplication::cursorFlashTime() / 2;
456                 if (time <= 0)
457                         return;
458                 d->caret_timeout_.setInterval(time);
459                 d->caret_timeout_.start();
460         }
461 }
462
463
464 void GuiWorkArea::toggleCaret()
465 {
466         if (d->caret_visible_)
467                 d->hideCaret();
468         else
469                 d->showCaret();
470 }
471
472
473 void GuiWorkArea::scheduleRedraw(bool update_metrics)
474 {
475         if (!isVisible())
476                 // No need to redraw in this case.
477                 return;
478
479         // No need to do anything if this is the current view. The BufferView
480         // metrics are already up to date.
481         if (update_metrics || d->lyx_view_ != guiApp->currentView()
482                 || d->lyx_view_->currentWorkArea() != this) {
483                 // FIXME: it would be nice to optimize for the off-screen case.
484                 d->buffer_view_->cursor().fixIfBroken();
485                 d->buffer_view_->updateMetrics();
486                 d->buffer_view_->cursor().fixIfBroken();
487         }
488
489         // update caret position, because otherwise it has to wait until
490         // the blinking interval is over
491         d->updateCaretGeometry();
492
493         LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
494         viewport()->update();
495
496         /// FIXME: is this still true now that paintEvent does the actual painting?
497         /// \warning: scrollbar updating *must* be done after the BufferView is drawn
498         /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
499         d->updateScrollbar();
500         d->lyx_view_->updateStatusBar();
501
502         if (lyxerr.debugging(Debug::WORKAREA))
503                 d->buffer_view_->coordCache().dump();
504
505         updateWindowTitle();
506
507         d->updateCursorShape();
508 }
509
510
511 // Keep in sync with GuiWorkArea::processKeySym below
512 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
513 {
514         return guiApp->queryKeySym(key, mod);
515 }
516
517
518 // Keep in sync with GuiWorkArea::queryKeySym above
519 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
520 {
521         if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
522                 && lyxrc.full_screen_menubar) {
523                 // FIXME HACK: we should not have to do this here. See related comment
524                 // in GuiView::event() (QEvent::ShortcutOverride)
525                 d->lyx_view_->menuBar()->hide();
526         }
527
528         // In order to avoid bad surprise in the middle of an operation,
529         // we better stop the blinking caret...
530         // the caret gets restarted in GuiView::restartCaret()
531         stopBlinkingCaret();
532         guiApp->processKeySym(key, mod);
533 }
534
535
536 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
537 {
538         // Handle drag&drop
539         if (cmd.action() == LFUN_FILE_OPEN) {
540                 DispatchResult dr;
541                 lyx_view_->dispatch(cmd, dr);
542                 return;
543         }
544
545         bool const notJustMovingTheMouse =
546                 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
547
548         // In order to avoid bad surprise in the middle of an operation, we better stop
549         // the blinking caret.
550         if (notJustMovingTheMouse)
551                 p->stopBlinkingCaret();
552
553         buffer_view_->mouseEventDispatch(cmd);
554
555         // Skip these when selecting
556         // FIXME: let GuiView take care of those.
557         if (cmd.action() != LFUN_MOUSE_MOTION) {
558                 completer_->updateVisibility(false, false);
559                 lyx_view_->updateDialogs();
560                 lyx_view_->updateStatusBar();
561         }
562
563         // GUI tweaks except with mouse motion with no button pressed.
564         if (notJustMovingTheMouse) {
565                 // Slight hack: this is only called currently when we
566                 // clicked somewhere, so we force through the display
567                 // of the new status here.
568                 // FIXME: let GuiView take care of those.
569                 lyx_view_->clearMessage();
570
571                 // Show the caret immediately after any operation
572                 p->startBlinkingCaret();
573         }
574
575         updateCursorShape();
576 }
577
578
579 void GuiWorkArea::Private::resizeBufferView()
580 {
581         // WARNING: Please don't put any code that will trigger a repaint here!
582         // We are already inside a paint event.
583         p->stopBlinkingCaret();
584         // Warn our container (GuiView).
585         p->busy(true);
586
587         bool const caret_in_view = buffer_view_->caretInView();
588         buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
589         if (caret_in_view)
590                 buffer_view_->scrollToCursor();
591         updateCaretGeometry();
592
593         // Update scrollbars which might have changed due different
594         // BufferView dimension. This is especially important when the
595         // BufferView goes from zero-size to the real-size for the first time,
596         // as the scrollbar paramters are then set for the first time.
597         updateScrollbar();
598
599         need_resize_ = false;
600         p->busy(false);
601         // Eventually, restart the caret after the resize event.
602         // We might be resizing even if the focus is on another widget so we only
603         // restart the caret if we have the focus.
604         if (p->hasFocus())
605                 QTimer::singleShot(50, p, SLOT(startBlinkingCaret()));
606 }
607
608
609 void GuiWorkArea::Private::updateCaretGeometry()
610 {
611         if (!buffer_view_->caretInView())
612                 return;
613
614         Point point;
615         int h = 0;
616         buffer_view_->caretPosAndHeight(point, h);
617
618         // RTL or not RTL
619         bool l_shape = false;
620         Font const & realfont = buffer_view_->cursor().real_current_font;
621         BufferParams const & bp = buffer_view_->buffer().params();
622         bool const samelang = realfont.language() == bp.language;
623         bool const isrtl = realfont.isVisibleRightToLeft();
624
625         if (!samelang || isrtl != bp.language->rightToLeft())
626                 l_shape = true;
627
628         // The ERT language hack needs fixing up
629         if (realfont.language() == latex_language)
630                 l_shape = false;
631
632         // show caret on screen
633         Cursor & cur = buffer_view_->cursor();
634         bool completable = cur.inset().showCompletionCursor()
635                 && completer_->completionAvailable()
636                 && !completer_->popupVisible()
637                 && !completer_->inlineVisible();
638         caret_visible_ = true;
639
640         caret_->update(point.x_, point.y_, h, l_shape, isrtl, completable);
641 }
642
643
644 void GuiWorkArea::Private::showCaret()
645 {
646         if (caret_visible_)
647                 return;
648
649         updateCaretGeometry();
650         p->viewport()->update();
651 }
652
653
654 void GuiWorkArea::Private::hideCaret()
655 {
656         if (!caret_visible_)
657                 return;
658
659         caret_visible_ = false;
660         //if (!qApp->focusWidget())
661                 p->viewport()->update();
662 }
663
664
665 void GuiWorkArea::Private::updateScrollbar()
666 {
667         // Prevent setRange() and setSliderPosition from causing recursive calls via
668         // the signal valueChanged. (#10311)
669         QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
670                             p, SLOT(scrollTo(int)));
671         ScrollbarParameters const & scroll = buffer_view_->scrollbarParameters();
672         p->verticalScrollBar()->setRange(scroll.min, scroll.max);
673         p->verticalScrollBar()->setPageStep(scroll.page_step);
674         p->verticalScrollBar()->setSingleStep(scroll.single_step);
675         p->verticalScrollBar()->setSliderPosition(0);
676         // Connect to the vertical scroll bar
677         QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
678                          p, SLOT(scrollTo(int)));
679 }
680
681
682 void GuiWorkArea::scrollTo(int value)
683 {
684         stopBlinkingCaret();
685         d->buffer_view_->scrollDocView(value, true);
686
687         if (lyxrc.cursor_follows_scrollbar) {
688                 d->buffer_view_->setCursorFromScrollbar();
689                 // FIXME: let GuiView take care of those.
690                 d->lyx_view_->updateLayoutList();
691         }
692         // Show the caret immediately after any operation.
693         startBlinkingCaret();
694         // FIXME QT5
695 #ifdef Q_WS_X11
696         QApplication::syncX();
697 #endif
698 }
699
700
701 bool GuiWorkArea::event(QEvent * e)
702 {
703         switch (e->type()) {
704         case QEvent::ToolTip: {
705                 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
706                 if (lyxrc.use_tooltip) {
707                         QPoint pos = helpEvent->pos();
708                         if (pos.x() < viewport()->width()) {
709                                 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
710                                 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
711                         }
712                         else
713                                 QToolTip::hideText();
714                 }
715                 // Don't forget to accept the event!
716                 e->accept();
717                 return true;
718         }
719
720         case QEvent::ShortcutOverride:
721                 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
722                 // this case
723                 keyPressEvent(static_cast<QKeyEvent *>(e));
724                 return e->isAccepted();
725
726         case QEvent::KeyPress: {
727                 // We catch this event in order to catch the Tab or Shift+Tab key press
728                 // which are otherwise reserved to focus switching between controls
729                 // within a dialog.
730                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
731                 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
732                         || (ke->key() == Qt::Key_Backtab && (
733                                 ke->modifiers() == Qt::ShiftModifier
734                                 || ke->modifiers() == Qt::NoModifier))) {
735                         keyPressEvent(ke);
736                         return true;
737                 }
738                 return QAbstractScrollArea::event(e);
739         }
740
741         default:
742                 return QAbstractScrollArea::event(e);
743         }
744         return false;
745 }
746
747
748 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
749 {
750         string name;
751         if (e->reason() == QContextMenuEvent::Mouse)
752                 // the menu name is set on mouse press
753                 name = d->context_menu_name_;
754         else {
755                 QPoint pos = e->pos();
756                 Cursor const & cur = d->buffer_view_->cursor();
757                 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
758                         // Do not access the context menu of math right in front of before
759                         // the cursor. This does not work when the cursor is in text.
760                         Inset * inset = cur.paragraph().getInset(cur.pos());
761                         if (inset && inset->asInsetMath())
762                                 --pos.rx();
763                         else if (cur.pos() > 0) {
764                                 inset = cur.paragraph().getInset(cur.pos() - 1);
765                                 if (inset)
766                                         ++pos.rx();
767                         }
768                 }
769                 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
770         }
771
772         if (name.empty()) {
773                 e->accept();
774                 return;
775         }
776         // always show mnemonics when the keyboard is used to show the context menu
777         // FIXME: This should be fixed in Qt itself
778         bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
779         QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
780         if (!menu) {
781                 e->accept();
782                 return;
783         }
784         // Position the menu to the right.
785         // FIXME: menu position should be different for RTL text.
786         menu->exec(e->globalPos());
787         e->accept();
788 }
789
790
791 void GuiWorkArea::focusInEvent(QFocusEvent * e)
792 {
793         LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
794         if (d->lyx_view_->currentWorkArea() != this) {
795                 d->lyx_view_->setCurrentWorkArea(this);
796                 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
797         }
798
799         startBlinkingCaret();
800         QAbstractScrollArea::focusInEvent(e);
801 }
802
803
804 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
805 {
806         LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
807         stopBlinkingCaret();
808         QAbstractScrollArea::focusOutEvent(e);
809 }
810
811
812 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
813 {
814         if (d->dc_event_.active && d->dc_event_ == *e) {
815                 d->dc_event_.active = false;
816                 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
817                         q_button_state(e->button()), q_key_state(e->modifiers()));
818                 d->dispatch(cmd);
819                 e->accept();
820                 return;
821         }
822
823 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
824         inputContext()->reset();
825 #endif
826
827         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
828                         q_button_state(e->button()), q_key_state(e->modifiers()));
829         d->dispatch(cmd);
830
831         // Save the context menu on mouse press, because also the mouse
832         // cursor is set on mouse press. Afterwards, we can either release
833         // the mousebutton somewhere else, or the cursor might have moved
834         // due to the DEPM. We need to do this after the mouse has been
835         // set in dispatch(), because the selection state might change.
836         if (e->button() == Qt::RightButton)
837                 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
838
839         e->accept();
840 }
841
842
843 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
844 {
845         if (d->synthetic_mouse_event_.timeout.running())
846                 d->synthetic_mouse_event_.timeout.stop();
847
848         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
849                         q_button_state(e->button()), q_key_state(e->modifiers()));
850         d->dispatch(cmd);
851         e->accept();
852 }
853
854
855 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
856 {
857         // we kill the triple click if we move
858         doubleClickTimeout();
859         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
860                         q_motion_state(e->buttons()), q_key_state(e->modifiers()));
861
862         e->accept();
863
864         // If we're above or below the work area...
865         if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
866                         && e->buttons() == mouse_button::button1) {
867                 // Make sure only a synthetic event can cause a page scroll,
868                 // so they come at a steady rate:
869                 if (e->y() <= 20)
870                         // _Force_ a scroll up:
871                         cmd.set_y(e->y() - 21);
872                 else
873                         cmd.set_y(e->y() + 21);
874                 // Store the event, to be handled when the timeout expires.
875                 d->synthetic_mouse_event_.cmd = cmd;
876
877                 if (d->synthetic_mouse_event_.timeout.running()) {
878                         // Discard the event. Note that it _may_ be handled
879                         // when the timeout expires if
880                         // synthetic_mouse_event_.cmd has not been overwritten.
881                         // Ie, when the timeout expires, we handle the
882                         // most recent event but discard all others that
883                         // occurred after the one used to start the timeout
884                         // in the first place.
885                         return;
886                 }
887
888                 d->synthetic_mouse_event_.restart_timeout = true;
889                 d->synthetic_mouse_event_.timeout.start();
890                 // Fall through to handle this event...
891
892         } else if (d->synthetic_mouse_event_.timeout.running()) {
893                 // Store the event, to be possibly handled when the timeout
894                 // expires.
895                 // Once the timeout has expired, normal control is returned
896                 // to mouseMoveEvent (restart_timeout = false).
897                 // This results in a much smoother 'feel' when moving the
898                 // mouse back into the work area.
899                 d->synthetic_mouse_event_.cmd = cmd;
900                 d->synthetic_mouse_event_.restart_timeout = false;
901                 return;
902         }
903         d->dispatch(cmd);
904 }
905
906
907 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
908 {
909         // Wheel rotation by one notch results in a delta() of 120 (see
910         // documentation of QWheelEvent)
911         // But first we have to ignore horizontal scroll events.
912 #if QT_VERSION < 0x050000
913         if (ev->orientation() == Qt::Horizontal) {
914                 ev->accept();
915                 return;
916         }
917         double const delta = ev->delta() / 120.0;
918 #else
919         QPoint const aDelta = ev->angleDelta();
920         // skip horizontal wheel event
921         if (abs(aDelta.x()) > abs(aDelta.y())) {
922                 ev->accept();
923                 return;
924         }
925         double const delta = aDelta.y() / 120.0;
926 #endif
927
928         bool zoom = false;
929         switch (lyxrc.scroll_wheel_zoom) {
930         case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
931                 zoom = ev->modifiers() & Qt::ControlModifier;
932                 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
933                 break;
934         case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
935                 zoom = ev->modifiers() & Qt::ShiftModifier;
936                 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
937                 break;
938         case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
939                 zoom = ev->modifiers() & Qt::AltModifier;
940                 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
941                 break;
942         case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
943                 break;
944         }
945         if (zoom) {
946                 docstring arg = convert<docstring>(int(5 * delta));
947                 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
948                 return;
949         }
950
951         // Take into account the desktop wide settings.
952         int const lines = qApp->wheelScrollLines();
953         int const page_step = verticalScrollBar()->pageStep();
954         // Test if the wheel mouse is set to one screen at a time.
955         // This is according to
956         // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
957         int scroll_value =
958                 min(lines * verticalScrollBar()->singleStep(), page_step);
959
960         // Take into account the rotation and the user preferences.
961         scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
962         LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
963                         << " delta = " << delta << " scroll_value = " << scroll_value
964                         << " page_step = " << page_step);
965         // Now scroll.
966         verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
967
968         ev->accept();
969 }
970
971
972 void GuiWorkArea::generateSyntheticMouseEvent()
973 {
974         int const e_y = d->synthetic_mouse_event_.cmd.y();
975         int const wh = d->buffer_view_->workHeight();
976         bool const up = e_y < 0;
977         bool const down = e_y > wh;
978
979         // Set things off to generate the _next_ 'pseudo' event.
980         int step = 50;
981         if (d->synthetic_mouse_event_.restart_timeout) {
982                 // This is some magic formulae to determine the speed
983                 // of scrolling related to the position of the mouse.
984                 int time = 200;
985                 if (up || down) {
986                         int dist = up ? -e_y : e_y - wh;
987                         time = max(min(200, 250000 / (dist * dist)), 1) ;
988
989                         if (time < 40) {
990                                 step = 80000 / (time * time);
991                                 time = 40;
992                         }
993                 }
994                 d->synthetic_mouse_event_.timeout.setTimeout(time);
995                 d->synthetic_mouse_event_.timeout.start();
996         }
997
998         // Can we scroll further ?
999         int const value = verticalScrollBar()->value();
1000         if (value == verticalScrollBar()->maximum()
1001                   || value == verticalScrollBar()->minimum()) {
1002                 d->synthetic_mouse_event_.timeout.stop();
1003                 return;
1004         }
1005
1006         // Scroll
1007         if (step <= 2 * wh) {
1008                 d->buffer_view_->scroll(up ? -step : step);
1009                 d->buffer_view_->updateMetrics();
1010         } else {
1011                 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
1012         }
1013
1014         // In which paragraph do we have to set the cursor ?
1015         Cursor & cur = d->buffer_view_->cursor();
1016         // FIXME: we don't know how to handle math.
1017         Text * text = cur.text();
1018         if (!text)
1019                 return;
1020         TextMetrics const & tm = d->buffer_view_->textMetrics(text);
1021
1022         // Quit gracefully if there are no metrics, since otherwise next
1023         // line would crash (bug #10324).
1024         // This situation seems related to a (not yet understood) timing problem.
1025         if (tm.empty())
1026                 return;
1027
1028         pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
1029         ParagraphMetrics const & pm = *pp.second;
1030         pit_type const pit = pp.first;
1031
1032         if (pm.rows().empty())
1033                 return;
1034
1035         // Find the row at which we set the cursor.
1036         RowList::const_iterator rit = pm.rows().begin();
1037         RowList::const_iterator rlast = pm.rows().end();
1038         int yy = pm.position() - pm.ascent();
1039         for (--rlast; rit != rlast; ++rit) {
1040                 int h = rit->height();
1041                 if ((up && yy + h > 0)
1042                           || (!up && yy + h > wh - defaultRowHeight()))
1043                         break;
1044                 yy += h;
1045         }
1046
1047         // Find the position of the cursor
1048         bool bound;
1049         int x = d->synthetic_mouse_event_.cmd.x();
1050         pos_type const pos = tm.getPosNearX(*rit, x, bound);
1051
1052         // Set the cursor
1053         cur.pit() = pit;
1054         cur.pos() = pos;
1055         cur.boundary(bound);
1056
1057         d->buffer_view_->buffer().changed(false);
1058         return;
1059 }
1060
1061
1062 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
1063 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
1064 {
1065         qRegisterMetaType<KeySymbol>("KeySymbol");
1066         qRegisterMetaType<KeyModifier>("KeyModifier");
1067         connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
1068                 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
1069                 Qt::QueuedConnection);
1070         connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
1071                 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1072 }
1073
1074
1075 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1076 {
1077         flag_ = true;
1078         if (isAutoRepeat)
1079                 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1080         bool result = flag_;
1081         flag_ = false;
1082         return result;
1083 }
1084
1085
1086 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1087 {
1088         if (emitCheck(isAutoRepeat))
1089                 Q_EMIT signal(sym, mod);
1090         else
1091                 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1092 }
1093
1094
1095 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1096 {
1097         // this is also called for ShortcutOverride events. In this case, one must
1098         // not act but simply accept the event explicitly.
1099         bool const act = (ev->type() != QEvent::ShortcutOverride);
1100
1101         // Do not process here some keys if dialog_mode_ is set
1102         bool const for_dialog_mode = d->dialog_mode_
1103                 && (ev->modifiers() == Qt::NoModifier
1104                     || ev->modifiers() == Qt::ShiftModifier)
1105                 && (ev->key() == Qt::Key_Escape
1106                     || ev->key() == Qt::Key_Enter
1107                     || ev->key() == Qt::Key_Return);
1108         // also do not use autoRepeat to input shortcuts
1109         bool const autoRepeat = ev->isAutoRepeat();
1110
1111         if (for_dialog_mode || (!act && autoRepeat)) {
1112                 ev->ignore();
1113                 return;
1114         }
1115
1116         // intercept some keys if completion popup is visible
1117         if (d->completer_->popupVisible()) {
1118                 switch (ev->key()) {
1119                 case Qt::Key_Enter:
1120                 case Qt::Key_Return:
1121                         if (act)
1122                                 d->completer_->activate();
1123                         ev->accept();
1124                         return;
1125                 }
1126         }
1127
1128         KeyModifier const m = q_key_state(ev->modifiers());
1129
1130         if (act && lyxerr.debugging(Debug::KEY)) {
1131                 std::string str;
1132                 if (m & ShiftModifier)
1133                         str += "Shift-";
1134                 if (m & ControlModifier)
1135                         str += "Control-";
1136                 if (m & AltModifier)
1137                         str += "Alt-";
1138                 if (m & MetaModifier)
1139                         str += "Meta-";
1140                 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1141                        << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1142                        << " keyState: " << str);
1143         }
1144
1145         KeySymbol sym;
1146         setKeySymbol(&sym, ev);
1147         if (sym.isOK()) {
1148                 if (act) {
1149                         Q_EMIT compressKeySym(sym, m, autoRepeat);
1150                         ev->accept();
1151                 } else
1152                         // here, !autoRepeat, as determined at the beginning
1153                         ev->setAccepted(queryKeySym(sym, m));
1154         } else {
1155                 ev->ignore();
1156         }
1157 }
1158
1159
1160 void GuiWorkArea::doubleClickTimeout()
1161 {
1162         d->dc_event_.active = false;
1163 }
1164
1165
1166 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1167 {
1168         d->dc_event_ = DoubleClick(ev);
1169         QTimer::singleShot(QApplication::doubleClickInterval(), this,
1170                         SLOT(doubleClickTimeout()));
1171         FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1172                         q_button_state(ev->button()), q_key_state(ev->modifiers()));
1173         d->dispatch(cmd);
1174         ev->accept();
1175 }
1176
1177
1178 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1179 {
1180         QAbstractScrollArea::resizeEvent(ev);
1181         d->need_resize_ = true;
1182         ev->accept();
1183 }
1184
1185
1186 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1187 {
1188         if (preedit_string_.empty())
1189                 return;
1190
1191         // FIXME: shall we use real_current_font here? (see #10478)
1192         FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1193         FontMetrics const & fm = theFontMetrics(font);
1194         int const height = fm.maxHeight();
1195         int cur_x = caret_->rect().left();
1196         int cur_y = caret_->rect().bottom();
1197
1198         // get attributes of input method cursor.
1199         // cursor_pos : cursor position in preedit string.
1200         size_t cursor_pos = 0;
1201         bool cursor_is_visible = false;
1202         for (auto const & attr : preedit_attr_) {
1203                 if (attr.type == QInputMethodEvent::Cursor) {
1204                         cursor_pos = attr.start;
1205                         cursor_is_visible = attr.length != 0;
1206                         break;
1207                 }
1208         }
1209
1210         size_t const preedit_length = preedit_string_.length();
1211
1212         // get position of selection in input method.
1213         // FIXME: isn't there a way to do this simplier?
1214         // rStart : cursor position in selected string in IM.
1215         size_t rStart = 0;
1216         // rLength : selected string length in IM.
1217         size_t rLength = 0;
1218         if (cursor_pos < preedit_length) {
1219                 for (auto const & attr : preedit_attr_) {
1220                         if (attr.type == QInputMethodEvent::TextFormat) {
1221                                 if (attr.start <= int(cursor_pos)
1222                                         && int(cursor_pos) < attr.start + attr.length) {
1223                                                 rStart = attr.start;
1224                                                 rLength = attr.length;
1225                                                 if (!cursor_is_visible)
1226                                                         cursor_pos += rLength;
1227                                                 break;
1228                                 }
1229                         }
1230                 }
1231         }
1232         else {
1233                 rStart = cursor_pos;
1234                 rLength = 0;
1235         }
1236
1237         int const right_margin = buffer_view_->rightMargin();
1238         Painter::preedit_style ps;
1239         // Most often there would be only one line:
1240         preedit_lines_ = 1;
1241         for (size_t pos = 0; pos != preedit_length; ++pos) {
1242                 char_type const typed_char = preedit_string_[pos];
1243                 // reset preedit string style
1244                 ps = Painter::preedit_default;
1245
1246                 // if we reached the right extremity of the screen, go to next line.
1247                 if (cur_x + fm.width(typed_char) > p->viewport()->width() - right_margin) {
1248                         cur_x = right_margin;
1249                         cur_y += height + 1;
1250                         ++preedit_lines_;
1251                 }
1252                 // preedit strings are displayed with dashed underline
1253                 // and partial strings are displayed white on black indicating
1254                 // that we are in selecting mode in the input method.
1255                 // FIXME: rLength == preedit_length is not a changing condition
1256                 // FIXME: should be put out of the loop.
1257                 if (pos >= rStart
1258                         && pos < rStart + rLength
1259                         && !(cursor_pos < rLength && rLength == preedit_length))
1260                         ps = Painter::preedit_selecting;
1261
1262                 if (pos == cursor_pos
1263                         && (cursor_pos < rLength && rLength == preedit_length))
1264                         ps = Painter::preedit_cursor;
1265
1266                 // draw one character and update cur_x.
1267                 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1268         }
1269 }
1270
1271
1272 void GuiWorkArea::Private::resetScreen()
1273 {
1274         if (use_backingstore_) {
1275                 int const pr = p->pixelRatio();
1276                 screen_ = QImage(static_cast<int>(pr * p->viewport()->width()),
1277                                  static_cast<int>(pr * p->viewport()->height()),
1278                                  QImage::Format_ARGB32_Premultiplied);
1279 #  if QT_VERSION >= 0x050000
1280                 screen_.setDevicePixelRatio(pr);
1281 #  endif
1282         }
1283 }
1284
1285
1286 QPaintDevice * GuiWorkArea::Private::screenDevice()
1287 {
1288         if (use_backingstore_)
1289                 return &screen_;
1290         else
1291                 return p->viewport();
1292 }
1293
1294
1295 void GuiWorkArea::Private::updateScreen(QRectF const & rc)
1296 {
1297         if (use_backingstore_) {
1298                 QPainter qpain(p->viewport());
1299                 double const pr = p->pixelRatio();
1300                 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr,
1301                                           rc.width() * pr, rc.height() * pr);
1302                 qpain.drawImage(rc, screen_, rcs);
1303         }
1304 }
1305
1306
1307 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1308 {
1309         // Do not trigger the painting machinery if we are not ready (see
1310         // bug #10989). The second test triggers when in the middle of a
1311         // dispatch operation.
1312         if (view().busy() || d->buffer_view_->buffer().undo().activeUndoGroup()) {
1313                 // Since macOS has turned the screen black at this point, our
1314                 // backing store has to be copied to screen (this is a no-op
1315                 // except on macOS).
1316                 d->updateScreen(ev->rect());
1317                 // Ignore this paint event, but request a new one for later.
1318                 viewport()->update(ev->rect());
1319                 ev->accept();
1320                 return;
1321         }
1322
1323         // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1324         //      << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1325
1326         if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_) {
1327                 d->resetScreen();
1328                 d->resizeBufferView();
1329         }
1330
1331         d->last_pixel_ratio_ = pixelRatio();
1332
1333         GuiPainter pain(d->screenDevice(), pixelRatio(), d->lyx_view_->develMode());
1334
1335         d->buffer_view_->draw(pain, d->caret_visible_);
1336
1337         // The preedit text, if needed
1338         d->paintPreeditText(pain);
1339
1340         // and the caret
1341         if (d->caret_visible_)
1342                 d->caret_->draw(pain, d->buffer_view_->horizScrollOffset());
1343
1344         d->updateScreen(ev->rect());
1345
1346         ev->accept();
1347 }
1348
1349
1350 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1351 {
1352         LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1353                    << " commitString: " << e->commitString());
1354
1355         // insert the processed text in the document (handles undo)
1356         if (!e->commitString().isEmpty()) {
1357                 FuncRequest cmd(LFUN_SELF_INSERT,
1358                                 qstring_to_ucs4(e->commitString()),
1359                                 FuncRequest::KEYBOARD);
1360                 dispatch(cmd);
1361                 // FIXME: this is supposed to remove traces from preedit
1362                 // string. Can we avoid calling it explicitely?
1363                 d->buffer_view_->updateMetrics();
1364         }
1365
1366         // Hide the caret during the test transformation.
1367         if (e->preeditString().isEmpty())
1368                 startBlinkingCaret();
1369         else
1370                 stopBlinkingCaret();
1371
1372         if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1373                 // Nothing to do
1374                 e->accept();
1375                 return;
1376         }
1377
1378         // The preedit text and its attributes will be used in paintPreeditText
1379         d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1380         d->preedit_attr_ = e->attributes();
1381
1382
1383         // redraw area of preedit string.
1384         int height = d->caret_->rect().height();
1385         int cur_y = d->caret_->rect().bottom();
1386         viewport()->update(0, cur_y - height, viewport()->width(),
1387                 (height + 1) * d->preedit_lines_);
1388
1389         if (d->preedit_string_.empty()) {
1390                 d->preedit_lines_ = 1;
1391                 e->accept();
1392                 return;
1393         }
1394
1395         // Don't forget to accept the event!
1396         e->accept();
1397 }
1398
1399
1400 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1401 {
1402         QRect cur_r(0, 0, 0, 0);
1403         switch (query) {
1404                 // this is the CJK-specific composition window position and
1405                 // the context menu position when the menu key is pressed.
1406                 case Qt::ImMicroFocus:
1407                         cur_r = d->caret_->rect();
1408                         if (d->preedit_lines_ != 1)
1409                                 cur_r.moveLeft(10);
1410                         cur_r.moveBottom(cur_r.bottom()
1411                                 + cur_r.height() * (d->preedit_lines_ - 1));
1412                         // return lower right of caret in LyX.
1413                         return cur_r;
1414                 default:
1415                         return QWidget::inputMethodQuery(query);
1416         }
1417 }
1418
1419
1420 void GuiWorkArea::updateWindowTitle()
1421 {
1422         Buffer const & buf = bufferView().buffer();
1423         if (buf.fileName() != d->file_name_
1424             || buf.params().shell_escape != d->shell_escape_
1425             || buf.hasReadonlyFlag() != d->read_only_
1426             || buf.lyxvc().vcstatus() != d->vc_status_
1427             || buf.isClean() != d->clean_
1428             || buf.notifiesExternalModification() != d->externally_modified_) {
1429                 d->file_name_ = buf.fileName();
1430                 d->shell_escape_ = buf.params().shell_escape;
1431                 d->read_only_ = buf.hasReadonlyFlag();
1432                 d->vc_status_ = buf.lyxvc().vcstatus();
1433                 d->clean_ = buf.isClean();
1434                 d->externally_modified_ = buf.notifiesExternalModification();
1435                 Q_EMIT titleChanged(this);
1436         }
1437 }
1438
1439
1440 bool GuiWorkArea::isFullScreen() const
1441 {
1442         return d->lyx_view_ && d->lyx_view_->isFullScreen();
1443 }
1444
1445
1446 bool GuiWorkArea::inDialogMode() const
1447 {
1448         return d->dialog_mode_;
1449 }
1450
1451
1452 void GuiWorkArea::setDialogMode(bool mode)
1453 {
1454         d->dialog_mode_ = mode;
1455 }
1456
1457
1458 GuiCompleter & GuiWorkArea::completer()
1459 {
1460         return *d->completer_;
1461 }
1462
1463 GuiView const & GuiWorkArea::view() const
1464 {
1465         return *d->lyx_view_;
1466 }
1467
1468
1469 GuiView & GuiWorkArea::view()
1470 {
1471         return *d->lyx_view_;
1472 }
1473
1474 ////////////////////////////////////////////////////////////////////
1475 //
1476 // EmbeddedWorkArea
1477 //
1478 ////////////////////////////////////////////////////////////////////
1479
1480
1481 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1482 {
1483         support::TempFile tempfile("embedded.internal");
1484         tempfile.setAutoRemove(false);
1485         buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1486         buffer_->setUnnamed(true);
1487         buffer_->setFullyLoaded(true);
1488         setBuffer(*buffer_);
1489         setDialogMode(true);
1490 }
1491
1492
1493 EmbeddedWorkArea::~EmbeddedWorkArea()
1494 {
1495         // No need to destroy buffer and bufferview here, because it is done
1496         // in theBufferList() destruction loop at application exit
1497 }
1498
1499
1500 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1501 {
1502         disable();
1503         GuiWorkArea::closeEvent(ev);
1504 }
1505
1506
1507 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1508 {
1509         disable();
1510         GuiWorkArea::hideEvent(ev);
1511 }
1512
1513
1514 QSize EmbeddedWorkArea::sizeHint () const
1515 {
1516         // FIXME(?):
1517         // GuiWorkArea sets the size to the screen's viewport
1518         // by returning a value this gets overridden
1519         // EmbeddedWorkArea is now sized to fit in the layout
1520         // of the parent, and has a minimum size set in GuiWorkArea
1521         // which is what we return here
1522         return QSize(100, 70);
1523 }
1524
1525
1526 void EmbeddedWorkArea::disable()
1527 {
1528         stopBlinkingCaret();
1529         if (view().currentWorkArea() != this)
1530                 return;
1531         // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1532         // tolerates it and shows the background logo), what happens if
1533         // an EmbeddedWorkArea is closed after closing all document WAs
1534         view().setCurrentWorkArea(view().currentMainWorkArea());
1535 }
1536
1537 ////////////////////////////////////////////////////////////////////
1538 //
1539 // TabWorkArea
1540 //
1541 ////////////////////////////////////////////////////////////////////
1542
1543 #ifdef Q_OS_MAC
1544 class NoTabFrameMacStyle : public QProxyStyle {
1545 public:
1546         ///
1547         QRect subElementRect(SubElement element, const QStyleOption * option,
1548                              const QWidget * widget = 0) const
1549         {
1550                 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1551                 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1552
1553                 // The Qt Mac style puts the contents into a 3 pixel wide box
1554                 // which looks very ugly and not like other Mac applications.
1555                 // Hence we remove this here, and moreover the 16 pixel round
1556                 // frame above if the tab bar is hidden.
1557                 if (element == QStyle::SE_TabWidgetTabContents) {
1558                         rect.adjust(- rect.left(), 0, rect.left(), 0);
1559                         if (noBar)
1560                                 rect.setTop(0);
1561                 }
1562
1563                 return rect;
1564         }
1565 };
1566
1567 NoTabFrameMacStyle noTabFrameMacStyle;
1568 #endif
1569
1570
1571 TabWorkArea::TabWorkArea(QWidget * parent)
1572         : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1573 {
1574 #ifdef Q_OS_MAC
1575         setStyle(&noTabFrameMacStyle);
1576 #endif
1577
1578         QPalette pal = palette();
1579         pal.setColor(QPalette::Active, QPalette::Button,
1580                 pal.color(QPalette::Active, QPalette::Window));
1581         pal.setColor(QPalette::Disabled, QPalette::Button,
1582                 pal.color(QPalette::Disabled, QPalette::Window));
1583         pal.setColor(QPalette::Inactive, QPalette::Button,
1584                 pal.color(QPalette::Inactive, QPalette::Window));
1585
1586         QObject::connect(this, SIGNAL(currentChanged(int)),
1587                 this, SLOT(on_currentTabChanged(int)));
1588
1589         closeBufferButton = new QToolButton(this);
1590         closeBufferButton->setPalette(pal);
1591         // FIXME: rename the icon to closebuffer.png
1592         closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1593         closeBufferButton->setText("Close File");
1594         closeBufferButton->setAutoRaise(true);
1595         closeBufferButton->setCursor(Qt::ArrowCursor);
1596         closeBufferButton->setToolTip(qt_("Close File"));
1597         closeBufferButton->setEnabled(true);
1598         QObject::connect(closeBufferButton, SIGNAL(clicked()),
1599                 this, SLOT(closeCurrentBuffer()));
1600         setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1601
1602         // set TabBar behaviour
1603         QTabBar * tb = tabBar();
1604         tb->setTabsClosable(!lyxrc.single_close_tab_button);
1605         tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1606         tb->setElideMode(Qt::ElideNone);
1607         // allow dragging tabs
1608         tb->setMovable(true);
1609         // make us responsible for the context menu of the tabbar
1610         tb->setContextMenuPolicy(Qt::CustomContextMenu);
1611         connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1612                 this, SLOT(showContextMenu(const QPoint &)));
1613         connect(tb, SIGNAL(tabCloseRequested(int)),
1614                 this, SLOT(closeTab(int)));
1615
1616         setUsesScrollButtons(true);
1617 }
1618
1619
1620 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1621 {
1622         if (me->button() == Qt::MidButton)
1623                 midpressed_tab_ = tabBar()->tabAt(me->pos());
1624         else
1625                 QTabWidget::mousePressEvent(me);
1626 }
1627
1628
1629 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1630 {
1631         if (me->button() == Qt::MidButton) {
1632                 int const midreleased_tab = tabBar()->tabAt(me->pos());
1633                 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1634                         closeTab(midreleased_tab);
1635         } else
1636                 QTabWidget::mouseReleaseEvent(me);
1637 }
1638
1639
1640 void TabWorkArea::paintEvent(QPaintEvent * event)
1641 {
1642         if (tabBar()->isVisible()) {
1643                 QTabWidget::paintEvent(event);
1644         } else {
1645                 // Prevent the selected tab to influence the
1646                 // painting of the frame of the tab widget.
1647                 // This is needed for gtk style in Qt.
1648                 QStylePainter p(this);
1649 #if QT_VERSION < 0x050000
1650                 QStyleOptionTabWidgetFrameV2 opt;
1651 #else
1652                 QStyleOptionTabWidgetFrame opt;
1653 #endif
1654                 initStyleOption(&opt);
1655                 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1656                         &opt, this);
1657                 opt.selectedTabRect = QRect();
1658                 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1659         }
1660 }
1661
1662
1663 bool TabWorkArea::posIsTab(QPoint position)
1664 {
1665         // tabAt returns -1 if tab does not covers position
1666         return tabBar()->tabAt(position) > -1;
1667 }
1668
1669
1670 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1671 {
1672         if (event->button() != Qt::LeftButton)
1673                 return;
1674
1675         // this code chunk is unnecessary because it seems the event only makes
1676         // it this far if it is not on a tab. I'm not sure why this is (maybe
1677         // it is handled and ended in DragTabBar?), and thus I'm not sure if
1678         // this is true in all cases and if it will be true in the future so I
1679         // leave this code for now. (skostysh, 2016-07-21)
1680         //
1681         // return early if double click on existing tabs
1682         if (posIsTab(event->pos()))
1683                 return;
1684
1685         dispatch(FuncRequest(LFUN_BUFFER_NEW));
1686 }
1687
1688
1689 void TabWorkArea::setFullScreen(bool full_screen)
1690 {
1691         for (int i = 0; i != count(); ++i) {
1692                 if (GuiWorkArea * wa = workArea(i))
1693                         wa->setFullScreen(full_screen);
1694         }
1695
1696         if (lyxrc.full_screen_tabbar)
1697                 showBar(!full_screen && count() > 1);
1698         else
1699                 showBar(count() > 1);
1700 }
1701
1702
1703 void TabWorkArea::showBar(bool show)
1704 {
1705         tabBar()->setEnabled(show);
1706         tabBar()->setVisible(show);
1707         closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1708         setTabsClosable(!lyxrc.single_close_tab_button);
1709 }
1710
1711
1712 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1713 {
1714         QWidget * w = QTabWidget::widget(index);
1715         if (!w)
1716                 return nullptr;
1717         GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1718         LATTEST(wac);
1719         return wac;
1720 }
1721
1722
1723 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1724 {
1725         return widget(currentIndex());
1726 }
1727
1728
1729 GuiWorkArea * TabWorkArea::workArea(int index) const
1730 {
1731         GuiWorkAreaContainer * w = widget(index);
1732         if (!w)
1733                 return nullptr;
1734         return w->workArea();
1735 }
1736
1737
1738 GuiWorkArea * TabWorkArea::currentWorkArea() const
1739 {
1740         return workArea(currentIndex());
1741 }
1742
1743
1744 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1745 {
1746         // FIXME: this method doesn't work if we have more than one work area
1747         // showing the same buffer.
1748         for (int i = 0; i != count(); ++i) {
1749                 GuiWorkArea * wa = workArea(i);
1750                 LASSERT(wa, return 0);
1751                 if (&wa->bufferView().buffer() == &buffer)
1752                         return wa;
1753         }
1754         return 0;
1755 }
1756
1757
1758 void TabWorkArea::closeAll()
1759 {
1760         while (count()) {
1761                 QWidget * wac = widget(0);
1762                 LASSERT(wac, return);
1763                 removeTab(0);
1764                 delete wac;
1765         }
1766 }
1767
1768
1769 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1770 {
1771         for (int index = 0; index < count(); ++index)
1772                 if (workArea(index) == w)
1773                         return index;
1774         return -1;
1775 }
1776
1777
1778 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1779 {
1780         LASSERT(work_area, return false);
1781         int index = indexOfWorkArea(work_area);
1782         if (index == -1)
1783                 return false;
1784
1785         if (index == currentIndex())
1786                 // Make sure the work area is up to date.
1787                 on_currentTabChanged(index);
1788         else
1789                 // Switch to the work area.
1790                 setCurrentIndex(index);
1791         work_area->setFocus();
1792
1793         return true;
1794 }
1795
1796
1797 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1798 {
1799         GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1800         GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1801         wa->setUpdatesEnabled(false);
1802         // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1803         // when hiding it again below).
1804         if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1805                 showBar(count() > 0);
1806         addTab(wac, wa->windowTitle());
1807         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1808                 this, SLOT(updateTabTexts()));
1809         if (currentWorkArea() && currentWorkArea()->isFullScreen())
1810                 setFullScreen(true);
1811         else
1812                 // Hide tabbar if there's only one tab.
1813                 showBar(count() > 1);
1814
1815         updateTabTexts();
1816
1817         return wa;
1818 }
1819
1820
1821 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1822 {
1823         LASSERT(work_area, return false);
1824         int index = indexOfWorkArea(work_area);
1825         if (index == -1)
1826                 return false;
1827
1828         work_area->setUpdatesEnabled(false);
1829         QWidget * wac = widget(index);
1830         removeTab(index);
1831         delete wac;
1832
1833         if (count()) {
1834                 // make sure the next work area is enabled.
1835                 currentWidget()->setUpdatesEnabled(true);
1836                 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1837                         setFullScreen(true);
1838                 else
1839                         // Show tabbar only if there's more than one tab.
1840                         showBar(count() > 1);
1841         } else
1842                 lastWorkAreaRemoved();
1843
1844         updateTabTexts();
1845
1846         return true;
1847 }
1848
1849
1850 void TabWorkArea::on_currentTabChanged(int i)
1851 {
1852         // returns e.g. on application destruction
1853         if (i == -1)
1854                 return;
1855         GuiWorkArea * wa = workArea(i);
1856         LASSERT(wa, return);
1857         wa->setUpdatesEnabled(true);
1858         wa->scheduleRedraw(true);
1859         wa->setFocus();
1860         ///
1861         currentWorkAreaChanged(wa);
1862
1863         LYXERR(Debug::GUI, "currentTabChanged " << i
1864                 << " File: " << wa->bufferView().buffer().absFileName());
1865 }
1866
1867
1868 void TabWorkArea::closeCurrentBuffer()
1869 {
1870         GuiWorkArea * wa;
1871         if (clicked_tab_ == -1)
1872                 wa = currentWorkArea();
1873         else {
1874                 wa = workArea(clicked_tab_);
1875                 LASSERT(wa, return);
1876         }
1877         wa->view().closeWorkArea(wa);
1878 }
1879
1880
1881 void TabWorkArea::hideCurrentTab()
1882 {
1883         GuiWorkArea * wa;
1884         if (clicked_tab_ == -1)
1885                 wa = currentWorkArea();
1886         else {
1887                 wa = workArea(clicked_tab_);
1888                 LASSERT(wa, return);
1889         }
1890         wa->view().hideWorkArea(wa);
1891 }
1892
1893
1894 void TabWorkArea::closeTab(int index)
1895 {
1896         on_currentTabChanged(index);
1897         GuiWorkArea * wa;
1898         if (index == -1)
1899                 wa = currentWorkArea();
1900         else {
1901                 wa = workArea(index);
1902                 LASSERT(wa, return);
1903         }
1904         wa->view().closeWorkArea(wa);
1905 }
1906
1907
1908 ///
1909 class DisplayPath {
1910 public:
1911         /// make vector happy
1912         DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1913         ///
1914         DisplayPath(int tab, FileName const & filename)
1915                 : tab_(tab)
1916         {
1917                 // Recode URL encoded chars via fromPercentEncoding()
1918                 string const fn = (filename.extension() == "lyx")
1919                         ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
1920                 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
1921                 postfix_ = toqstr(filename.absoluteFilePath()).
1922                         split("/", QString::SkipEmptyParts);
1923                 postfix_.pop_back();
1924                 abs_ = toqstr(filename.absoluteFilePath());
1925                 dottedPrefix_ = false;
1926         }
1927
1928         /// Absolute path for debugging.
1929         QString abs() const
1930         {
1931                 return abs_;
1932         }
1933         /// Add the first segment from the postfix or three dots to the prefix.
1934         /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1935         /// when really needed.
1936         void shiftPathSegment(bool dotted)
1937         {
1938                 if (postfix_.count() <= 0)
1939                         return;
1940
1941                 if (!dotted) {
1942                         if (dottedPrefix_ && !prefix_.isEmpty())
1943                                 prefix_ += ellipsisSlash_;
1944                         prefix_ += postfix_.front() + "/";
1945                 }
1946                 dottedPrefix_ = dotted && !prefix_.isEmpty();
1947                 postfix_.pop_front();
1948         }
1949         ///
1950         QString displayString() const
1951         {
1952                 if (prefix_.isEmpty())
1953                         return filename_;
1954
1955                 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1956                 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1957         }
1958         ///
1959         QString forecastPathString() const
1960         {
1961                 if (postfix_.count() == 0)
1962                         return displayString();
1963
1964                 return prefix_
1965                         + (dottedPrefix_ ? ellipsisSlash_ : "")
1966                         + postfix_.front() + "/";
1967         }
1968         ///
1969         bool final() const { return postfix_.empty(); }
1970         ///
1971         int tab() const { return tab_; }
1972
1973 private:
1974         /// ".../"
1975         static QString const ellipsisSlash_;
1976         ///
1977         QString prefix_;
1978         ///
1979         QStringList postfix_;
1980         ///
1981         QString filename_;
1982         ///
1983         QString abs_;
1984         ///
1985         int tab_;
1986         ///
1987         bool dottedPrefix_;
1988 };
1989
1990
1991 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1992
1993
1994 ///
1995 bool operator<(DisplayPath const & a, DisplayPath const & b)
1996 {
1997         return a.displayString() < b.displayString();
1998 }
1999
2000 ///
2001 bool operator==(DisplayPath const & a, DisplayPath const & b)
2002 {
2003         return a.displayString() == b.displayString();
2004 }
2005
2006
2007 void TabWorkArea::updateTabTexts()
2008 {
2009         size_t n = count();
2010         if (n == 0)
2011                 return;
2012         std::list<DisplayPath> paths;
2013         typedef std::list<DisplayPath>::iterator It;
2014
2015         // collect full names first: path into postfix, empty prefix and
2016         // filename without extension
2017         for (size_t i = 0; i < n; ++i) {
2018                 GuiWorkArea * i_wa = workArea(i);
2019                 FileName const fn = i_wa->bufferView().buffer().fileName();
2020                 paths.push_back(DisplayPath(i, fn));
2021         }
2022
2023         // go through path segments and see if it helps to make the path more unique
2024         bool somethingChanged = true;
2025         bool allFinal = false;
2026         while (somethingChanged && !allFinal) {
2027                 // adding path segments changes order
2028                 paths.sort();
2029
2030                 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
2031                 somethingChanged = false;
2032                 allFinal = true;
2033
2034                 // find segments which are not unique (i.e. non-atomic)
2035                 It it = paths.begin();
2036                 It segStart = it;
2037                 QString segString = it->displayString();
2038                 for (; it != paths.end(); ++it) {
2039                         // look to the next item
2040                         It next = it;
2041                         ++next;
2042
2043                         // final?
2044                         allFinal = allFinal && it->final();
2045
2046                         LYXERR(Debug::GUI, "it = " << it->abs()
2047                                << " => " << it->displayString());
2048
2049                         // still the same segment?
2050                         QString nextString;
2051                         if ((next != paths.end()
2052                              && (nextString = next->displayString()) == segString))
2053                                 continue;
2054                         LYXERR(Debug::GUI, "segment ended");
2055
2056                         // only a trivial one with one element?
2057                         if (it == segStart) {
2058                                 // start new segment
2059                                 segStart = next;
2060                                 segString = nextString;
2061                                 continue;
2062                         }
2063
2064                         // We found a non-atomic segment
2065                         // We know that segStart <= it < next <= paths.end().
2066                         // The assertion below tells coverity about it.
2067                         LATTEST(segStart != paths.end());
2068                         QString dspString = segStart->forecastPathString();
2069                         LYXERR(Debug::GUI, "first forecast found for "
2070                                << segStart->abs() << " => " << dspString);
2071                         It sit = segStart;
2072                         ++sit;
2073                         // Shift path segments and hope for the best
2074                         // that it makes the path more unique.
2075                         somethingChanged = true;
2076                         bool moreUnique = false;
2077                         for (; sit != next; ++sit) {
2078                                 if (sit->forecastPathString() != dspString) {
2079                                         LYXERR(Debug::GUI, "different forecast found for "
2080                                                 << sit->abs() << " => " << sit->forecastPathString());
2081                                         moreUnique = true;
2082                                         break;
2083                                 }
2084                                 LYXERR(Debug::GUI, "same forecast found for "
2085                                         << sit->abs() << " => " << dspString);
2086                         }
2087
2088                         // if the path segment helped, add it. Otherwise add dots
2089                         bool dots = !moreUnique;
2090                         LYXERR(Debug::GUI, "using dots = " << dots);
2091                         for (sit = segStart; sit != next; ++sit) {
2092                                 sit->shiftPathSegment(dots);
2093                                 LYXERR(Debug::GUI, "shifting "
2094                                         << sit->abs() << " => " << sit->displayString());
2095                         }
2096
2097                         // start new segment
2098                         segStart = next;
2099                         segString = nextString;
2100                 }
2101         }
2102
2103         // set new tab titles
2104         for (It it = paths.begin(); it != paths.end(); ++it) {
2105                 int const tab_index = it->tab();
2106                 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2107                 QString tab_text = it->displayString().replace("&", "&&");
2108                 if (!buf.fileName().empty() && !buf.isClean())
2109                         tab_text += "*";
2110                 QString tab_tooltip = it->abs();
2111                 if (buf.hasReadonlyFlag()) {
2112                         setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2113                         tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2114                 } else
2115                         setTabIcon(tab_index, QIcon());
2116                 if (buf.notifiesExternalModification()) {
2117                         QString const warn = qt_("%1 (modified externally)");
2118                         tab_tooltip = warn.arg(tab_tooltip);
2119                         tab_text += QChar(0x26a0);
2120                 }
2121                 setTabText(tab_index, tab_text);
2122                 setTabToolTip(tab_index, tab_tooltip);
2123         }
2124 }
2125
2126
2127 void TabWorkArea::showContextMenu(const QPoint & pos)
2128 {
2129         // which tab?
2130         clicked_tab_ = tabBar()->tabAt(pos);
2131         if (clicked_tab_ == -1)
2132                 return;
2133
2134         GuiWorkArea * wa = workArea(clicked_tab_);
2135         LASSERT(wa, return);
2136
2137         // show tab popup
2138         QMenu popup;
2139         popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2140                 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2141
2142         // we want to show the 'close' option only if this is not a child buffer.
2143         Buffer const & buf = wa->bufferView().buffer();
2144         if (!buf.parent())
2145                 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2146                         qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2147         popup.exec(tabBar()->mapToGlobal(pos));
2148
2149         clicked_tab_ = -1;
2150 }
2151
2152
2153 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2154 {
2155         QWidget * w = widget(fromIndex);
2156         QIcon icon = tabIcon(fromIndex);
2157         QString text = tabText(fromIndex);
2158
2159         setCurrentIndex(fromIndex);
2160         removeTab(fromIndex);
2161         insertTab(toIndex, w, icon, text);
2162         setCurrentIndex(toIndex);
2163 }
2164
2165
2166 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2167         : QWidget(parent), wa_(wa)
2168 {
2169         LASSERT(wa, return);
2170         Ui::WorkAreaUi::setupUi(this);
2171         layout()->addWidget(wa);
2172         connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2173                 this, SLOT(updateDisplay()));
2174         connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2175         connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2176         setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2177         updateDisplay();
2178 }
2179
2180
2181 void GuiWorkAreaContainer::updateDisplay()
2182 {
2183         Buffer const & buf = wa_->bufferView().buffer();
2184         notificationFrame->setHidden(!buf.notifiesExternalModification());
2185         QString const label = qt_("<b>The file %1 changed on disk.</b>")
2186                 .arg(toqstr(buf.fileName().displayName()));
2187         externalModificationLabel->setText(label);
2188 }
2189
2190
2191 void GuiWorkAreaContainer::dispatch(FuncRequest f) const
2192 {
2193         lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2194                                   wa_->bufferView().buffer().absFileName()));
2195         lyx::dispatch(f);
2196 }
2197
2198
2199 void GuiWorkAreaContainer::reload() const
2200 {
2201         dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2202 }
2203
2204
2205 void GuiWorkAreaContainer::ignore() const
2206 {
2207         dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2208 }
2209
2210
2211 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2212 {
2213         // prevent TabWorkArea from opening a new buffer on double click
2214         event->accept();
2215 }
2216
2217
2218 } // namespace frontend
2219 } // namespace lyx
2220
2221 #include "moc_GuiWorkArea.cpp"