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