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