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