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