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