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