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