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