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