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