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