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