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