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