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