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