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