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