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