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