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