]> git.lyx.org Git - features.git/blob - src/frontends/qt/GuiWorkArea.cpp
Refactoring
[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         QRect cur_r(0, 0, 0, 0);
1414         switch (query) {
1415                 // this is the CJK-specific composition window position and
1416                 // the context menu position when the menu key is pressed.
1417                 case Qt::ImMicroFocus:
1418                         return QRect(d->caret_->x - 10 * (d->preedit_lines_ != 1),
1419                                                  d->caret_->y + d->caret_->dim.height() * d->preedit_lines_,
1420                                                  d->caret_->dim.width(), d->caret_->dim.height());
1421                 default:
1422                         return QWidget::inputMethodQuery(query);
1423         }
1424 }
1425
1426
1427 void GuiWorkArea::updateWindowTitle()
1428 {
1429         Buffer const & buf = bufferView().buffer();
1430         if (buf.fileName() != d->file_name_
1431             || buf.params().shell_escape != d->shell_escape_
1432             || buf.hasReadonlyFlag() != d->read_only_
1433             || buf.lyxvc().vcstatus() != d->vc_status_
1434             || buf.isClean() != d->clean_
1435             || buf.notifiesExternalModification() != d->externally_modified_) {
1436                 d->file_name_ = buf.fileName();
1437                 d->shell_escape_ = buf.params().shell_escape;
1438                 d->read_only_ = buf.hasReadonlyFlag();
1439                 d->vc_status_ = buf.lyxvc().vcstatus();
1440                 d->clean_ = buf.isClean();
1441                 d->externally_modified_ = buf.notifiesExternalModification();
1442                 Q_EMIT titleChanged(this);
1443         }
1444 }
1445
1446
1447 bool GuiWorkArea::isFullScreen() const
1448 {
1449         return d->lyx_view_ && d->lyx_view_->isFullScreen();
1450 }
1451
1452
1453 bool GuiWorkArea::inDialogMode() const
1454 {
1455         return d->dialog_mode_;
1456 }
1457
1458
1459 void GuiWorkArea::setDialogMode(bool mode)
1460 {
1461         d->dialog_mode_ = mode;
1462 }
1463
1464
1465 GuiCompleter & GuiWorkArea::completer()
1466 {
1467         return *d->completer_;
1468 }
1469
1470 GuiView const & GuiWorkArea::view() const
1471 {
1472         return *d->lyx_view_;
1473 }
1474
1475
1476 GuiView & GuiWorkArea::view()
1477 {
1478         return *d->lyx_view_;
1479 }
1480
1481 ////////////////////////////////////////////////////////////////////
1482 //
1483 // EmbeddedWorkArea
1484 //
1485 ////////////////////////////////////////////////////////////////////
1486
1487
1488 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1489 {
1490         support::TempFile tempfile("embedded.internal");
1491         tempfile.setAutoRemove(false);
1492         buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1493         buffer_->setUnnamed(true);
1494         buffer_->setFullyLoaded(true);
1495         setBuffer(*buffer_);
1496         setDialogMode(true);
1497 }
1498
1499
1500 EmbeddedWorkArea::~EmbeddedWorkArea()
1501 {
1502         // No need to destroy buffer and bufferview here, because it is done
1503         // in theBufferList() destruction loop at application exit
1504 }
1505
1506
1507 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1508 {
1509         disable();
1510         GuiWorkArea::closeEvent(ev);
1511 }
1512
1513
1514 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1515 {
1516         disable();
1517         GuiWorkArea::hideEvent(ev);
1518 }
1519
1520
1521 QSize EmbeddedWorkArea::sizeHint () const
1522 {
1523         // FIXME(?):
1524         // GuiWorkArea sets the size to the screen's viewport
1525         // by returning a value this gets overridden
1526         // EmbeddedWorkArea is now sized to fit in the layout
1527         // of the parent, and has a minimum size set in GuiWorkArea
1528         // which is what we return here
1529         return QSize(100, 70);
1530 }
1531
1532
1533 void EmbeddedWorkArea::disable()
1534 {
1535         stopBlinkingCaret();
1536         if (view().currentWorkArea() != this)
1537                 return;
1538         // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1539         // tolerates it and shows the background logo), what happens if
1540         // an EmbeddedWorkArea is closed after closing all document WAs
1541         view().setCurrentWorkArea(view().currentMainWorkArea());
1542 }
1543
1544 ////////////////////////////////////////////////////////////////////
1545 //
1546 // TabWorkArea
1547 //
1548 ////////////////////////////////////////////////////////////////////
1549
1550 #ifdef Q_OS_MAC
1551 class NoTabFrameMacStyle : public QProxyStyle {
1552 public:
1553         ///
1554         QRect subElementRect(SubElement element, const QStyleOption * option,
1555                              const QWidget * widget = 0) const
1556         {
1557                 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1558                 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1559
1560                 // The Qt Mac style puts the contents into a 3 pixel wide box
1561                 // which looks very ugly and not like other Mac applications.
1562                 // Hence we remove this here, and moreover the 16 pixel round
1563                 // frame above if the tab bar is hidden.
1564                 if (element == QStyle::SE_TabWidgetTabContents) {
1565                         rect.adjust(- rect.left(), 0, rect.left(), 0);
1566                         if (noBar)
1567                                 rect.setTop(0);
1568                 }
1569
1570                 return rect;
1571         }
1572 };
1573
1574 NoTabFrameMacStyle noTabFrameMacStyle;
1575 #endif
1576
1577
1578 TabWorkArea::TabWorkArea(QWidget * parent)
1579         : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1580 {
1581 #ifdef Q_OS_MAC
1582         setStyle(&noTabFrameMacStyle);
1583 #endif
1584
1585         QPalette pal = palette();
1586         pal.setColor(QPalette::Active, QPalette::Button,
1587                 pal.color(QPalette::Active, QPalette::Window));
1588         pal.setColor(QPalette::Disabled, QPalette::Button,
1589                 pal.color(QPalette::Disabled, QPalette::Window));
1590         pal.setColor(QPalette::Inactive, QPalette::Button,
1591                 pal.color(QPalette::Inactive, QPalette::Window));
1592
1593         QObject::connect(this, SIGNAL(currentChanged(int)),
1594                 this, SLOT(on_currentTabChanged(int)));
1595
1596         closeBufferButton = new QToolButton(this);
1597         closeBufferButton->setPalette(pal);
1598         // FIXME: rename the icon to closebuffer.png
1599         closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1600         closeBufferButton->setText("Close File");
1601         closeBufferButton->setAutoRaise(true);
1602         closeBufferButton->setCursor(Qt::ArrowCursor);
1603         closeBufferButton->setToolTip(qt_("Close File"));
1604         closeBufferButton->setEnabled(true);
1605         QObject::connect(closeBufferButton, SIGNAL(clicked()),
1606                 this, SLOT(closeCurrentBuffer()));
1607         setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1608
1609         // set TabBar behaviour
1610         QTabBar * tb = tabBar();
1611         tb->setTabsClosable(!lyxrc.single_close_tab_button);
1612         tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1613         tb->setElideMode(Qt::ElideNone);
1614         // allow dragging tabs
1615         tb->setMovable(true);
1616         // make us responsible for the context menu of the tabbar
1617         tb->setContextMenuPolicy(Qt::CustomContextMenu);
1618         connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1619                 this, SLOT(showContextMenu(const QPoint &)));
1620         connect(tb, SIGNAL(tabCloseRequested(int)),
1621                 this, SLOT(closeTab(int)));
1622
1623         setUsesScrollButtons(true);
1624 }
1625
1626
1627 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1628 {
1629         if (me->button() == Qt::MidButton)
1630                 midpressed_tab_ = tabBar()->tabAt(me->pos());
1631         else
1632                 QTabWidget::mousePressEvent(me);
1633 }
1634
1635
1636 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1637 {
1638         if (me->button() == Qt::MidButton) {
1639                 int const midreleased_tab = tabBar()->tabAt(me->pos());
1640                 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1641                         closeTab(midreleased_tab);
1642         } else
1643                 QTabWidget::mouseReleaseEvent(me);
1644 }
1645
1646
1647 void TabWorkArea::paintEvent(QPaintEvent * event)
1648 {
1649         if (tabBar()->isVisible()) {
1650                 QTabWidget::paintEvent(event);
1651         } else {
1652                 // Prevent the selected tab to influence the
1653                 // painting of the frame of the tab widget.
1654                 // This is needed for gtk style in Qt.
1655                 QStylePainter p(this);
1656 #if QT_VERSION < 0x050000
1657                 QStyleOptionTabWidgetFrameV2 opt;
1658 #else
1659                 QStyleOptionTabWidgetFrame opt;
1660 #endif
1661                 initStyleOption(&opt);
1662                 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1663                         &opt, this);
1664                 opt.selectedTabRect = QRect();
1665                 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1666         }
1667 }
1668
1669
1670 bool TabWorkArea::posIsTab(QPoint position)
1671 {
1672         // tabAt returns -1 if tab does not covers position
1673         return tabBar()->tabAt(position) > -1;
1674 }
1675
1676
1677 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1678 {
1679         if (event->button() != Qt::LeftButton)
1680                 return;
1681
1682         // this code chunk is unnecessary because it seems the event only makes
1683         // it this far if it is not on a tab. I'm not sure why this is (maybe
1684         // it is handled and ended in DragTabBar?), and thus I'm not sure if
1685         // this is true in all cases and if it will be true in the future so I
1686         // leave this code for now. (skostysh, 2016-07-21)
1687         //
1688         // return early if double click on existing tabs
1689         if (posIsTab(event->pos()))
1690                 return;
1691
1692         dispatch(FuncRequest(LFUN_BUFFER_NEW));
1693 }
1694
1695
1696 void TabWorkArea::setFullScreen(bool full_screen)
1697 {
1698         for (int i = 0; i != count(); ++i) {
1699                 if (GuiWorkArea * wa = workArea(i))
1700                         wa->setFullScreen(full_screen);
1701         }
1702
1703         if (lyxrc.full_screen_tabbar)
1704                 showBar(!full_screen && count() > 1);
1705         else
1706                 showBar(count() > 1);
1707 }
1708
1709
1710 void TabWorkArea::showBar(bool show)
1711 {
1712         tabBar()->setEnabled(show);
1713         tabBar()->setVisible(show);
1714         closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1715         setTabsClosable(!lyxrc.single_close_tab_button);
1716 }
1717
1718
1719 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1720 {
1721         QWidget * w = QTabWidget::widget(index);
1722         if (!w)
1723                 return nullptr;
1724         GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1725         LATTEST(wac);
1726         return wac;
1727 }
1728
1729
1730 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1731 {
1732         return widget(currentIndex());
1733 }
1734
1735
1736 GuiWorkArea * TabWorkArea::workArea(int index) const
1737 {
1738         GuiWorkAreaContainer * w = widget(index);
1739         if (!w)
1740                 return nullptr;
1741         return w->workArea();
1742 }
1743
1744
1745 GuiWorkArea * TabWorkArea::currentWorkArea() const
1746 {
1747         return workArea(currentIndex());
1748 }
1749
1750
1751 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1752 {
1753         // FIXME: this method doesn't work if we have more than one work area
1754         // showing the same buffer.
1755         for (int i = 0; i != count(); ++i) {
1756                 GuiWorkArea * wa = workArea(i);
1757                 LASSERT(wa, return nullptr);
1758                 if (&wa->bufferView().buffer() == &buffer)
1759                         return wa;
1760         }
1761         return nullptr;
1762 }
1763
1764
1765 void TabWorkArea::closeAll()
1766 {
1767         while (count()) {
1768                 QWidget * wac = widget(0);
1769                 LASSERT(wac, return);
1770                 removeTab(0);
1771                 delete wac;
1772         }
1773 }
1774
1775
1776 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1777 {
1778         for (int index = 0; index < count(); ++index)
1779                 if (workArea(index) == w)
1780                         return index;
1781         return -1;
1782 }
1783
1784
1785 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1786 {
1787         LASSERT(work_area, return false);
1788         int index = indexOfWorkArea(work_area);
1789         if (index == -1)
1790                 return false;
1791
1792         if (index == currentIndex())
1793                 // Make sure the work area is up to date.
1794                 on_currentTabChanged(index);
1795         else
1796                 // Switch to the work area.
1797                 setCurrentIndex(index);
1798         work_area->setFocus();
1799
1800         return true;
1801 }
1802
1803
1804 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1805 {
1806         GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1807         GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1808         wa->setUpdatesEnabled(false);
1809         // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1810         // when hiding it again below).
1811         if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1812                 showBar(count() > 0);
1813         addTab(wac, wa->windowTitle());
1814         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1815                 this, SLOT(updateTabTexts()));
1816         if (currentWorkArea() && currentWorkArea()->isFullScreen())
1817                 setFullScreen(true);
1818         else
1819                 // Hide tabbar if there's only one tab.
1820                 showBar(count() > 1);
1821
1822         updateTabTexts();
1823
1824         return wa;
1825 }
1826
1827
1828 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1829 {
1830         LASSERT(work_area, return false);
1831         int index = indexOfWorkArea(work_area);
1832         if (index == -1)
1833                 return false;
1834
1835         work_area->setUpdatesEnabled(false);
1836         QWidget * wac = widget(index);
1837         removeTab(index);
1838         delete wac;
1839
1840         if (count()) {
1841                 // make sure the next work area is enabled.
1842                 currentWidget()->setUpdatesEnabled(true);
1843                 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1844                         setFullScreen(true);
1845                 else
1846                         // Show tabbar only if there's more than one tab.
1847                         showBar(count() > 1);
1848         } else
1849                 lastWorkAreaRemoved();
1850
1851         updateTabTexts();
1852
1853         return true;
1854 }
1855
1856
1857 void TabWorkArea::on_currentTabChanged(int i)
1858 {
1859         // returns e.g. on application destruction
1860         if (i == -1)
1861                 return;
1862         GuiWorkArea * wa = workArea(i);
1863         LASSERT(wa, return);
1864         wa->setUpdatesEnabled(true);
1865         wa->scheduleRedraw(true);
1866         wa->setFocus();
1867         ///
1868         currentWorkAreaChanged(wa);
1869
1870         LYXERR(Debug::GUI, "currentTabChanged " << i
1871                 << " File: " << wa->bufferView().buffer().absFileName());
1872 }
1873
1874
1875 void TabWorkArea::closeCurrentBuffer()
1876 {
1877         GuiWorkArea * wa;
1878         if (clicked_tab_ == -1)
1879                 wa = currentWorkArea();
1880         else {
1881                 wa = workArea(clicked_tab_);
1882                 LASSERT(wa, return);
1883         }
1884         wa->view().closeWorkArea(wa);
1885 }
1886
1887
1888 void TabWorkArea::hideCurrentTab()
1889 {
1890         GuiWorkArea * wa;
1891         if (clicked_tab_ == -1)
1892                 wa = currentWorkArea();
1893         else {
1894                 wa = workArea(clicked_tab_);
1895                 LASSERT(wa, return);
1896         }
1897         wa->view().hideWorkArea(wa);
1898 }
1899
1900
1901 void TabWorkArea::closeTab(int index)
1902 {
1903         on_currentTabChanged(index);
1904         GuiWorkArea * wa;
1905         if (index == -1)
1906                 wa = currentWorkArea();
1907         else {
1908                 wa = workArea(index);
1909                 LASSERT(wa, return);
1910         }
1911         wa->view().closeWorkArea(wa);
1912 }
1913
1914
1915 ///
1916 class DisplayPath {
1917 public:
1918         /// make vector happy
1919         DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1920         ///
1921         DisplayPath(int tab, FileName const & filename)
1922                 : tab_(tab)
1923         {
1924                 // Recode URL encoded chars via fromPercentEncoding()
1925                 string const fn = (filename.extension() == "lyx")
1926                         ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
1927                 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
1928                 postfix_ = toqstr(filename.absoluteFilePath()).
1929                         split("/", QString::SkipEmptyParts);
1930                 postfix_.pop_back();
1931                 abs_ = toqstr(filename.absoluteFilePath());
1932                 dottedPrefix_ = false;
1933         }
1934
1935         /// Absolute path for debugging.
1936         QString abs() const
1937         {
1938                 return abs_;
1939         }
1940         /// Add the first segment from the postfix or three dots to the prefix.
1941         /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1942         /// when really needed.
1943         void shiftPathSegment(bool dotted)
1944         {
1945                 if (postfix_.count() <= 0)
1946                         return;
1947
1948                 if (!dotted) {
1949                         if (dottedPrefix_ && !prefix_.isEmpty())
1950                                 prefix_ += ellipsisSlash_;
1951                         prefix_ += postfix_.front() + "/";
1952                 }
1953                 dottedPrefix_ = dotted && !prefix_.isEmpty();
1954                 postfix_.pop_front();
1955         }
1956         ///
1957         QString displayString() const
1958         {
1959                 if (prefix_.isEmpty())
1960                         return filename_;
1961
1962                 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1963                 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1964         }
1965         ///
1966         QString forecastPathString() const
1967         {
1968                 if (postfix_.count() == 0)
1969                         return displayString();
1970
1971                 return prefix_
1972                         + (dottedPrefix_ ? ellipsisSlash_ : "")
1973                         + postfix_.front() + "/";
1974         }
1975         ///
1976         bool final() const { return postfix_.empty(); }
1977         ///
1978         int tab() const { return tab_; }
1979
1980 private:
1981         /// ".../"
1982         static QString const ellipsisSlash_;
1983         ///
1984         QString prefix_;
1985         ///
1986         QStringList postfix_;
1987         ///
1988         QString filename_;
1989         ///
1990         QString abs_;
1991         ///
1992         int tab_;
1993         ///
1994         bool dottedPrefix_;
1995 };
1996
1997
1998 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1999
2000
2001 ///
2002 bool operator<(DisplayPath const & a, DisplayPath const & b)
2003 {
2004         return a.displayString() < b.displayString();
2005 }
2006
2007 ///
2008 bool operator==(DisplayPath const & a, DisplayPath const & b)
2009 {
2010         return a.displayString() == b.displayString();
2011 }
2012
2013
2014 void TabWorkArea::updateTabTexts()
2015 {
2016         int const n = count();
2017         if (n == 0)
2018                 return;
2019         std::list<DisplayPath> paths;
2020         typedef std::list<DisplayPath>::iterator It;
2021
2022         // collect full names first: path into postfix, empty prefix and
2023         // filename without extension
2024         for (int i = 0; i < n; ++i) {
2025                 GuiWorkArea * i_wa = workArea(i);
2026                 FileName const fn = i_wa->bufferView().buffer().fileName();
2027                 paths.push_back(DisplayPath(i, fn));
2028         }
2029
2030         // go through path segments and see if it helps to make the path more unique
2031         bool somethingChanged = true;
2032         bool allFinal = false;
2033         while (somethingChanged && !allFinal) {
2034                 // adding path segments changes order
2035                 paths.sort();
2036
2037                 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
2038                 somethingChanged = false;
2039                 allFinal = true;
2040
2041                 // find segments which are not unique (i.e. non-atomic)
2042                 It it = paths.begin();
2043                 It segStart = it;
2044                 QString segString = it->displayString();
2045                 for (; it != paths.end(); ++it) {
2046                         // look to the next item
2047                         It next = it;
2048                         ++next;
2049
2050                         // final?
2051                         allFinal = allFinal && it->final();
2052
2053                         LYXERR(Debug::GUI, "it = " << it->abs()
2054                                << " => " << it->displayString());
2055
2056                         // still the same segment?
2057                         QString nextString;
2058                         if ((next != paths.end()
2059                              && (nextString = next->displayString()) == segString))
2060                                 continue;
2061                         LYXERR(Debug::GUI, "segment ended");
2062
2063                         // only a trivial one with one element?
2064                         if (it == segStart) {
2065                                 // start new segment
2066                                 segStart = next;
2067                                 segString = nextString;
2068                                 continue;
2069                         }
2070
2071                         // We found a non-atomic segment
2072                         // We know that segStart <= it < next <= paths.end().
2073                         // The assertion below tells coverity about it.
2074                         LATTEST(segStart != paths.end());
2075                         QString dspString = segStart->forecastPathString();
2076                         LYXERR(Debug::GUI, "first forecast found for "
2077                                << segStart->abs() << " => " << dspString);
2078                         It sit = segStart;
2079                         ++sit;
2080                         // Shift path segments and hope for the best
2081                         // that it makes the path more unique.
2082                         somethingChanged = true;
2083                         bool moreUnique = false;
2084                         for (; sit != next; ++sit) {
2085                                 if (sit->forecastPathString() != dspString) {
2086                                         LYXERR(Debug::GUI, "different forecast found for "
2087                                                 << sit->abs() << " => " << sit->forecastPathString());
2088                                         moreUnique = true;
2089                                         break;
2090                                 }
2091                                 LYXERR(Debug::GUI, "same forecast found for "
2092                                         << sit->abs() << " => " << dspString);
2093                         }
2094
2095                         // if the path segment helped, add it. Otherwise add dots
2096                         bool dots = !moreUnique;
2097                         LYXERR(Debug::GUI, "using dots = " << dots);
2098                         for (sit = segStart; sit != next; ++sit) {
2099                                 sit->shiftPathSegment(dots);
2100                                 LYXERR(Debug::GUI, "shifting "
2101                                         << sit->abs() << " => " << sit->displayString());
2102                         }
2103
2104                         // start new segment
2105                         segStart = next;
2106                         segString = nextString;
2107                 }
2108         }
2109
2110         // set new tab titles
2111         for (It it = paths.begin(); it != paths.end(); ++it) {
2112                 int const tab_index = it->tab();
2113                 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2114                 QString tab_text = it->displayString().replace("&", "&&");
2115                 if (!buf.fileName().empty() && !buf.isClean())
2116                         tab_text += "*";
2117                 QString tab_tooltip = it->abs();
2118                 if (buf.hasReadonlyFlag()) {
2119                         setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2120                         tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2121                 } else
2122                         setTabIcon(tab_index, QIcon());
2123                 if (buf.notifiesExternalModification()) {
2124                         QString const warn = qt_("%1 (modified externally)");
2125                         tab_tooltip = warn.arg(tab_tooltip);
2126                         tab_text += QChar(0x26a0);
2127                 }
2128                 setTabText(tab_index, tab_text);
2129                 setTabToolTip(tab_index, tab_tooltip);
2130         }
2131 }
2132
2133
2134 void TabWorkArea::showContextMenu(const QPoint & pos)
2135 {
2136         // which tab?
2137         clicked_tab_ = tabBar()->tabAt(pos);
2138         if (clicked_tab_ == -1)
2139                 return;
2140
2141         GuiWorkArea * wa = workArea(clicked_tab_);
2142         LASSERT(wa, return);
2143
2144         // show tab popup
2145         QMenu popup;
2146         popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2147                 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2148
2149         // we want to show the 'close' option only if this is not a child buffer.
2150         Buffer const & buf = wa->bufferView().buffer();
2151         if (!buf.parent())
2152                 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2153                         qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2154         popup.exec(tabBar()->mapToGlobal(pos));
2155
2156         clicked_tab_ = -1;
2157 }
2158
2159
2160 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2161 {
2162         QWidget * w = widget(fromIndex);
2163         QIcon icon = tabIcon(fromIndex);
2164         QString text = tabText(fromIndex);
2165
2166         setCurrentIndex(fromIndex);
2167         removeTab(fromIndex);
2168         insertTab(toIndex, w, icon, text);
2169         setCurrentIndex(toIndex);
2170 }
2171
2172
2173 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2174         : QWidget(parent), wa_(wa)
2175 {
2176         LASSERT(wa, return);
2177         Ui::WorkAreaUi::setupUi(this);
2178         layout()->addWidget(wa);
2179         connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2180                 this, SLOT(updateDisplay()));
2181         connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2182         connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2183         setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2184         updateDisplay();
2185 }
2186
2187
2188 void GuiWorkAreaContainer::updateDisplay()
2189 {
2190         Buffer const & buf = wa_->bufferView().buffer();
2191         notificationFrame->setHidden(!buf.notifiesExternalModification());
2192         QString const label = qt_("<b>The file %1 changed on disk.</b>")
2193                 .arg(toqstr(buf.fileName().displayName()));
2194         externalModificationLabel->setText(label);
2195 }
2196
2197
2198 void GuiWorkAreaContainer::dispatch(FuncRequest f) const
2199 {
2200         lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2201                                   wa_->bufferView().buffer().absFileName()));
2202         lyx::dispatch(f);
2203 }
2204
2205
2206 void GuiWorkAreaContainer::reload() const
2207 {
2208         dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2209 }
2210
2211
2212 void GuiWorkAreaContainer::ignore() const
2213 {
2214         dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2215 }
2216
2217
2218 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2219 {
2220         // prevent TabWorkArea from opening a new buffer on double click
2221         event->accept();
2222 }
2223
2224
2225 } // namespace frontend
2226 } // namespace lyx
2227
2228 #include "moc_GuiWorkArea.cpp"