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