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