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