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