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