]> git.lyx.org Git - features.git/blob - src/frontends/qt/GuiWorkArea.cpp
Remove deprecated enum value with Qt5
[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 #if (QT_VERSION < 0x050000)
1349         case Qt::ImMicroFocus: {
1350 #else
1351         case Qt::ImCursorRectangle: {
1352 #endif
1353                 CaretGeometry const & cg = bufferView().caretGeometry();
1354                 return QRect(cg.left - 10 * (d->preedit_lines_ != 1),
1355                              cg.top + cg.height() * d->preedit_lines_,
1356                              cg.width(), cg.height());
1357         }
1358         default:
1359                 return QWidget::inputMethodQuery(query);
1360         }
1361 }
1362
1363
1364 void GuiWorkArea::updateWindowTitle()
1365 {
1366         Buffer const & buf = bufferView().buffer();
1367         if (buf.fileName() != d->file_name_
1368             || buf.params().shell_escape != d->shell_escape_
1369             || buf.hasReadonlyFlag() != d->read_only_
1370             || buf.lyxvc().vcstatus() != d->vc_status_
1371             || buf.isClean() != d->clean_
1372             || buf.notifiesExternalModification() != d->externally_modified_) {
1373                 d->file_name_ = buf.fileName();
1374                 d->shell_escape_ = buf.params().shell_escape;
1375                 d->read_only_ = buf.hasReadonlyFlag();
1376                 d->vc_status_ = buf.lyxvc().vcstatus();
1377                 d->clean_ = buf.isClean();
1378                 d->externally_modified_ = buf.notifiesExternalModification();
1379                 Q_EMIT titleChanged(this);
1380         }
1381 }
1382
1383
1384 bool GuiWorkArea::isFullScreen() const
1385 {
1386         return d->lyx_view_ && d->lyx_view_->isFullScreen();
1387 }
1388
1389
1390 bool GuiWorkArea::inDialogMode() const
1391 {
1392         return d->dialog_mode_;
1393 }
1394
1395
1396 void GuiWorkArea::setDialogMode(bool mode)
1397 {
1398         d->dialog_mode_ = mode;
1399 }
1400
1401
1402 GuiCompleter & GuiWorkArea::completer()
1403 {
1404         return *d->completer_;
1405 }
1406
1407 GuiView const & GuiWorkArea::view() const
1408 {
1409         return *d->lyx_view_;
1410 }
1411
1412
1413 GuiView & GuiWorkArea::view()
1414 {
1415         return *d->lyx_view_;
1416 }
1417
1418 ////////////////////////////////////////////////////////////////////
1419 //
1420 // EmbeddedWorkArea
1421 //
1422 ////////////////////////////////////////////////////////////////////
1423
1424
1425 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1426 {
1427         support::TempFile tempfile("embedded.internal");
1428         tempfile.setAutoRemove(false);
1429         buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1430         buffer_->setUnnamed(true);
1431         buffer_->setFullyLoaded(true);
1432         setBuffer(*buffer_);
1433         setDialogMode(true);
1434 }
1435
1436
1437 EmbeddedWorkArea::~EmbeddedWorkArea()
1438 {
1439         // No need to destroy buffer and bufferview here, because it is done
1440         // in theBufferList() destruction loop at application exit
1441 }
1442
1443
1444 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1445 {
1446         disable();
1447         GuiWorkArea::closeEvent(ev);
1448 }
1449
1450
1451 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1452 {
1453         disable();
1454         GuiWorkArea::hideEvent(ev);
1455 }
1456
1457
1458 QSize EmbeddedWorkArea::sizeHint () const
1459 {
1460         // FIXME(?):
1461         // GuiWorkArea sets the size to the screen's viewport
1462         // by returning a value this gets overridden
1463         // EmbeddedWorkArea is now sized to fit in the layout
1464         // of the parent, and has a minimum size set in GuiWorkArea
1465         // which is what we return here
1466         return QSize(100, 70);
1467 }
1468
1469
1470 void EmbeddedWorkArea::disable()
1471 {
1472         stopBlinkingCaret();
1473         if (view().currentWorkArea() != this)
1474                 return;
1475         // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1476         // tolerates it and shows the background logo), what happens if
1477         // an EmbeddedWorkArea is closed after closing all document WAs
1478         view().setCurrentWorkArea(view().currentMainWorkArea());
1479 }
1480
1481 ////////////////////////////////////////////////////////////////////
1482 //
1483 // TabWorkArea
1484 //
1485 ////////////////////////////////////////////////////////////////////
1486
1487 #ifdef Q_OS_MAC
1488 class NoTabFrameMacStyle : public QProxyStyle {
1489 public:
1490         ///
1491         QRect subElementRect(SubElement element, const QStyleOption * option,
1492                              const QWidget * widget = 0) const
1493         {
1494                 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1495                 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1496
1497                 // The Qt Mac style puts the contents into a 3 pixel wide box
1498                 // which looks very ugly and not like other Mac applications.
1499                 // Hence we remove this here, and moreover the 16 pixel round
1500                 // frame above if the tab bar is hidden.
1501                 if (element == QStyle::SE_TabWidgetTabContents) {
1502                         rect.adjust(- rect.left(), 0, rect.left(), 0);
1503                         if (noBar)
1504                                 rect.setTop(0);
1505                 }
1506
1507                 return rect;
1508         }
1509 };
1510
1511 NoTabFrameMacStyle noTabFrameMacStyle;
1512 #endif
1513
1514
1515 TabWorkArea::TabWorkArea(QWidget * parent)
1516         : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1517 {
1518 #ifdef Q_OS_MAC
1519         setStyle(&noTabFrameMacStyle);
1520 #endif
1521
1522         QPalette pal = palette();
1523         pal.setColor(QPalette::Active, QPalette::Button,
1524                 pal.color(QPalette::Active, QPalette::Window));
1525         pal.setColor(QPalette::Disabled, QPalette::Button,
1526                 pal.color(QPalette::Disabled, QPalette::Window));
1527         pal.setColor(QPalette::Inactive, QPalette::Button,
1528                 pal.color(QPalette::Inactive, QPalette::Window));
1529
1530         QObject::connect(this, SIGNAL(currentChanged(int)),
1531                 this, SLOT(on_currentTabChanged(int)));
1532
1533         closeBufferButton = new QToolButton(this);
1534         closeBufferButton->setPalette(pal);
1535         // FIXME: rename the icon to closebuffer.png
1536         closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1537         closeBufferButton->setText("Close File");
1538         closeBufferButton->setAutoRaise(true);
1539         closeBufferButton->setCursor(Qt::ArrowCursor);
1540         closeBufferButton->setToolTip(qt_("Close File"));
1541         closeBufferButton->setEnabled(true);
1542         QObject::connect(closeBufferButton, SIGNAL(clicked()),
1543                 this, SLOT(closeCurrentBuffer()));
1544         setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1545
1546         // set TabBar behaviour
1547         QTabBar * tb = tabBar();
1548         tb->setTabsClosable(!lyxrc.single_close_tab_button);
1549         tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1550         tb->setElideMode(Qt::ElideNone);
1551         // allow dragging tabs
1552         tb->setMovable(true);
1553         // make us responsible for the context menu of the tabbar
1554         tb->setContextMenuPolicy(Qt::CustomContextMenu);
1555         connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1556                 this, SLOT(showContextMenu(const QPoint &)));
1557         connect(tb, SIGNAL(tabCloseRequested(int)),
1558                 this, SLOT(closeTab(int)));
1559
1560         setUsesScrollButtons(true);
1561 }
1562
1563
1564 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1565 {
1566         if (me->button() == Qt::MidButton)
1567                 midpressed_tab_ = tabBar()->tabAt(me->pos());
1568         else
1569                 QTabWidget::mousePressEvent(me);
1570 }
1571
1572
1573 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1574 {
1575         if (me->button() == Qt::MidButton) {
1576                 int const midreleased_tab = tabBar()->tabAt(me->pos());
1577                 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1578                         closeTab(midreleased_tab);
1579         } else
1580                 QTabWidget::mouseReleaseEvent(me);
1581 }
1582
1583
1584 void TabWorkArea::paintEvent(QPaintEvent * event)
1585 {
1586         if (tabBar()->isVisible()) {
1587                 QTabWidget::paintEvent(event);
1588         } else {
1589                 // Prevent the selected tab to influence the
1590                 // painting of the frame of the tab widget.
1591                 // This is needed for gtk style in Qt.
1592                 QStylePainter p(this);
1593 #if QT_VERSION < 0x050000
1594                 QStyleOptionTabWidgetFrameV2 opt;
1595 #else
1596                 QStyleOptionTabWidgetFrame opt;
1597 #endif
1598                 initStyleOption(&opt);
1599                 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1600                         &opt, this);
1601                 opt.selectedTabRect = QRect();
1602                 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1603         }
1604 }
1605
1606
1607 bool TabWorkArea::posIsTab(QPoint position)
1608 {
1609         // tabAt returns -1 if tab does not covers position
1610         return tabBar()->tabAt(position) > -1;
1611 }
1612
1613
1614 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1615 {
1616         if (event->button() != Qt::LeftButton)
1617                 return;
1618
1619         // this code chunk is unnecessary because it seems the event only makes
1620         // it this far if it is not on a tab. I'm not sure why this is (maybe
1621         // it is handled and ended in DragTabBar?), and thus I'm not sure if
1622         // this is true in all cases and if it will be true in the future so I
1623         // leave this code for now. (skostysh, 2016-07-21)
1624         //
1625         // return early if double click on existing tabs
1626         if (posIsTab(event->pos()))
1627                 return;
1628
1629         dispatch(FuncRequest(LFUN_BUFFER_NEW));
1630 }
1631
1632
1633 void TabWorkArea::setFullScreen(bool full_screen)
1634 {
1635         for (int i = 0; i != count(); ++i) {
1636                 if (GuiWorkArea * wa = workArea(i))
1637                         wa->setFullScreen(full_screen);
1638         }
1639
1640         if (lyxrc.full_screen_tabbar)
1641                 showBar(!full_screen && count() > 1);
1642         else
1643                 showBar(count() > 1);
1644 }
1645
1646
1647 void TabWorkArea::showBar(bool show)
1648 {
1649         tabBar()->setEnabled(show);
1650         tabBar()->setVisible(show);
1651         closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1652         setTabsClosable(!lyxrc.single_close_tab_button);
1653 }
1654
1655
1656 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1657 {
1658         QWidget * w = QTabWidget::widget(index);
1659         if (!w)
1660                 return nullptr;
1661         GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1662         LATTEST(wac);
1663         return wac;
1664 }
1665
1666
1667 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1668 {
1669         return widget(currentIndex());
1670 }
1671
1672
1673 GuiWorkArea * TabWorkArea::workArea(int index) const
1674 {
1675         GuiWorkAreaContainer * w = widget(index);
1676         if (!w)
1677                 return nullptr;
1678         return w->workArea();
1679 }
1680
1681
1682 GuiWorkArea * TabWorkArea::currentWorkArea() const
1683 {
1684         return workArea(currentIndex());
1685 }
1686
1687
1688 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1689 {
1690         // FIXME: this method doesn't work if we have more than one work area
1691         // showing the same buffer.
1692         for (int i = 0; i != count(); ++i) {
1693                 GuiWorkArea * wa = workArea(i);
1694                 LASSERT(wa, return nullptr);
1695                 if (&wa->bufferView().buffer() == &buffer)
1696                         return wa;
1697         }
1698         return nullptr;
1699 }
1700
1701
1702 void TabWorkArea::closeAll()
1703 {
1704         while (count()) {
1705                 QWidget * wac = widget(0);
1706                 LASSERT(wac, return);
1707                 removeTab(0);
1708                 delete wac;
1709         }
1710 }
1711
1712
1713 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1714 {
1715         for (int index = 0; index < count(); ++index)
1716                 if (workArea(index) == w)
1717                         return index;
1718         return -1;
1719 }
1720
1721
1722 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1723 {
1724         LASSERT(work_area, return false);
1725         int index = indexOfWorkArea(work_area);
1726         if (index == -1)
1727                 return false;
1728
1729         if (index == currentIndex())
1730                 // Make sure the work area is up to date.
1731                 on_currentTabChanged(index);
1732         else
1733                 // Switch to the work area.
1734                 setCurrentIndex(index);
1735         work_area->setFocus();
1736
1737         return true;
1738 }
1739
1740
1741 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1742 {
1743         GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1744         GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1745         wa->setUpdatesEnabled(false);
1746         // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1747         // when hiding it again below).
1748         if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1749                 showBar(count() > 0);
1750         addTab(wac, wa->windowTitle());
1751         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1752                 this, SLOT(updateTabTexts()));
1753         if (currentWorkArea() && currentWorkArea()->isFullScreen())
1754                 setFullScreen(true);
1755         else
1756                 // Hide tabbar if there's only one tab.
1757                 showBar(count() > 1);
1758
1759         updateTabTexts();
1760
1761         return wa;
1762 }
1763
1764
1765 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1766 {
1767         LASSERT(work_area, return false);
1768         int index = indexOfWorkArea(work_area);
1769         if (index == -1)
1770                 return false;
1771
1772         work_area->setUpdatesEnabled(false);
1773         QWidget * wac = widget(index);
1774         removeTab(index);
1775         delete wac;
1776
1777         if (count()) {
1778                 // make sure the next work area is enabled.
1779                 currentWidget()->setUpdatesEnabled(true);
1780                 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1781                         setFullScreen(true);
1782                 else
1783                         // Show tabbar only if there's more than one tab.
1784                         showBar(count() > 1);
1785         } else
1786                 lastWorkAreaRemoved();
1787
1788         updateTabTexts();
1789
1790         return true;
1791 }
1792
1793
1794 void TabWorkArea::on_currentTabChanged(int i)
1795 {
1796         // returns e.g. on application destruction
1797         if (i == -1)
1798                 return;
1799         GuiWorkArea * wa = workArea(i);
1800         LASSERT(wa, return);
1801         wa->setUpdatesEnabled(true);
1802         wa->scheduleRedraw(true);
1803         wa->setFocus();
1804         ///
1805         currentWorkAreaChanged(wa);
1806
1807         LYXERR(Debug::GUI, "currentTabChanged " << i
1808                 << " File: " << wa->bufferView().buffer().absFileName());
1809 }
1810
1811
1812 void TabWorkArea::closeCurrentBuffer()
1813 {
1814         GuiWorkArea * wa;
1815         if (clicked_tab_ == -1)
1816                 wa = currentWorkArea();
1817         else {
1818                 wa = workArea(clicked_tab_);
1819                 LASSERT(wa, return);
1820         }
1821         wa->view().closeWorkArea(wa);
1822 }
1823
1824
1825 void TabWorkArea::hideCurrentTab()
1826 {
1827         GuiWorkArea * wa;
1828         if (clicked_tab_ == -1)
1829                 wa = currentWorkArea();
1830         else {
1831                 wa = workArea(clicked_tab_);
1832                 LASSERT(wa, return);
1833         }
1834         wa->view().hideWorkArea(wa);
1835 }
1836
1837
1838 void TabWorkArea::closeTab(int index)
1839 {
1840         on_currentTabChanged(index);
1841         GuiWorkArea * wa;
1842         if (index == -1)
1843                 wa = currentWorkArea();
1844         else {
1845                 wa = workArea(index);
1846                 LASSERT(wa, return);
1847         }
1848         wa->view().closeWorkArea(wa);
1849 }
1850
1851
1852 ///
1853 class DisplayPath {
1854 public:
1855         /// make vector happy
1856         DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1857         ///
1858         DisplayPath(int tab, FileName const & filename)
1859                 : tab_(tab)
1860         {
1861                 // Recode URL encoded chars via fromPercentEncoding()
1862                 string const fn = (filename.extension() == "lyx")
1863                         ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
1864                 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
1865                 postfix_ = toqstr(filename.absoluteFilePath()).
1866                         split("/", QString::SkipEmptyParts);
1867                 postfix_.pop_back();
1868                 abs_ = toqstr(filename.absoluteFilePath());
1869                 dottedPrefix_ = false;
1870         }
1871
1872         /// Absolute path for debugging.
1873         QString abs() const
1874         {
1875                 return abs_;
1876         }
1877         /// Add the first segment from the postfix or three dots to the prefix.
1878         /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1879         /// when really needed.
1880         void shiftPathSegment(bool dotted)
1881         {
1882                 if (postfix_.count() <= 0)
1883                         return;
1884
1885                 if (!dotted) {
1886                         if (dottedPrefix_ && !prefix_.isEmpty())
1887                                 prefix_ += ellipsisSlash_;
1888                         prefix_ += postfix_.front() + "/";
1889                 }
1890                 dottedPrefix_ = dotted && !prefix_.isEmpty();
1891                 postfix_.pop_front();
1892         }
1893         ///
1894         QString displayString() const
1895         {
1896                 if (prefix_.isEmpty())
1897                         return filename_;
1898
1899                 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1900                 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1901         }
1902         ///
1903         QString forecastPathString() const
1904         {
1905                 if (postfix_.count() == 0)
1906                         return displayString();
1907
1908                 return prefix_
1909                         + (dottedPrefix_ ? ellipsisSlash_ : "")
1910                         + postfix_.front() + "/";
1911         }
1912         ///
1913         bool final() const { return postfix_.empty(); }
1914         ///
1915         int tab() const { return tab_; }
1916
1917 private:
1918         /// ".../"
1919         static QString const ellipsisSlash_;
1920         ///
1921         QString prefix_;
1922         ///
1923         QStringList postfix_;
1924         ///
1925         QString filename_;
1926         ///
1927         QString abs_;
1928         ///
1929         int tab_;
1930         ///
1931         bool dottedPrefix_;
1932 };
1933
1934
1935 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1936
1937
1938 ///
1939 bool operator<(DisplayPath const & a, DisplayPath const & b)
1940 {
1941         return a.displayString() < b.displayString();
1942 }
1943
1944 ///
1945 bool operator==(DisplayPath const & a, DisplayPath const & b)
1946 {
1947         return a.displayString() == b.displayString();
1948 }
1949
1950
1951 void TabWorkArea::updateTabTexts()
1952 {
1953         int const n = count();
1954         if (n == 0)
1955                 return;
1956         std::list<DisplayPath> paths;
1957         typedef std::list<DisplayPath>::iterator It;
1958
1959         // collect full names first: path into postfix, empty prefix and
1960         // filename without extension
1961         for (int i = 0; i < n; ++i) {
1962                 GuiWorkArea * i_wa = workArea(i);
1963                 FileName const fn = i_wa->bufferView().buffer().fileName();
1964                 paths.push_back(DisplayPath(i, fn));
1965         }
1966
1967         // go through path segments and see if it helps to make the path more unique
1968         bool somethingChanged = true;
1969         bool allFinal = false;
1970         while (somethingChanged && !allFinal) {
1971                 // adding path segments changes order
1972                 paths.sort();
1973
1974                 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1975                 somethingChanged = false;
1976                 allFinal = true;
1977
1978                 // find segments which are not unique (i.e. non-atomic)
1979                 It it = paths.begin();
1980                 It segStart = it;
1981                 QString segString = it->displayString();
1982                 for (; it != paths.end(); ++it) {
1983                         // look to the next item
1984                         It next = it;
1985                         ++next;
1986
1987                         // final?
1988                         allFinal = allFinal && it->final();
1989
1990                         LYXERR(Debug::GUI, "it = " << it->abs()
1991                                << " => " << it->displayString());
1992
1993                         // still the same segment?
1994                         QString nextString;
1995                         if ((next != paths.end()
1996                              && (nextString = next->displayString()) == segString))
1997                                 continue;
1998                         LYXERR(Debug::GUI, "segment ended");
1999
2000                         // only a trivial one with one element?
2001                         if (it == segStart) {
2002                                 // start new segment
2003                                 segStart = next;
2004                                 segString = nextString;
2005                                 continue;
2006                         }
2007
2008                         // We found a non-atomic segment
2009                         // We know that segStart <= it < next <= paths.end().
2010                         // The assertion below tells coverity about it.
2011                         LATTEST(segStart != paths.end());
2012                         QString dspString = segStart->forecastPathString();
2013                         LYXERR(Debug::GUI, "first forecast found for "
2014                                << segStart->abs() << " => " << dspString);
2015                         It sit = segStart;
2016                         ++sit;
2017                         // Shift path segments and hope for the best
2018                         // that it makes the path more unique.
2019                         somethingChanged = true;
2020                         bool moreUnique = false;
2021                         for (; sit != next; ++sit) {
2022                                 if (sit->forecastPathString() != dspString) {
2023                                         LYXERR(Debug::GUI, "different forecast found for "
2024                                                 << sit->abs() << " => " << sit->forecastPathString());
2025                                         moreUnique = true;
2026                                         break;
2027                                 }
2028                                 LYXERR(Debug::GUI, "same forecast found for "
2029                                         << sit->abs() << " => " << dspString);
2030                         }
2031
2032                         // if the path segment helped, add it. Otherwise add dots
2033                         bool dots = !moreUnique;
2034                         LYXERR(Debug::GUI, "using dots = " << dots);
2035                         for (sit = segStart; sit != next; ++sit) {
2036                                 sit->shiftPathSegment(dots);
2037                                 LYXERR(Debug::GUI, "shifting "
2038                                         << sit->abs() << " => " << sit->displayString());
2039                         }
2040
2041                         // start new segment
2042                         segStart = next;
2043                         segString = nextString;
2044                 }
2045         }
2046
2047         // set new tab titles
2048         for (It it = paths.begin(); it != paths.end(); ++it) {
2049                 int const tab_index = it->tab();
2050                 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2051                 QString tab_text = it->displayString().replace("&", "&&");
2052                 if (!buf.fileName().empty() && !buf.isClean())
2053                         tab_text += "*";
2054                 QString tab_tooltip = it->abs();
2055                 if (buf.hasReadonlyFlag()) {
2056                         setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2057                         tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2058                 } else
2059                         setTabIcon(tab_index, QIcon());
2060                 if (buf.notifiesExternalModification()) {
2061                         QString const warn = qt_("%1 (modified externally)");
2062                         tab_tooltip = warn.arg(tab_tooltip);
2063                         tab_text += QChar(0x26a0);
2064                 }
2065                 setTabText(tab_index, tab_text);
2066                 setTabToolTip(tab_index, tab_tooltip);
2067         }
2068 }
2069
2070
2071 void TabWorkArea::showContextMenu(const QPoint & pos)
2072 {
2073         // which tab?
2074         clicked_tab_ = tabBar()->tabAt(pos);
2075         if (clicked_tab_ == -1)
2076                 return;
2077
2078         GuiWorkArea * wa = workArea(clicked_tab_);
2079         LASSERT(wa, return);
2080
2081         // show tab popup
2082         QMenu popup;
2083         popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2084                 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2085
2086         // we want to show the 'close' option only if this is not a child buffer.
2087         Buffer const & buf = wa->bufferView().buffer();
2088         if (!buf.parent())
2089                 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2090                         qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2091         popup.exec(tabBar()->mapToGlobal(pos));
2092
2093         clicked_tab_ = -1;
2094 }
2095
2096
2097 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2098 {
2099         QWidget * w = widget(fromIndex);
2100         QIcon icon = tabIcon(fromIndex);
2101         QString text = tabText(fromIndex);
2102
2103         setCurrentIndex(fromIndex);
2104         removeTab(fromIndex);
2105         insertTab(toIndex, w, icon, text);
2106         setCurrentIndex(toIndex);
2107 }
2108
2109
2110 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2111         : QWidget(parent), wa_(wa)
2112 {
2113         LASSERT(wa, return);
2114         Ui::WorkAreaUi::setupUi(this);
2115         layout()->addWidget(wa);
2116         connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2117                 this, SLOT(updateDisplay()));
2118         connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2119         connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2120         setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2121         updateDisplay();
2122 }
2123
2124
2125 void GuiWorkAreaContainer::updateDisplay()
2126 {
2127         Buffer const & buf = wa_->bufferView().buffer();
2128         notificationFrame->setHidden(!buf.notifiesExternalModification());
2129         QString const label = qt_("<b>The file %1 changed on disk.</b>")
2130                 .arg(toqstr(buf.fileName().displayName()));
2131         externalModificationLabel->setText(label);
2132 }
2133
2134
2135 void GuiWorkAreaContainer::dispatch(FuncRequest const & f) const
2136 {
2137         lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2138                                   wa_->bufferView().buffer().absFileName()));
2139         lyx::dispatch(f);
2140 }
2141
2142
2143 void GuiWorkAreaContainer::reload() const
2144 {
2145         dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2146 }
2147
2148
2149 void GuiWorkAreaContainer::ignore() const
2150 {
2151         dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2152 }
2153
2154
2155 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2156 {
2157         // prevent TabWorkArea from opening a new buffer on double click
2158         event->accept();
2159 }
2160
2161
2162 } // namespace frontend
2163 } // namespace lyx
2164
2165 #include "moc_GuiWorkArea.cpp"