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