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