2 * \file GuiWorkArea.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Abdelrazak Younes
9 * Full author contact details are available in file CREDITS.
14 #include "GuiWorkArea.h"
15 #include "GuiWorkArea_Private.h"
17 #include "ColorCache.h"
18 #include "FontLoader.h"
19 #include "GuiApplication.h"
20 #include "GuiCompleter.h"
21 #include "GuiKeySymbol.h"
22 #include "GuiPainter.h"
25 #include "qt_helpers.h"
28 #include "BufferList.h"
29 #include "BufferParams.h"
30 #include "BufferView.h"
31 #include "CoordCache.h"
34 #include "FuncRequest.h"
35 #include "KeySymbol.h"
41 #include "TextMetrics.h"
45 #include "graphics/GraphicsImage.h"
46 #include "graphics/GraphicsLoader.h"
48 #include "support/convert.h"
49 #include "support/debug.h"
50 #include "support/lassert.h"
51 #include "support/TempFile.h"
53 #include "frontends/Application.h"
54 #include "frontends/FontMetrics.h"
55 #include "frontends/WorkAreaManager.h"
57 #include <QContextMenuEvent>
58 #if (QT_VERSION < 0x050000)
59 #include <QInputContext>
64 #include <QProxyStyle>
66 #include <QMainWindow>
72 #include <QStyleOption>
73 #include <QStylePainter>
75 #include <QToolButton>
82 int const TabIndicatorWidth = 3;
88 using namespace lyx::support;
93 /// return the LyX mouse button state from Qt's
94 static mouse_button::state q_button_state(Qt::MouseButton button)
96 mouse_button::state b = mouse_button::none;
99 b = mouse_button::button1;
102 b = mouse_button::button2;
104 case Qt::RightButton:
105 b = mouse_button::button3;
114 /// return the LyX mouse button state from Qt's
115 mouse_button::state q_motion_state(Qt::MouseButtons state)
117 mouse_button::state b = mouse_button::none;
118 if (state & Qt::LeftButton)
119 b |= mouse_button::button1;
120 if (state & Qt::MidButton)
121 b |= mouse_button::button2;
122 if (state & Qt::RightButton)
123 b |= mouse_button::button3;
132 CaretWidget() : rtl_(false), l_shape_(false), completable_(false),
133 x_(0), caret_width_(0)
136 /* Draw the caret. Parameter \c horiz_offset is not 0 when there
137 * has been horizontal scrolling in current row
139 void draw(QPainter & painter, int horiz_offset)
141 if (!rect_.isValid())
144 int const x = x_ - horiz_offset;
145 int const y = rect_.top();
146 int const l = x_ - rect_.left();
147 int const r = rect_.right() - x_;
148 int const bot = rect_.bottom();
150 // draw vertical line
151 painter.fillRect(x, y, caret_width_, rect_.height(), color_);
153 // draw RTL/LTR indication
154 painter.setPen(color_);
157 painter.drawLine(x, bot, x - l + 1, bot);
159 painter.drawLine(x, bot, x + caret_width_ + r - 1, bot);
162 // draw completion triangle
164 int m = y + rect_.height() / 2;
165 int d = TabIndicatorWidth - 1;
167 painter.drawLine(x - 1, m - d, x - 1 - d, m);
168 painter.drawLine(x - 1, m + d, x - 1 - d, m);
170 painter.drawLine(x + caret_width_, m - d, x + caret_width_ + d, m);
171 painter.drawLine(x + caret_width_, m + d, x + caret_width_ + d, m);
176 void update(int x, int y, int h, bool l_shape,
177 bool rtl, bool completable)
179 color_ = guiApp->colorCache().get(Color_cursor);
182 completable_ = completable;
185 // extension to left and right
189 // RTL/LTR indication
197 // completion triangle
200 l = max(l, TabIndicatorWidth);
202 r = max(r, TabIndicatorWidth);
205 //FIXME: LyXRC::cursor_width should be caret_width
206 caret_width_ = lyxrc.cursor_width
208 : 1 + int((lyxrc.currentZoom + 50) / 200.0);
210 // compute overall rectangle
211 rect_ = QRect(x - l, y, caret_width_ + r + l, h);
214 QRect const & rect() { return rect_; }
217 /// caret is in RTL or LTR text
219 /// indication for RTL or LTR
221 /// triangle to show that a completion is available
225 /// rectangle, possibly with l_shape and completion triangle
227 /// x position (were the vertical line is drawn)
229 /// the width of the vertical blinking bar
234 // This is a 'heartbeat' generating synthetic mouse move events when the
235 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
236 SyntheticMouseEvent::SyntheticMouseEvent()
237 : timeout(200), restart_timeout(true)
241 GuiWorkArea::Private::Private(GuiWorkArea * parent)
242 : p(parent), buffer_view_(nullptr), lyx_view_(nullptr), caret_(nullptr),
243 caret_visible_(false), need_resize_(false), preedit_lines_(1),
244 last_pixel_ratio_(1.0), completer_(new GuiCompleter(p, p)),
245 dialog_mode_(false), shell_escape_(false), read_only_(false),
246 clean_(true), externally_modified_(false)
248 /* Qt on macOS and Wayland does not respect the
249 * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
250 * store at each update. Therefore, we use our own backing store in
251 * these two cases. */
252 #if QT_VERSION >= 0x050000
253 use_backingstore_ = guiApp->platformName() == "cocoa"
254 || guiApp->platformName().contains("wayland");
257 use_backingstore_ = true;
259 use_backingstore_ = false;
263 int const time = QApplication::cursorFlashTime() / 2;
265 caret_timeout_.setInterval(time);
266 caret_timeout_.start();
268 // let's initialize this just to be safe
269 caret_timeout_.setInterval(500);
274 GuiWorkArea::Private::~Private()
276 // If something is wrong with the buffer, we can ignore it safely
278 buffer_view_->buffer().workAreaManager().remove(p);
282 // Completer has a QObject parent and is thus automatically destroyed.
284 // delete completer_;
288 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
289 : d(new Private(this))
291 new CompressorProxy(this); // not a leak
295 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
296 : d(new Private(this))
298 new CompressorProxy(this); // not a leak
300 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
306 double GuiWorkArea::pixelRatio() const
308 #if QT_VERSION >= 0x050000
309 return qt_scale_factor * devicePixelRatio();
316 void GuiWorkArea::init()
319 connect(&d->caret_timeout_, SIGNAL(timeout()),
320 this, SLOT(toggleCaret()));
322 // This connection is closed at the same time as this is destroyed.
323 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
324 generateSyntheticMouseEvent();
328 // With Qt4.5 a mouse event will happen before the first paint event
329 // so make sure that the buffer view has an up to date metrics.
330 d->buffer_view_->resize(viewport()->width(), viewport()->height());
331 d->caret_ = new frontend::CaretWidget();
333 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
334 setAcceptDrops(true);
335 setMouseTracking(true);
336 setMinimumSize(100, 70);
337 setFrameStyle(QFrame::NoFrame);
340 d->updateCursorShape();
342 // we paint our own background
343 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
345 setFocusPolicy(Qt::StrongFocus);
347 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
348 << " viewport height: " << viewport()->height());
350 // Enables input methods for asian languages.
351 // Must be set when creating custom text editing widgets.
352 setAttribute(Qt::WA_InputMethodEnabled, true);
356 GuiWorkArea::~GuiWorkArea()
362 void GuiWorkArea::Private::updateCursorShape()
364 bool const clickable = buffer_view_ && buffer_view_->clickableInset();
365 p->viewport()->setCursor(clickable ? Qt::PointingHandCursor
370 void GuiWorkArea::setGuiView(GuiView & gv)
376 void GuiWorkArea::setBuffer(Buffer & buffer)
378 delete d->buffer_view_;
379 d->buffer_view_ = new BufferView(buffer);
380 buffer.workAreaManager().add(this);
382 // HACK: Prevents an additional redraw when the scrollbar pops up
383 // which regularly happens on documents with more than one page.
384 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
385 // Since we have no geometry information yet, we assume that
386 // a document needs a scrollbar if there is more then four
387 // paragraph in the outermost text.
388 if (buffer.text().paragraphs().size() > 4)
389 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
390 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
391 Q_EMIT bufferViewChanged();
395 void GuiWorkArea::fixVerticalScrollBar()
398 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
402 void GuiWorkArea::close()
404 d->lyx_view_->removeWorkArea(this);
408 void GuiWorkArea::setFullScreen(bool full_screen)
410 d->buffer_view_->setFullScreen(full_screen);
411 if (full_screen && lyxrc.full_screen_scrollbar)
412 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
414 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
418 BufferView & GuiWorkArea::bufferView()
420 return *d->buffer_view_;
424 BufferView const & GuiWorkArea::bufferView() const
426 return *d->buffer_view_;
430 void GuiWorkArea::stopBlinkingCaret()
432 d->caret_timeout_.stop();
437 void GuiWorkArea::startBlinkingCaret()
439 // do not show the cursor if the view is busy
443 // Don't start blinking if the cursor isn't on screen, unless we
444 // are not ready to know whether the cursor is on screen.
445 if (!d->buffer_view_->buffer().undo().activeUndoGroup()
446 && !d->buffer_view_->caretInView())
451 // Avoid blinking when debugging PAINTING, since it creates too much noise
452 if (!lyxerr.debugging(Debug::PAINTING)) {
453 // we are not supposed to cache this value.
454 int const time = QApplication::cursorFlashTime() / 2;
457 d->caret_timeout_.setInterval(time);
458 d->caret_timeout_.start();
463 void GuiWorkArea::toggleCaret()
465 if (d->caret_visible_)
472 void GuiWorkArea::scheduleRedraw(bool update_metrics)
475 // No need to redraw in this case.
478 // No need to do anything if this is the current view. The BufferView
479 // metrics are already up to date.
480 if (update_metrics || d->lyx_view_ != guiApp->currentView()
481 || d->lyx_view_->currentWorkArea() != this) {
482 // FIXME: it would be nice to optimize for the off-screen case.
483 d->buffer_view_->cursor().fixIfBroken();
484 d->buffer_view_->updateMetrics();
485 d->buffer_view_->cursor().fixIfBroken();
488 // update caret position, because otherwise it has to wait until
489 // the blinking interval is over
490 d->updateCaretGeometry();
492 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
493 viewport()->update();
495 /// FIXME: is this still true now that paintEvent does the actual painting?
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();
501 if (lyxerr.debugging(Debug::WORKAREA))
502 d->buffer_view_->coordCache().dump();
506 d->updateCursorShape();
510 // Keep in sync with GuiWorkArea::processKeySym below
511 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
513 return guiApp->queryKeySym(key, mod);
517 // Keep in sync with GuiWorkArea::queryKeySym above
518 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
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();
527 // In order to avoid bad surprise in the middle of an operation,
528 // we better stop the blinking caret...
529 // the caret gets restarted in GuiView::restartCaret()
531 guiApp->processKeySym(key, mod);
535 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
538 if (cmd.action() == LFUN_FILE_OPEN) {
540 lyx_view_->dispatch(cmd, dr);
544 bool const notJustMovingTheMouse =
545 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
547 // In order to avoid bad surprise in the middle of an operation, we better stop
548 // the blinking caret.
549 if (notJustMovingTheMouse)
550 p->stopBlinkingCaret();
552 buffer_view_->mouseEventDispatch(cmd);
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();
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();
570 // Show the caret immediately after any operation
571 p->startBlinkingCaret();
578 void GuiWorkArea::Private::resizeBufferView()
580 // WARNING: Please don't put any code that will trigger a repaint here!
581 // We are already inside a paint event.
582 p->stopBlinkingCaret();
583 // Warn our container (GuiView).
586 bool const caret_in_view = buffer_view_->caretInView();
587 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
589 buffer_view_->scrollToCursor();
590 updateCaretGeometry();
592 // Update scrollbars which might have changed due different
593 // BufferView dimension. This is especially important when the
594 // BufferView goes from zero-size to the real-size for the first time,
595 // as the scrollbar parameters are then set for the first time.
598 need_resize_ = false;
600 // Eventually, restart the caret after the resize event.
601 // We might be resizing even if the focus is on another widget so we only
602 // restart the caret if we have the focus.
604 QTimer::singleShot(50, p, SLOT(startBlinkingCaret()));
608 void GuiWorkArea::Private::updateCaretGeometry()
610 // we cannot update geometry if not ready and we do not need to if
611 // caret is not in view.
612 if (buffer_view_->buffer().undo().activeUndoGroup()
613 || !buffer_view_->caretInView())
618 buffer_view_->caretPosAndHeight(point, h);
621 bool l_shape = false;
622 Font const & realfont = buffer_view_->cursor().real_current_font;
623 BufferParams const & bp = buffer_view_->buffer().params();
624 bool const samelang = realfont.language() == bp.language;
625 bool const isrtl = realfont.isVisibleRightToLeft();
627 if (!samelang || isrtl != bp.language->rightToLeft())
630 // The ERT language hack needs fixing up
631 if (realfont.language() == latex_language)
634 // show caret on screen
635 Cursor & cur = buffer_view_->cursor();
636 bool completable = cur.inset().showCompletionCursor()
637 && completer_->completionAvailable()
638 && !completer_->popupVisible()
639 && !completer_->inlineVisible();
640 caret_visible_ = true;
642 caret_->update(point.x_, point.y_, h, l_shape, isrtl, completable);
646 void GuiWorkArea::Private::showCaret()
651 updateCaretGeometry();
652 p->viewport()->update();
656 void GuiWorkArea::Private::hideCaret()
661 caret_visible_ = false;
662 //if (!qApp->focusWidget())
663 p->viewport()->update();
667 void GuiWorkArea::Private::updateScrollbar()
669 // Prevent setRange() and setSliderPosition from causing recursive calls via
670 // the signal valueChanged. (#10311)
671 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
672 p, SLOT(scrollTo(int)));
673 ScrollbarParameters const & scroll = buffer_view_->scrollbarParameters();
674 p->verticalScrollBar()->setRange(scroll.min, scroll.max);
675 p->verticalScrollBar()->setPageStep(scroll.page_step);
676 p->verticalScrollBar()->setSingleStep(scroll.single_step);
677 p->verticalScrollBar()->setSliderPosition(0);
678 // Connect to the vertical scroll bar
679 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
680 p, SLOT(scrollTo(int)));
684 void GuiWorkArea::scrollTo(int value)
687 d->buffer_view_->scrollDocView(value, true);
689 if (lyxrc.cursor_follows_scrollbar) {
690 d->buffer_view_->setCursorFromScrollbar();
691 // FIXME: let GuiView take care of those.
692 d->lyx_view_->updateLayoutList();
694 // Show the caret immediately after any operation.
695 startBlinkingCaret();
698 QApplication::syncX();
703 bool GuiWorkArea::event(QEvent * e)
706 case QEvent::ToolTip: {
707 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
708 if (lyxrc.use_tooltip) {
709 QPoint pos = helpEvent->pos();
710 if (pos.x() < viewport()->width()) {
711 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
712 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
715 QToolTip::hideText();
717 // Don't forget to accept the event!
722 case QEvent::ShortcutOverride:
723 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
725 keyPressEvent(static_cast<QKeyEvent *>(e));
726 return e->isAccepted();
728 case QEvent::KeyPress: {
729 // We catch this event in order to catch the Tab or Shift+Tab key press
730 // which are otherwise reserved to focus switching between controls
732 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
733 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
734 || (ke->key() == Qt::Key_Backtab && (
735 ke->modifiers() == Qt::ShiftModifier
736 || ke->modifiers() == Qt::NoModifier))) {
740 return QAbstractScrollArea::event(e);
744 return QAbstractScrollArea::event(e);
750 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
753 if (e->reason() == QContextMenuEvent::Mouse)
754 // the menu name is set on mouse press
755 name = d->context_menu_name_;
757 QPoint pos = e->pos();
758 Cursor const & cur = d->buffer_view_->cursor();
759 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
760 // Do not access the context menu of math right in front of before
761 // the cursor. This does not work when the cursor is in text.
762 Inset * inset = cur.paragraph().getInset(cur.pos());
763 if (inset && inset->asInsetMath())
765 else if (cur.pos() > 0) {
766 inset = cur.paragraph().getInset(cur.pos() - 1);
771 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
778 // always show mnemonics when the keyboard is used to show the context menu
779 // FIXME: This should be fixed in Qt itself
780 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
781 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
786 // Position the menu to the right.
787 // FIXME: menu position should be different for RTL text.
788 menu->exec(e->globalPos());
793 void GuiWorkArea::focusInEvent(QFocusEvent * e)
795 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
796 if (d->lyx_view_->currentWorkArea() != this) {
797 d->lyx_view_->setCurrentWorkArea(this);
798 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
801 startBlinkingCaret();
802 QAbstractScrollArea::focusInEvent(e);
806 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
808 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
810 QAbstractScrollArea::focusOutEvent(e);
814 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
816 if (d->dc_event_.active && d->dc_event_ == *e) {
817 d->dc_event_.active = false;
818 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
819 q_button_state(e->button()), q_key_state(e->modifiers()));
825 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
826 inputContext()->reset();
829 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
830 q_button_state(e->button()), q_key_state(e->modifiers()));
833 // Save the context menu on mouse press, because also the mouse
834 // cursor is set on mouse press. Afterwards, we can either release
835 // the mousebutton somewhere else, or the cursor might have moved
836 // due to the DEPM. We need to do this after the mouse has been
837 // set in dispatch(), because the selection state might change.
838 if (e->button() == Qt::RightButton)
839 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
845 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
847 if (d->synthetic_mouse_event_.timeout.running())
848 d->synthetic_mouse_event_.timeout.stop();
850 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
851 q_button_state(e->button()), q_key_state(e->modifiers()));
852 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1))
853 d->synthetic_mouse_event_.cmd = cmd; // QtBug QAbstractScrollArea::mouseMoveEvent
860 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
862 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1))
863 // cancel the event if the coordinates didn't change, this is due to QtBug
864 // QAbstractScrollArea::mouseMoveEvent, the event is triggered falsely when quickly
865 // double tapping a touchpad. To test: try to select a word by quickly double tapping
866 // on a touchpad while hovering the cursor over that word in the work area.
867 // This bug does not occur on Qt versions 5.10.1 and below. Only Windows seems to be affected.
868 // ML thread: https://www.mail-archive.com/lyx-devel@lists.lyx.org/msg211699.html
869 // Qt bugtracker: https://bugreports.qt.io/browse/QTBUG-85431
870 if (e->x() == d->synthetic_mouse_event_.cmd.x() && // QtBug QAbstractScrollArea::mouseMoveEvent
871 e->y() == d->synthetic_mouse_event_.cmd.y()) // QtBug QAbstractScrollArea::mouseMoveEvent
872 return; // QtBug QAbstractScrollArea::mouseMoveEvent
875 // we kill the triple click if we move
876 doubleClickTimeout();
877 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
878 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
882 // If we're above or below the work area...
883 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
884 && e->buttons() == mouse_button::button1) {
885 // Make sure only a synthetic event can cause a page scroll,
886 // so they come at a steady rate:
888 // _Force_ a scroll up:
889 cmd.set_y(e->y() - 21);
891 cmd.set_y(e->y() + 21);
892 // Store the event, to be handled when the timeout expires.
893 d->synthetic_mouse_event_.cmd = cmd;
895 if (d->synthetic_mouse_event_.timeout.running()) {
896 // Discard the event. Note that it _may_ be handled
897 // when the timeout expires if
898 // synthetic_mouse_event_.cmd has not been overwritten.
899 // Ie, when the timeout expires, we handle the
900 // most recent event but discard all others that
901 // occurred after the one used to start the timeout
902 // in the first place.
906 d->synthetic_mouse_event_.restart_timeout = true;
907 d->synthetic_mouse_event_.timeout.start();
908 // Fall through to handle this event...
910 } else if (d->synthetic_mouse_event_.timeout.running()) {
911 // Store the event, to be possibly handled when the timeout
913 // Once the timeout has expired, normal control is returned
914 // to mouseMoveEvent (restart_timeout = false).
915 // This results in a much smoother 'feel' when moving the
916 // mouse back into the work area.
917 d->synthetic_mouse_event_.cmd = cmd;
918 d->synthetic_mouse_event_.restart_timeout = false;
925 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
927 // Wheel rotation by one notch results in a delta() of 120 (see
928 // documentation of QWheelEvent)
929 // But first we have to ignore horizontal scroll events.
930 #if QT_VERSION < 0x050000
931 if (ev->orientation() == Qt::Horizontal) {
935 double const delta = ev->delta() / 120.0;
937 QPoint const aDelta = ev->angleDelta();
938 // skip horizontal wheel event
939 if (abs(aDelta.x()) > abs(aDelta.y())) {
943 double const delta = aDelta.y() / 120.0;
947 switch (lyxrc.scroll_wheel_zoom) {
948 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
949 zoom = ev->modifiers() & Qt::ControlModifier;
950 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
952 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
953 zoom = ev->modifiers() & Qt::ShiftModifier;
954 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
956 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
957 zoom = ev->modifiers() & Qt::AltModifier;
958 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
960 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
964 docstring arg = convert<docstring>(int(5 * delta));
965 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
969 // Take into account the desktop wide settings.
970 int const lines = qApp->wheelScrollLines();
971 int const page_step = verticalScrollBar()->pageStep();
972 // Test if the wheel mouse is set to one screen at a time.
973 // This is according to
974 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
976 min(lines * verticalScrollBar()->singleStep(), page_step);
978 // Take into account the rotation and the user preferences.
979 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
980 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
981 << " delta = " << delta << " scroll_value = " << scroll_value
982 << " page_step = " << page_step);
984 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
990 void GuiWorkArea::generateSyntheticMouseEvent()
992 int const e_y = d->synthetic_mouse_event_.cmd.y();
993 int const wh = d->buffer_view_->workHeight();
994 bool const up = e_y < 0;
995 bool const down = e_y > wh;
997 // Set things off to generate the _next_ 'pseudo' event.
999 if (d->synthetic_mouse_event_.restart_timeout) {
1000 // This is some magic formulae to determine the speed
1001 // of scrolling related to the position of the mouse.
1004 int dist = up ? -e_y : e_y - wh;
1005 time = max(min(200, 250000 / (dist * dist)), 1) ;
1008 step = 80000 / (time * time);
1012 d->synthetic_mouse_event_.timeout.setTimeout(time);
1013 d->synthetic_mouse_event_.timeout.start();
1016 // Can we scroll further ?
1017 int const value = verticalScrollBar()->value();
1018 if (value == verticalScrollBar()->maximum()
1019 || value == verticalScrollBar()->minimum()) {
1020 d->synthetic_mouse_event_.timeout.stop();
1025 if (step <= 2 * wh) {
1026 d->buffer_view_->scroll(up ? -step : step);
1027 d->buffer_view_->updateMetrics();
1029 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
1032 // In which paragraph do we have to set the cursor ?
1033 Cursor & cur = d->buffer_view_->cursor();
1034 // FIXME: we don't know how to handle math.
1035 Text * text = cur.text();
1038 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
1040 // Quit gracefully if there are no metrics, since otherwise next
1041 // line would crash (bug #10324).
1042 // This situation seems related to a (not yet understood) timing problem.
1046 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
1047 ParagraphMetrics const & pm = *pp.second;
1048 pit_type const pit = pp.first;
1050 if (pm.rows().empty())
1053 // Find the row at which we set the cursor.
1054 RowList::const_iterator rit = pm.rows().begin();
1055 RowList::const_iterator rlast = pm.rows().end();
1056 int yy = pm.position() - pm.ascent();
1057 for (--rlast; rit != rlast; ++rit) {
1058 int h = rit->height();
1059 if ((up && yy + h > 0)
1060 || (!up && yy + h > wh - defaultRowHeight()))
1065 // Find the position of the cursor
1067 int x = d->synthetic_mouse_event_.cmd.x();
1068 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1073 cur.boundary(bound);
1075 d->buffer_view_->buffer().changed(false);
1080 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
1081 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
1083 qRegisterMetaType<KeySymbol>("KeySymbol");
1084 qRegisterMetaType<KeyModifier>("KeyModifier");
1085 connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
1086 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
1087 Qt::QueuedConnection);
1088 connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
1089 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1093 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1097 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1098 bool result = flag_;
1104 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1106 if (emitCheck(isAutoRepeat))
1107 Q_EMIT signal(sym, mod);
1109 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1113 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1115 // this is also called for ShortcutOverride events. In this case, one must
1116 // not act but simply accept the event explicitly.
1117 bool const act = (ev->type() != QEvent::ShortcutOverride);
1119 // Do not process here some keys if dialog_mode_ is set
1120 bool const for_dialog_mode = d->dialog_mode_
1121 && (ev->modifiers() == Qt::NoModifier
1122 || ev->modifiers() == Qt::ShiftModifier)
1123 && (ev->key() == Qt::Key_Escape
1124 || ev->key() == Qt::Key_Enter
1125 || ev->key() == Qt::Key_Return);
1126 // also do not use autoRepeat to input shortcuts
1127 bool const autoRepeat = ev->isAutoRepeat();
1129 if (for_dialog_mode || (!act && autoRepeat)) {
1134 // intercept some keys if completion popup is visible
1135 if (d->completer_->popupVisible()) {
1136 switch (ev->key()) {
1138 case Qt::Key_Return:
1140 d->completer_->activate();
1146 KeyModifier const m = q_key_state(ev->modifiers());
1148 if (act && lyxerr.debugging(Debug::KEY)) {
1150 if (m & ShiftModifier)
1152 if (m & ControlModifier)
1154 if (m & AltModifier)
1156 if (m & MetaModifier)
1158 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1159 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1160 << " keyState: " << str);
1164 setKeySymbol(&sym, ev);
1167 Q_EMIT compressKeySym(sym, m, autoRepeat);
1170 // here, !autoRepeat, as determined at the beginning
1171 ev->setAccepted(queryKeySym(sym, m));
1178 void GuiWorkArea::doubleClickTimeout()
1180 d->dc_event_.active = false;
1184 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1186 d->dc_event_ = DoubleClick(ev);
1187 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1188 SLOT(doubleClickTimeout()));
1189 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1190 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1196 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1198 QAbstractScrollArea::resizeEvent(ev);
1199 d->need_resize_ = true;
1204 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1206 if (preedit_string_.empty())
1209 // FIXME: shall we use real_current_font here? (see #10478)
1210 FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1211 FontMetrics const & fm = theFontMetrics(font);
1212 int const height = fm.maxHeight();
1213 int cur_x = caret_->rect().left();
1214 int cur_y = caret_->rect().bottom();
1216 // get attributes of input method cursor.
1217 // cursor_pos : cursor position in preedit string.
1218 size_t cursor_pos = 0;
1219 bool cursor_is_visible = false;
1220 for (auto const & attr : preedit_attr_) {
1221 if (attr.type == QInputMethodEvent::Cursor) {
1222 cursor_pos = size_t(attr.start);
1223 cursor_is_visible = attr.length != 0;
1228 size_t const preedit_length = preedit_string_.length();
1230 // get position of selection in input method.
1231 // FIXME: isn't there a simpler way to do this?
1232 // rStart : cursor position in selected string in IM.
1234 // rLength : selected string length in IM.
1236 if (cursor_pos < preedit_length) {
1237 for (auto const & attr : preedit_attr_) {
1238 if (attr.type == QInputMethodEvent::TextFormat) {
1239 if (attr.start <= int(cursor_pos)
1240 && int(cursor_pos) < attr.start + attr.length) {
1241 rStart = size_t(attr.start);
1242 rLength = size_t(attr.length);
1243 if (!cursor_is_visible)
1244 cursor_pos += rLength;
1251 rStart = cursor_pos;
1255 int const right_margin = buffer_view_->rightMargin();
1256 Painter::preedit_style ps;
1257 // Most often there would be only one line:
1259 for (size_t pos = 0; pos != preedit_length; ++pos) {
1260 char_type const typed_char = preedit_string_[pos];
1261 // reset preedit string style
1262 ps = Painter::preedit_default;
1264 // if we reached the right extremity of the screen, go to next line.
1265 if (cur_x + fm.width(typed_char) > p->viewport()->width() - right_margin) {
1266 cur_x = right_margin;
1267 cur_y += height + 1;
1270 // preedit strings are displayed with dashed underline
1271 // and partial strings are displayed white on black indicating
1272 // that we are in selecting mode in the input method.
1273 // FIXME: rLength == preedit_length is not a changing condition
1274 // FIXME: should be put out of the loop.
1276 && pos < rStart + rLength
1277 && !(cursor_pos < rLength && rLength == preedit_length))
1278 ps = Painter::preedit_selecting;
1280 if (pos == cursor_pos
1281 && (cursor_pos < rLength && rLength == preedit_length))
1282 ps = Painter::preedit_cursor;
1284 // draw one character and update cur_x.
1285 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1290 void GuiWorkArea::Private::resetScreen()
1292 if (use_backingstore_) {
1293 int const pr = p->pixelRatio();
1294 screen_ = QImage(static_cast<int>(pr * p->viewport()->width()),
1295 static_cast<int>(pr * p->viewport()->height()),
1296 QImage::Format_ARGB32_Premultiplied);
1297 # if QT_VERSION >= 0x050000
1298 screen_.setDevicePixelRatio(pr);
1304 QPaintDevice * GuiWorkArea::Private::screenDevice()
1306 if (use_backingstore_)
1309 return p->viewport();
1313 void GuiWorkArea::Private::updateScreen(QRectF const & rc)
1315 if (use_backingstore_) {
1316 QPainter qpain(p->viewport());
1317 double const pr = p->pixelRatio();
1318 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr,
1319 rc.width() * pr, rc.height() * pr);
1320 qpain.drawImage(rc, screen_, rcs);
1325 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1327 // Do not trigger the painting machinery if we are not ready (see
1328 // bug #10989). The second test triggers when in the middle of a
1329 // dispatch operation.
1330 if (view().busy() || d->buffer_view_->buffer().undo().activeUndoGroup()) {
1331 // Since macOS has turned the screen black at this point, our
1332 // backing store has to be copied to screen (this is a no-op
1333 // except on macOS).
1334 d->updateScreen(ev->rect());
1335 // Ignore this paint event, but request a new one for later.
1336 viewport()->update(ev->rect());
1341 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1342 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1344 if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_) {
1346 d->resizeBufferView();
1349 d->last_pixel_ratio_ = pixelRatio();
1351 GuiPainter pain(d->screenDevice(), pixelRatio(), d->lyx_view_->develMode());
1353 d->buffer_view_->draw(pain, d->caret_visible_);
1355 // The preedit text, if needed
1356 d->paintPreeditText(pain);
1359 if (d->caret_visible_)
1360 d->caret_->draw(pain, d->buffer_view_->horizScrollOffset());
1362 d->updateScreen(ev->rect());
1368 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1370 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1371 << " commitString: " << e->commitString());
1373 // insert the processed text in the document (handles undo)
1374 if (!e->commitString().isEmpty()) {
1375 FuncRequest cmd(LFUN_SELF_INSERT,
1376 qstring_to_ucs4(e->commitString()),
1377 FuncRequest::KEYBOARD);
1379 // FIXME: this is supposed to remove traces from preedit
1380 // string. Can we avoid calling it explicitly?
1381 d->buffer_view_->updateMetrics();
1384 // Hide the caret during the test transformation.
1385 if (e->preeditString().isEmpty())
1386 startBlinkingCaret();
1388 stopBlinkingCaret();
1390 if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1396 // The preedit text and its attributes will be used in paintPreeditText
1397 d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1398 d->preedit_attr_ = e->attributes();
1401 // redraw area of preedit string.
1402 int height = d->caret_->rect().height();
1403 int cur_y = d->caret_->rect().bottom();
1404 viewport()->update(0, cur_y - height, viewport()->width(),
1405 (height + 1) * d->preedit_lines_);
1407 if (d->preedit_string_.empty()) {
1408 d->preedit_lines_ = 1;
1413 // Don't forget to accept the event!
1418 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1420 QRect cur_r(0, 0, 0, 0);
1422 // this is the CJK-specific composition window position and
1423 // the context menu position when the menu key is pressed.
1424 case Qt::ImMicroFocus:
1425 cur_r = d->caret_->rect();
1426 if (d->preedit_lines_ != 1)
1428 cur_r.moveBottom(cur_r.bottom()
1429 + cur_r.height() * (d->preedit_lines_ - 1));
1430 // return lower right of caret in LyX.
1433 return QWidget::inputMethodQuery(query);
1438 void GuiWorkArea::updateWindowTitle()
1440 Buffer const & buf = bufferView().buffer();
1441 if (buf.fileName() != d->file_name_
1442 || buf.params().shell_escape != d->shell_escape_
1443 || buf.hasReadonlyFlag() != d->read_only_
1444 || buf.lyxvc().vcstatus() != d->vc_status_
1445 || buf.isClean() != d->clean_
1446 || buf.notifiesExternalModification() != d->externally_modified_) {
1447 d->file_name_ = buf.fileName();
1448 d->shell_escape_ = buf.params().shell_escape;
1449 d->read_only_ = buf.hasReadonlyFlag();
1450 d->vc_status_ = buf.lyxvc().vcstatus();
1451 d->clean_ = buf.isClean();
1452 d->externally_modified_ = buf.notifiesExternalModification();
1453 Q_EMIT titleChanged(this);
1458 bool GuiWorkArea::isFullScreen() const
1460 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1464 bool GuiWorkArea::inDialogMode() const
1466 return d->dialog_mode_;
1470 void GuiWorkArea::setDialogMode(bool mode)
1472 d->dialog_mode_ = mode;
1476 GuiCompleter & GuiWorkArea::completer()
1478 return *d->completer_;
1481 GuiView const & GuiWorkArea::view() const
1483 return *d->lyx_view_;
1487 GuiView & GuiWorkArea::view()
1489 return *d->lyx_view_;
1492 ////////////////////////////////////////////////////////////////////
1496 ////////////////////////////////////////////////////////////////////
1499 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1501 support::TempFile tempfile("embedded.internal");
1502 tempfile.setAutoRemove(false);
1503 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1504 buffer_->setUnnamed(true);
1505 buffer_->setFullyLoaded(true);
1506 setBuffer(*buffer_);
1507 setDialogMode(true);
1511 EmbeddedWorkArea::~EmbeddedWorkArea()
1513 // No need to destroy buffer and bufferview here, because it is done
1514 // in theBufferList() destruction loop at application exit
1518 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1521 GuiWorkArea::closeEvent(ev);
1525 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1528 GuiWorkArea::hideEvent(ev);
1532 QSize EmbeddedWorkArea::sizeHint () const
1535 // GuiWorkArea sets the size to the screen's viewport
1536 // by returning a value this gets overridden
1537 // EmbeddedWorkArea is now sized to fit in the layout
1538 // of the parent, and has a minimum size set in GuiWorkArea
1539 // which is what we return here
1540 return QSize(100, 70);
1544 void EmbeddedWorkArea::disable()
1546 stopBlinkingCaret();
1547 if (view().currentWorkArea() != this)
1549 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1550 // tolerates it and shows the background logo), what happens if
1551 // an EmbeddedWorkArea is closed after closing all document WAs
1552 view().setCurrentWorkArea(view().currentMainWorkArea());
1555 ////////////////////////////////////////////////////////////////////
1559 ////////////////////////////////////////////////////////////////////
1562 class NoTabFrameMacStyle : public QProxyStyle {
1565 QRect subElementRect(SubElement element, const QStyleOption * option,
1566 const QWidget * widget = 0) const
1568 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1569 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1571 // The Qt Mac style puts the contents into a 3 pixel wide box
1572 // which looks very ugly and not like other Mac applications.
1573 // Hence we remove this here, and moreover the 16 pixel round
1574 // frame above if the tab bar is hidden.
1575 if (element == QStyle::SE_TabWidgetTabContents) {
1576 rect.adjust(- rect.left(), 0, rect.left(), 0);
1585 NoTabFrameMacStyle noTabFrameMacStyle;
1589 TabWorkArea::TabWorkArea(QWidget * parent)
1590 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1593 setStyle(&noTabFrameMacStyle);
1596 QPalette pal = palette();
1597 pal.setColor(QPalette::Active, QPalette::Button,
1598 pal.color(QPalette::Active, QPalette::Window));
1599 pal.setColor(QPalette::Disabled, QPalette::Button,
1600 pal.color(QPalette::Disabled, QPalette::Window));
1601 pal.setColor(QPalette::Inactive, QPalette::Button,
1602 pal.color(QPalette::Inactive, QPalette::Window));
1604 QObject::connect(this, SIGNAL(currentChanged(int)),
1605 this, SLOT(on_currentTabChanged(int)));
1607 closeBufferButton = new QToolButton(this);
1608 closeBufferButton->setPalette(pal);
1609 // FIXME: rename the icon to closebuffer.png
1610 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1611 closeBufferButton->setText("Close File");
1612 closeBufferButton->setAutoRaise(true);
1613 closeBufferButton->setCursor(Qt::ArrowCursor);
1614 closeBufferButton->setToolTip(qt_("Close File"));
1615 closeBufferButton->setEnabled(true);
1616 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1617 this, SLOT(closeCurrentBuffer()));
1618 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1620 // set TabBar behaviour
1621 QTabBar * tb = tabBar();
1622 tb->setTabsClosable(!lyxrc.single_close_tab_button);
1623 tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1624 tb->setElideMode(Qt::ElideNone);
1625 // allow dragging tabs
1626 tb->setMovable(true);
1627 // make us responsible for the context menu of the tabbar
1628 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1629 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1630 this, SLOT(showContextMenu(const QPoint &)));
1631 connect(tb, SIGNAL(tabCloseRequested(int)),
1632 this, SLOT(closeTab(int)));
1634 setUsesScrollButtons(true);
1638 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1640 if (me->button() == Qt::MidButton)
1641 midpressed_tab_ = tabBar()->tabAt(me->pos());
1643 QTabWidget::mousePressEvent(me);
1647 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1649 if (me->button() == Qt::MidButton) {
1650 int const midreleased_tab = tabBar()->tabAt(me->pos());
1651 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1652 closeTab(midreleased_tab);
1654 QTabWidget::mouseReleaseEvent(me);
1658 void TabWorkArea::paintEvent(QPaintEvent * event)
1660 if (tabBar()->isVisible()) {
1661 QTabWidget::paintEvent(event);
1663 // Prevent the selected tab to influence the
1664 // painting of the frame of the tab widget.
1665 // This is needed for gtk style in Qt.
1666 QStylePainter p(this);
1667 #if QT_VERSION < 0x050000
1668 QStyleOptionTabWidgetFrameV2 opt;
1670 QStyleOptionTabWidgetFrame opt;
1672 initStyleOption(&opt);
1673 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1675 opt.selectedTabRect = QRect();
1676 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1681 bool TabWorkArea::posIsTab(QPoint position)
1683 // tabAt returns -1 if tab does not covers position
1684 return tabBar()->tabAt(position) > -1;
1688 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1690 if (event->button() != Qt::LeftButton)
1693 // this code chunk is unnecessary because it seems the event only makes
1694 // it this far if it is not on a tab. I'm not sure why this is (maybe
1695 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1696 // this is true in all cases and if it will be true in the future so I
1697 // leave this code for now. (skostysh, 2016-07-21)
1699 // return early if double click on existing tabs
1700 if (posIsTab(event->pos()))
1703 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1707 void TabWorkArea::setFullScreen(bool full_screen)
1709 for (int i = 0; i != count(); ++i) {
1710 if (GuiWorkArea * wa = workArea(i))
1711 wa->setFullScreen(full_screen);
1714 if (lyxrc.full_screen_tabbar)
1715 showBar(!full_screen && count() > 1);
1717 showBar(count() > 1);
1721 void TabWorkArea::showBar(bool show)
1723 tabBar()->setEnabled(show);
1724 tabBar()->setVisible(show);
1725 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1726 setTabsClosable(!lyxrc.single_close_tab_button);
1730 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1732 QWidget * w = QTabWidget::widget(index);
1735 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1741 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1743 return widget(currentIndex());
1747 GuiWorkArea * TabWorkArea::workArea(int index) const
1749 GuiWorkAreaContainer * w = widget(index);
1752 return w->workArea();
1756 GuiWorkArea * TabWorkArea::currentWorkArea() const
1758 return workArea(currentIndex());
1762 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1764 // FIXME: this method doesn't work if we have more than one work area
1765 // showing the same buffer.
1766 for (int i = 0; i != count(); ++i) {
1767 GuiWorkArea * wa = workArea(i);
1768 LASSERT(wa, return nullptr);
1769 if (&wa->bufferView().buffer() == &buffer)
1776 void TabWorkArea::closeAll()
1779 QWidget * wac = widget(0);
1780 LASSERT(wac, return);
1787 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1789 for (int index = 0; index < count(); ++index)
1790 if (workArea(index) == w)
1796 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1798 LASSERT(work_area, return false);
1799 int index = indexOfWorkArea(work_area);
1803 if (index == currentIndex())
1804 // Make sure the work area is up to date.
1805 on_currentTabChanged(index);
1807 // Switch to the work area.
1808 setCurrentIndex(index);
1809 work_area->setFocus();
1815 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1817 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1818 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1819 wa->setUpdatesEnabled(false);
1820 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1821 // when hiding it again below).
1822 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1823 showBar(count() > 0);
1824 addTab(wac, wa->windowTitle());
1825 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1826 this, SLOT(updateTabTexts()));
1827 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1828 setFullScreen(true);
1830 // Hide tabbar if there's only one tab.
1831 showBar(count() > 1);
1839 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1841 LASSERT(work_area, return false);
1842 int index = indexOfWorkArea(work_area);
1846 work_area->setUpdatesEnabled(false);
1847 QWidget * wac = widget(index);
1852 // make sure the next work area is enabled.
1853 currentWidget()->setUpdatesEnabled(true);
1854 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1855 setFullScreen(true);
1857 // Show tabbar only if there's more than one tab.
1858 showBar(count() > 1);
1860 lastWorkAreaRemoved();
1868 void TabWorkArea::on_currentTabChanged(int i)
1870 // returns e.g. on application destruction
1873 GuiWorkArea * wa = workArea(i);
1874 LASSERT(wa, return);
1875 wa->setUpdatesEnabled(true);
1876 wa->scheduleRedraw(true);
1879 currentWorkAreaChanged(wa);
1881 LYXERR(Debug::GUI, "currentTabChanged " << i
1882 << " File: " << wa->bufferView().buffer().absFileName());
1886 void TabWorkArea::closeCurrentBuffer()
1889 if (clicked_tab_ == -1)
1890 wa = currentWorkArea();
1892 wa = workArea(clicked_tab_);
1893 LASSERT(wa, return);
1895 wa->view().closeWorkArea(wa);
1899 void TabWorkArea::hideCurrentTab()
1902 if (clicked_tab_ == -1)
1903 wa = currentWorkArea();
1905 wa = workArea(clicked_tab_);
1906 LASSERT(wa, return);
1908 wa->view().hideWorkArea(wa);
1912 void TabWorkArea::closeTab(int index)
1914 on_currentTabChanged(index);
1917 wa = currentWorkArea();
1919 wa = workArea(index);
1920 LASSERT(wa, return);
1922 wa->view().closeWorkArea(wa);
1929 /// make vector happy
1930 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1932 DisplayPath(int tab, FileName const & filename)
1935 // Recode URL encoded chars via fromPercentEncoding()
1936 string const fn = (filename.extension() == "lyx")
1937 ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
1938 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
1939 postfix_ = toqstr(filename.absoluteFilePath()).
1940 split("/", QString::SkipEmptyParts);
1941 postfix_.pop_back();
1942 abs_ = toqstr(filename.absoluteFilePath());
1943 dottedPrefix_ = false;
1946 /// Absolute path for debugging.
1951 /// Add the first segment from the postfix or three dots to the prefix.
1952 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1953 /// when really needed.
1954 void shiftPathSegment(bool dotted)
1956 if (postfix_.count() <= 0)
1960 if (dottedPrefix_ && !prefix_.isEmpty())
1961 prefix_ += ellipsisSlash_;
1962 prefix_ += postfix_.front() + "/";
1964 dottedPrefix_ = dotted && !prefix_.isEmpty();
1965 postfix_.pop_front();
1968 QString displayString() const
1970 if (prefix_.isEmpty())
1973 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1974 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1977 QString forecastPathString() const
1979 if (postfix_.count() == 0)
1980 return displayString();
1983 + (dottedPrefix_ ? ellipsisSlash_ : "")
1984 + postfix_.front() + "/";
1987 bool final() const { return postfix_.empty(); }
1989 int tab() const { return tab_; }
1993 static QString const ellipsisSlash_;
1997 QStringList postfix_;
2009 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
2013 bool operator<(DisplayPath const & a, DisplayPath const & b)
2015 return a.displayString() < b.displayString();
2019 bool operator==(DisplayPath const & a, DisplayPath const & b)
2021 return a.displayString() == b.displayString();
2025 void TabWorkArea::updateTabTexts()
2027 int const n = count();
2030 std::list<DisplayPath> paths;
2031 typedef std::list<DisplayPath>::iterator It;
2033 // collect full names first: path into postfix, empty prefix and
2034 // filename without extension
2035 for (int i = 0; i < n; ++i) {
2036 GuiWorkArea * i_wa = workArea(i);
2037 FileName const fn = i_wa->bufferView().buffer().fileName();
2038 paths.push_back(DisplayPath(i, fn));
2041 // go through path segments and see if it helps to make the path more unique
2042 bool somethingChanged = true;
2043 bool allFinal = false;
2044 while (somethingChanged && !allFinal) {
2045 // adding path segments changes order
2048 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
2049 somethingChanged = false;
2052 // find segments which are not unique (i.e. non-atomic)
2053 It it = paths.begin();
2055 QString segString = it->displayString();
2056 for (; it != paths.end(); ++it) {
2057 // look to the next item
2062 allFinal = allFinal && it->final();
2064 LYXERR(Debug::GUI, "it = " << it->abs()
2065 << " => " << it->displayString());
2067 // still the same segment?
2069 if ((next != paths.end()
2070 && (nextString = next->displayString()) == segString))
2072 LYXERR(Debug::GUI, "segment ended");
2074 // only a trivial one with one element?
2075 if (it == segStart) {
2076 // start new segment
2078 segString = nextString;
2082 // We found a non-atomic segment
2083 // We know that segStart <= it < next <= paths.end().
2084 // The assertion below tells coverity about it.
2085 LATTEST(segStart != paths.end());
2086 QString dspString = segStart->forecastPathString();
2087 LYXERR(Debug::GUI, "first forecast found for "
2088 << segStart->abs() << " => " << dspString);
2091 // Shift path segments and hope for the best
2092 // that it makes the path more unique.
2093 somethingChanged = true;
2094 bool moreUnique = false;
2095 for (; sit != next; ++sit) {
2096 if (sit->forecastPathString() != dspString) {
2097 LYXERR(Debug::GUI, "different forecast found for "
2098 << sit->abs() << " => " << sit->forecastPathString());
2102 LYXERR(Debug::GUI, "same forecast found for "
2103 << sit->abs() << " => " << dspString);
2106 // if the path segment helped, add it. Otherwise add dots
2107 bool dots = !moreUnique;
2108 LYXERR(Debug::GUI, "using dots = " << dots);
2109 for (sit = segStart; sit != next; ++sit) {
2110 sit->shiftPathSegment(dots);
2111 LYXERR(Debug::GUI, "shifting "
2112 << sit->abs() << " => " << sit->displayString());
2115 // start new segment
2117 segString = nextString;
2121 // set new tab titles
2122 for (It it = paths.begin(); it != paths.end(); ++it) {
2123 int const tab_index = it->tab();
2124 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2125 QString tab_text = it->displayString().replace("&", "&&");
2126 if (!buf.fileName().empty() && !buf.isClean())
2128 QString tab_tooltip = it->abs();
2129 if (buf.hasReadonlyFlag()) {
2130 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2131 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2133 setTabIcon(tab_index, QIcon());
2134 if (buf.notifiesExternalModification()) {
2135 QString const warn = qt_("%1 (modified externally)");
2136 tab_tooltip = warn.arg(tab_tooltip);
2137 tab_text += QChar(0x26a0);
2139 setTabText(tab_index, tab_text);
2140 setTabToolTip(tab_index, tab_tooltip);
2145 void TabWorkArea::showContextMenu(const QPoint & pos)
2148 clicked_tab_ = tabBar()->tabAt(pos);
2149 if (clicked_tab_ == -1)
2152 GuiWorkArea * wa = workArea(clicked_tab_);
2153 LASSERT(wa, return);
2157 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2158 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2160 // we want to show the 'close' option only if this is not a child buffer.
2161 Buffer const & buf = wa->bufferView().buffer();
2163 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2164 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2165 popup.exec(tabBar()->mapToGlobal(pos));
2171 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2173 QWidget * w = widget(fromIndex);
2174 QIcon icon = tabIcon(fromIndex);
2175 QString text = tabText(fromIndex);
2177 setCurrentIndex(fromIndex);
2178 removeTab(fromIndex);
2179 insertTab(toIndex, w, icon, text);
2180 setCurrentIndex(toIndex);
2184 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2185 : QWidget(parent), wa_(wa)
2187 LASSERT(wa, return);
2188 Ui::WorkAreaUi::setupUi(this);
2189 layout()->addWidget(wa);
2190 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2191 this, SLOT(updateDisplay()));
2192 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2193 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2194 setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2199 void GuiWorkAreaContainer::updateDisplay()
2201 Buffer const & buf = wa_->bufferView().buffer();
2202 notificationFrame->setHidden(!buf.notifiesExternalModification());
2203 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2204 .arg(toqstr(buf.fileName().displayName()));
2205 externalModificationLabel->setText(label);
2209 void GuiWorkAreaContainer::dispatch(FuncRequest f) const
2211 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2212 wa_->bufferView().buffer().absFileName()));
2217 void GuiWorkAreaContainer::reload() const
2219 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2223 void GuiWorkAreaContainer::ignore() const
2225 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2229 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2231 // prevent TabWorkArea from opening a new buffer on double click
2236 } // namespace frontend
2239 #include "moc_GuiWorkArea.cpp"