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 "GuiApplication.h"
19 #include "GuiCompleter.h"
20 #include "GuiKeySymbol.h"
21 #include "GuiPainter.h"
24 #include "qt_helpers.h"
27 #include "BufferList.h"
28 #include "BufferParams.h"
29 #include "BufferView.h"
30 #include "CoordCache.h"
33 #include "FuncRequest.h"
35 #include "KeySymbol.h"
36 #include "KeySequence.h"
41 #include "TextMetrics.h"
44 #include "support/convert.h"
45 #include "support/debug.h"
46 #include "support/lassert.h"
47 #include "support/TempFile.h"
49 #include "frontends/Application.h"
50 #include "frontends/CaretGeometry.h"
51 #include "frontends/FontMetrics.h"
52 #include "frontends/WorkAreaManager.h"
54 #include <QContextMenuEvent>
57 #include <QInputMethod>
59 #include <QProxyStyle>
61 #include <QMainWindow>
67 #include <QStyleOption>
68 #include <QStylePainter>
70 #include <QToolButton>
81 using namespace lyx::support;
86 /// return the LyX mouse button state from Qt's
87 static mouse_button::state q_button_state(Qt::MouseButton button)
89 mouse_button::state b = mouse_button::none;
92 b = mouse_button::button1;
94 case Qt::MiddleButton:
95 b = mouse_button::button2;
98 b = mouse_button::button3;
107 /// return the LyX mouse button state from Qt's
108 mouse_button::state q_motion_state(Qt::MouseButtons state)
110 mouse_button::state b = mouse_button::none;
111 if (state & Qt::LeftButton)
112 b |= mouse_button::button1;
113 if (state & Qt::MiddleButton)
114 b |= mouse_button::button2;
115 if (state & Qt::RightButton)
116 b |= mouse_button::button3;
123 // This is a 'heartbeat' generating synthetic mouse move events when the
124 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
125 SyntheticMouseEvent::SyntheticMouseEvent()
126 : timeout(200), restart_timeout(true)
130 GuiWorkArea::Private::Private(GuiWorkArea * parent)
131 : p(parent), completer_(new GuiCompleter(p, p))
133 use_backingstore_ = lyxrc.draw_strategy == LyXRC::DS_BACKINGSTORE
134 || (lyxrc.draw_strategy == LyXRC::DS_PARTIAL && guiApp->noPartialDraw());
135 if (use_backingstore_)
136 LYXERR(Debug::WORKAREA, "Drawing strategy: partial draw on backing store");
138 LYXERR(Debug::WORKAREA, "Drawing strategy: "
139 << (lyxrc.draw_strategy == LyXRC::DS_PARTIAL ? "partial draw"
142 int const time = QApplication::cursorFlashTime() / 2;
144 caret_timeout_.setInterval(time);
145 caret_timeout_.start();
147 // let's initialize this just to be safe
148 caret_timeout_.setInterval(500);
153 GuiWorkArea::Private::~Private()
155 // If something is wrong with the buffer, we can ignore it safely
157 buffer_view_->buffer().workAreaManager().remove(p);
160 // Completer has a QObject parent and is thus automatically destroyed.
162 // delete completer_;
166 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
167 : d(new Private(this))
169 new CompressorProxy(this); // not a leak
173 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
174 : d(new Private(this))
176 new CompressorProxy(this); // not a leak
178 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
184 double GuiWorkArea::pixelRatio() const
186 #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
187 return devicePixelRatioF();
189 return devicePixelRatio();
194 void GuiWorkArea::init()
197 connect(&d->caret_timeout_, SIGNAL(timeout()),
198 this, SLOT(toggleCaret()));
200 // This connection is closed at the same time as this is destroyed.
201 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
202 generateSyntheticMouseEvent();
207 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
208 setAcceptDrops(true);
209 setMouseTracking(true);
210 setMinimumSize(100, 70);
211 setFrameStyle(QFrame::NoFrame);
214 d->updateCursorShape();
216 // we paint our own background
217 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
219 setFocusPolicy(Qt::StrongFocus);
221 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
222 << " viewport height: " << viewport()->height());
224 // Enables input methods for asian languages.
225 // Must be set when creating custom text editing widgets.
226 setAttribute(Qt::WA_InputMethodEnabled, true);
228 // Initialize d->im_cursor_rect_
231 d->buffer_view_->caretPosAndDim(point, dim);
232 int cur_x = point.x_ - dim.width();
233 int cur_y = point.y_ + dim.height();
234 d->im_cursor_rect_ = QRectF(cur_x, (cur_y - dim.height()) , 1, dim.height() );
238 GuiWorkArea::~GuiWorkArea()
244 void GuiWorkArea::Private::updateCursorShape()
246 bool const clickable = buffer_view_ && buffer_view_->clickableInset();
247 p->viewport()->setCursor(clickable ? Qt::PointingHandCursor
252 void GuiWorkArea::setGuiView(GuiView & gv)
258 void GuiWorkArea::setBuffer(Buffer & buffer)
260 delete d->buffer_view_;
261 d->buffer_view_ = new BufferView(buffer);
262 buffer.workAreaManager().add(this);
264 // HACK: Prevents an additional redraw when the scrollbar pops up
265 // which regularly happens on documents with more than one page.
266 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
267 // Since we have no geometry information yet, we assume that
268 // a document needs a scrollbar if there is more then four
269 // paragraph in the outermost text.
270 if (buffer.text().paragraphs().size() > 4)
271 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
272 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
273 Q_EMIT bufferViewChanged();
277 void GuiWorkArea::fixVerticalScrollBar()
280 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
284 void GuiWorkArea::close()
286 d->lyx_view_->removeWorkArea(this);
290 void GuiWorkArea::setFullScreen(bool full_screen)
292 d->buffer_view_->setFullScreen(full_screen);
294 queryInputItemTransform();
296 if (full_screen && lyxrc.full_screen_scrollbar)
297 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
299 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
303 BufferView & GuiWorkArea::bufferView()
305 return *d->buffer_view_;
309 BufferView const & GuiWorkArea::bufferView() const
311 return *d->buffer_view_;
315 void GuiWorkArea::stopBlinkingCaret()
317 d->caret_timeout_.stop();
322 void GuiWorkArea::startBlinkingCaret()
324 // do not show the cursor if the view is busy
328 // Don't start blinking if the cursor isn't on screen, unless we
329 // are not ready to know whether the cursor is on screen.
330 if (!d->buffer_view_->busy() && !d->buffer_view_->caretInView())
335 // Avoid blinking when debugging PAINTING, since it creates too much noise
336 if (!lyxerr.debugging(Debug::PAINTING)) {
337 // we are not supposed to cache this value.
338 int const time = QApplication::cursorFlashTime() / 2;
341 d->caret_timeout_.setInterval(time);
342 d->caret_timeout_.start();
347 void GuiWorkArea::toggleCaret()
349 if (d->caret_visible_)
356 void GuiWorkArea::scheduleRedraw(bool update_metrics)
358 if (!isVisible() || view().busy())
359 // No need to redraw in this case.
362 // No need to do anything if this is the current view. The BufferView
363 // metrics are already up to date.
364 if (update_metrics || d->lyx_view_ != guiApp->currentView()
365 || d->lyx_view_->currentWorkArea() != this) {
366 // FIXME: it would be nice to optimize for the off-screen case.
367 d->buffer_view_->cursor().fixIfBroken();
368 d->buffer_view_->updateMetrics();
369 d->buffer_view_->cursor().fixIfBroken();
372 // update caret position, because otherwise it has to wait until
373 // the blinking interval is over
376 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
377 viewport()->update();
379 /// FIXME: is this still true now that paintEvent does the actual painting?
380 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
381 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
382 d->updateScrollbar();
383 d->lyx_view_->updateStatusBar();
385 if (lyxerr.debugging(Debug::WORKAREA))
386 d->buffer_view_->coordCache().dump();
390 d->updateCursorShape();
394 // Keep in sync with GuiWorkArea::processKeySym below
395 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
397 return guiApp->queryKeySym(key, mod);
401 // Keep in sync with GuiWorkArea::queryKeySym above
402 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
404 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
405 && lyxrc.full_screen_menubar) {
406 // FIXME HACK: we should not have to do this here. See related comment
407 // in GuiView::event() (QEvent::ShortcutOverride)
408 d->lyx_view_->menuBar()->hide();
411 // In order to avoid bad surprise in the middle of an operation,
412 // we better stop the blinking caret...
413 // the caret gets restarted in GuiView::restartCaret()
415 guiApp->processKeySym(key, mod);
419 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
422 if (cmd.action() == LFUN_FILE_OPEN) {
424 lyx_view_->dispatch(cmd, dr);
428 bool const notJustMovingTheMouse =
429 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
431 // In order to avoid bad surprise in the middle of an operation, we better stop
432 // the blinking caret.
433 if (notJustMovingTheMouse)
434 p->stopBlinkingCaret();
436 buffer_view_->mouseEventDispatch(cmd);
438 // Skip these when selecting
439 // FIXME: let GuiView take care of those.
440 if (notJustMovingTheMouse && !buffer_view_->mouseSelecting()) {
441 completer_->updateVisibility(false, false);
442 lyx_view_->updateDialogs();
443 lyx_view_->updateStatusBar();
446 // GUI tweaks except with mouse motion with no button pressed.
447 if (notJustMovingTheMouse) {
448 // Slight hack: this is only called currently when we
449 // clicked somewhere, so we force through the display
450 // of the new status here.
451 // FIXME: let GuiView take care of those.
452 lyx_view_->clearMessage();
454 // Show the caret immediately after any operation
455 p->startBlinkingCaret();
462 void GuiWorkArea::resizeBufferView()
464 // WARNING: Please don't put any code that will trigger a repaint here!
465 // We are already inside a paint event.
467 // Warn our container (GuiView).
470 bool const caret_in_view = d->buffer_view_->caretInView();
471 // Change backing store size if needed
473 // Do the actual work: recompute metrics
474 d->buffer_view_->resize(viewport()->width(), viewport()->height());
476 d->buffer_view_->showCursor();
479 // Update scrollbars which might have changed due different
480 // BufferView dimension. This is especially important when the
481 // BufferView goes from zero-size to the real-size for the first time,
482 // as the scrollbar parameters are then set for the first time.
483 d->updateScrollbar();
485 d->need_resize_ = false;
487 // Eventually, restart the caret after the resize event.
488 // We might be resizing even if the focus is on another widget so we only
489 // restart the caret if we have the focus.
491 QTimer::singleShot(50, this, SLOT(startBlinkingCaret()));
495 void GuiWorkArea::Private::resetCaret()
497 // Don't start blinking if the cursor isn't on screen or the window
498 // does not have focus
499 if (!buffer_view_->caretInView() || !p->hasFocus())
502 needs_caret_geometry_update_ = true;
503 caret_visible_ = true;
507 void GuiWorkArea::Private::updateCaretGeometry()
509 // we cannot update geometry if not ready and we do not need to if
510 // caret is not in view.
511 if (buffer_view_->busy() || !buffer_view_->caretInView())
514 // completion indicator
515 Cursor const & cur = buffer_view_->cursor();
516 bool const completable = cur.inset().showCompletionCursor()
517 && completer_->completionAvailable()
518 && !completer_->popupVisible()
519 && !completer_->inlineVisible();
521 buffer_view_->buildCaretGeometry(completable);
523 needs_caret_geometry_update_ = false;
527 void GuiWorkArea::Private::showCaret()
533 p->viewport()->update();
537 void GuiWorkArea::Private::hideCaret()
542 caret_visible_ = false;
543 //if (!qApp->focusWidget())
544 p->viewport()->update();
548 /* Draw the caret. Parameter \c horiz_offset is not 0 when there
549 * has been horizontal scrolling in current row
551 void GuiWorkArea::Private::drawCaret(QPainter & painter, int horiz_offset) const
553 if (buffer_view_->caretGeometry().shapes.empty())
556 QColor const color = guiApp->colorCache().get(Color_cursor);
557 painter.setPen(color);
558 painter.setRenderHint(QPainter::Antialiasing, true);
559 for (auto const & shape : buffer_view_->caretGeometry().shapes) {
562 for (Point const & p : shape) {
564 path.moveTo(p.x_ - horiz_offset, p.y_);
567 path.lineTo(p.x_ - horiz_offset, p.y_);
569 painter.fillPath(path, color);
571 painter.setRenderHint(QPainter::Antialiasing, false);
575 void GuiWorkArea::Private::updateScrollbar()
577 // Prevent setRange() and setSliderPosition from causing recursive calls via
578 // the signal valueChanged. (#10311)
579 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
580 p, SLOT(scrollTo(int)));
581 ScrollbarParameters const & scroll = buffer_view_->scrollbarParameters();
582 p->verticalScrollBar()->setRange(scroll.min, scroll.max);
583 p->verticalScrollBar()->setPageStep(scroll.page_step);
584 p->verticalScrollBar()->setSingleStep(scroll.single_step);
585 p->verticalScrollBar()->setSliderPosition(0);
586 // Connect to the vertical scroll bar
587 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
588 p, SLOT(scrollTo(int)));
592 void GuiWorkArea::scrollTo(int value)
595 d->buffer_view_->scrollDocView(value, true);
597 if (lyxrc.cursor_follows_scrollbar) {
598 d->buffer_view_->setCursorFromScrollbar();
599 // FIXME: let GuiView take care of those.
600 d->lyx_view_->updateLayoutList();
602 // Show the caret immediately after any operation.
603 startBlinkingCaret();
607 bool GuiWorkArea::event(QEvent * e)
610 case QEvent::ToolTip: {
611 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
612 if (lyxrc.use_tooltip) {
613 QPoint pos = helpEvent->pos();
614 if (pos.x() < viewport()->width()) {
615 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
616 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
619 QToolTip::hideText();
621 // Don't forget to accept the event!
626 case QEvent::ShortcutOverride:
627 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
629 keyPressEvent(static_cast<QKeyEvent *>(e));
630 return e->isAccepted();
632 case QEvent::KeyPress: {
633 // We catch this event in order to catch the Tab or Shift+Tab key press
634 // which are otherwise reserved to focus switching between controls
636 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
637 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
638 || (ke->key() == Qt::Key_Backtab && (
639 ke->modifiers() == Qt::ShiftModifier
640 || ke->modifiers() == Qt::NoModifier))) {
644 return QAbstractScrollArea::event(e);
648 return QAbstractScrollArea::event(e);
654 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
657 if (e->reason() == QContextMenuEvent::Mouse)
658 // the menu name is set on mouse press
659 name = d->context_menu_name_;
661 QPoint pos = e->pos();
662 Cursor const & cur = d->buffer_view_->cursor();
663 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
664 // Do not access the context menu of math right in front of before
665 // the cursor. This does not work when the cursor is in text.
666 Inset * inset = cur.paragraph().getInset(cur.pos());
667 if (inset && inset->asInsetMath())
669 else if (cur.pos() > 0) {
670 inset = cur.paragraph().getInset(cur.pos() - 1);
675 if (e->reason() == QContextMenuEvent::Keyboard)
676 // Subtract the top margin, see #12811
677 pos.setY(pos.y() - d->buffer_view_->topMargin());
679 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
686 // always show mnemonics when the keyboard is used to show the context menu
687 // FIXME: This should be fixed in Qt itself
688 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
689 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
694 // Position the menu to the right.
695 // FIXME: menu position should be different for RTL text.
696 menu->exec(e->globalPos());
701 void GuiWorkArea::focusInEvent(QFocusEvent * e)
703 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << " reason() = " << e->reason() << endl);
704 if (d->lyx_view_->currentWorkArea() != this) {
705 d->lyx_view_->setCurrentWorkArea(this);
706 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
709 // needs to reset IM item coordinates when focus in from dialogs or other apps
710 if ((e->reason() == Qt::PopupFocusReason || e->reason() == Qt::ActiveWindowFocusReason) &&
711 !(this->inDialogMode())) {
712 // Switched from most of dialogs or other apps, and not on a dialog (e.g. findreplaceadv)
713 d->item_trans_needs_reset_ = true;
715 // Switched from advanced search dialog or else (e.g. mouse event)
716 d->item_trans_needs_reset_ = false;
719 startBlinkingCaret();
720 QAbstractScrollArea::focusInEvent(e);
724 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
726 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
728 QAbstractScrollArea::focusOutEvent(e);
732 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
734 if (d->dc_event_.active && d->dc_event_ == *e) {
735 d->dc_event_.active = false;
736 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
737 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->position().x(), e->position().y(),
739 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
741 q_button_state(e->button()), q_key_state(e->modifiers()));
747 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
748 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->position().x(), e->position().y(),
750 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
752 q_button_state(e->button()), q_key_state(e->modifiers()));
755 // Save the context menu on mouse press, because also the mouse
756 // cursor is set on mouse press. Afterwards, we can either release
757 // the mousebutton somewhere else, or the cursor might have moved
758 // due to the DEPM. We need to do this after the mouse has been
759 // set in dispatch(), because the selection state might change.
760 if (e->button() == Qt::RightButton)
761 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
762 d->context_menu_name_ = d->buffer_view_->contextMenu(e->position().x(), e->position().y());
764 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
771 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
773 if (d->synthetic_mouse_event_.timeout.running())
774 d->synthetic_mouse_event_.timeout.stop();
776 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
777 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->position().x(), e->position().y(),
779 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
781 q_button_state(e->button()), q_key_state(e->modifiers()));
782 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
783 QT_VERSION < QT_VERSION_CHECK(5,15,1))
784 d->synthetic_mouse_event_.cmd = cmd; // QtBug QAbstractScrollArea::mouseMoveEvent
791 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
793 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
794 QT_VERSION < QT_VERSION_CHECK(5,15,1))
795 // cancel the event if the coordinates didn't change, this is due to QtBug
796 // QAbstractScrollArea::mouseMoveEvent, the event is triggered falsely when quickly
797 // double tapping a touchpad. To test: try to select a word by quickly double tapping
798 // on a touchpad while hovering the cursor over that word in the work area.
799 // This bug does not occur on Qt versions 5.10.1 and below. Only Windows seems to be affected.
800 // ML thread: https://www.mail-archive.com/lyx-devel@lists.lyx.org/msg211699.html
801 // Qt bugtracker: https://bugreports.qt.io/browse/QTBUG-85431
802 // Bug was fixed in Qt 5.15.1
803 if (e->x() == d->synthetic_mouse_event_.cmd.x() && // QtBug QAbstractScrollArea::mouseMoveEvent
804 e->y() == d->synthetic_mouse_event_.cmd.y()) // QtBug QAbstractScrollArea::mouseMoveEvent
805 return; // QtBug QAbstractScrollArea::mouseMoveEvent
808 // we kill the triple click if we move
809 doubleClickTimeout();
810 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
811 FuncRequest cmd(LFUN_MOUSE_MOTION, e->position().x(), e->position().y(),
813 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
815 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
819 // If we're above or below the work area...
820 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
821 if ((e->position().y() <= 20 || e->position().y() >= viewport()->height() - 20)
823 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
825 && e->buttons() == mouse_button::button1) {
826 // Make sure only a synthetic event can cause a page scroll,
827 // so they come at a steady rate:
828 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
829 if (e->position().y() <= 20)
830 // _Force_ a scroll up:
831 cmd.set_y(e->position().y() - 21);
833 cmd.set_y(e->position().y() + 21);
836 // _Force_ a scroll up:
837 cmd.set_y(e->y() - 21);
839 cmd.set_y(e->y() + 21);
841 // Store the event, to be handled when the timeout expires.
842 d->synthetic_mouse_event_.cmd = cmd;
844 if (d->synthetic_mouse_event_.timeout.running()) {
845 // Discard the event. Note that it _may_ be handled
846 // when the timeout expires if
847 // synthetic_mouse_event_.cmd has not been overwritten.
848 // Ie, when the timeout expires, we handle the
849 // most recent event but discard all others that
850 // occurred after the one used to start the timeout
851 // in the first place.
855 d->synthetic_mouse_event_.restart_timeout = true;
856 d->synthetic_mouse_event_.timeout.start();
857 // Fall through to handle this event...
859 } else if (d->synthetic_mouse_event_.timeout.running()) {
860 // Store the event, to be possibly handled when the timeout
862 // Once the timeout has expired, normal control is returned
863 // to mouseMoveEvent (restart_timeout = false).
864 // This results in a much smoother 'feel' when moving the
865 // mouse back into the work area.
866 d->synthetic_mouse_event_.cmd = cmd;
867 d->synthetic_mouse_event_.restart_timeout = false;
874 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
876 // Wheel rotation by one notch results in a delta() of 120 (see
877 // documentation of QWheelEvent)
878 // But first we have to ignore horizontal scroll events.
879 QPoint const aDelta = ev->angleDelta();
880 // skip horizontal wheel event
881 if (abs(aDelta.x()) > abs(aDelta.y())) {
885 double const delta = aDelta.y() / 120.0;
888 switch (lyxrc.scroll_wheel_zoom) {
889 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
890 zoom = ev->modifiers() & Qt::ControlModifier;
891 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
893 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
894 zoom = ev->modifiers() & Qt::ShiftModifier;
895 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
897 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
898 zoom = ev->modifiers() & Qt::AltModifier;
899 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
901 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
905 docstring arg = convert<docstring>(int(5 * delta));
906 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
910 // Take into account the desktop wide settings.
911 int const lines = qApp->wheelScrollLines();
912 int const page_step = verticalScrollBar()->pageStep();
913 // Test if the wheel mouse is set to one screen at a time.
914 // This is according to
915 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
917 min(lines * verticalScrollBar()->singleStep(), page_step);
919 // Take into account the rotation and the user preferences.
920 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
921 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
922 << " delta = " << delta << " scroll_value = " << scroll_value
923 << " page_step = " << page_step);
925 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
931 void GuiWorkArea::generateSyntheticMouseEvent()
933 int const e_y = d->synthetic_mouse_event_.cmd.y();
934 int const wh = d->buffer_view_->workHeight();
935 bool const up = e_y < 0;
936 bool const down = e_y > wh;
938 // Set things off to generate the _next_ 'pseudo' event.
940 if (d->synthetic_mouse_event_.restart_timeout) {
941 // This is some magic formulae to determine the speed
942 // of scrolling related to the position of the mouse.
945 int dist = up ? -e_y : e_y - wh;
946 time = max(min(200, 250000 / (dist * dist)), 1) ;
949 step = 80000 / (time * time);
953 d->synthetic_mouse_event_.timeout.setTimeout(time);
954 d->synthetic_mouse_event_.timeout.start();
957 // Can we scroll further ?
958 int const value = verticalScrollBar()->value();
959 if (value == verticalScrollBar()->maximum()
960 || value == verticalScrollBar()->minimum()) {
961 d->synthetic_mouse_event_.timeout.stop();
966 if (step <= 2 * wh) {
967 d->buffer_view_->scroll(up ? -step : step);
968 d->buffer_view_->updateMetrics();
970 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
973 // In which paragraph do we have to set the cursor ?
974 Cursor & cur = d->buffer_view_->cursor();
975 // FIXME: we don't know how to handle math.
976 Text * text = cur.text();
979 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
981 // Quit gracefully if there are no metrics, since otherwise next
982 // line would crash (bug #10324).
983 // This situation seems related to a (not yet understood) timing problem.
987 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
988 ParagraphMetrics const & pm = *pp.second;
989 pit_type const pit = pp.first;
991 if (pm.rows().empty())
994 // Find the row at which we set the cursor.
995 RowList::const_iterator rit = pm.rows().begin();
996 RowList::const_iterator rlast = pm.rows().end();
998 for (--rlast; rit != rlast; ++rit) {
999 int h = rit->height();
1000 if ((up && yy + h > 0)
1001 || (!up && yy + h > wh - defaultRowHeight()))
1006 // Find the position of the cursor
1008 int x = d->synthetic_mouse_event_.cmd.x();
1009 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1014 cur.boundary(bound);
1016 d->buffer_view_->buffer().changed(false);
1020 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
1021 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
1023 qRegisterMetaType<KeySymbol>("KeySymbol");
1024 qRegisterMetaType<KeyModifier>("KeyModifier");
1025 connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
1026 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
1027 Qt::QueuedConnection);
1028 connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
1029 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1033 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1037 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1038 bool result = flag_;
1044 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1046 if (emitCheck(isAutoRepeat))
1047 Q_EMIT signal(sym, mod);
1049 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1053 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1055 // this is also called for ShortcutOverride events. In this case, one must
1056 // not act but simply accept the event explicitly.
1057 bool const act = (ev->type() != QEvent::ShortcutOverride);
1059 // Do not process here some keys if dialog_mode_ is set
1060 bool const for_dialog_mode = d->dialog_mode_
1061 && (ev->modifiers() == Qt::NoModifier
1062 || ev->modifiers() == Qt::ShiftModifier)
1063 && (ev->key() == Qt::Key_Escape
1064 || ev->key() == Qt::Key_Enter
1065 || ev->key() == Qt::Key_Return);
1066 // also do not use autoRepeat to input shortcuts
1067 bool const autoRepeat = ev->isAutoRepeat();
1069 if (for_dialog_mode || (!act && autoRepeat)) {
1074 // intercept some keys if completion popup is visible
1075 if (d->completer_->popupVisible()) {
1076 switch (ev->key()) {
1078 case Qt::Key_Return:
1080 d->completer_->activate();
1086 KeyModifier const m = q_key_state(ev->modifiers());
1088 if (act && lyxerr.debugging(Debug::KEY)) {
1090 if (m & ShiftModifier)
1092 if (m & ControlModifier)
1094 if (m & AltModifier)
1096 if (m & MetaModifier)
1098 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1099 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1100 << " keyState: " << str);
1104 setKeySymbol(&sym, ev);
1107 Q_EMIT compressKeySym(sym, m, autoRepeat);
1110 // here, !autoRepeat, as determined at the beginning
1111 ev->setAccepted(queryKeySym(sym, m));
1118 void GuiWorkArea::doubleClickTimeout()
1120 d->dc_event_.active = false;
1124 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1126 d->dc_event_ = DoubleClick(ev);
1127 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1128 SLOT(doubleClickTimeout()));
1129 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
1130 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->position().x(), ev->position().y(),
1132 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1134 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1140 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1142 QAbstractScrollArea::resizeEvent(ev);
1143 d->need_resize_ = true;
1148 void GuiWorkArea::queryInputItemTransform()
1152 "item_trans_ is aquired: dx() = " << d->item_trans_.dx() <<
1153 " -> " << d->im_->inputItemTransform().dx() <<
1154 ", dy() = " << d->item_trans_.dy() <<
1155 " -> " << d->im_->inputItemTransform().dy()
1158 d->item_trans_ = d->im_->inputItemTransform();
1162 void GuiWorkArea::Private::resetInputItemTransform()
1164 if (item_trans_needs_reset_) {
1168 ") item_trans_ is reset: dx() = " << im_->inputItemTransform().dx() <<
1169 " -> " << item_trans_.dx() <<
1170 ", dy() = " << im_->inputItemTransform().dy() <<
1171 " -> " << item_trans_.dy()
1173 im_->setInputItemTransform(item_trans_);
1174 item_trans_needs_reset_ = false;
1179 //#define DEBUG_PREEDIT
1181 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1183 #ifdef DEBUG_PREEDIT
1184 // check the language that current input method uses
1185 QLocale::Language lang = im_->locale().language();
1186 if (lang != im_lang_) {
1187 LYXERR0("QLocale = " << QLocale::languageToString(lang));
1192 // Chinese IM may want cursor position even when preedit string is empty
1193 // such a case is handled below
1194 if (preedit_string_.empty() && im_->locale().language() != QLocale::Chinese)
1197 // lower margin of the preedit area to separate the candidate window
1198 // report to IM the height of preedit rectangle larger than the actual by
1199 // preedit_lower_margin so that the conversion suggestion window does not
1200 // hide the underline of the preedit text
1201 int preedit_lower_margin = 1;
1205 buffer_view_->caretPosAndDim(point, dim);
1206 int cur_x = point.x_ - dim.width();
1207 int cur_y = point.y_ + dim.height();
1209 if (preedit_string_.empty()) {
1210 // Chinese input methods may exit here just obtaining im_cursor_rect
1212 QRectF(cur_x, cur_y - dim.height(), 1, dim.height() + preedit_lower_margin);
1213 im_->update(Qt::ImCursorRectangle);
1217 // reset item transformation since it can go wrong after the item gets
1218 // lost and regains focus or after a new tab (dis)appears etc.
1219 resetInputItemTransform();
1221 // FIXME: shall we use real_current_font here? (see #10478)
1222 FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1223 FontMetrics const & fm = theFontMetrics(font);
1225 // force fulldraw to remove previous paint remaining on screen
1226 // FIXME: This is costly to do
1227 buffer_view_->processUpdateFlags(Update::ForceDraw);
1229 // get attributes of input method cursor.
1230 // cursor_pos : cursor position in preedit string.
1231 size_t cursor_pos = 0;
1232 bool cursor_is_visible = false;
1233 for (auto const & attr : preedit_attr_) {
1234 if (attr.type == QInputMethodEvent::Cursor) {
1235 cursor_pos = size_t(attr.start);
1236 cursor_is_visible = attr.length != 0;
1241 size_t const preedit_length = preedit_string_.length();
1243 // get position of selection in input method.
1244 // FIXME: isn't there a simpler way to do this?
1245 // rStart : cursor position in selected string in IM.
1247 // rLength : selected string length in IM.
1249 if (cursor_pos < preedit_length) {
1250 for (auto const & attr : preedit_attr_) {
1251 if (attr.type == QInputMethodEvent::TextFormat) {
1252 if (attr.start <= int(cursor_pos)
1253 && int(cursor_pos) < attr.start + attr.length) {
1254 rStart = size_t(attr.start);
1255 rLength = size_t(attr.length);
1256 if (!cursor_is_visible)
1257 cursor_pos += rLength;
1264 rStart = cursor_pos;
1268 int const text_width = p->viewport()->width() - buffer_view_->rightMargin()
1269 - buffer_view_->leftMargin();
1270 Painter::preedit_style ps;
1271 // Most often there would be only one line:
1273 for (size_t pos = 0; pos != preedit_length; ++pos) {
1274 char_type const typed_char = preedit_string_[pos];
1275 // reset preedit string style
1276 ps = Painter::preedit_default;
1278 // if we reached the right extremity of the screen, go to next line.
1279 if (cur_x + fm.width(typed_char) > p->viewport()->width() - buffer_view_->rightMargin()) {
1280 cur_x = buffer_view_->leftMargin();
1281 cur_y += dim.height() + 1;
1284 // preedit strings are displayed with dashed underline
1285 // and partial strings are displayed white on black indicating
1286 // that we are in selecting mode in the input method.
1287 // FIXME: rLength == preedit_length is not a changing condition
1288 // FIXME: should be put out of the loop.
1290 && pos < rStart + rLength
1291 && !(cursor_pos < rLength && rLength == preedit_length)) {
1292 ps = Painter::preedit_selecting;
1295 if (pos == cursor_pos
1296 && (cursor_pos < rLength && rLength == preedit_length))
1297 ps = Painter::preedit_cursor;
1299 // draw one character and update cur_x.
1300 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1303 // the selection candidate window follows the position of Qt::ImCursorRectangle
1304 // so we set it here in preparation for InputMethodQuery.
1306 // candidate selection mode
1307 div_t mod_cur, mod_anc;
1308 // width of preedit string in pixels
1309 int preedit_width = fm.width(preedit_string_);
1310 // calculate for modular so that its remainder and quotient become horizontal
1311 // and vertical adjustment factor respectively
1312 // FIXME: divider should be (text_width - font width of the end-of-line character)
1313 // however, since it's very rare that preedit becomes so long that it goes over
1314 // more than two lines, current error of position is more or less negligible
1315 mod_cur = div(text_width + cur_x - (preedit_width - fm.width(preedit_string_.substr(0, rStart))),
1317 mod_anc = div(text_width + cur_x - (preedit_width - fm.width(preedit_string_.substr(0, rStart + rLength))),
1319 // Obtain cursor and anchor rectangles to bind starting and ending points of selection.
1320 // Since the remainder of div moves from positive to negative as the line becomes longer
1321 // while its quotient repeats zero twice, we need to take it into account by conditioning.
1322 if (mod_cur.rem >= 0)
1323 im_cursor_rect_ = QRectF(mod_cur.rem,
1324 (cur_y - dim.height()) + (dim.height() + 1) * (mod_cur.quot - 1), 1,
1325 dim.height() + preedit_lower_margin);
1327 im_cursor_rect_ = QRectF(text_width + mod_cur.rem,
1328 (cur_y - dim.height()) + (dim.height() + 1) * (mod_cur.quot - 2), 1,
1329 dim.height() + preedit_lower_margin);
1330 if (mod_anc.rem >= 0)
1331 im_anchor_rect_ = QRectF(mod_anc.rem,
1332 point.y_ + (dim.height() + 1) * (mod_anc.quot - 1), 1,
1333 dim.height() + preedit_lower_margin );
1335 im_anchor_rect_ = QRectF(text_width + mod_anc.rem,
1336 point.y_ + (dim.height() + 1) * (mod_anc.quot - 2), 1,
1337 dim.height() + preedit_lower_margin );
1339 im_cursor_rect_ = QRectF(point.x_, point.y_, 1, dim.height() + preedit_lower_margin);
1340 im_anchor_rect_ = im_cursor_rect_;
1342 // Urge platform input method to make inputMethodQuery to check the values
1344 im_->update(Qt::ImQueryInput);
1348 void GuiWorkArea::Private::resetScreen()
1350 if (use_backingstore_) {
1351 double const pr = p->pixelRatio();
1352 screen_ = QImage(int(pr * p->viewport()->width()),
1353 int(pr * p->viewport()->height()),
1354 QImage::Format_ARGB32_Premultiplied);
1355 screen_.setDevicePixelRatio(pr);
1360 QPaintDevice * GuiWorkArea::Private::screenDevice()
1362 if (use_backingstore_)
1365 return p->viewport();
1369 void GuiWorkArea::Private::updateScreen(QRectF const & rc)
1371 if (use_backingstore_) {
1372 QPainter qpain(p->viewport());
1373 double const pr = p->pixelRatio();
1374 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr,
1375 rc.width() * pr, rc.height() * pr);
1376 qpain.drawImage(rc, screen_, rcs);
1381 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1383 // Do not trigger the painting machinery if we are not ready (see
1384 // bug #10989). The second test triggers when in the middle of a
1385 // dispatch operation.
1386 if (view().busy() || d->buffer_view_->busy()) {
1387 // Since the screen may have turned black at this point, our
1388 // backing store has to be copied to screen. This is a no-op
1389 // except when our drawing strategy is "backingstore" (macOS,
1390 // Wayland, or set in prefs).
1391 d->updateScreen(ev->rect());
1392 // Ignore this paint event, but request a new one for later.
1393 viewport()->update(ev->rect());
1398 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1399 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1401 if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_)
1404 d->last_pixel_ratio_ = pixelRatio();
1406 GuiPainter pain(d->screenDevice(), pixelRatio(), d->lyx_view_->develMode());
1408 d->buffer_view_->draw(pain, d->caret_visible_);
1410 // The preedit text, if needed
1411 d->paintPreeditText(pain);
1414 // FIXME: the code would be a little bit simpler if caret geometry
1415 // was updated unconditionally. Some profiling is required to see
1416 // how expensive this is (especially when idle).
1417 if (d->caret_visible_) {
1418 if (d->needs_caret_geometry_update_)
1419 d->updateCaretGeometry();
1420 d->drawCaret(pain, d->buffer_view_->horizScrollOffset());
1423 d->updateScreen(ev->rect());
1429 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1431 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1432 << " commitString: " << e->commitString());
1434 if (!e->commitString().isEmpty()) {
1436 // take care of commit string assigned to a shortcut
1437 // e.g. quotation mark on international keyboard
1439 for (QChar const & ch : e->commitString()) {
1441 keysym.init(ch.unicode());
1442 keyseq.addkey(keysym, NoModifier);
1444 cmd = theTopLevelKeymap().getBinding(keyseq);
1446 if (cmd == FuncRequest::noaction || cmd == FuncRequest::unknown
1447 || cmd.action() == LFUN_SELF_INSERT)
1448 // insert the processed text in the document (handles undo)
1449 cmd = FuncRequest(LFUN_SELF_INSERT, qstring_to_ucs4(e->commitString()));
1451 cmd.setOrigin(FuncRequest::KEYBOARD);
1453 // FIXME: this is supposed to remove traces from preedit
1454 // string. Can we avoid calling it explicitly?
1455 d->buffer_view_->updateMetrics();
1458 // Hide the caret during the test transformation.
1459 if (e->preeditString().isEmpty())
1460 startBlinkingCaret();
1462 stopBlinkingCaret();
1464 if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1470 // The preedit text and its attributes will be used in paintPreeditText
1471 d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1472 d->preedit_attr_ = e->attributes();
1475 // redraw area of preedit string.
1476 // int height = d->caret_->dim.height();
1477 // int cur_y = d->caret_->y;
1478 // viewport()->update(0, cur_y, viewport()->width(),
1479 // (height + 1) * d->preedit_lines_);
1480 viewport()->update();
1482 if (d->preedit_string_.empty()) {
1483 d->preedit_lines_ = 1;
1488 // Don't forget to accept the event!
1493 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1495 LYXERR(Debug::INFO, "incoming InputMethodQuery Value: 0x" << std::hex << query);
1497 // this is the CJK-specific composition window position and
1498 // the context menu position when the menu key is pressed.
1499 case Qt::ImCursorRectangle: {
1500 return QVariant(d->im_cursor_rect_);
1503 #if QT_VERSION >= QT_VERSION_CHECK(5, 7, 0)
1504 case Qt::ImAnchorRectangle: {
1505 return QVariant(d->im_anchor_rect_);
1510 return QWidget::inputMethodQuery(query);
1515 void GuiWorkArea::updateWindowTitle()
1517 Buffer const & buf = bufferView().buffer();
1518 if (buf.fileName() != d->file_name_
1519 || buf.params().shell_escape != d->shell_escape_
1520 || buf.hasReadonlyFlag() != d->read_only_
1521 || buf.lyxvc().vcstatus() != d->vc_status_
1522 || buf.isClean() != d->clean_
1523 || buf.notifiesExternalModification() != d->externally_modified_) {
1524 d->file_name_ = buf.fileName();
1525 d->shell_escape_ = buf.params().shell_escape;
1526 d->read_only_ = buf.hasReadonlyFlag();
1527 d->vc_status_ = buf.lyxvc().vcstatus();
1528 d->clean_ = buf.isClean();
1529 d->externally_modified_ = buf.notifiesExternalModification();
1530 Q_EMIT titleChanged(this);
1535 bool GuiWorkArea::isFullScreen() const
1537 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1541 bool GuiWorkArea::inDialogMode() const
1543 return d->dialog_mode_;
1547 void GuiWorkArea::setDialogMode(bool mode)
1549 d->dialog_mode_ = mode;
1553 GuiCompleter & GuiWorkArea::completer()
1555 return *d->completer_;
1558 GuiView const & GuiWorkArea::view() const
1560 return *d->lyx_view_;
1564 GuiView & GuiWorkArea::view()
1566 return *d->lyx_view_;
1569 ////////////////////////////////////////////////////////////////////
1573 ////////////////////////////////////////////////////////////////////
1576 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1578 support::TempFile tempfile("embedded.internal");
1579 tempfile.setAutoRemove(false);
1580 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1581 buffer_->setUnnamed(true);
1582 buffer_->setFullyLoaded(true);
1583 setBuffer(*buffer_);
1584 setDialogMode(true);
1588 EmbeddedWorkArea::~EmbeddedWorkArea()
1590 // No need to destroy buffer and bufferview here, because it is done
1591 // in theBufferList() destruction loop at application exit
1595 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1598 GuiWorkArea::closeEvent(ev);
1602 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1605 GuiWorkArea::hideEvent(ev);
1609 QSize EmbeddedWorkArea::sizeHint () const
1612 // GuiWorkArea sets the size to the screen's viewport
1613 // by returning a value this gets overridden
1614 // EmbeddedWorkArea is now sized to fit in the layout
1615 // of the parent, and has a minimum size set in GuiWorkArea
1616 // which is what we return here
1617 return QSize(100, 70);
1621 void EmbeddedWorkArea::disable()
1623 stopBlinkingCaret();
1624 if (view().currentWorkArea() != this)
1626 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1627 // tolerates it and shows the background logo), what happens if
1628 // an EmbeddedWorkArea is closed after closing all document WAs
1629 view().setCurrentWorkArea(view().currentMainWorkArea());
1632 ////////////////////////////////////////////////////////////////////
1636 ////////////////////////////////////////////////////////////////////
1638 TabWorkArea::TabWorkArea(QWidget * parent)
1639 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1641 QPalette pal = palette();
1642 pal.setColor(QPalette::Active, QPalette::Button,
1643 pal.color(QPalette::Active, QPalette::Window));
1644 pal.setColor(QPalette::Disabled, QPalette::Button,
1645 pal.color(QPalette::Disabled, QPalette::Window));
1646 pal.setColor(QPalette::Inactive, QPalette::Button,
1647 pal.color(QPalette::Inactive, QPalette::Window));
1649 QObject::connect(this, SIGNAL(currentChanged(int)),
1650 this, SLOT(on_currentTabChanged(int)));
1652 QObject::connect(this, SIGNAL(tabBarClicked(int)),
1653 this, SLOT(on_currentTabChanged(int)));
1655 closeBufferButton = new QToolButton(this);
1656 closeBufferButton->setPalette(pal);
1657 // FIXME: rename the icon to closebuffer.png
1658 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1659 closeBufferButton->setText("Close File");
1660 closeBufferButton->setAutoRaise(true);
1661 closeBufferButton->setCursor(Qt::ArrowCursor);
1662 closeBufferButton->setToolTip(qt_("Close File"));
1663 closeBufferButton->setEnabled(true);
1664 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1665 this, SLOT(closeCurrentBuffer()));
1666 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1668 // set TabBar behaviour
1669 QTabBar * tb = tabBar();
1670 tb->setTabsClosable(!lyxrc.single_close_tab_button);
1671 tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1672 tb->setElideMode(Qt::ElideNone);
1673 // allow dragging tabs
1674 tb->setMovable(true);
1675 // make us responsible for the context menu of the tabbar
1676 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1677 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1678 this, SLOT(showContextMenu(const QPoint &)));
1679 connect(tb, SIGNAL(tabCloseRequested(int)),
1680 this, SLOT(closeTab(int)));
1682 setUsesScrollButtons(true);
1684 // use document mode tabs
1685 setDocumentMode(true);
1690 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1692 if (me->button() == Qt::MiddleButton)
1693 midpressed_tab_ = tabBar()->tabAt(me->pos());
1695 QTabWidget::mousePressEvent(me);
1699 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1701 if (me->button() == Qt::MiddleButton) {
1702 int const midreleased_tab = tabBar()->tabAt(me->pos());
1703 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1704 closeTab(midreleased_tab);
1706 QTabWidget::mouseReleaseEvent(me);
1710 void TabWorkArea::paintEvent(QPaintEvent * event)
1712 if (tabBar()->isVisible()) {
1713 QTabWidget::paintEvent(event);
1715 // Prevent the selected tab to influence the
1716 // painting of the frame of the tab widget.
1717 // This is needed for gtk style in Qt.
1718 QStylePainter p(this);
1719 QStyleOptionTabWidgetFrame opt;
1720 initStyleOption(&opt);
1721 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1723 opt.selectedTabRect = QRect();
1724 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1729 bool TabWorkArea::posIsTab(QPoint position)
1731 // tabAt returns -1 if tab does not covers position
1732 return tabBar()->tabAt(position) > -1;
1736 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1738 if (event->button() != Qt::LeftButton)
1741 // this code chunk is unnecessary because it seems the event only makes
1742 // it this far if it is not on a tab. I'm not sure why this is (maybe
1743 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1744 // this is true in all cases and if it will be true in the future so I
1745 // leave this code for now. (skostysh, 2016-07-21)
1747 // return early if double click on existing tabs
1748 if (posIsTab(event->pos()))
1751 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1755 void TabWorkArea::setFullScreen(bool full_screen)
1757 for (int i = 0; i != count(); ++i) {
1758 if (GuiWorkArea * wa = workArea(i))
1759 wa->setFullScreen(full_screen);
1762 if (lyxrc.full_screen_tabbar)
1763 showBar(!full_screen && count() > 1);
1765 showBar(count() > 1);
1769 void TabWorkArea::showBar(bool show)
1771 tabBar()->setEnabled(show);
1772 tabBar()->setVisible(show);
1773 if (documentMode()) {
1774 // avoid blank corner widget when documentMode(true) is used
1775 if (show && lyxrc.single_close_tab_button) {
1776 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1777 closeBufferButton->setVisible(true);
1779 // remove corner widget
1780 setCornerWidget(nullptr);
1782 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1783 setTabsClosable(!lyxrc.single_close_tab_button);
1787 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1789 QWidget * w = QTabWidget::widget(index);
1792 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1798 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1800 return widget(currentIndex());
1804 GuiWorkArea * TabWorkArea::workArea(int index) const
1806 GuiWorkAreaContainer * w = widget(index);
1809 return w->workArea();
1813 GuiWorkArea * TabWorkArea::currentWorkArea() const
1815 return workArea(currentIndex());
1819 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1821 // FIXME: this method doesn't work if we have more than one work area
1822 // showing the same buffer.
1823 for (int i = 0; i != count(); ++i) {
1824 GuiWorkArea * wa = workArea(i);
1825 LASSERT(wa, return nullptr);
1826 if (&wa->bufferView().buffer() == &buffer)
1833 void TabWorkArea::closeAll()
1836 QWidget * wac = widget(0);
1837 LASSERT(wac, return);
1844 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1846 for (int index = 0; index < count(); ++index)
1847 if (workArea(index) == w)
1853 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1855 LASSERT(work_area, return false);
1856 int index = indexOfWorkArea(work_area);
1860 if (index == currentIndex())
1861 // Make sure the work area is up to date.
1862 on_currentTabChanged(index);
1864 // Switch to the work area.
1865 setCurrentIndex(index);
1866 work_area->setFocus(Qt::OtherFocusReason);
1872 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1875 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1876 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1877 wa->setUpdatesEnabled(false);
1878 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1879 // when hiding it again below).
1880 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1881 showBar(count() > 0);
1882 addTab(wac, wa->windowTitle());
1883 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1884 this, SLOT(updateTabTexts()));
1885 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1886 setFullScreen(true);
1888 // Hide tabbar if there's only one tab.
1889 showBar(count() > 1);
1893 // obtain new input item coordinates in the new and old work areas
1894 wa->queryInputItemTransform();
1895 if (currentWorkArea())
1896 currentWorkArea()->queryInputItemTransform();
1898 view.setBusy(false);
1904 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1906 LASSERT(work_area, return false);
1907 int index = indexOfWorkArea(work_area);
1911 work_area->setUpdatesEnabled(false);
1912 QWidget * wac = widget(index);
1917 // make sure the next work area is enabled.
1918 currentWidget()->setUpdatesEnabled(true);
1919 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1920 setFullScreen(true);
1922 // Show tabbar only if there's more than one tab.
1923 showBar(count() > 1);
1924 currentWorkArea()->queryInputItemTransform();
1926 lastWorkAreaRemoved();
1934 void TabWorkArea::on_currentTabChanged(int i)
1936 // returns e.g. on application destruction
1939 GuiWorkArea * wa = workArea(i);
1940 LASSERT(wa, return);
1941 wa->setUpdatesEnabled(true);
1942 wa->scheduleRedraw(true);
1945 currentWorkAreaChanged(wa);
1947 LYXERR(Debug::GUI, "currentTabChanged " << i
1948 << " File: " << wa->bufferView().buffer().absFileName());
1952 void TabWorkArea::closeCurrentBuffer()
1955 if (clicked_tab_ == -1)
1956 wa = currentWorkArea();
1958 wa = workArea(clicked_tab_);
1959 LASSERT(wa, return);
1961 wa->view().closeWorkArea(wa);
1965 bool TabWorkArea::closeTabsToRight()
1967 if (clicked_tab_ == -1)
1970 int const initialCurrentIndex = currentIndex();
1972 while (count() - 1 > clicked_tab_) {
1973 GuiWorkArea * wa = workArea(count() - 1);
1974 LASSERT(wa, return false);
1975 if (!wa->view().closeWorkArea(wa)) {
1976 // closing cancelled, if possible, reset initial current tab index
1977 if (initialCurrentIndex < count())
1978 setCurrentIndex(initialCurrentIndex);
1980 setCurrentIndex(clicked_tab_);
1988 bool TabWorkArea::openEnclosingFolder()
1991 if (clicked_tab_ == -1)
1994 Buffer const & buf = workArea(clicked_tab_)->bufferView().buffer();
1995 showDirectory(buf.fileName().onlyPath());
2000 bool TabWorkArea::closeTabsToLeft()
2002 if (clicked_tab_ == -1)
2005 int const initialCurrentIndex = currentIndex();
2007 int n = clicked_tab_;
2009 for (int i = 0; i < n; ++i) {
2010 GuiWorkArea * wa = workArea(0);
2011 LASSERT(wa, return false);
2012 if (!wa->view().closeWorkArea(wa)) {
2013 // closing cancelled, if possible, reset initial current tab index
2014 if (initialCurrentIndex - i >= 0)
2015 setCurrentIndex(initialCurrentIndex - i);
2017 setCurrentIndex(clicked_tab_ - i);
2025 void TabWorkArea::closeOtherTabs()
2027 if (clicked_tab_ == -1)
2030 closeTabsToRight() && closeTabsToLeft();
2034 void TabWorkArea::hideCurrentTab()
2037 if (clicked_tab_ == -1)
2038 wa = currentWorkArea();
2040 wa = workArea(clicked_tab_);
2041 LASSERT(wa, return);
2043 wa->view().hideWorkArea(wa);
2047 void TabWorkArea::closeTab(int index)
2049 on_currentTabChanged(index);
2052 wa = currentWorkArea();
2054 wa = workArea(index);
2055 LASSERT(wa, return);
2057 wa->view().closeWorkArea(wa);
2061 void TabWorkArea::moveToStartCurrentTab()
2063 if (clicked_tab_ == -1)
2065 tabBar()->moveTab(clicked_tab_, 0);
2069 void TabWorkArea::moveToEndCurrentTab()
2071 if (clicked_tab_ == -1)
2073 tabBar()->moveTab(clicked_tab_, count() - 1);
2080 /// make vector happy
2081 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
2083 DisplayPath(int tab, FileName const & filename)
2086 // Recode URL encoded chars via fromPercentEncoding()
2087 string const fn = (filename.extension() == "lyx")
2088 ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
2089 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
2090 #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
2091 postfix_ = toqstr(filename.absoluteFilePath()).
2092 split("/", Qt::SkipEmptyParts);
2094 postfix_ = toqstr(filename.absoluteFilePath()).
2095 split("/", QString::SkipEmptyParts);
2097 postfix_.pop_back();
2098 abs_ = toqstr(filename.absoluteFilePath());
2099 dottedPrefix_ = false;
2102 /// Absolute path for debugging.
2107 /// Add the first segment from the postfix or three dots to the prefix.
2108 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
2109 /// when really needed.
2110 void shiftPathSegment(bool dotted)
2112 if (postfix_.count() <= 0)
2116 if (dottedPrefix_ && !prefix_.isEmpty())
2117 prefix_ += ellipsisSlash_;
2118 prefix_ += postfix_.front() + "/";
2120 dottedPrefix_ = dotted && !prefix_.isEmpty();
2121 postfix_.pop_front();
2124 QString displayString() const
2126 if (prefix_.isEmpty())
2129 bool dots = dottedPrefix_ || !postfix_.isEmpty();
2130 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
2133 QString forecastPathString() const
2135 if (postfix_.count() == 0)
2136 return displayString();
2139 + (dottedPrefix_ ? ellipsisSlash_ : "")
2140 + postfix_.front() + "/";
2143 bool final() const { return postfix_.empty(); }
2145 int tab() const { return tab_; }
2149 static QString const ellipsisSlash_;
2153 QStringList postfix_;
2165 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
2169 bool operator<(DisplayPath const & a, DisplayPath const & b)
2171 return a.displayString() < b.displayString();
2175 bool operator==(DisplayPath const & a, DisplayPath const & b)
2177 return a.displayString() == b.displayString();
2181 void TabWorkArea::updateTabTexts()
2183 int const n = count();
2186 std::list<DisplayPath> paths;
2187 typedef std::list<DisplayPath>::iterator It;
2189 // collect full names first: path into postfix, empty prefix and
2190 // filename without extension
2191 for (int i = 0; i < n; ++i) {
2192 GuiWorkArea * i_wa = workArea(i);
2193 FileName const fn = i_wa->bufferView().buffer().fileName();
2194 paths.push_back(DisplayPath(i, fn));
2197 // go through path segments and see if it helps to make the path more unique
2198 bool somethingChanged = true;
2199 bool allFinal = false;
2200 while (somethingChanged && !allFinal) {
2201 // adding path segments changes order
2204 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
2205 somethingChanged = false;
2208 // find segments which are not unique (i.e. non-atomic)
2209 It it = paths.begin();
2211 QString segString = it->displayString();
2212 for (; it != paths.end(); ++it) {
2213 // look to the next item
2218 allFinal = allFinal && it->final();
2220 LYXERR(Debug::GUI, "it = " << it->abs()
2221 << " => " << it->displayString());
2223 // still the same segment?
2225 if ((next != paths.end()
2226 && (nextString = next->displayString()) == segString))
2228 LYXERR(Debug::GUI, "segment ended");
2230 // only a trivial one with one element?
2231 if (it == segStart) {
2232 // start new segment
2234 segString = nextString;
2238 // We found a non-atomic segment
2239 // We know that segStart <= it < next <= paths.end().
2240 // The assertion below tells coverity about it.
2241 LATTEST(segStart != paths.end());
2242 QString dspString = segStart->forecastPathString();
2243 LYXERR(Debug::GUI, "first forecast found for "
2244 << segStart->abs() << " => " << dspString);
2247 // Shift path segments and hope for the best
2248 // that it makes the path more unique.
2249 somethingChanged = true;
2250 bool moreUnique = false;
2251 for (; sit != next; ++sit) {
2252 if (sit->forecastPathString() != dspString) {
2253 LYXERR(Debug::GUI, "different forecast found for "
2254 << sit->abs() << " => " << sit->forecastPathString());
2258 LYXERR(Debug::GUI, "same forecast found for "
2259 << sit->abs() << " => " << dspString);
2262 // if the path segment helped, add it. Otherwise add dots
2263 bool dots = !moreUnique;
2264 LYXERR(Debug::GUI, "using dots = " << dots);
2265 for (sit = segStart; sit != next; ++sit) {
2266 sit->shiftPathSegment(dots);
2267 LYXERR(Debug::GUI, "shifting "
2268 << sit->abs() << " => " << sit->displayString());
2271 // start new segment
2273 segString = nextString;
2277 // set new tab titles
2278 for (It it = paths.begin(); it != paths.end(); ++it) {
2279 int const tab_index = it->tab();
2280 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2281 QString tab_text = it->displayString().replace("&", "&&");
2282 if (!buf.fileName().empty() && !buf.isClean())
2284 QString tab_tooltip = it->abs();
2285 if (buf.hasReadonlyFlag()) {
2287 QLabel * readOnlyButton = new QLabel();
2288 QIcon icon = QIcon(getPixmap("images/", "emblem-readonly", "svgz,png"));
2289 readOnlyButton->setPixmap(icon.pixmap(QSize(16, 16)));
2290 tabBar()->setTabButton(tab_index, QTabBar::RightSide, readOnlyButton);
2292 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2294 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2297 tabBar()->setTabButton(tab_index, QTabBar::RightSide, 0);
2299 setTabIcon(tab_index, QIcon());
2301 if (buf.notifiesExternalModification()) {
2302 QString const warn = qt_("%1 (modified externally)");
2303 tab_tooltip = warn.arg(tab_tooltip);
2304 tab_text += QChar(0x26a0);
2306 setTabText(tab_index, tab_text);
2307 setTabToolTip(tab_index, tab_tooltip);
2312 void TabWorkArea::showContextMenu(const QPoint & pos)
2315 clicked_tab_ = tabBar()->tabAt(pos);
2316 if (clicked_tab_ == -1)
2319 GuiWorkArea * wa = workArea(clicked_tab_);
2320 LASSERT(wa, return);
2324 popup.addAction(qt_("&Hide Tab"), this, SLOT(hideCurrentTab()));
2326 // we want to show the 'close' option only if this is not a child buffer.
2327 Buffer const & buf = wa->bufferView().buffer();
2329 popup.addAction(qt_("&Close Tab"), this, SLOT(closeCurrentBuffer()));
2331 popup.addSeparator();
2333 QAction * closeOther = popup.addAction(qt_("Close &Other Tabs"), this, SLOT(closeOtherTabs()));
2334 closeOther->setEnabled(clicked_tab_ != 0 || hasTabsToRight(clicked_tab_));
2335 QAction * closeRight = popup.addAction(qt_("Close Tabs to the &Right"), this, SLOT(closeTabsToRight()));
2336 closeRight->setEnabled(hasTabsToRight(clicked_tab_));
2337 QAction * closeLeft = popup.addAction(qt_("Close Tabs to the &Left"), this, SLOT(closeTabsToLeft()));
2338 closeLeft->setEnabled(clicked_tab_ != 0);
2340 popup.addSeparator();
2342 QAction * moveStart = popup.addAction(qt_("Move Tab to &Start"), this, SLOT(moveToStartCurrentTab()));
2343 moveStart->setEnabled(closeLeft->isEnabled());
2344 QAction * moveEnd = popup.addAction(qt_("Move Tab to &End"), this, SLOT(moveToEndCurrentTab()));
2345 moveEnd->setEnabled(closeRight->isEnabled());
2347 popup.addSeparator();
2349 popup.addAction(qt_("Open Enclosing &Folder"), this, SLOT(openEnclosingFolder()));
2351 popup.exec(tabBar()->mapToGlobal(pos));
2356 bool TabWorkArea::hasTabsToRight(int index) {
2357 return count() - 1 > index;
2361 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2363 QWidget * w = widget(fromIndex);
2364 QIcon icon = tabIcon(fromIndex);
2365 QString text = tabText(fromIndex);
2367 setCurrentIndex(fromIndex);
2368 removeTab(fromIndex);
2369 insertTab(toIndex, w, icon, text);
2370 setCurrentIndex(toIndex);
2374 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2375 : QWidget(parent), wa_(wa)
2377 LASSERT(wa, return);
2378 Ui::WorkAreaUi::setupUi(this);
2379 layout()->addWidget(wa);
2380 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2381 this, SLOT(updateDisplay()));
2382 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2383 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2384 setMessageColour({notificationFrame, externalModificationLabel},
2385 {reloadPB, ignorePB});
2390 void GuiWorkAreaContainer::updateDisplay()
2392 Buffer const & buf = wa_->bufferView().buffer();
2393 notificationFrame->setHidden(!buf.notifiesExternalModification());
2394 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2395 .arg(toqstr(buf.fileName().displayName()));
2396 externalModificationLabel->setText(label);
2400 void GuiWorkAreaContainer::dispatch(FuncRequest const & f) const
2402 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2403 wa_->bufferView().buffer().absFileName()));
2408 void GuiWorkAreaContainer::reload() const
2410 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2414 void GuiWorkAreaContainer::ignore() const
2416 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2420 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2422 // prevent TabWorkArea from opening a new buffer on double click
2427 } // namespace frontend
2430 #include "moc_GuiWorkArea.cpp"