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