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