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