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