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 || guiApp->needsBackingStore();
135 LYXERR(Debug::WORKAREA, "Drawing strategy is: "
136 << (use_backingstore_ ? "backingstore" : "partial"));
138 int const time = QApplication::cursorFlashTime() / 2;
140 caret_timeout_.setInterval(time);
141 caret_timeout_.start();
143 // let's initialize this just to be safe
144 caret_timeout_.setInterval(500);
149 GuiWorkArea::Private::~Private()
151 // If something is wrong with the buffer, we can ignore it safely
153 buffer_view_->buffer().workAreaManager().remove(p);
156 // Completer has a QObject parent and is thus automatically destroyed.
158 // delete completer_;
162 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
163 : d(new Private(this))
165 new CompressorProxy(this); // not a leak
169 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
170 : d(new Private(this))
172 new CompressorProxy(this); // not a leak
174 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
180 double GuiWorkArea::pixelRatio() const
182 #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
183 return devicePixelRatioF();
185 return devicePixelRatio();
190 void GuiWorkArea::init()
193 connect(&d->caret_timeout_, SIGNAL(timeout()),
194 this, SLOT(toggleCaret()));
196 // This connection is closed at the same time as this is destroyed.
197 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
198 generateSyntheticMouseEvent();
203 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
204 setAcceptDrops(true);
205 setMouseTracking(true);
206 setMinimumSize(100, 70);
207 setFrameStyle(QFrame::NoFrame);
210 d->updateCursorShape();
212 // we paint our own background
213 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
215 setFocusPolicy(Qt::StrongFocus);
217 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
218 << " viewport height: " << viewport()->height());
220 // Enables input methods for asian languages.
221 // Must be set when creating custom text editing widgets.
222 setAttribute(Qt::WA_InputMethodEnabled, true);
224 // Initialize d->im_cursor_rect_
227 d->buffer_view_->caretPosAndDim(point, dim);
228 int cur_x = point.x_ - dim.width();
229 int cur_y = point.y_ + dim.height();
230 d->im_cursor_rect_ = QRectF(cur_x, (cur_y - dim.height()) , 1, dim.height() );
234 GuiWorkArea::~GuiWorkArea()
240 void GuiWorkArea::Private::updateCursorShape()
242 bool const clickable = buffer_view_ && buffer_view_->clickableInset();
243 p->viewport()->setCursor(clickable ? Qt::PointingHandCursor
248 void GuiWorkArea::setGuiView(GuiView & gv)
254 void GuiWorkArea::setBuffer(Buffer & buffer)
256 delete d->buffer_view_;
257 d->buffer_view_ = new BufferView(buffer);
258 buffer.workAreaManager().add(this);
260 // HACK: Prevents an additional redraw when the scrollbar pops up
261 // which regularly happens on documents with more than one page.
262 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
263 // Since we have no geometry information yet, we assume that
264 // a document needs a scrollbar if there is more then four
265 // paragraph in the outermost text.
266 if (buffer.text().paragraphs().size() > 4)
267 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
268 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
269 Q_EMIT bufferViewChanged();
273 void GuiWorkArea::fixVerticalScrollBar()
276 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
280 void GuiWorkArea::close()
282 d->lyx_view_->removeWorkArea(this);
286 void GuiWorkArea::setFullScreen(bool full_screen)
288 d->buffer_view_->setFullScreen(full_screen);
290 queryInputItemTransform();
292 if (full_screen && lyxrc.full_screen_scrollbar)
293 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
295 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
299 BufferView & GuiWorkArea::bufferView()
301 return *d->buffer_view_;
305 BufferView const & GuiWorkArea::bufferView() const
307 return *d->buffer_view_;
311 void GuiWorkArea::stopBlinkingCaret()
313 d->caret_timeout_.stop();
318 void GuiWorkArea::startBlinkingCaret()
320 // do not show the cursor if the view is busy
324 // Don't start blinking if the cursor isn't on screen, unless we
325 // are not ready to know whether the cursor is on screen.
326 if (!d->buffer_view_->busy() && !d->buffer_view_->caretInView())
331 // Avoid blinking when debugging PAINTING, since it creates too much noise
332 if (!lyxerr.debugging(Debug::PAINTING)) {
333 // we are not supposed to cache this value.
334 int const time = QApplication::cursorFlashTime() / 2;
337 d->caret_timeout_.setInterval(time);
338 d->caret_timeout_.start();
343 void GuiWorkArea::toggleCaret()
345 if (d->caret_visible_)
352 void GuiWorkArea::scheduleRedraw(bool update_metrics)
354 if (!isVisible() || view().busy())
355 // No need to redraw in this case.
358 // No need to do anything if this is the current view. The BufferView
359 // metrics are already up to date.
360 if (update_metrics || d->lyx_view_ != guiApp->currentView()
361 || d->lyx_view_->currentWorkArea() != this) {
362 // FIXME: it would be nice to optimize for the off-screen case.
363 d->buffer_view_->cursor().fixIfBroken();
364 d->buffer_view_->updateMetrics();
365 d->buffer_view_->cursor().fixIfBroken();
368 // update caret position, because otherwise it has to wait until
369 // the blinking interval is over
372 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
373 viewport()->update();
375 /// FIXME: is this still true now that paintEvent does the actual painting?
376 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
377 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
378 d->updateScrollbar();
379 d->lyx_view_->updateStatusBar();
381 if (lyxerr.debugging(Debug::WORKAREA))
382 d->buffer_view_->coordCache().dump();
386 d->updateCursorShape();
390 // Keep in sync with GuiWorkArea::processKeySym below
391 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
393 return guiApp->queryKeySym(key, mod);
397 // Keep in sync with GuiWorkArea::queryKeySym above
398 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
400 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
401 && lyxrc.full_screen_menubar) {
402 // FIXME HACK: we should not have to do this here. See related comment
403 // in GuiView::event() (QEvent::ShortcutOverride)
404 d->lyx_view_->menuBar()->hide();
407 // In order to avoid bad surprise in the middle of an operation,
408 // we better stop the blinking caret...
409 // the caret gets restarted in GuiView::restartCaret()
411 guiApp->processKeySym(key, mod);
415 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
418 if (cmd.action() == LFUN_FILE_OPEN) {
420 lyx_view_->dispatch(cmd, dr);
424 bool const notJustMovingTheMouse =
425 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
427 // In order to avoid bad surprise in the middle of an operation, we better stop
428 // the blinking caret.
429 if (notJustMovingTheMouse)
430 p->stopBlinkingCaret();
432 buffer_view_->mouseEventDispatch(cmd);
434 // Skip these when selecting
435 // FIXME: let GuiView take care of those.
436 if (notJustMovingTheMouse && !buffer_view_->mouseSelecting()) {
437 completer_->updateVisibility(false, false);
438 lyx_view_->updateDialogs();
439 lyx_view_->updateStatusBar();
442 // GUI tweaks except with mouse motion with no button pressed.
443 if (notJustMovingTheMouse) {
444 // Slight hack: this is only called currently when we
445 // clicked somewhere, so we force through the display
446 // of the new status here.
447 // FIXME: let GuiView take care of those.
448 lyx_view_->clearMessage();
450 // Show the caret immediately after any operation
451 p->startBlinkingCaret();
458 void GuiWorkArea::resizeBufferView()
460 // WARNING: Please don't put any code that will trigger a repaint here!
461 // We are already inside a paint event.
463 // Warn our container (GuiView).
466 bool const caret_in_view = d->buffer_view_->caretInView();
467 d->buffer_view_->resize(viewport()->width(), viewport()->height());
469 d->buffer_view_->showCursor();
472 // Update scrollbars which might have changed due different
473 // BufferView dimension. This is especially important when the
474 // BufferView goes from zero-size to the real-size for the first time,
475 // as the scrollbar parameters are then set for the first time.
476 d->updateScrollbar();
478 d->need_resize_ = false;
480 // Eventually, restart the caret after the resize event.
481 // We might be resizing even if the focus is on another widget so we only
482 // restart the caret if we have the focus.
484 QTimer::singleShot(50, this, SLOT(startBlinkingCaret()));
488 void GuiWorkArea::Private::resetCaret()
490 // Don't start blinking if the cursor isn't on screen or the window
491 // does not have focus
492 if (!buffer_view_->caretInView() || !p->hasFocus())
495 needs_caret_geometry_update_ = true;
496 caret_visible_ = true;
500 void GuiWorkArea::Private::updateCaretGeometry()
502 // we cannot update geometry if not ready and we do not need to if
503 // caret is not in view.
504 if (buffer_view_->busy() || !buffer_view_->caretInView())
507 // completion indicator
508 Cursor const & cur = buffer_view_->cursor();
509 bool const completable = cur.inset().showCompletionCursor()
510 && completer_->completionAvailable()
511 && !completer_->popupVisible()
512 && !completer_->inlineVisible();
514 buffer_view_->buildCaretGeometry(completable);
516 needs_caret_geometry_update_ = false;
520 void GuiWorkArea::Private::showCaret()
526 p->viewport()->update();
530 void GuiWorkArea::Private::hideCaret()
535 caret_visible_ = false;
536 //if (!qApp->focusWidget())
537 p->viewport()->update();
541 /* Draw the caret. Parameter \c horiz_offset is not 0 when there
542 * has been horizontal scrolling in current row
544 void GuiWorkArea::Private::drawCaret(QPainter & painter, int horiz_offset) const
546 if (buffer_view_->caretGeometry().shapes.empty())
549 QColor const color = guiApp->colorCache().get(Color_cursor);
550 painter.setPen(color);
551 painter.setRenderHint(QPainter::Antialiasing, true);
552 for (auto const & shape : buffer_view_->caretGeometry().shapes) {
555 for (Point const & p : shape) {
557 path.moveTo(p.x_ - horiz_offset, p.y_);
560 path.lineTo(p.x_ - horiz_offset, p.y_);
562 painter.fillPath(path, color);
564 painter.setRenderHint(QPainter::Antialiasing, false);
568 void GuiWorkArea::Private::updateScrollbar()
570 // Prevent setRange() and setSliderPosition from causing recursive calls via
571 // the signal valueChanged. (#10311)
572 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
573 p, SLOT(scrollTo(int)));
574 ScrollbarParameters const & scroll = buffer_view_->scrollbarParameters();
575 p->verticalScrollBar()->setRange(scroll.min, scroll.max);
576 p->verticalScrollBar()->setPageStep(scroll.page_step);
577 p->verticalScrollBar()->setSingleStep(scroll.single_step);
578 p->verticalScrollBar()->setSliderPosition(0);
579 // Connect to the vertical scroll bar
580 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
581 p, SLOT(scrollTo(int)));
585 void GuiWorkArea::scrollTo(int value)
588 d->buffer_view_->scrollDocView(value, true);
590 if (lyxrc.cursor_follows_scrollbar) {
591 d->buffer_view_->setCursorFromScrollbar();
592 // FIXME: let GuiView take care of those.
593 d->lyx_view_->updateLayoutList();
595 // Show the caret immediately after any operation.
596 startBlinkingCaret();
600 bool GuiWorkArea::event(QEvent * e)
603 case QEvent::ToolTip: {
604 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
605 if (lyxrc.use_tooltip) {
606 QPoint pos = helpEvent->pos();
607 if (pos.x() < viewport()->width()) {
608 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
609 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
612 QToolTip::hideText();
614 // Don't forget to accept the event!
619 case QEvent::ShortcutOverride:
620 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
622 keyPressEvent(static_cast<QKeyEvent *>(e));
623 return e->isAccepted();
625 case QEvent::KeyPress: {
626 // We catch this event in order to catch the Tab or Shift+Tab key press
627 // which are otherwise reserved to focus switching between controls
629 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
630 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
631 || (ke->key() == Qt::Key_Backtab && (
632 ke->modifiers() == Qt::ShiftModifier
633 || ke->modifiers() == Qt::NoModifier))) {
637 return QAbstractScrollArea::event(e);
641 return QAbstractScrollArea::event(e);
647 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
650 if (e->reason() == QContextMenuEvent::Mouse)
651 // the menu name is set on mouse press
652 name = d->context_menu_name_;
654 QPoint pos = e->pos();
655 Cursor const & cur = d->buffer_view_->cursor();
656 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
657 // Do not access the context menu of math right in front of before
658 // the cursor. This does not work when the cursor is in text.
659 Inset * inset = cur.paragraph().getInset(cur.pos());
660 if (inset && inset->asInsetMath())
662 else if (cur.pos() > 0) {
663 inset = cur.paragraph().getInset(cur.pos() - 1);
668 if (e->reason() == QContextMenuEvent::Keyboard)
669 // Subtract the top margin, see #12811
670 pos.setY(pos.y() - d->buffer_view_->topMargin());
672 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
679 // always show mnemonics when the keyboard is used to show the context menu
680 // FIXME: This should be fixed in Qt itself
681 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
682 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
687 // Position the menu to the right.
688 // FIXME: menu position should be different for RTL text.
689 menu->exec(e->globalPos());
694 void GuiWorkArea::focusInEvent(QFocusEvent * e)
696 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << " reason() = " << e->reason() << endl);
697 if (d->lyx_view_->currentWorkArea() != this) {
698 d->lyx_view_->setCurrentWorkArea(this);
699 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
702 // needs to reset IM item coordinates when focus in from dialogs or other apps
703 if ((e->reason() == Qt::PopupFocusReason || e->reason() == Qt::ActiveWindowFocusReason) &&
704 !(this->inDialogMode())) {
705 // Switched from most of dialogs or other apps, and not on a dialog (e.g. findreplaceadv)
706 d->item_trans_needs_reset_ = true;
708 // Switched from advanced search dialog or else (e.g. mouse event)
709 d->item_trans_needs_reset_ = false;
712 startBlinkingCaret();
713 QAbstractScrollArea::focusInEvent(e);
717 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
719 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
721 QAbstractScrollArea::focusOutEvent(e);
725 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
727 if (d->dc_event_.active && d->dc_event_ == *e) {
728 d->dc_event_.active = false;
729 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
730 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->position().x(), e->position().y(),
732 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
734 q_button_state(e->button()), q_key_state(e->modifiers()));
740 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
741 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->position().x(), e->position().y(),
743 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
745 q_button_state(e->button()), q_key_state(e->modifiers()));
748 // Save the context menu on mouse press, because also the mouse
749 // cursor is set on mouse press. Afterwards, we can either release
750 // the mousebutton somewhere else, or the cursor might have moved
751 // due to the DEPM. We need to do this after the mouse has been
752 // set in dispatch(), because the selection state might change.
753 if (e->button() == Qt::RightButton)
754 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
755 d->context_menu_name_ = d->buffer_view_->contextMenu(e->position().x(), e->position().y());
757 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
764 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
766 if (d->synthetic_mouse_event_.timeout.running())
767 d->synthetic_mouse_event_.timeout.stop();
769 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
770 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->position().x(), e->position().y(),
772 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
774 q_button_state(e->button()), q_key_state(e->modifiers()));
775 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
776 QT_VERSION < QT_VERSION_CHECK(5,15,1))
777 d->synthetic_mouse_event_.cmd = cmd; // QtBug QAbstractScrollArea::mouseMoveEvent
784 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
786 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
787 QT_VERSION < QT_VERSION_CHECK(5,15,1))
788 // cancel the event if the coordinates didn't change, this is due to QtBug
789 // QAbstractScrollArea::mouseMoveEvent, the event is triggered falsely when quickly
790 // double tapping a touchpad. To test: try to select a word by quickly double tapping
791 // on a touchpad while hovering the cursor over that word in the work area.
792 // This bug does not occur on Qt versions 5.10.1 and below. Only Windows seems to be affected.
793 // ML thread: https://www.mail-archive.com/lyx-devel@lists.lyx.org/msg211699.html
794 // Qt bugtracker: https://bugreports.qt.io/browse/QTBUG-85431
795 // Bug was fixed in Qt 5.15.1
796 if (e->x() == d->synthetic_mouse_event_.cmd.x() && // QtBug QAbstractScrollArea::mouseMoveEvent
797 e->y() == d->synthetic_mouse_event_.cmd.y()) // QtBug QAbstractScrollArea::mouseMoveEvent
798 return; // QtBug QAbstractScrollArea::mouseMoveEvent
801 // we kill the triple click if we move
802 doubleClickTimeout();
803 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
804 FuncRequest cmd(LFUN_MOUSE_MOTION, e->position().x(), e->position().y(),
806 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
808 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
812 // If we're above or below the work area...
813 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
814 if ((e->position().y() <= 20 || e->position().y() >= viewport()->height() - 20)
816 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
818 && e->buttons() == mouse_button::button1) {
819 // Make sure only a synthetic event can cause a page scroll,
820 // so they come at a steady rate:
821 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
822 if (e->position().y() <= 20)
823 // _Force_ a scroll up:
824 cmd.set_y(e->position().y() - 21);
826 cmd.set_y(e->position().y() + 21);
829 // _Force_ a scroll up:
830 cmd.set_y(e->y() - 21);
832 cmd.set_y(e->y() + 21);
834 // Store the event, to be handled when the timeout expires.
835 d->synthetic_mouse_event_.cmd = cmd;
837 if (d->synthetic_mouse_event_.timeout.running()) {
838 // Discard the event. Note that it _may_ be handled
839 // when the timeout expires if
840 // synthetic_mouse_event_.cmd has not been overwritten.
841 // Ie, when the timeout expires, we handle the
842 // most recent event but discard all others that
843 // occurred after the one used to start the timeout
844 // in the first place.
848 d->synthetic_mouse_event_.restart_timeout = true;
849 d->synthetic_mouse_event_.timeout.start();
850 // Fall through to handle this event...
852 } else if (d->synthetic_mouse_event_.timeout.running()) {
853 // Store the event, to be possibly handled when the timeout
855 // Once the timeout has expired, normal control is returned
856 // to mouseMoveEvent (restart_timeout = false).
857 // This results in a much smoother 'feel' when moving the
858 // mouse back into the work area.
859 d->synthetic_mouse_event_.cmd = cmd;
860 d->synthetic_mouse_event_.restart_timeout = false;
867 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
869 // Wheel rotation by one notch results in a delta() of 120 (see
870 // documentation of QWheelEvent)
871 // But first we have to ignore horizontal scroll events.
872 QPoint const aDelta = ev->angleDelta();
873 // skip horizontal wheel event
874 if (abs(aDelta.x()) > abs(aDelta.y())) {
878 double const delta = aDelta.y() / 120.0;
881 switch (lyxrc.scroll_wheel_zoom) {
882 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
883 zoom = ev->modifiers() & Qt::ControlModifier;
884 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
886 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
887 zoom = ev->modifiers() & Qt::ShiftModifier;
888 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
890 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
891 zoom = ev->modifiers() & Qt::AltModifier;
892 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
894 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
898 docstring arg = convert<docstring>(int(5 * delta));
899 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
903 // Take into account the desktop wide settings.
904 int const lines = qApp->wheelScrollLines();
905 int const page_step = verticalScrollBar()->pageStep();
906 // Test if the wheel mouse is set to one screen at a time.
907 // This is according to
908 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
910 min(lines * verticalScrollBar()->singleStep(), page_step);
912 // Take into account the rotation and the user preferences.
913 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
914 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
915 << " delta = " << delta << " scroll_value = " << scroll_value
916 << " page_step = " << page_step);
918 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
924 void GuiWorkArea::generateSyntheticMouseEvent()
926 int const e_y = d->synthetic_mouse_event_.cmd.y();
927 int const wh = d->buffer_view_->workHeight();
928 bool const up = e_y < 0;
929 bool const down = e_y > wh;
931 // Set things off to generate the _next_ 'pseudo' event.
933 if (d->synthetic_mouse_event_.restart_timeout) {
934 // This is some magic formulae to determine the speed
935 // of scrolling related to the position of the mouse.
938 int dist = up ? -e_y : e_y - wh;
939 time = max(min(200, 250000 / (dist * dist)), 1) ;
942 step = 80000 / (time * time);
946 d->synthetic_mouse_event_.timeout.setTimeout(time);
947 d->synthetic_mouse_event_.timeout.start();
950 // Can we scroll further ?
951 int const value = verticalScrollBar()->value();
952 if (value == verticalScrollBar()->maximum()
953 || value == verticalScrollBar()->minimum()) {
954 d->synthetic_mouse_event_.timeout.stop();
959 if (step <= 2 * wh) {
960 d->buffer_view_->scroll(up ? -step : step);
961 d->buffer_view_->updateMetrics();
963 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
966 // In which paragraph do we have to set the cursor ?
967 Cursor & cur = d->buffer_view_->cursor();
968 // FIXME: we don't know how to handle math.
969 Text * text = cur.text();
972 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
974 // Quit gracefully if there are no metrics, since otherwise next
975 // line would crash (bug #10324).
976 // This situation seems related to a (not yet understood) timing problem.
980 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
981 ParagraphMetrics const & pm = *pp.second;
982 pit_type const pit = pp.first;
984 if (pm.rows().empty())
987 // Find the row at which we set the cursor.
988 RowList::const_iterator rit = pm.rows().begin();
989 RowList::const_iterator rlast = pm.rows().end();
991 for (--rlast; rit != rlast; ++rit) {
992 int h = rit->height();
993 if ((up && yy + h > 0)
994 || (!up && yy + h > wh - defaultRowHeight()))
999 // Find the position of the cursor
1001 int x = d->synthetic_mouse_event_.cmd.x();
1002 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1007 cur.boundary(bound);
1009 d->buffer_view_->buffer().changed(false);
1013 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
1014 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
1016 qRegisterMetaType<KeySymbol>("KeySymbol");
1017 qRegisterMetaType<KeyModifier>("KeyModifier");
1018 connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
1019 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
1020 Qt::QueuedConnection);
1021 connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
1022 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1026 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1030 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1031 bool result = flag_;
1037 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1039 if (emitCheck(isAutoRepeat))
1040 Q_EMIT signal(sym, mod);
1042 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1046 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1048 // this is also called for ShortcutOverride events. In this case, one must
1049 // not act but simply accept the event explicitly.
1050 bool const act = (ev->type() != QEvent::ShortcutOverride);
1052 // Do not process here some keys if dialog_mode_ is set
1053 bool const for_dialog_mode = d->dialog_mode_
1054 && (ev->modifiers() == Qt::NoModifier
1055 || ev->modifiers() == Qt::ShiftModifier)
1056 && (ev->key() == Qt::Key_Escape
1057 || ev->key() == Qt::Key_Enter
1058 || ev->key() == Qt::Key_Return);
1059 // also do not use autoRepeat to input shortcuts
1060 bool const autoRepeat = ev->isAutoRepeat();
1062 if (for_dialog_mode || (!act && autoRepeat)) {
1067 // intercept some keys if completion popup is visible
1068 if (d->completer_->popupVisible()) {
1069 switch (ev->key()) {
1071 case Qt::Key_Return:
1073 d->completer_->activate();
1079 KeyModifier const m = q_key_state(ev->modifiers());
1081 if (act && lyxerr.debugging(Debug::KEY)) {
1083 if (m & ShiftModifier)
1085 if (m & ControlModifier)
1087 if (m & AltModifier)
1089 if (m & MetaModifier)
1091 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1092 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1093 << " keyState: " << str);
1097 setKeySymbol(&sym, ev);
1100 Q_EMIT compressKeySym(sym, m, autoRepeat);
1103 // here, !autoRepeat, as determined at the beginning
1104 ev->setAccepted(queryKeySym(sym, m));
1111 void GuiWorkArea::doubleClickTimeout()
1113 d->dc_event_.active = false;
1117 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1119 d->dc_event_ = DoubleClick(ev);
1120 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1121 SLOT(doubleClickTimeout()));
1122 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
1123 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->position().x(), ev->position().y(),
1125 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1127 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1133 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1135 QAbstractScrollArea::resizeEvent(ev);
1136 d->need_resize_ = true;
1141 void GuiWorkArea::queryInputItemTransform()
1145 "item_trans_ is aquired: dx() = " << d->item_trans_.dx() <<
1146 " -> " << d->im_->inputItemTransform().dx() <<
1147 ", dy() = " << d->item_trans_.dy() <<
1148 " -> " << d->im_->inputItemTransform().dy()
1151 d->item_trans_ = d->im_->inputItemTransform();
1155 void GuiWorkArea::Private::resetInputItemTransform()
1157 if (item_trans_needs_reset_) {
1161 ") item_trans_ is reset: dx() = " << im_->inputItemTransform().dx() <<
1162 " -> " << item_trans_.dx() <<
1163 ", dy() = " << im_->inputItemTransform().dy() <<
1164 " -> " << item_trans_.dy()
1166 im_->setInputItemTransform(item_trans_);
1167 item_trans_needs_reset_ = false;
1172 //#define DEBUG_PREEDIT
1174 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1176 #ifdef DEBUG_PREEDIT
1177 // check the language that current input method uses
1178 QLocale::Language lang = im_->locale().language();
1179 if (lang != im_lang_) {
1180 LYXERR0("QLocale = " << QLocale::languageToString(lang));
1185 // Chinese IM may want cursor position even when preedit string is empty
1186 // such a case is handled below
1187 if (preedit_string_.empty() && im_->locale().language() != QLocale::Chinese)
1190 // lower margin of the preedit area to separate the candidate window
1191 // report to IM the height of preedit rectangle larger than the actual by
1192 // preedit_lower_margin so that the conversion suggestion window does not
1193 // hide the underline of the preedit text
1194 int preedit_lower_margin = 1;
1198 buffer_view_->caretPosAndDim(point, dim);
1199 int cur_x = point.x_ - dim.width();
1200 int cur_y = point.y_ + dim.height();
1202 if (preedit_string_.empty()) {
1203 // Chinese input methods may exit here just obtaining im_cursor_rect
1205 QRectF(cur_x, cur_y - dim.height(), 1, dim.height() + preedit_lower_margin);
1206 im_->update(Qt::ImCursorRectangle);
1210 // reset item transformation since it can go wrong after the item gets
1211 // lost and regains focus or after a new tab (dis)appears etc.
1212 resetInputItemTransform();
1214 // FIXME: shall we use real_current_font here? (see #10478)
1215 FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1216 FontMetrics const & fm = theFontMetrics(font);
1218 // force fulldraw to remove previous paint remaining on screen
1219 // FIXME: This is costly to do
1220 buffer_view_->processUpdateFlags(Update::ForceDraw);
1222 // get attributes of input method cursor.
1223 // cursor_pos : cursor position in preedit string.
1224 size_t cursor_pos = 0;
1225 bool cursor_is_visible = false;
1226 for (auto const & attr : preedit_attr_) {
1227 if (attr.type == QInputMethodEvent::Cursor) {
1228 cursor_pos = size_t(attr.start);
1229 cursor_is_visible = attr.length != 0;
1234 size_t const preedit_length = preedit_string_.length();
1236 // get position of selection in input method.
1237 // FIXME: isn't there a simpler way to do this?
1238 // rStart : cursor position in selected string in IM.
1240 // rLength : selected string length in IM.
1242 if (cursor_pos < preedit_length) {
1243 for (auto const & attr : preedit_attr_) {
1244 if (attr.type == QInputMethodEvent::TextFormat) {
1245 if (attr.start <= int(cursor_pos)
1246 && int(cursor_pos) < attr.start + attr.length) {
1247 rStart = size_t(attr.start);
1248 rLength = size_t(attr.length);
1249 if (!cursor_is_visible)
1250 cursor_pos += rLength;
1257 rStart = cursor_pos;
1261 int const text_width = p->viewport()->width() - buffer_view_->rightMargin()
1262 - buffer_view_->leftMargin();
1263 Painter::preedit_style ps;
1264 // Most often there would be only one line:
1266 for (size_t pos = 0; pos != preedit_length; ++pos) {
1267 char_type const typed_char = preedit_string_[pos];
1268 // reset preedit string style
1269 ps = Painter::preedit_default;
1271 // if we reached the right extremity of the screen, go to next line.
1272 if (cur_x + fm.width(typed_char) > p->viewport()->width() - buffer_view_->rightMargin()) {
1273 cur_x = buffer_view_->leftMargin();
1274 cur_y += dim.height() + 1;
1277 // preedit strings are displayed with dashed underline
1278 // and partial strings are displayed white on black indicating
1279 // that we are in selecting mode in the input method.
1280 // FIXME: rLength == preedit_length is not a changing condition
1281 // FIXME: should be put out of the loop.
1283 && pos < rStart + rLength
1284 && !(cursor_pos < rLength && rLength == preedit_length)) {
1285 ps = Painter::preedit_selecting;
1288 if (pos == cursor_pos
1289 && (cursor_pos < rLength && rLength == preedit_length))
1290 ps = Painter::preedit_cursor;
1292 // draw one character and update cur_x.
1293 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1296 // the selection candidate window follows the position of Qt::ImCursorRectangle
1297 // so we set it here in preparation for InputMethodQuery.
1299 // candidate selection mode
1300 div_t mod_cur, mod_anc;
1301 // width of preedit string in pixels
1302 int preedit_width = fm.width(preedit_string_);
1303 // calculate for modular so that its remainder and quotient become horizontal
1304 // and vertical adjustment factor respectively
1305 // FIXME: divider should be (text_width - font width of the end-of-line character)
1306 // however, since it's very rare that preedit becomes so long that it goes over
1307 // more than two lines, current error of position is more or less negligible
1308 mod_cur = div(text_width + cur_x - (preedit_width - fm.width(preedit_string_.substr(0, rStart))),
1310 mod_anc = div(text_width + cur_x - (preedit_width - fm.width(preedit_string_.substr(0, rStart + rLength))),
1312 // Obtain cursor and anchor rectangles to bind starting and ending points of selection.
1313 // Since the remainder of div moves from positive to negative as the line becomes longer
1314 // while its quotient repeats zero twice, we need to take it into account by conditioning.
1315 if (mod_cur.rem >= 0)
1316 im_cursor_rect_ = QRectF(mod_cur.rem,
1317 (cur_y - dim.height()) + (dim.height() + 1) * (mod_cur.quot - 1), 1,
1318 dim.height() + preedit_lower_margin);
1320 im_cursor_rect_ = QRectF(text_width + mod_cur.rem,
1321 (cur_y - dim.height()) + (dim.height() + 1) * (mod_cur.quot - 2), 1,
1322 dim.height() + preedit_lower_margin);
1323 if (mod_anc.rem >= 0)
1324 im_anchor_rect_ = QRectF(mod_anc.rem,
1325 point.y_ + (dim.height() + 1) * (mod_anc.quot - 1), 1,
1326 dim.height() + preedit_lower_margin );
1328 im_anchor_rect_ = QRectF(text_width + mod_anc.rem,
1329 point.y_ + (dim.height() + 1) * (mod_anc.quot - 2), 1,
1330 dim.height() + preedit_lower_margin );
1332 im_cursor_rect_ = QRectF(point.x_, point.y_, 1, dim.height() + preedit_lower_margin);
1333 im_anchor_rect_ = im_cursor_rect_;
1335 // Urge platform input method to make inputMethodQuery to check the values
1337 im_->update(Qt::ImQueryInput);
1341 void GuiWorkArea::Private::resetScreen()
1343 if (use_backingstore_) {
1344 double const pr = p->pixelRatio();
1345 screen_ = QImage(int(pr * p->viewport()->width()),
1346 int(pr * p->viewport()->height()),
1347 QImage::Format_ARGB32_Premultiplied);
1348 screen_.setDevicePixelRatio(pr);
1353 QPaintDevice * GuiWorkArea::Private::screenDevice()
1355 if (use_backingstore_)
1358 return p->viewport();
1362 void GuiWorkArea::Private::updateScreen(QRectF const & rc)
1364 if (use_backingstore_) {
1365 QPainter qpain(p->viewport());
1366 double const pr = p->pixelRatio();
1367 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr,
1368 rc.width() * pr, rc.height() * pr);
1369 qpain.drawImage(rc, screen_, rcs);
1374 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1376 // Do not trigger the painting machinery if we are not ready (see
1377 // bug #10989). The second test triggers when in the middle of a
1378 // dispatch operation.
1379 if (view().busy() || d->buffer_view_->busy()) {
1380 // Since the screen may have turned black at this point, our
1381 // backing store has to be copied to screen. This is a no-op
1382 // except when our drawing strategy is "backingstore" (macOS,
1383 // Wayland, or set in prefs).
1384 d->updateScreen(ev->rect());
1385 // Ignore this paint event, but request a new one for later.
1386 viewport()->update(ev->rect());
1391 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1392 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1394 if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_) {
1399 d->last_pixel_ratio_ = pixelRatio();
1401 GuiPainter pain(d->screenDevice(), pixelRatio(), d->lyx_view_->develMode());
1403 d->buffer_view_->draw(pain, d->caret_visible_);
1405 // The preedit text, if needed
1406 d->paintPreeditText(pain);
1409 // FIXME: the code would be a little bit simpler if caret geometry
1410 // was updated unconditionally. Some profiling is required to see
1411 // how expensive this is (especially when idle).
1412 if (d->caret_visible_) {
1413 if (d->needs_caret_geometry_update_)
1414 d->updateCaretGeometry();
1415 d->drawCaret(pain, d->buffer_view_->horizScrollOffset());
1418 d->updateScreen(ev->rect());
1424 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1426 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1427 << " commitString: " << e->commitString());
1429 if (!e->commitString().isEmpty()) {
1431 // take care of commit string assigned to a shortcut
1432 // e.g. quotation mark on international keyboard
1434 for (QChar const & ch : e->commitString()) {
1436 keysym.init(ch.unicode());
1437 keyseq.addkey(keysym, NoModifier);
1439 cmd = theTopLevelKeymap().getBinding(keyseq);
1441 if (cmd == FuncRequest::noaction || cmd == FuncRequest::unknown
1442 || cmd.action() == LFUN_SELF_INSERT)
1443 // insert the processed text in the document (handles undo)
1444 cmd = FuncRequest(LFUN_SELF_INSERT, qstring_to_ucs4(e->commitString()));
1446 cmd.setOrigin(FuncRequest::KEYBOARD);
1448 // FIXME: this is supposed to remove traces from preedit
1449 // string. Can we avoid calling it explicitly?
1450 d->buffer_view_->updateMetrics();
1453 // Hide the caret during the test transformation.
1454 if (e->preeditString().isEmpty())
1455 startBlinkingCaret();
1457 stopBlinkingCaret();
1459 if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1465 // The preedit text and its attributes will be used in paintPreeditText
1466 d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1467 d->preedit_attr_ = e->attributes();
1470 // redraw area of preedit string.
1471 // int height = d->caret_->dim.height();
1472 // int cur_y = d->caret_->y;
1473 // viewport()->update(0, cur_y, viewport()->width(),
1474 // (height + 1) * d->preedit_lines_);
1475 viewport()->update();
1477 if (d->preedit_string_.empty()) {
1478 d->preedit_lines_ = 1;
1483 // Don't forget to accept the event!
1488 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1490 LYXERR(Debug::INFO, "incoming InputMethodQuery Value: 0x" << std::hex << query);
1492 // this is the CJK-specific composition window position and
1493 // the context menu position when the menu key is pressed.
1494 case Qt::ImCursorRectangle: {
1495 return QVariant(d->im_cursor_rect_);
1498 #if QT_VERSION >= QT_VERSION_CHECK(5, 7, 0)
1499 case Qt::ImAnchorRectangle: {
1500 return QVariant(d->im_anchor_rect_);
1505 return QWidget::inputMethodQuery(query);
1510 void GuiWorkArea::updateWindowTitle()
1512 Buffer const & buf = bufferView().buffer();
1513 if (buf.fileName() != d->file_name_
1514 || buf.params().shell_escape != d->shell_escape_
1515 || buf.hasReadonlyFlag() != d->read_only_
1516 || buf.lyxvc().vcstatus() != d->vc_status_
1517 || buf.isClean() != d->clean_
1518 || buf.notifiesExternalModification() != d->externally_modified_) {
1519 d->file_name_ = buf.fileName();
1520 d->shell_escape_ = buf.params().shell_escape;
1521 d->read_only_ = buf.hasReadonlyFlag();
1522 d->vc_status_ = buf.lyxvc().vcstatus();
1523 d->clean_ = buf.isClean();
1524 d->externally_modified_ = buf.notifiesExternalModification();
1525 Q_EMIT titleChanged(this);
1530 bool GuiWorkArea::isFullScreen() const
1532 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1536 bool GuiWorkArea::inDialogMode() const
1538 return d->dialog_mode_;
1542 void GuiWorkArea::setDialogMode(bool mode)
1544 d->dialog_mode_ = mode;
1548 GuiCompleter & GuiWorkArea::completer()
1550 return *d->completer_;
1553 GuiView const & GuiWorkArea::view() const
1555 return *d->lyx_view_;
1559 GuiView & GuiWorkArea::view()
1561 return *d->lyx_view_;
1564 ////////////////////////////////////////////////////////////////////
1568 ////////////////////////////////////////////////////////////////////
1571 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1573 support::TempFile tempfile("embedded.internal");
1574 tempfile.setAutoRemove(false);
1575 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1576 buffer_->setUnnamed(true);
1577 buffer_->setFullyLoaded(true);
1578 setBuffer(*buffer_);
1579 setDialogMode(true);
1583 EmbeddedWorkArea::~EmbeddedWorkArea()
1585 // No need to destroy buffer and bufferview here, because it is done
1586 // in theBufferList() destruction loop at application exit
1590 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1593 GuiWorkArea::closeEvent(ev);
1597 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1600 GuiWorkArea::hideEvent(ev);
1604 QSize EmbeddedWorkArea::sizeHint () const
1607 // GuiWorkArea sets the size to the screen's viewport
1608 // by returning a value this gets overridden
1609 // EmbeddedWorkArea is now sized to fit in the layout
1610 // of the parent, and has a minimum size set in GuiWorkArea
1611 // which is what we return here
1612 return QSize(100, 70);
1616 void EmbeddedWorkArea::disable()
1618 stopBlinkingCaret();
1619 if (view().currentWorkArea() != this)
1621 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1622 // tolerates it and shows the background logo), what happens if
1623 // an EmbeddedWorkArea is closed after closing all document WAs
1624 view().setCurrentWorkArea(view().currentMainWorkArea());
1627 ////////////////////////////////////////////////////////////////////
1631 ////////////////////////////////////////////////////////////////////
1633 TabWorkArea::TabWorkArea(QWidget * parent)
1634 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1636 QPalette pal = palette();
1637 pal.setColor(QPalette::Active, QPalette::Button,
1638 pal.color(QPalette::Active, QPalette::Window));
1639 pal.setColor(QPalette::Disabled, QPalette::Button,
1640 pal.color(QPalette::Disabled, QPalette::Window));
1641 pal.setColor(QPalette::Inactive, QPalette::Button,
1642 pal.color(QPalette::Inactive, QPalette::Window));
1644 QObject::connect(this, SIGNAL(currentChanged(int)),
1645 this, SLOT(on_currentTabChanged(int)));
1647 QObject::connect(this, SIGNAL(tabBarClicked(int)),
1648 this, SLOT(on_currentTabChanged(int)));
1650 closeBufferButton = new QToolButton(this);
1651 closeBufferButton->setPalette(pal);
1652 // FIXME: rename the icon to closebuffer.png
1653 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1654 closeBufferButton->setText("Close File");
1655 closeBufferButton->setAutoRaise(true);
1656 closeBufferButton->setCursor(Qt::ArrowCursor);
1657 closeBufferButton->setToolTip(qt_("Close File"));
1658 closeBufferButton->setEnabled(true);
1659 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1660 this, SLOT(closeCurrentBuffer()));
1661 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1663 // set TabBar behaviour
1664 QTabBar * tb = tabBar();
1665 tb->setTabsClosable(!lyxrc.single_close_tab_button);
1666 tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1667 tb->setElideMode(Qt::ElideNone);
1668 // allow dragging tabs
1669 tb->setMovable(true);
1670 // make us responsible for the context menu of the tabbar
1671 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1672 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1673 this, SLOT(showContextMenu(const QPoint &)));
1674 connect(tb, SIGNAL(tabCloseRequested(int)),
1675 this, SLOT(closeTab(int)));
1677 setUsesScrollButtons(true);
1679 // use document mode tabs
1680 setDocumentMode(true);
1685 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1687 if (me->button() == Qt::MiddleButton)
1688 midpressed_tab_ = tabBar()->tabAt(me->pos());
1690 QTabWidget::mousePressEvent(me);
1694 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1696 if (me->button() == Qt::MiddleButton) {
1697 int const midreleased_tab = tabBar()->tabAt(me->pos());
1698 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1699 closeTab(midreleased_tab);
1701 QTabWidget::mouseReleaseEvent(me);
1705 void TabWorkArea::paintEvent(QPaintEvent * event)
1707 if (tabBar()->isVisible()) {
1708 QTabWidget::paintEvent(event);
1710 // Prevent the selected tab to influence the
1711 // painting of the frame of the tab widget.
1712 // This is needed for gtk style in Qt.
1713 QStylePainter p(this);
1714 QStyleOptionTabWidgetFrame opt;
1715 initStyleOption(&opt);
1716 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1718 opt.selectedTabRect = QRect();
1719 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1724 bool TabWorkArea::posIsTab(QPoint position)
1726 // tabAt returns -1 if tab does not covers position
1727 return tabBar()->tabAt(position) > -1;
1731 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1733 if (event->button() != Qt::LeftButton)
1736 // this code chunk is unnecessary because it seems the event only makes
1737 // it this far if it is not on a tab. I'm not sure why this is (maybe
1738 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1739 // this is true in all cases and if it will be true in the future so I
1740 // leave this code for now. (skostysh, 2016-07-21)
1742 // return early if double click on existing tabs
1743 if (posIsTab(event->pos()))
1746 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1750 void TabWorkArea::setFullScreen(bool full_screen)
1752 for (int i = 0; i != count(); ++i) {
1753 if (GuiWorkArea * wa = workArea(i))
1754 wa->setFullScreen(full_screen);
1757 if (lyxrc.full_screen_tabbar)
1758 showBar(!full_screen && count() > 1);
1760 showBar(count() > 1);
1764 void TabWorkArea::showBar(bool show)
1766 tabBar()->setEnabled(show);
1767 tabBar()->setVisible(show);
1768 if (documentMode()) {
1769 // avoid blank corner widget when documentMode(true) is used
1770 if (show && lyxrc.single_close_tab_button) {
1771 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1772 closeBufferButton->setVisible(true);
1774 // remove corner widget
1775 setCornerWidget(nullptr);
1777 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1778 setTabsClosable(!lyxrc.single_close_tab_button);
1782 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1784 QWidget * w = QTabWidget::widget(index);
1787 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1793 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1795 return widget(currentIndex());
1799 GuiWorkArea * TabWorkArea::workArea(int index) const
1801 GuiWorkAreaContainer * w = widget(index);
1804 return w->workArea();
1808 GuiWorkArea * TabWorkArea::currentWorkArea() const
1810 return workArea(currentIndex());
1814 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1816 // FIXME: this method doesn't work if we have more than one work area
1817 // showing the same buffer.
1818 for (int i = 0; i != count(); ++i) {
1819 GuiWorkArea * wa = workArea(i);
1820 LASSERT(wa, return nullptr);
1821 if (&wa->bufferView().buffer() == &buffer)
1828 void TabWorkArea::closeAll()
1831 QWidget * wac = widget(0);
1832 LASSERT(wac, return);
1839 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1841 for (int index = 0; index < count(); ++index)
1842 if (workArea(index) == w)
1848 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1850 LASSERT(work_area, return false);
1851 int index = indexOfWorkArea(work_area);
1855 if (index == currentIndex())
1856 // Make sure the work area is up to date.
1857 on_currentTabChanged(index);
1859 // Switch to the work area.
1860 setCurrentIndex(index);
1861 work_area->setFocus(Qt::OtherFocusReason);
1867 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1870 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1871 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1872 wa->setUpdatesEnabled(false);
1873 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1874 // when hiding it again below).
1875 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1876 showBar(count() > 0);
1877 addTab(wac, wa->windowTitle());
1878 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1879 this, SLOT(updateTabTexts()));
1880 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1881 setFullScreen(true);
1883 // Hide tabbar if there's only one tab.
1884 showBar(count() > 1);
1888 // obtain new input item coordinates in the new and old work areas
1889 wa->queryInputItemTransform();
1890 if (currentWorkArea())
1891 currentWorkArea()->queryInputItemTransform();
1893 view.setBusy(false);
1899 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1901 LASSERT(work_area, return false);
1902 int index = indexOfWorkArea(work_area);
1906 work_area->setUpdatesEnabled(false);
1907 QWidget * wac = widget(index);
1912 // make sure the next work area is enabled.
1913 currentWidget()->setUpdatesEnabled(true);
1914 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1915 setFullScreen(true);
1917 // Show tabbar only if there's more than one tab.
1918 showBar(count() > 1);
1919 currentWorkArea()->queryInputItemTransform();
1921 lastWorkAreaRemoved();
1929 void TabWorkArea::on_currentTabChanged(int i)
1931 // returns e.g. on application destruction
1934 GuiWorkArea * wa = workArea(i);
1935 LASSERT(wa, return);
1936 wa->setUpdatesEnabled(true);
1937 wa->scheduleRedraw(true);
1940 currentWorkAreaChanged(wa);
1942 LYXERR(Debug::GUI, "currentTabChanged " << i
1943 << " File: " << wa->bufferView().buffer().absFileName());
1947 void TabWorkArea::closeCurrentBuffer()
1950 if (clicked_tab_ == -1)
1951 wa = currentWorkArea();
1953 wa = workArea(clicked_tab_);
1954 LASSERT(wa, return);
1956 wa->view().closeWorkArea(wa);
1960 void TabWorkArea::hideCurrentTab()
1963 if (clicked_tab_ == -1)
1964 wa = currentWorkArea();
1966 wa = workArea(clicked_tab_);
1967 LASSERT(wa, return);
1969 wa->view().hideWorkArea(wa);
1973 void TabWorkArea::closeTab(int index)
1975 on_currentTabChanged(index);
1978 wa = currentWorkArea();
1980 wa = workArea(index);
1981 LASSERT(wa, return);
1983 wa->view().closeWorkArea(wa);
1990 /// make vector happy
1991 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1993 DisplayPath(int tab, FileName const & filename)
1996 // Recode URL encoded chars via fromPercentEncoding()
1997 string const fn = (filename.extension() == "lyx")
1998 ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
1999 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
2000 #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
2001 postfix_ = toqstr(filename.absoluteFilePath()).
2002 split("/", Qt::SkipEmptyParts);
2004 postfix_ = toqstr(filename.absoluteFilePath()).
2005 split("/", QString::SkipEmptyParts);
2007 postfix_.pop_back();
2008 abs_ = toqstr(filename.absoluteFilePath());
2009 dottedPrefix_ = false;
2012 /// Absolute path for debugging.
2017 /// Add the first segment from the postfix or three dots to the prefix.
2018 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
2019 /// when really needed.
2020 void shiftPathSegment(bool dotted)
2022 if (postfix_.count() <= 0)
2026 if (dottedPrefix_ && !prefix_.isEmpty())
2027 prefix_ += ellipsisSlash_;
2028 prefix_ += postfix_.front() + "/";
2030 dottedPrefix_ = dotted && !prefix_.isEmpty();
2031 postfix_.pop_front();
2034 QString displayString() const
2036 if (prefix_.isEmpty())
2039 bool dots = dottedPrefix_ || !postfix_.isEmpty();
2040 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
2043 QString forecastPathString() const
2045 if (postfix_.count() == 0)
2046 return displayString();
2049 + (dottedPrefix_ ? ellipsisSlash_ : "")
2050 + postfix_.front() + "/";
2053 bool final() const { return postfix_.empty(); }
2055 int tab() const { return tab_; }
2059 static QString const ellipsisSlash_;
2063 QStringList postfix_;
2075 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
2079 bool operator<(DisplayPath const & a, DisplayPath const & b)
2081 return a.displayString() < b.displayString();
2085 bool operator==(DisplayPath const & a, DisplayPath const & b)
2087 return a.displayString() == b.displayString();
2091 void TabWorkArea::updateTabTexts()
2093 int const n = count();
2096 std::list<DisplayPath> paths;
2097 typedef std::list<DisplayPath>::iterator It;
2099 // collect full names first: path into postfix, empty prefix and
2100 // filename without extension
2101 for (int i = 0; i < n; ++i) {
2102 GuiWorkArea * i_wa = workArea(i);
2103 FileName const fn = i_wa->bufferView().buffer().fileName();
2104 paths.push_back(DisplayPath(i, fn));
2107 // go through path segments and see if it helps to make the path more unique
2108 bool somethingChanged = true;
2109 bool allFinal = false;
2110 while (somethingChanged && !allFinal) {
2111 // adding path segments changes order
2114 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
2115 somethingChanged = false;
2118 // find segments which are not unique (i.e. non-atomic)
2119 It it = paths.begin();
2121 QString segString = it->displayString();
2122 for (; it != paths.end(); ++it) {
2123 // look to the next item
2128 allFinal = allFinal && it->final();
2130 LYXERR(Debug::GUI, "it = " << it->abs()
2131 << " => " << it->displayString());
2133 // still the same segment?
2135 if ((next != paths.end()
2136 && (nextString = next->displayString()) == segString))
2138 LYXERR(Debug::GUI, "segment ended");
2140 // only a trivial one with one element?
2141 if (it == segStart) {
2142 // start new segment
2144 segString = nextString;
2148 // We found a non-atomic segment
2149 // We know that segStart <= it < next <= paths.end().
2150 // The assertion below tells coverity about it.
2151 LATTEST(segStart != paths.end());
2152 QString dspString = segStart->forecastPathString();
2153 LYXERR(Debug::GUI, "first forecast found for "
2154 << segStart->abs() << " => " << dspString);
2157 // Shift path segments and hope for the best
2158 // that it makes the path more unique.
2159 somethingChanged = true;
2160 bool moreUnique = false;
2161 for (; sit != next; ++sit) {
2162 if (sit->forecastPathString() != dspString) {
2163 LYXERR(Debug::GUI, "different forecast found for "
2164 << sit->abs() << " => " << sit->forecastPathString());
2168 LYXERR(Debug::GUI, "same forecast found for "
2169 << sit->abs() << " => " << dspString);
2172 // if the path segment helped, add it. Otherwise add dots
2173 bool dots = !moreUnique;
2174 LYXERR(Debug::GUI, "using dots = " << dots);
2175 for (sit = segStart; sit != next; ++sit) {
2176 sit->shiftPathSegment(dots);
2177 LYXERR(Debug::GUI, "shifting "
2178 << sit->abs() << " => " << sit->displayString());
2181 // start new segment
2183 segString = nextString;
2187 // set new tab titles
2188 for (It it = paths.begin(); it != paths.end(); ++it) {
2189 int const tab_index = it->tab();
2190 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2191 QString tab_text = it->displayString().replace("&", "&&");
2192 if (!buf.fileName().empty() && !buf.isClean())
2194 QString tab_tooltip = it->abs();
2195 if (buf.hasReadonlyFlag()) {
2197 QLabel * readOnlyButton = new QLabel();
2198 QIcon icon = QIcon(getPixmap("images/", "emblem-readonly", "svgz,png"));
2199 readOnlyButton->setPixmap(icon.pixmap(QSize(16, 16)));
2200 tabBar()->setTabButton(tab_index, QTabBar::RightSide, readOnlyButton);
2202 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2204 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2207 tabBar()->setTabButton(tab_index, QTabBar::RightSide, 0);
2209 setTabIcon(tab_index, QIcon());
2211 if (buf.notifiesExternalModification()) {
2212 QString const warn = qt_("%1 (modified externally)");
2213 tab_tooltip = warn.arg(tab_tooltip);
2214 tab_text += QChar(0x26a0);
2216 setTabText(tab_index, tab_text);
2217 setTabToolTip(tab_index, tab_tooltip);
2222 void TabWorkArea::showContextMenu(const QPoint & pos)
2225 clicked_tab_ = tabBar()->tabAt(pos);
2226 if (clicked_tab_ == -1)
2229 GuiWorkArea * wa = workArea(clicked_tab_);
2230 LASSERT(wa, return);
2234 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2235 qt_("&Hide Tab"), this, SLOT(hideCurrentTab()));
2237 // we want to show the 'close' option only if this is not a child buffer.
2238 Buffer const & buf = wa->bufferView().buffer();
2240 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2241 qt_("&Close Tab"), this, SLOT(closeCurrentBuffer()));
2242 popup.exec(tabBar()->mapToGlobal(pos));
2248 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2250 QWidget * w = widget(fromIndex);
2251 QIcon icon = tabIcon(fromIndex);
2252 QString text = tabText(fromIndex);
2254 setCurrentIndex(fromIndex);
2255 removeTab(fromIndex);
2256 insertTab(toIndex, w, icon, text);
2257 setCurrentIndex(toIndex);
2261 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2262 : QWidget(parent), wa_(wa)
2264 LASSERT(wa, return);
2265 Ui::WorkAreaUi::setupUi(this);
2266 layout()->addWidget(wa);
2267 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2268 this, SLOT(updateDisplay()));
2269 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2270 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2271 setMessageColour({notificationFrame, externalModificationLabel},
2272 {reloadPB, ignorePB});
2277 void GuiWorkAreaContainer::updateDisplay()
2279 Buffer const & buf = wa_->bufferView().buffer();
2280 notificationFrame->setHidden(!buf.notifiesExternalModification());
2281 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2282 .arg(toqstr(buf.fileName().displayName()));
2283 externalModificationLabel->setText(label);
2287 void GuiWorkAreaContainer::dispatch(FuncRequest const & f) const
2289 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2290 wa_->bufferView().buffer().absFileName()));
2295 void GuiWorkAreaContainer::reload() const
2297 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2301 void GuiWorkAreaContainer::ignore() const
2303 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2307 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2309 // prevent TabWorkArea from opening a new buffer on double click
2314 } // namespace frontend
2317 #include "moc_GuiWorkArea.cpp"