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