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