]> git.lyx.org Git - features.git/blob - src/frontends/qt/GuiWorkArea.cpp
Change FontMetrics::breakAt to return a position
[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::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_->showCursor();
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 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
719                 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->position().x(), e->position().y(),
720 #else
721                 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
722 #endif
723                         q_button_state(e->button()), q_key_state(e->modifiers()));
724                 d->dispatch(cmd);
725                 e->accept();
726                 return;
727         }
728
729 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
730         inputContext()->reset();
731 #endif
732
733 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
734         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->position().x(), e->position().y(),
735 #else
736         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
737 #endif
738                         q_button_state(e->button()), q_key_state(e->modifiers()));
739         d->dispatch(cmd);
740
741         // Save the context menu on mouse press, because also the mouse
742         // cursor is set on mouse press. Afterwards, we can either release
743         // the mousebutton somewhere else, or the cursor might have moved
744         // due to the DEPM. We need to do this after the mouse has been
745         // set in dispatch(), because the selection state might change.
746         if (e->button() == Qt::RightButton)
747 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
748                 d->context_menu_name_ = d->buffer_view_->contextMenu(e->position().x(), e->position().y());
749 #else
750                 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
751 #endif
752
753         e->accept();
754 }
755
756
757 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
758 {
759         if (d->synthetic_mouse_event_.timeout.running())
760                 d->synthetic_mouse_event_.timeout.stop();
761
762 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
763         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->position().x(), e->position().y(),
764 #else
765         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
766 #endif
767                         q_button_state(e->button()), q_key_state(e->modifiers()));
768 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
769         QT_VERSION < QT_VERSION_CHECK(5,15,1))
770         d->synthetic_mouse_event_.cmd = cmd; // QtBug QAbstractScrollArea::mouseMoveEvent
771 #endif
772         d->dispatch(cmd);
773         e->accept();
774 }
775
776
777 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
778 {
779 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
780         QT_VERSION < QT_VERSION_CHECK(5,15,1))
781         // cancel the event if the coordinates didn't change, this is due to QtBug
782         // QAbstractScrollArea::mouseMoveEvent, the event is triggered falsely when quickly
783         // double tapping a touchpad. To test: try to select a word by quickly double tapping
784         // on a touchpad while hovering the cursor over that word in the work area.
785         // This bug does not occur on Qt versions 5.10.1 and below. Only Windows seems to be affected.
786         // ML thread: https://www.mail-archive.com/lyx-devel@lists.lyx.org/msg211699.html
787         // Qt bugtracker: https://bugreports.qt.io/browse/QTBUG-85431
788         // Bug was fixed in Qt 5.15.1
789         if (e->x() == d->synthetic_mouse_event_.cmd.x() && // QtBug QAbstractScrollArea::mouseMoveEvent
790                         e->y() == d->synthetic_mouse_event_.cmd.y()) // QtBug QAbstractScrollArea::mouseMoveEvent
791                 return; // QtBug QAbstractScrollArea::mouseMoveEvent
792 #endif
793
794         // we kill the triple click if we move
795         doubleClickTimeout();
796 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
797         FuncRequest cmd(LFUN_MOUSE_MOTION, e->position().x(), e->position().y(),
798 #else
799         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
800 #endif
801                         q_motion_state(e->buttons()), q_key_state(e->modifiers()));
802
803         e->accept();
804
805         // If we're above or below the work area...
806 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
807         if ((e->position().y() <= 20 || e->position().y() >= viewport()->height() - 20)
808 #else
809         if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
810 #endif
811                         && e->buttons() == mouse_button::button1) {
812                 // Make sure only a synthetic event can cause a page scroll,
813                 // so they come at a steady rate:
814 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
815                 if (e->position().y() <= 20)
816                         // _Force_ a scroll up:
817                         cmd.set_y(e->position().y() - 21);
818                 else
819                         cmd.set_y(e->position().y() + 21);
820 #else
821                 if (e->y() <= 20)
822                         // _Force_ a scroll up:
823                         cmd.set_y(e->y() - 21);
824                 else
825                         cmd.set_y(e->y() + 21);
826 #endif
827                 // Store the event, to be handled when the timeout expires.
828                 d->synthetic_mouse_event_.cmd = cmd;
829
830                 if (d->synthetic_mouse_event_.timeout.running()) {
831                         // Discard the event. Note that it _may_ be handled
832                         // when the timeout expires if
833                         // synthetic_mouse_event_.cmd has not been overwritten.
834                         // Ie, when the timeout expires, we handle the
835                         // most recent event but discard all others that
836                         // occurred after the one used to start the timeout
837                         // in the first place.
838                         return;
839                 }
840
841                 d->synthetic_mouse_event_.restart_timeout = true;
842                 d->synthetic_mouse_event_.timeout.start();
843                 // Fall through to handle this event...
844
845         } else if (d->synthetic_mouse_event_.timeout.running()) {
846                 // Store the event, to be possibly handled when the timeout
847                 // expires.
848                 // Once the timeout has expired, normal control is returned
849                 // to mouseMoveEvent (restart_timeout = false).
850                 // This results in a much smoother 'feel' when moving the
851                 // mouse back into the work area.
852                 d->synthetic_mouse_event_.cmd = cmd;
853                 d->synthetic_mouse_event_.restart_timeout = false;
854                 return;
855         }
856         d->dispatch(cmd);
857 }
858
859
860 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
861 {
862         // Wheel rotation by one notch results in a delta() of 120 (see
863         // documentation of QWheelEvent)
864         // But first we have to ignore horizontal scroll events.
865 #if QT_VERSION < 0x050000
866         if (ev->orientation() == Qt::Horizontal) {
867                 ev->accept();
868                 return;
869         }
870         double const delta = ev->delta() / 120.0;
871 #else
872         QPoint const aDelta = ev->angleDelta();
873         // skip horizontal wheel event
874         if (abs(aDelta.x()) > abs(aDelta.y())) {
875                 ev->accept();
876                 return;
877         }
878         double const delta = aDelta.y() / 120.0;
879 #endif
880
881         bool zoom = false;
882         switch (lyxrc.scroll_wheel_zoom) {
883         case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
884                 zoom = ev->modifiers() & Qt::ControlModifier;
885                 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
886                 break;
887         case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
888                 zoom = ev->modifiers() & Qt::ShiftModifier;
889                 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
890                 break;
891         case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
892                 zoom = ev->modifiers() & Qt::AltModifier;
893                 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
894                 break;
895         case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
896                 break;
897         }
898         if (zoom) {
899                 docstring arg = convert<docstring>(int(5 * delta));
900                 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
901                 return;
902         }
903
904         // Take into account the desktop wide settings.
905         int const lines = qApp->wheelScrollLines();
906         int const page_step = verticalScrollBar()->pageStep();
907         // Test if the wheel mouse is set to one screen at a time.
908         // This is according to
909         // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
910         int scroll_value =
911                 min(lines * verticalScrollBar()->singleStep(), page_step);
912
913         // Take into account the rotation and the user preferences.
914         scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
915         LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
916                         << " delta = " << delta << " scroll_value = " << scroll_value
917                         << " page_step = " << page_step);
918         // Now scroll.
919         verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
920
921         ev->accept();
922 }
923
924
925 void GuiWorkArea::generateSyntheticMouseEvent()
926 {
927         int const e_y = d->synthetic_mouse_event_.cmd.y();
928         int const wh = d->buffer_view_->workHeight();
929         bool const up = e_y < 0;
930         bool const down = e_y > wh;
931
932         // Set things off to generate the _next_ 'pseudo' event.
933         int step = 50;
934         if (d->synthetic_mouse_event_.restart_timeout) {
935                 // This is some magic formulae to determine the speed
936                 // of scrolling related to the position of the mouse.
937                 int time = 200;
938                 if (up || down) {
939                         int dist = up ? -e_y : e_y - wh;
940                         time = max(min(200, 250000 / (dist * dist)), 1) ;
941
942                         if (time < 40) {
943                                 step = 80000 / (time * time);
944                                 time = 40;
945                         }
946                 }
947                 d->synthetic_mouse_event_.timeout.setTimeout(time);
948                 d->synthetic_mouse_event_.timeout.start();
949         }
950
951         // Can we scroll further ?
952         int const value = verticalScrollBar()->value();
953         if (value == verticalScrollBar()->maximum()
954                   || value == verticalScrollBar()->minimum()) {
955                 d->synthetic_mouse_event_.timeout.stop();
956                 return;
957         }
958
959         // Scroll
960         if (step <= 2 * wh) {
961                 d->buffer_view_->scroll(up ? -step : step);
962                 d->buffer_view_->updateMetrics();
963         } else {
964                 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
965         }
966
967         // In which paragraph do we have to set the cursor ?
968         Cursor & cur = d->buffer_view_->cursor();
969         // FIXME: we don't know how to handle math.
970         Text * text = cur.text();
971         if (!text)
972                 return;
973         TextMetrics const & tm = d->buffer_view_->textMetrics(text);
974
975         // Quit gracefully if there are no metrics, since otherwise next
976         // line would crash (bug #10324).
977         // This situation seems related to a (not yet understood) timing problem.
978         if (tm.empty())
979                 return;
980
981         pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
982         ParagraphMetrics const & pm = *pp.second;
983         pit_type const pit = pp.first;
984
985         if (pm.rows().empty())
986                 return;
987
988         // Find the row at which we set the cursor.
989         RowList::const_iterator rit = pm.rows().begin();
990         RowList::const_iterator rlast = pm.rows().end();
991         int yy = pm.position() - pm.ascent();
992         for (--rlast; rit != rlast; ++rit) {
993                 int h = rit->height();
994                 if ((up && yy + h > 0)
995                           || (!up && yy + h > wh - defaultRowHeight()))
996                         break;
997                 yy += h;
998         }
999
1000         // Find the position of the cursor
1001         bool bound;
1002         int x = d->synthetic_mouse_event_.cmd.x();
1003         pos_type const pos = tm.getPosNearX(*rit, x, bound);
1004
1005         // Set the cursor
1006         cur.pit() = pit;
1007         cur.pos() = pos;
1008         cur.boundary(bound);
1009
1010         d->buffer_view_->buffer().changed(false);
1011 }
1012
1013
1014 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
1015 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
1016 {
1017         qRegisterMetaType<KeySymbol>("KeySymbol");
1018         qRegisterMetaType<KeyModifier>("KeyModifier");
1019         connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
1020                 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
1021                 Qt::QueuedConnection);
1022         connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
1023                 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1024 }
1025
1026
1027 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1028 {
1029         flag_ = true;
1030         if (isAutoRepeat)
1031                 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1032         bool result = flag_;
1033         flag_ = false;
1034         return result;
1035 }
1036
1037
1038 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1039 {
1040         if (emitCheck(isAutoRepeat))
1041                 Q_EMIT signal(sym, mod);
1042         else
1043                 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1044 }
1045
1046
1047 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1048 {
1049         // this is also called for ShortcutOverride events. In this case, one must
1050         // not act but simply accept the event explicitly.
1051         bool const act = (ev->type() != QEvent::ShortcutOverride);
1052
1053         // Do not process here some keys if dialog_mode_ is set
1054         bool const for_dialog_mode = d->dialog_mode_
1055                 && (ev->modifiers() == Qt::NoModifier
1056                     || ev->modifiers() == Qt::ShiftModifier)
1057                 && (ev->key() == Qt::Key_Escape
1058                     || ev->key() == Qt::Key_Enter
1059                     || ev->key() == Qt::Key_Return);
1060         // also do not use autoRepeat to input shortcuts
1061         bool const autoRepeat = ev->isAutoRepeat();
1062
1063         if (for_dialog_mode || (!act && autoRepeat)) {
1064                 ev->ignore();
1065                 return;
1066         }
1067
1068         // intercept some keys if completion popup is visible
1069         if (d->completer_->popupVisible()) {
1070                 switch (ev->key()) {
1071                 case Qt::Key_Enter:
1072                 case Qt::Key_Return:
1073                         if (act)
1074                                 d->completer_->activate();
1075                         ev->accept();
1076                         return;
1077                 }
1078         }
1079
1080         KeyModifier const m = q_key_state(ev->modifiers());
1081
1082         if (act && lyxerr.debugging(Debug::KEY)) {
1083                 std::string str;
1084                 if (m & ShiftModifier)
1085                         str += "Shift-";
1086                 if (m & ControlModifier)
1087                         str += "Control-";
1088                 if (m & AltModifier)
1089                         str += "Alt-";
1090                 if (m & MetaModifier)
1091                         str += "Meta-";
1092                 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1093                        << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1094                        << " keyState: " << str);
1095         }
1096
1097         KeySymbol sym;
1098         setKeySymbol(&sym, ev);
1099         if (sym.isOK()) {
1100                 if (act) {
1101                         Q_EMIT compressKeySym(sym, m, autoRepeat);
1102                         ev->accept();
1103                 } else
1104                         // here, !autoRepeat, as determined at the beginning
1105                         ev->setAccepted(queryKeySym(sym, m));
1106         } else {
1107                 ev->ignore();
1108         }
1109 }
1110
1111
1112 void GuiWorkArea::doubleClickTimeout()
1113 {
1114         d->dc_event_.active = false;
1115 }
1116
1117
1118 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1119 {
1120         d->dc_event_ = DoubleClick(ev);
1121         QTimer::singleShot(QApplication::doubleClickInterval(), this,
1122                         SLOT(doubleClickTimeout()));
1123 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
1124         FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->position().x(), ev->position().y(),
1125 #else
1126         FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1127 #endif
1128                         q_button_state(ev->button()), q_key_state(ev->modifiers()));
1129         d->dispatch(cmd);
1130         ev->accept();
1131 }
1132
1133
1134 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1135 {
1136         QAbstractScrollArea::resizeEvent(ev);
1137         d->need_resize_ = true;
1138         ev->accept();
1139 }
1140
1141
1142 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1143 {
1144         if (preedit_string_.empty())
1145                 return;
1146
1147         // FIXME: shall we use real_current_font here? (see #10478)
1148         FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1149         FontMetrics const & fm = theFontMetrics(font);
1150         Point point;
1151         Dimension dim;
1152         buffer_view_->caretPosAndDim(point, dim);
1153         int cur_x = point.x_;
1154         int cur_y = point.y_ + dim.height();
1155
1156         // get attributes of input method cursor.
1157         // cursor_pos : cursor position in preedit string.
1158         size_t cursor_pos = 0;
1159         bool cursor_is_visible = false;
1160         for (auto const & attr : preedit_attr_) {
1161                 if (attr.type == QInputMethodEvent::Cursor) {
1162                         cursor_pos = size_t(attr.start);
1163                         cursor_is_visible = attr.length != 0;
1164                         break;
1165                 }
1166         }
1167
1168         size_t const preedit_length = preedit_string_.length();
1169
1170         // get position of selection in input method.
1171         // FIXME: isn't there a simpler way to do this?
1172         // rStart : cursor position in selected string in IM.
1173         size_t rStart = 0;
1174         // rLength : selected string length in IM.
1175         size_t rLength = 0;
1176         if (cursor_pos < preedit_length) {
1177                 for (auto const & attr : preedit_attr_) {
1178                         if (attr.type == QInputMethodEvent::TextFormat) {
1179                                 if (attr.start <= int(cursor_pos)
1180                                         && int(cursor_pos) < attr.start + attr.length) {
1181                                                 rStart = size_t(attr.start);
1182                                                 rLength = size_t(attr.length);
1183                                                 if (!cursor_is_visible)
1184                                                         cursor_pos += rLength;
1185                                                 break;
1186                                 }
1187                         }
1188                 }
1189         }
1190         else {
1191                 rStart = cursor_pos;
1192                 rLength = 0;
1193         }
1194
1195         int const right_margin = buffer_view_->rightMargin();
1196         Painter::preedit_style ps;
1197         // Most often there would be only one line:
1198         preedit_lines_ = 1;
1199         for (size_t pos = 0; pos != preedit_length; ++pos) {
1200                 char_type const typed_char = preedit_string_[pos];
1201                 // reset preedit string style
1202                 ps = Painter::preedit_default;
1203
1204                 // if we reached the right extremity of the screen, go to next line.
1205                 if (cur_x + fm.width(typed_char) > p->viewport()->width() - right_margin) {
1206                         cur_x = right_margin;
1207                         cur_y += dim.height() + 1;
1208                         ++preedit_lines_;
1209                 }
1210                 // preedit strings are displayed with dashed underline
1211                 // and partial strings are displayed white on black indicating
1212                 // that we are in selecting mode in the input method.
1213                 // FIXME: rLength == preedit_length is not a changing condition
1214                 // FIXME: should be put out of the loop.
1215                 if (pos >= rStart
1216                         && pos < rStart + rLength
1217                         && !(cursor_pos < rLength && rLength == preedit_length))
1218                         ps = Painter::preedit_selecting;
1219
1220                 if (pos == cursor_pos
1221                         && (cursor_pos < rLength && rLength == preedit_length))
1222                         ps = Painter::preedit_cursor;
1223
1224                 // draw one character and update cur_x.
1225                 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1226         }
1227 }
1228
1229
1230 void GuiWorkArea::Private::resetScreen()
1231 {
1232         if (use_backingstore_) {
1233                 int const pr = p->pixelRatio();
1234                 screen_ = QImage(pr * p->viewport()->width(),
1235                                  pr * p->viewport()->height(),
1236                                  QImage::Format_ARGB32_Premultiplied);
1237 #  if QT_VERSION >= 0x050000
1238                 screen_.setDevicePixelRatio(pr);
1239 #  endif
1240         }
1241 }
1242
1243
1244 QPaintDevice * GuiWorkArea::Private::screenDevice()
1245 {
1246         if (use_backingstore_)
1247                 return &screen_;
1248         else
1249                 return p->viewport();
1250 }
1251
1252
1253 void GuiWorkArea::Private::updateScreen(QRectF const & rc)
1254 {
1255         if (use_backingstore_) {
1256                 QPainter qpain(p->viewport());
1257                 double const pr = p->pixelRatio();
1258                 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr,
1259                                           rc.width() * pr, rc.height() * pr);
1260                 qpain.drawImage(rc, screen_, rcs);
1261         }
1262 }
1263
1264
1265 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1266 {
1267         // Do not trigger the painting machinery if we are not ready (see
1268         // bug #10989). The second test triggers when in the middle of a
1269         // dispatch operation.
1270         if (view().busy() || d->buffer_view_->buffer().undo().activeUndoGroup()) {
1271                 // Since macOS has turned the screen black at this point, our
1272                 // backing store has to be copied to screen (this is a no-op
1273                 // except on macOS).
1274                 d->updateScreen(ev->rect());
1275                 // Ignore this paint event, but request a new one for later.
1276                 viewport()->update(ev->rect());
1277                 ev->accept();
1278                 return;
1279         }
1280
1281         // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1282         //      << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1283
1284         if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_) {
1285                 d->resetScreen();
1286                 d->resizeBufferView();
1287         }
1288
1289         d->last_pixel_ratio_ = pixelRatio();
1290
1291         GuiPainter pain(d->screenDevice(), pixelRatio(), d->lyx_view_->develMode());
1292
1293         d->buffer_view_->draw(pain, d->caret_visible_);
1294
1295         // The preedit text, if needed
1296         d->paintPreeditText(pain);
1297
1298         // and the caret
1299         // FIXME: the code would be a little bit simpler if caret geometry
1300         // was updated unconditionally. Some profiling is required to see
1301         // how expensive this is (especially when idle).
1302         if (d->caret_visible_) {
1303                 if (d->needs_caret_geometry_update_)
1304                         d->updateCaretGeometry();
1305                 d->drawCaret(pain, d->buffer_view_->horizScrollOffset());
1306         }
1307
1308         d->updateScreen(ev->rect());
1309
1310         ev->accept();
1311 }
1312
1313
1314 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1315 {
1316         LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1317                    << " commitString: " << e->commitString());
1318
1319         // insert the processed text in the document (handles undo)
1320         if (!e->commitString().isEmpty()) {
1321                 FuncRequest cmd(LFUN_SELF_INSERT,
1322                                 qstring_to_ucs4(e->commitString()),
1323                                 FuncRequest::KEYBOARD);
1324                 dispatch(cmd);
1325                 // FIXME: this is supposed to remove traces from preedit
1326                 // string. Can we avoid calling it explicitly?
1327                 d->buffer_view_->updateMetrics();
1328         }
1329
1330         // Hide the caret during the test transformation.
1331         if (e->preeditString().isEmpty())
1332                 startBlinkingCaret();
1333         else
1334                 stopBlinkingCaret();
1335
1336         if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1337                 // Nothing to do
1338                 e->accept();
1339                 return;
1340         }
1341
1342         // The preedit text and its attributes will be used in paintPreeditText
1343         d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1344         d->preedit_attr_ = e->attributes();
1345
1346
1347         // redraw area of preedit string.
1348         // int height = d->caret_->dim.height();
1349         // int cur_y = d->caret_->y;
1350         // viewport()->update(0, cur_y, viewport()->width(),
1351         //      (height + 1) * d->preedit_lines_);
1352         viewport()->update();
1353
1354         if (d->preedit_string_.empty()) {
1355                 d->preedit_lines_ = 1;
1356                 e->accept();
1357                 return;
1358         }
1359
1360         // Don't forget to accept the event!
1361         e->accept();
1362 }
1363
1364
1365 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1366 {
1367         switch (query) {
1368                 // this is the CJK-specific composition window position and
1369                 // the context menu position when the menu key is pressed.
1370 #if (QT_VERSION < 0x050000)
1371         case Qt::ImMicroFocus: {
1372 #else
1373         case Qt::ImCursorRectangle: {
1374 #endif
1375                 CaretGeometry const & cg = bufferView().caretGeometry();
1376                 return QRect(cg.left - 10 * (d->preedit_lines_ != 1),
1377                              cg.top + cg.height() * d->preedit_lines_,
1378                              cg.width(), cg.height());
1379         }
1380         default:
1381                 return QWidget::inputMethodQuery(query);
1382         }
1383 }
1384
1385
1386 void GuiWorkArea::updateWindowTitle()
1387 {
1388         Buffer const & buf = bufferView().buffer();
1389         if (buf.fileName() != d->file_name_
1390             || buf.params().shell_escape != d->shell_escape_
1391             || buf.hasReadonlyFlag() != d->read_only_
1392             || buf.lyxvc().vcstatus() != d->vc_status_
1393             || buf.isClean() != d->clean_
1394             || buf.notifiesExternalModification() != d->externally_modified_) {
1395                 d->file_name_ = buf.fileName();
1396                 d->shell_escape_ = buf.params().shell_escape;
1397                 d->read_only_ = buf.hasReadonlyFlag();
1398                 d->vc_status_ = buf.lyxvc().vcstatus();
1399                 d->clean_ = buf.isClean();
1400                 d->externally_modified_ = buf.notifiesExternalModification();
1401                 Q_EMIT titleChanged(this);
1402         }
1403 }
1404
1405
1406 bool GuiWorkArea::isFullScreen() const
1407 {
1408         return d->lyx_view_ && d->lyx_view_->isFullScreen();
1409 }
1410
1411
1412 bool GuiWorkArea::inDialogMode() const
1413 {
1414         return d->dialog_mode_;
1415 }
1416
1417
1418 void GuiWorkArea::setDialogMode(bool mode)
1419 {
1420         d->dialog_mode_ = mode;
1421 }
1422
1423
1424 GuiCompleter & GuiWorkArea::completer()
1425 {
1426         return *d->completer_;
1427 }
1428
1429 GuiView const & GuiWorkArea::view() const
1430 {
1431         return *d->lyx_view_;
1432 }
1433
1434
1435 GuiView & GuiWorkArea::view()
1436 {
1437         return *d->lyx_view_;
1438 }
1439
1440 ////////////////////////////////////////////////////////////////////
1441 //
1442 // EmbeddedWorkArea
1443 //
1444 ////////////////////////////////////////////////////////////////////
1445
1446
1447 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1448 {
1449         support::TempFile tempfile("embedded.internal");
1450         tempfile.setAutoRemove(false);
1451         buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1452         buffer_->setUnnamed(true);
1453         buffer_->setFullyLoaded(true);
1454         setBuffer(*buffer_);
1455         setDialogMode(true);
1456 }
1457
1458
1459 EmbeddedWorkArea::~EmbeddedWorkArea()
1460 {
1461         // No need to destroy buffer and bufferview here, because it is done
1462         // in theBufferList() destruction loop at application exit
1463 }
1464
1465
1466 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1467 {
1468         disable();
1469         GuiWorkArea::closeEvent(ev);
1470 }
1471
1472
1473 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1474 {
1475         disable();
1476         GuiWorkArea::hideEvent(ev);
1477 }
1478
1479
1480 QSize EmbeddedWorkArea::sizeHint () const
1481 {
1482         // FIXME(?):
1483         // GuiWorkArea sets the size to the screen's viewport
1484         // by returning a value this gets overridden
1485         // EmbeddedWorkArea is now sized to fit in the layout
1486         // of the parent, and has a minimum size set in GuiWorkArea
1487         // which is what we return here
1488         return QSize(100, 70);
1489 }
1490
1491
1492 void EmbeddedWorkArea::disable()
1493 {
1494         stopBlinkingCaret();
1495         if (view().currentWorkArea() != this)
1496                 return;
1497         // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1498         // tolerates it and shows the background logo), what happens if
1499         // an EmbeddedWorkArea is closed after closing all document WAs
1500         view().setCurrentWorkArea(view().currentMainWorkArea());
1501 }
1502
1503 ////////////////////////////////////////////////////////////////////
1504 //
1505 // TabWorkArea
1506 //
1507 ////////////////////////////////////////////////////////////////////
1508
1509 TabWorkArea::TabWorkArea(QWidget * parent)
1510         : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1511 {
1512         QPalette pal = palette();
1513         pal.setColor(QPalette::Active, QPalette::Button,
1514                 pal.color(QPalette::Active, QPalette::Window));
1515         pal.setColor(QPalette::Disabled, QPalette::Button,
1516                 pal.color(QPalette::Disabled, QPalette::Window));
1517         pal.setColor(QPalette::Inactive, QPalette::Button,
1518                 pal.color(QPalette::Inactive, QPalette::Window));
1519
1520         QObject::connect(this, SIGNAL(currentChanged(int)),
1521                 this, SLOT(on_currentTabChanged(int)));
1522
1523         closeBufferButton = new QToolButton(this);
1524         closeBufferButton->setPalette(pal);
1525         // FIXME: rename the icon to closebuffer.png
1526         closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1527         closeBufferButton->setText("Close File");
1528         closeBufferButton->setAutoRaise(true);
1529         closeBufferButton->setCursor(Qt::ArrowCursor);
1530         closeBufferButton->setToolTip(qt_("Close File"));
1531         closeBufferButton->setEnabled(true);
1532         QObject::connect(closeBufferButton, SIGNAL(clicked()),
1533                 this, SLOT(closeCurrentBuffer()));
1534         setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1535
1536         // set TabBar behaviour
1537         QTabBar * tb = tabBar();
1538         tb->setTabsClosable(!lyxrc.single_close_tab_button);
1539         tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1540         tb->setElideMode(Qt::ElideNone);
1541         // allow dragging tabs
1542         tb->setMovable(true);
1543         // make us responsible for the context menu of the tabbar
1544         tb->setContextMenuPolicy(Qt::CustomContextMenu);
1545         connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1546                 this, SLOT(showContextMenu(const QPoint &)));
1547         connect(tb, SIGNAL(tabCloseRequested(int)),
1548                 this, SLOT(closeTab(int)));
1549
1550         setUsesScrollButtons(true);
1551 #ifdef Q_OS_MAC
1552         // use document mode tabs
1553         setDocumentMode(true);
1554 #endif
1555 }
1556
1557
1558 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1559 {
1560         if (me->button() == Qt::MiddleButton)
1561                 midpressed_tab_ = tabBar()->tabAt(me->pos());
1562         else
1563                 QTabWidget::mousePressEvent(me);
1564 }
1565
1566
1567 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1568 {
1569         if (me->button() == Qt::MiddleButton) {
1570                 int const midreleased_tab = tabBar()->tabAt(me->pos());
1571                 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1572                         closeTab(midreleased_tab);
1573         } else
1574                 QTabWidget::mouseReleaseEvent(me);
1575 }
1576
1577
1578 void TabWorkArea::paintEvent(QPaintEvent * event)
1579 {
1580         if (tabBar()->isVisible()) {
1581                 QTabWidget::paintEvent(event);
1582         } else {
1583                 // Prevent the selected tab to influence the
1584                 // painting of the frame of the tab widget.
1585                 // This is needed for gtk style in Qt.
1586                 QStylePainter p(this);
1587 #if QT_VERSION < 0x050000
1588                 QStyleOptionTabWidgetFrameV2 opt;
1589 #else
1590                 QStyleOptionTabWidgetFrame opt;
1591 #endif
1592                 initStyleOption(&opt);
1593                 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1594                         &opt, this);
1595                 opt.selectedTabRect = QRect();
1596                 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1597         }
1598 }
1599
1600
1601 bool TabWorkArea::posIsTab(QPoint position)
1602 {
1603         // tabAt returns -1 if tab does not covers position
1604         return tabBar()->tabAt(position) > -1;
1605 }
1606
1607
1608 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1609 {
1610         if (event->button() != Qt::LeftButton)
1611                 return;
1612
1613         // this code chunk is unnecessary because it seems the event only makes
1614         // it this far if it is not on a tab. I'm not sure why this is (maybe
1615         // it is handled and ended in DragTabBar?), and thus I'm not sure if
1616         // this is true in all cases and if it will be true in the future so I
1617         // leave this code for now. (skostysh, 2016-07-21)
1618         //
1619         // return early if double click on existing tabs
1620         if (posIsTab(event->pos()))
1621                 return;
1622
1623         dispatch(FuncRequest(LFUN_BUFFER_NEW));
1624 }
1625
1626
1627 void TabWorkArea::setFullScreen(bool full_screen)
1628 {
1629         for (int i = 0; i != count(); ++i) {
1630                 if (GuiWorkArea * wa = workArea(i))
1631                         wa->setFullScreen(full_screen);
1632         }
1633
1634         if (lyxrc.full_screen_tabbar)
1635                 showBar(!full_screen && count() > 1);
1636         else
1637                 showBar(count() > 1);
1638 }
1639
1640
1641 void TabWorkArea::showBar(bool show)
1642 {
1643         tabBar()->setEnabled(show);
1644         tabBar()->setVisible(show);
1645         if (documentMode()) {
1646                 // avoid blank corner widget when documentMode(true) is used
1647                 if (show && lyxrc.single_close_tab_button) {
1648                         setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1649                         closeBufferButton->setVisible(true);
1650                 } else
1651                         // remove corner widget
1652                         setCornerWidget(nullptr);
1653         } else
1654                 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1655         setTabsClosable(!lyxrc.single_close_tab_button);
1656 }
1657
1658
1659 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1660 {
1661         QWidget * w = QTabWidget::widget(index);
1662         if (!w)
1663                 return nullptr;
1664         GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1665         LATTEST(wac);
1666         return wac;
1667 }
1668
1669
1670 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1671 {
1672         return widget(currentIndex());
1673 }
1674
1675
1676 GuiWorkArea * TabWorkArea::workArea(int index) const
1677 {
1678         GuiWorkAreaContainer * w = widget(index);
1679         if (!w)
1680                 return nullptr;
1681         return w->workArea();
1682 }
1683
1684
1685 GuiWorkArea * TabWorkArea::currentWorkArea() const
1686 {
1687         return workArea(currentIndex());
1688 }
1689
1690
1691 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1692 {
1693         // FIXME: this method doesn't work if we have more than one work area
1694         // showing the same buffer.
1695         for (int i = 0; i != count(); ++i) {
1696                 GuiWorkArea * wa = workArea(i);
1697                 LASSERT(wa, return nullptr);
1698                 if (&wa->bufferView().buffer() == &buffer)
1699                         return wa;
1700         }
1701         return nullptr;
1702 }
1703
1704
1705 void TabWorkArea::closeAll()
1706 {
1707         while (count()) {
1708                 QWidget * wac = widget(0);
1709                 LASSERT(wac, return);
1710                 removeTab(0);
1711                 delete wac;
1712         }
1713 }
1714
1715
1716 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1717 {
1718         for (int index = 0; index < count(); ++index)
1719                 if (workArea(index) == w)
1720                         return index;
1721         return -1;
1722 }
1723
1724
1725 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1726 {
1727         LASSERT(work_area, return false);
1728         int index = indexOfWorkArea(work_area);
1729         if (index == -1)
1730                 return false;
1731
1732         if (index == currentIndex())
1733                 // Make sure the work area is up to date.
1734                 on_currentTabChanged(index);
1735         else
1736                 // Switch to the work area.
1737                 setCurrentIndex(index);
1738         work_area->setFocus();
1739
1740         return true;
1741 }
1742
1743
1744 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1745 {
1746         GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1747         GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1748         wa->setUpdatesEnabled(false);
1749         // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1750         // when hiding it again below).
1751         if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1752                 showBar(count() > 0);
1753         addTab(wac, wa->windowTitle());
1754         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1755                 this, SLOT(updateTabTexts()));
1756         if (currentWorkArea() && currentWorkArea()->isFullScreen())
1757                 setFullScreen(true);
1758         else
1759                 // Hide tabbar if there's only one tab.
1760                 showBar(count() > 1);
1761
1762         updateTabTexts();
1763
1764         return wa;
1765 }
1766
1767
1768 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1769 {
1770         LASSERT(work_area, return false);
1771         int index = indexOfWorkArea(work_area);
1772         if (index == -1)
1773                 return false;
1774
1775         work_area->setUpdatesEnabled(false);
1776         QWidget * wac = widget(index);
1777         removeTab(index);
1778         delete wac;
1779
1780         if (count()) {
1781                 // make sure the next work area is enabled.
1782                 currentWidget()->setUpdatesEnabled(true);
1783                 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1784                         setFullScreen(true);
1785                 else
1786                         // Show tabbar only if there's more than one tab.
1787                         showBar(count() > 1);
1788         } else
1789                 lastWorkAreaRemoved();
1790
1791         updateTabTexts();
1792
1793         return true;
1794 }
1795
1796
1797 void TabWorkArea::on_currentTabChanged(int i)
1798 {
1799         // returns e.g. on application destruction
1800         if (i == -1)
1801                 return;
1802         GuiWorkArea * wa = workArea(i);
1803         LASSERT(wa, return);
1804         wa->setUpdatesEnabled(true);
1805         wa->scheduleRedraw(true);
1806         wa->setFocus();
1807         ///
1808         currentWorkAreaChanged(wa);
1809
1810         LYXERR(Debug::GUI, "currentTabChanged " << i
1811                 << " File: " << wa->bufferView().buffer().absFileName());
1812 }
1813
1814
1815 void TabWorkArea::closeCurrentBuffer()
1816 {
1817         GuiWorkArea * wa;
1818         if (clicked_tab_ == -1)
1819                 wa = currentWorkArea();
1820         else {
1821                 wa = workArea(clicked_tab_);
1822                 LASSERT(wa, return);
1823         }
1824         wa->view().closeWorkArea(wa);
1825 }
1826
1827
1828 void TabWorkArea::hideCurrentTab()
1829 {
1830         GuiWorkArea * wa;
1831         if (clicked_tab_ == -1)
1832                 wa = currentWorkArea();
1833         else {
1834                 wa = workArea(clicked_tab_);
1835                 LASSERT(wa, return);
1836         }
1837         wa->view().hideWorkArea(wa);
1838 }
1839
1840
1841 void TabWorkArea::closeTab(int index)
1842 {
1843         on_currentTabChanged(index);
1844         GuiWorkArea * wa;
1845         if (index == -1)
1846                 wa = currentWorkArea();
1847         else {
1848                 wa = workArea(index);
1849                 LASSERT(wa, return);
1850         }
1851         wa->view().closeWorkArea(wa);
1852 }
1853
1854
1855 ///
1856 class DisplayPath {
1857 public:
1858         /// make vector happy
1859         DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1860         ///
1861         DisplayPath(int tab, FileName const & filename)
1862                 : tab_(tab)
1863         {
1864                 // Recode URL encoded chars via fromPercentEncoding()
1865                 string const fn = (filename.extension() == "lyx")
1866                         ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
1867                 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
1868 #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
1869                 postfix_ = toqstr(filename.absoluteFilePath()).
1870                         split("/", Qt::SkipEmptyParts);
1871 #else
1872                 postfix_ = toqstr(filename.absoluteFilePath()).
1873                         split("/", QString::SkipEmptyParts);
1874 #endif
1875                 postfix_.pop_back();
1876                 abs_ = toqstr(filename.absoluteFilePath());
1877                 dottedPrefix_ = false;
1878         }
1879
1880         /// Absolute path for debugging.
1881         QString abs() const
1882         {
1883                 return abs_;
1884         }
1885         /// Add the first segment from the postfix or three dots to the prefix.
1886         /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1887         /// when really needed.
1888         void shiftPathSegment(bool dotted)
1889         {
1890                 if (postfix_.count() <= 0)
1891                         return;
1892
1893                 if (!dotted) {
1894                         if (dottedPrefix_ && !prefix_.isEmpty())
1895                                 prefix_ += ellipsisSlash_;
1896                         prefix_ += postfix_.front() + "/";
1897                 }
1898                 dottedPrefix_ = dotted && !prefix_.isEmpty();
1899                 postfix_.pop_front();
1900         }
1901         ///
1902         QString displayString() const
1903         {
1904                 if (prefix_.isEmpty())
1905                         return filename_;
1906
1907                 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1908                 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1909         }
1910         ///
1911         QString forecastPathString() const
1912         {
1913                 if (postfix_.count() == 0)
1914                         return displayString();
1915
1916                 return prefix_
1917                         + (dottedPrefix_ ? ellipsisSlash_ : "")
1918                         + postfix_.front() + "/";
1919         }
1920         ///
1921         bool final() const { return postfix_.empty(); }
1922         ///
1923         int tab() const { return tab_; }
1924
1925 private:
1926         /// ".../"
1927         static QString const ellipsisSlash_;
1928         ///
1929         QString prefix_;
1930         ///
1931         QStringList postfix_;
1932         ///
1933         QString filename_;
1934         ///
1935         QString abs_;
1936         ///
1937         int tab_;
1938         ///
1939         bool dottedPrefix_;
1940 };
1941
1942
1943 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1944
1945
1946 ///
1947 bool operator<(DisplayPath const & a, DisplayPath const & b)
1948 {
1949         return a.displayString() < b.displayString();
1950 }
1951
1952 ///
1953 bool operator==(DisplayPath const & a, DisplayPath const & b)
1954 {
1955         return a.displayString() == b.displayString();
1956 }
1957
1958
1959 void TabWorkArea::updateTabTexts()
1960 {
1961         int const n = count();
1962         if (n == 0)
1963                 return;
1964         std::list<DisplayPath> paths;
1965         typedef std::list<DisplayPath>::iterator It;
1966
1967         // collect full names first: path into postfix, empty prefix and
1968         // filename without extension
1969         for (int i = 0; i < n; ++i) {
1970                 GuiWorkArea * i_wa = workArea(i);
1971                 FileName const fn = i_wa->bufferView().buffer().fileName();
1972                 paths.push_back(DisplayPath(i, fn));
1973         }
1974
1975         // go through path segments and see if it helps to make the path more unique
1976         bool somethingChanged = true;
1977         bool allFinal = false;
1978         while (somethingChanged && !allFinal) {
1979                 // adding path segments changes order
1980                 paths.sort();
1981
1982                 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1983                 somethingChanged = false;
1984                 allFinal = true;
1985
1986                 // find segments which are not unique (i.e. non-atomic)
1987                 It it = paths.begin();
1988                 It segStart = it;
1989                 QString segString = it->displayString();
1990                 for (; it != paths.end(); ++it) {
1991                         // look to the next item
1992                         It next = it;
1993                         ++next;
1994
1995                         // final?
1996                         allFinal = allFinal && it->final();
1997
1998                         LYXERR(Debug::GUI, "it = " << it->abs()
1999                                << " => " << it->displayString());
2000
2001                         // still the same segment?
2002                         QString nextString;
2003                         if ((next != paths.end()
2004                              && (nextString = next->displayString()) == segString))
2005                                 continue;
2006                         LYXERR(Debug::GUI, "segment ended");
2007
2008                         // only a trivial one with one element?
2009                         if (it == segStart) {
2010                                 // start new segment
2011                                 segStart = next;
2012                                 segString = nextString;
2013                                 continue;
2014                         }
2015
2016                         // We found a non-atomic segment
2017                         // We know that segStart <= it < next <= paths.end().
2018                         // The assertion below tells coverity about it.
2019                         LATTEST(segStart != paths.end());
2020                         QString dspString = segStart->forecastPathString();
2021                         LYXERR(Debug::GUI, "first forecast found for "
2022                                << segStart->abs() << " => " << dspString);
2023                         It sit = segStart;
2024                         ++sit;
2025                         // Shift path segments and hope for the best
2026                         // that it makes the path more unique.
2027                         somethingChanged = true;
2028                         bool moreUnique = false;
2029                         for (; sit != next; ++sit) {
2030                                 if (sit->forecastPathString() != dspString) {
2031                                         LYXERR(Debug::GUI, "different forecast found for "
2032                                                 << sit->abs() << " => " << sit->forecastPathString());
2033                                         moreUnique = true;
2034                                         break;
2035                                 }
2036                                 LYXERR(Debug::GUI, "same forecast found for "
2037                                         << sit->abs() << " => " << dspString);
2038                         }
2039
2040                         // if the path segment helped, add it. Otherwise add dots
2041                         bool dots = !moreUnique;
2042                         LYXERR(Debug::GUI, "using dots = " << dots);
2043                         for (sit = segStart; sit != next; ++sit) {
2044                                 sit->shiftPathSegment(dots);
2045                                 LYXERR(Debug::GUI, "shifting "
2046                                         << sit->abs() << " => " << sit->displayString());
2047                         }
2048
2049                         // start new segment
2050                         segStart = next;
2051                         segString = nextString;
2052                 }
2053         }
2054
2055         // set new tab titles
2056         for (It it = paths.begin(); it != paths.end(); ++it) {
2057                 int const tab_index = it->tab();
2058                 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2059                 QString tab_text = it->displayString().replace("&", "&&");
2060                 if (!buf.fileName().empty() && !buf.isClean())
2061                         tab_text += "*";
2062                 QString tab_tooltip = it->abs();
2063                 if (buf.hasReadonlyFlag()) {
2064 #ifdef Q_OS_MAC
2065                         QLabel * readOnlyButton = new QLabel();
2066                         QIcon icon = QIcon(getPixmap("images/", "emblem-readonly", "svgz,png"));
2067                         readOnlyButton->setPixmap(icon.pixmap(QSize(16, 16)));
2068                         tabBar()->setTabButton(tab_index, QTabBar::RightSide, readOnlyButton);
2069 #else
2070                         setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2071 #endif
2072                         tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2073                 } else
2074 #ifdef Q_OS_MAC
2075                         tabBar()->setTabButton(tab_index, QTabBar::RightSide, 0);
2076 #else
2077                         setTabIcon(tab_index, QIcon());
2078 #endif
2079                 if (buf.notifiesExternalModification()) {
2080                         QString const warn = qt_("%1 (modified externally)");
2081                         tab_tooltip = warn.arg(tab_tooltip);
2082                         tab_text += QChar(0x26a0);
2083                 }
2084                 setTabText(tab_index, tab_text);
2085                 setTabToolTip(tab_index, tab_tooltip);
2086         }
2087 }
2088
2089
2090 void TabWorkArea::showContextMenu(const QPoint & pos)
2091 {
2092         // which tab?
2093         clicked_tab_ = tabBar()->tabAt(pos);
2094         if (clicked_tab_ == -1)
2095                 return;
2096
2097         GuiWorkArea * wa = workArea(clicked_tab_);
2098         LASSERT(wa, return);
2099
2100         // show tab popup
2101         QMenu popup;
2102         popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2103                 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2104
2105         // we want to show the 'close' option only if this is not a child buffer.
2106         Buffer const & buf = wa->bufferView().buffer();
2107         if (!buf.parent())
2108                 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2109                         qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2110         popup.exec(tabBar()->mapToGlobal(pos));
2111
2112         clicked_tab_ = -1;
2113 }
2114
2115
2116 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2117 {
2118         QWidget * w = widget(fromIndex);
2119         QIcon icon = tabIcon(fromIndex);
2120         QString text = tabText(fromIndex);
2121
2122         setCurrentIndex(fromIndex);
2123         removeTab(fromIndex);
2124         insertTab(toIndex, w, icon, text);
2125         setCurrentIndex(toIndex);
2126 }
2127
2128
2129 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2130         : QWidget(parent), wa_(wa)
2131 {
2132         LASSERT(wa, return);
2133         Ui::WorkAreaUi::setupUi(this);
2134         layout()->addWidget(wa);
2135         connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2136                 this, SLOT(updateDisplay()));
2137         connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2138         connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2139         setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2140         updateDisplay();
2141 }
2142
2143
2144 void GuiWorkAreaContainer::updateDisplay()
2145 {
2146         Buffer const & buf = wa_->bufferView().buffer();
2147         notificationFrame->setHidden(!buf.notifiesExternalModification());
2148         QString const label = qt_("<b>The file %1 changed on disk.</b>")
2149                 .arg(toqstr(buf.fileName().displayName()));
2150         externalModificationLabel->setText(label);
2151 }
2152
2153
2154 void GuiWorkAreaContainer::dispatch(FuncRequest const & f) const
2155 {
2156         lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2157                                   wa_->bufferView().buffer().absFileName()));
2158         lyx::dispatch(f);
2159 }
2160
2161
2162 void GuiWorkAreaContainer::reload() const
2163 {
2164         dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2165 }
2166
2167
2168 void GuiWorkAreaContainer::ignore() const
2169 {
2170         dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2171 }
2172
2173
2174 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2175 {
2176         // prevent TabWorkArea from opening a new buffer on double click
2177         event->accept();
2178 }
2179
2180
2181 } // namespace frontend
2182 } // namespace lyx
2183
2184 #include "moc_GuiWorkArea.cpp"