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