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