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