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