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