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