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