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