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"
34 #include "KeySymbol.h"
39 #include "TextMetrics.h"
43 #include "support/convert.h"
44 #include "support/debug.h"
45 #include "support/lassert.h"
46 #include "support/TempFile.h"
48 #include "frontends/Application.h"
49 #include "frontends/CaretGeometry.h"
51 #include "frontends/FontMetrics.h"
52 #include "frontends/WorkAreaManager.h"
54 #include <QContextMenuEvent>
55 #if (QT_VERSION < 0x050000)
56 #include <QInputContext>
61 #include <QProxyStyle>
63 #include <QMainWindow>
69 #include <QStyleOption>
70 #include <QStylePainter>
72 #include <QToolButton>
83 using namespace lyx::support;
88 /// return the LyX mouse button state from Qt's
89 static mouse_button::state q_button_state(Qt::MouseButton button)
91 mouse_button::state b = mouse_button::none;
94 b = mouse_button::button1;
96 case Qt::MiddleButton:
97 b = mouse_button::button2;
100 b = mouse_button::button3;
109 /// return the LyX mouse button state from Qt's
110 mouse_button::state q_motion_state(Qt::MouseButtons state)
112 mouse_button::state b = mouse_button::none;
113 if (state & Qt::LeftButton)
114 b |= mouse_button::button1;
115 if (state & Qt::MiddleButton)
116 b |= mouse_button::button2;
117 if (state & Qt::RightButton)
118 b |= mouse_button::button3;
125 // This is a 'heartbeat' generating synthetic mouse move events when the
126 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
127 SyntheticMouseEvent::SyntheticMouseEvent()
128 : timeout(200), restart_timeout(true)
132 GuiWorkArea::Private::Private(GuiWorkArea * parent)
133 : p(parent), completer_(new GuiCompleter(p, p))
135 /* Qt on macOS and Wayland does not respect the
136 * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
137 * store at each update. Therefore, we use our own backing store
138 * in these two cases.
140 use_backingstore_ = guiApp->platformName() == "cocoa"
141 || guiApp->platformName().contains("wayland");
143 int const time = QApplication::cursorFlashTime() / 2;
145 caret_timeout_.setInterval(time);
146 caret_timeout_.start();
148 // let's initialize this just to be safe
149 caret_timeout_.setInterval(500);
154 GuiWorkArea::Private::~Private()
156 // If something is wrong with the buffer, we can ignore it safely
158 buffer_view_->buffer().workAreaManager().remove(p);
161 // Completer has a QObject parent and is thus automatically destroyed.
163 // delete completer_;
167 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
168 : d(new Private(this))
170 new CompressorProxy(this); // not a leak
174 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
175 : d(new Private(this))
177 new CompressorProxy(this); // not a leak
179 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
185 double GuiWorkArea::pixelRatio() const
187 #if QT_VERSION >= 0x050000
188 return qt_scale_factor * devicePixelRatio();
195 void GuiWorkArea::init()
198 connect(&d->caret_timeout_, SIGNAL(timeout()),
199 this, SLOT(toggleCaret()));
201 // This connection is closed at the same time as this is destroyed.
202 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
203 generateSyntheticMouseEvent();
207 // With Qt4.5 a mouse event will happen before the first paint event
208 // so make sure that the buffer view has an up to date metrics.
209 d->buffer_view_->resize(viewport()->width(), viewport()->height());
211 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
212 setAcceptDrops(true);
213 setMouseTracking(true);
214 setMinimumSize(100, 70);
215 setFrameStyle(QFrame::NoFrame);
218 d->updateCursorShape();
220 // we paint our own background
221 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
223 setFocusPolicy(Qt::StrongFocus);
225 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
226 << " viewport height: " << viewport()->height());
228 // Enables input methods for asian languages.
229 // Must be set when creating custom text editing widgets.
230 setAttribute(Qt::WA_InputMethodEnabled, true);
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);
289 if (full_screen && lyxrc.full_screen_scrollbar)
290 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
292 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
296 BufferView & GuiWorkArea::bufferView()
298 return *d->buffer_view_;
302 BufferView const & GuiWorkArea::bufferView() const
304 return *d->buffer_view_;
308 void GuiWorkArea::stopBlinkingCaret()
310 d->caret_timeout_.stop();
315 void GuiWorkArea::startBlinkingCaret()
317 // do not show the cursor if the view is busy
321 // Don't start blinking if the cursor isn't on screen, unless we
322 // are not ready to know whether the cursor is on screen.
323 if (!d->buffer_view_->buffer().undo().activeUndoGroup()
324 && !d->buffer_view_->caretInView())
329 // Avoid blinking when debugging PAINTING, since it creates too much noise
330 if (!lyxerr.debugging(Debug::PAINTING)) {
331 // we are not supposed to cache this value.
332 int const time = QApplication::cursorFlashTime() / 2;
335 d->caret_timeout_.setInterval(time);
336 d->caret_timeout_.start();
341 void GuiWorkArea::toggleCaret()
343 if (d->caret_visible_)
350 void GuiWorkArea::scheduleRedraw(bool update_metrics)
353 // No need to redraw in this case.
356 // No need to do anything if this is the current view. The BufferView
357 // metrics are already up to date.
358 if (update_metrics || d->lyx_view_ != guiApp->currentView()
359 || d->lyx_view_->currentWorkArea() != this) {
360 // FIXME: it would be nice to optimize for the off-screen case.
361 d->buffer_view_->cursor().fixIfBroken();
362 d->buffer_view_->updateMetrics();
363 d->buffer_view_->cursor().fixIfBroken();
366 // update caret position, because otherwise it has to wait until
367 // the blinking interval is over
370 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
371 viewport()->update();
373 /// FIXME: is this still true now that paintEvent does the actual painting?
374 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
375 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
376 d->updateScrollbar();
377 d->lyx_view_->updateStatusBar();
379 if (lyxerr.debugging(Debug::WORKAREA))
380 d->buffer_view_->coordCache().dump();
384 d->updateCursorShape();
388 // Keep in sync with GuiWorkArea::processKeySym below
389 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
391 return guiApp->queryKeySym(key, mod);
395 // Keep in sync with GuiWorkArea::queryKeySym above
396 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
398 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
399 && lyxrc.full_screen_menubar) {
400 // FIXME HACK: we should not have to do this here. See related comment
401 // in GuiView::event() (QEvent::ShortcutOverride)
402 d->lyx_view_->menuBar()->hide();
405 // In order to avoid bad surprise in the middle of an operation,
406 // we better stop the blinking caret...
407 // the caret gets restarted in GuiView::restartCaret()
409 guiApp->processKeySym(key, mod);
413 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
416 if (cmd.action() == LFUN_FILE_OPEN) {
418 lyx_view_->dispatch(cmd, dr);
422 bool const notJustMovingTheMouse =
423 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
425 // In order to avoid bad surprise in the middle of an operation, we better stop
426 // the blinking caret.
427 if (notJustMovingTheMouse)
428 p->stopBlinkingCaret();
430 buffer_view_->mouseEventDispatch(cmd);
432 // Skip these when selecting
433 // FIXME: let GuiView take care of those.
434 if (cmd.action() != LFUN_MOUSE_MOTION) {
435 completer_->updateVisibility(false, false);
436 lyx_view_->updateDialogs();
437 lyx_view_->updateStatusBar();
440 // GUI tweaks except with mouse motion with no button pressed.
441 if (notJustMovingTheMouse) {
442 // Slight hack: this is only called currently when we
443 // clicked somewhere, so we force through the display
444 // of the new status here.
445 // FIXME: let GuiView take care of those.
446 lyx_view_->clearMessage();
448 // Show the caret immediately after any operation
449 p->startBlinkingCaret();
456 void GuiWorkArea::Private::resizeBufferView()
458 // WARNING: Please don't put any code that will trigger a repaint here!
459 // We are already inside a paint event.
460 p->stopBlinkingCaret();
461 // Warn our container (GuiView).
464 bool const caret_in_view = buffer_view_->caretInView();
465 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
467 buffer_view_->showCursor();
470 // Update scrollbars which might have changed due different
471 // BufferView dimension. This is especially important when the
472 // BufferView goes from zero-size to the real-size for the first time,
473 // as the scrollbar parameters are then set for the first time.
476 need_resize_ = false;
478 // Eventually, restart the caret after the resize event.
479 // We might be resizing even if the focus is on another widget so we only
480 // restart the caret if we have the focus.
482 QTimer::singleShot(50, p, SLOT(startBlinkingCaret()));
486 void GuiWorkArea::Private::resetCaret()
488 // Don't start blinking if the cursor isn't on screen.
489 if (!buffer_view_->caretInView())
492 // completion indicator
493 Cursor const & cur = buffer_view_->cursor();
494 bool const completable = cur.inset().showCompletionCursor()
495 && completer_->completionAvailable()
496 && !completer_->popupVisible()
497 && !completer_->inlineVisible();
499 buffer_view_->buildCaretGeometry(completable);
501 needs_caret_geometry_update_ = true;
502 caret_visible_ = true;
506 void GuiWorkArea::Private::updateCaretGeometry()
508 // we cannot update geometry if not ready and we do not need to if
509 // caret is not in view.
510 if (buffer_view_->buffer().undo().activeUndoGroup()
511 || !buffer_view_->caretInView())
515 needs_caret_geometry_update_ = false;
519 void GuiWorkArea::Private::showCaret()
525 p->viewport()->update();
529 void GuiWorkArea::Private::hideCaret()
534 caret_visible_ = false;
535 //if (!qApp->focusWidget())
536 p->viewport()->update();
540 /* Draw the caret. Parameter \c horiz_offset is not 0 when there
541 * has been horizontal scrolling in current row
543 void GuiWorkArea::Private::drawCaret(QPainter & painter, int horiz_offset) const
545 if (buffer_view_->caretGeometry().shapes.empty())
548 QColor const color = guiApp->colorCache().get(Color_cursor);
549 painter.setPen(color);
550 painter.setRenderHint(QPainter::Antialiasing, true);
551 for (auto const & shape : buffer_view_->caretGeometry().shapes) {
554 for (Point const & p : shape) {
556 path.moveTo(p.x_ - horiz_offset, p.y_);
559 path.lineTo(p.x_ - horiz_offset, p.y_);
561 painter.fillPath(path, color);
563 painter.setRenderHint(QPainter::Antialiasing, false);
567 void GuiWorkArea::Private::updateScrollbar()
569 // Prevent setRange() and setSliderPosition from causing recursive calls via
570 // the signal valueChanged. (#10311)
571 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
572 p, SLOT(scrollTo(int)));
573 ScrollbarParameters const & scroll = buffer_view_->scrollbarParameters();
574 p->verticalScrollBar()->setRange(scroll.min, scroll.max);
575 p->verticalScrollBar()->setPageStep(scroll.page_step);
576 p->verticalScrollBar()->setSingleStep(scroll.single_step);
577 p->verticalScrollBar()->setSliderPosition(0);
578 // Connect to the vertical scroll bar
579 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
580 p, SLOT(scrollTo(int)));
584 void GuiWorkArea::scrollTo(int value)
587 d->buffer_view_->scrollDocView(value, true);
589 if (lyxrc.cursor_follows_scrollbar) {
590 d->buffer_view_->setCursorFromScrollbar();
591 // FIXME: let GuiView take care of those.
592 d->lyx_view_->updateLayoutList();
594 // Show the caret immediately after any operation.
595 startBlinkingCaret();
598 QApplication::syncX();
603 bool GuiWorkArea::event(QEvent * e)
606 case QEvent::ToolTip: {
607 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
608 if (lyxrc.use_tooltip) {
609 QPoint pos = helpEvent->pos();
610 if (pos.x() < viewport()->width()) {
611 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
612 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
615 QToolTip::hideText();
617 // Don't forget to accept the event!
622 case QEvent::ShortcutOverride:
623 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
625 keyPressEvent(static_cast<QKeyEvent *>(e));
626 return e->isAccepted();
628 case QEvent::KeyPress: {
629 // We catch this event in order to catch the Tab or Shift+Tab key press
630 // which are otherwise reserved to focus switching between controls
632 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
633 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
634 || (ke->key() == Qt::Key_Backtab && (
635 ke->modifiers() == Qt::ShiftModifier
636 || ke->modifiers() == Qt::NoModifier))) {
640 return QAbstractScrollArea::event(e);
644 return QAbstractScrollArea::event(e);
650 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
653 if (e->reason() == QContextMenuEvent::Mouse)
654 // the menu name is set on mouse press
655 name = d->context_menu_name_;
657 QPoint pos = e->pos();
658 Cursor const & cur = d->buffer_view_->cursor();
659 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
660 // Do not access the context menu of math right in front of before
661 // the cursor. This does not work when the cursor is in text.
662 Inset * inset = cur.paragraph().getInset(cur.pos());
663 if (inset && inset->asInsetMath())
665 else if (cur.pos() > 0) {
666 inset = cur.paragraph().getInset(cur.pos() - 1);
671 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
678 // always show mnemonics when the keyboard is used to show the context menu
679 // FIXME: This should be fixed in Qt itself
680 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
681 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
686 // Position the menu to the right.
687 // FIXME: menu position should be different for RTL text.
688 menu->exec(e->globalPos());
693 void GuiWorkArea::focusInEvent(QFocusEvent * e)
695 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
696 if (d->lyx_view_->currentWorkArea() != this) {
697 d->lyx_view_->setCurrentWorkArea(this);
698 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
701 startBlinkingCaret();
702 QAbstractScrollArea::focusInEvent(e);
706 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
708 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
710 QAbstractScrollArea::focusOutEvent(e);
714 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
716 if (d->dc_event_.active && d->dc_event_ == *e) {
717 d->dc_event_.active = false;
718 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
719 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->position().x(), e->position().y(),
721 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
723 q_button_state(e->button()), q_key_state(e->modifiers()));
729 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
730 inputContext()->reset();
733 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
734 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->position().x(), e->position().y(),
736 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
738 q_button_state(e->button()), q_key_state(e->modifiers()));
741 // Save the context menu on mouse press, because also the mouse
742 // cursor is set on mouse press. Afterwards, we can either release
743 // the mousebutton somewhere else, or the cursor might have moved
744 // due to the DEPM. We need to do this after the mouse has been
745 // set in dispatch(), because the selection state might change.
746 if (e->button() == Qt::RightButton)
747 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
748 d->context_menu_name_ = d->buffer_view_->contextMenu(e->position().x(), e->position().y());
750 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
757 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
759 if (d->synthetic_mouse_event_.timeout.running())
760 d->synthetic_mouse_event_.timeout.stop();
762 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
763 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->position().x(), e->position().y(),
765 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
767 q_button_state(e->button()), q_key_state(e->modifiers()));
768 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
769 QT_VERSION < QT_VERSION_CHECK(5,15,1))
770 d->synthetic_mouse_event_.cmd = cmd; // QtBug QAbstractScrollArea::mouseMoveEvent
777 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
779 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
780 QT_VERSION < QT_VERSION_CHECK(5,15,1))
781 // cancel the event if the coordinates didn't change, this is due to QtBug
782 // QAbstractScrollArea::mouseMoveEvent, the event is triggered falsely when quickly
783 // double tapping a touchpad. To test: try to select a word by quickly double tapping
784 // on a touchpad while hovering the cursor over that word in the work area.
785 // This bug does not occur on Qt versions 5.10.1 and below. Only Windows seems to be affected.
786 // ML thread: https://www.mail-archive.com/lyx-devel@lists.lyx.org/msg211699.html
787 // Qt bugtracker: https://bugreports.qt.io/browse/QTBUG-85431
788 // Bug was fixed in Qt 5.15.1
789 if (e->x() == d->synthetic_mouse_event_.cmd.x() && // QtBug QAbstractScrollArea::mouseMoveEvent
790 e->y() == d->synthetic_mouse_event_.cmd.y()) // QtBug QAbstractScrollArea::mouseMoveEvent
791 return; // QtBug QAbstractScrollArea::mouseMoveEvent
794 // we kill the triple click if we move
795 doubleClickTimeout();
796 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
797 FuncRequest cmd(LFUN_MOUSE_MOTION, e->position().x(), e->position().y(),
799 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
801 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
805 // If we're above or below the work area...
806 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
807 if ((e->position().y() <= 20 || e->position().y() >= viewport()->height() - 20)
809 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
811 && e->buttons() == mouse_button::button1) {
812 // Make sure only a synthetic event can cause a page scroll,
813 // so they come at a steady rate:
814 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
815 if (e->position().y() <= 20)
816 // _Force_ a scroll up:
817 cmd.set_y(e->position().y() - 21);
819 cmd.set_y(e->position().y() + 21);
822 // _Force_ a scroll up:
823 cmd.set_y(e->y() - 21);
825 cmd.set_y(e->y() + 21);
827 // Store the event, to be handled when the timeout expires.
828 d->synthetic_mouse_event_.cmd = cmd;
830 if (d->synthetic_mouse_event_.timeout.running()) {
831 // Discard the event. Note that it _may_ be handled
832 // when the timeout expires if
833 // synthetic_mouse_event_.cmd has not been overwritten.
834 // Ie, when the timeout expires, we handle the
835 // most recent event but discard all others that
836 // occurred after the one used to start the timeout
837 // in the first place.
841 d->synthetic_mouse_event_.restart_timeout = true;
842 d->synthetic_mouse_event_.timeout.start();
843 // Fall through to handle this event...
845 } else if (d->synthetic_mouse_event_.timeout.running()) {
846 // Store the event, to be possibly handled when the timeout
848 // Once the timeout has expired, normal control is returned
849 // to mouseMoveEvent (restart_timeout = false).
850 // This results in a much smoother 'feel' when moving the
851 // mouse back into the work area.
852 d->synthetic_mouse_event_.cmd = cmd;
853 d->synthetic_mouse_event_.restart_timeout = false;
860 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
862 // Wheel rotation by one notch results in a delta() of 120 (see
863 // documentation of QWheelEvent)
864 // But first we have to ignore horizontal scroll events.
865 #if QT_VERSION < 0x050000
866 if (ev->orientation() == Qt::Horizontal) {
870 double const delta = ev->delta() / 120.0;
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;
882 switch (lyxrc.scroll_wheel_zoom) {
883 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
884 zoom = ev->modifiers() & Qt::ControlModifier;
885 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
887 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
888 zoom = ev->modifiers() & Qt::ShiftModifier;
889 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
891 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
892 zoom = ev->modifiers() & Qt::AltModifier;
893 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
895 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
899 docstring arg = convert<docstring>(int(5 * delta));
900 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
904 // Take into account the desktop wide settings.
905 int const lines = qApp->wheelScrollLines();
906 int const page_step = verticalScrollBar()->pageStep();
907 // Test if the wheel mouse is set to one screen at a time.
908 // This is according to
909 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
911 min(lines * verticalScrollBar()->singleStep(), page_step);
913 // Take into account the rotation and the user preferences.
914 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
915 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
916 << " delta = " << delta << " scroll_value = " << scroll_value
917 << " page_step = " << page_step);
919 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
925 void GuiWorkArea::generateSyntheticMouseEvent()
927 int const e_y = d->synthetic_mouse_event_.cmd.y();
928 int const wh = d->buffer_view_->workHeight();
929 bool const up = e_y < 0;
930 bool const down = e_y > wh;
932 // Set things off to generate the _next_ 'pseudo' event.
934 if (d->synthetic_mouse_event_.restart_timeout) {
935 // This is some magic formulae to determine the speed
936 // of scrolling related to the position of the mouse.
939 int dist = up ? -e_y : e_y - wh;
940 time = max(min(200, 250000 / (dist * dist)), 1) ;
943 step = 80000 / (time * time);
947 d->synthetic_mouse_event_.timeout.setTimeout(time);
948 d->synthetic_mouse_event_.timeout.start();
951 // Can we scroll further ?
952 int const value = verticalScrollBar()->value();
953 if (value == verticalScrollBar()->maximum()
954 || value == verticalScrollBar()->minimum()) {
955 d->synthetic_mouse_event_.timeout.stop();
960 if (step <= 2 * wh) {
961 d->buffer_view_->scroll(up ? -step : step);
962 d->buffer_view_->updateMetrics();
964 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
967 // In which paragraph do we have to set the cursor ?
968 Cursor & cur = d->buffer_view_->cursor();
969 // FIXME: we don't know how to handle math.
970 Text * text = cur.text();
973 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
975 // Quit gracefully if there are no metrics, since otherwise next
976 // line would crash (bug #10324).
977 // This situation seems related to a (not yet understood) timing problem.
981 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
982 ParagraphMetrics const & pm = *pp.second;
983 pit_type const pit = pp.first;
985 if (pm.rows().empty())
988 // Find the row at which we set the cursor.
989 RowList::const_iterator rit = pm.rows().begin();
990 RowList::const_iterator rlast = pm.rows().end();
991 int yy = pm.position() - pm.ascent();
992 for (--rlast; rit != rlast; ++rit) {
993 int h = rit->height();
994 if ((up && yy + h > 0)
995 || (!up && yy + h > wh - defaultRowHeight()))
1000 // Find the position of the cursor
1002 int x = d->synthetic_mouse_event_.cmd.x();
1003 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1008 cur.boundary(bound);
1010 d->buffer_view_->buffer().changed(false);
1014 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
1015 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
1017 qRegisterMetaType<KeySymbol>("KeySymbol");
1018 qRegisterMetaType<KeyModifier>("KeyModifier");
1019 connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
1020 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
1021 Qt::QueuedConnection);
1022 connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
1023 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1027 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1031 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1032 bool result = flag_;
1038 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1040 if (emitCheck(isAutoRepeat))
1041 Q_EMIT signal(sym, mod);
1043 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1047 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1049 // this is also called for ShortcutOverride events. In this case, one must
1050 // not act but simply accept the event explicitly.
1051 bool const act = (ev->type() != QEvent::ShortcutOverride);
1053 // Do not process here some keys if dialog_mode_ is set
1054 bool const for_dialog_mode = d->dialog_mode_
1055 && (ev->modifiers() == Qt::NoModifier
1056 || ev->modifiers() == Qt::ShiftModifier)
1057 && (ev->key() == Qt::Key_Escape
1058 || ev->key() == Qt::Key_Enter
1059 || ev->key() == Qt::Key_Return);
1060 // also do not use autoRepeat to input shortcuts
1061 bool const autoRepeat = ev->isAutoRepeat();
1063 if (for_dialog_mode || (!act && autoRepeat)) {
1068 // intercept some keys if completion popup is visible
1069 if (d->completer_->popupVisible()) {
1070 switch (ev->key()) {
1072 case Qt::Key_Return:
1074 d->completer_->activate();
1080 KeyModifier const m = q_key_state(ev->modifiers());
1082 if (act && lyxerr.debugging(Debug::KEY)) {
1084 if (m & ShiftModifier)
1086 if (m & ControlModifier)
1088 if (m & AltModifier)
1090 if (m & MetaModifier)
1092 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1093 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1094 << " keyState: " << str);
1098 setKeySymbol(&sym, ev);
1101 Q_EMIT compressKeySym(sym, m, autoRepeat);
1104 // here, !autoRepeat, as determined at the beginning
1105 ev->setAccepted(queryKeySym(sym, m));
1112 void GuiWorkArea::doubleClickTimeout()
1114 d->dc_event_.active = false;
1118 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1120 d->dc_event_ = DoubleClick(ev);
1121 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1122 SLOT(doubleClickTimeout()));
1123 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
1124 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->position().x(), ev->position().y(),
1126 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1128 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1134 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1136 QAbstractScrollArea::resizeEvent(ev);
1137 d->need_resize_ = true;
1142 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1144 if (preedit_string_.empty())
1147 // FIXME: shall we use real_current_font here? (see #10478)
1148 FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1149 FontMetrics const & fm = theFontMetrics(font);
1152 buffer_view_->caretPosAndDim(point, dim);
1153 int cur_x = point.x_;
1154 int cur_y = point.y_ + dim.height();
1156 // get attributes of input method cursor.
1157 // cursor_pos : cursor position in preedit string.
1158 size_t cursor_pos = 0;
1159 bool cursor_is_visible = false;
1160 for (auto const & attr : preedit_attr_) {
1161 if (attr.type == QInputMethodEvent::Cursor) {
1162 cursor_pos = size_t(attr.start);
1163 cursor_is_visible = attr.length != 0;
1168 size_t const preedit_length = preedit_string_.length();
1170 // get position of selection in input method.
1171 // FIXME: isn't there a simpler way to do this?
1172 // rStart : cursor position in selected string in IM.
1174 // rLength : selected string length in IM.
1176 if (cursor_pos < preedit_length) {
1177 for (auto const & attr : preedit_attr_) {
1178 if (attr.type == QInputMethodEvent::TextFormat) {
1179 if (attr.start <= int(cursor_pos)
1180 && int(cursor_pos) < attr.start + attr.length) {
1181 rStart = size_t(attr.start);
1182 rLength = size_t(attr.length);
1183 if (!cursor_is_visible)
1184 cursor_pos += rLength;
1191 rStart = cursor_pos;
1195 int const right_margin = buffer_view_->rightMargin();
1196 Painter::preedit_style ps;
1197 // Most often there would be only one line:
1199 for (size_t pos = 0; pos != preedit_length; ++pos) {
1200 char_type const typed_char = preedit_string_[pos];
1201 // reset preedit string style
1202 ps = Painter::preedit_default;
1204 // if we reached the right extremity of the screen, go to next line.
1205 if (cur_x + fm.width(typed_char) > p->viewport()->width() - right_margin) {
1206 cur_x = right_margin;
1207 cur_y += dim.height() + 1;
1210 // preedit strings are displayed with dashed underline
1211 // and partial strings are displayed white on black indicating
1212 // that we are in selecting mode in the input method.
1213 // FIXME: rLength == preedit_length is not a changing condition
1214 // FIXME: should be put out of the loop.
1216 && pos < rStart + rLength
1217 && !(cursor_pos < rLength && rLength == preedit_length))
1218 ps = Painter::preedit_selecting;
1220 if (pos == cursor_pos
1221 && (cursor_pos < rLength && rLength == preedit_length))
1222 ps = Painter::preedit_cursor;
1224 // draw one character and update cur_x.
1225 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1230 void GuiWorkArea::Private::resetScreen()
1232 if (use_backingstore_) {
1233 int const pr = p->pixelRatio();
1234 screen_ = QImage(pr * p->viewport()->width(),
1235 pr * p->viewport()->height(),
1236 QImage::Format_ARGB32_Premultiplied);
1237 # if QT_VERSION >= 0x050000
1238 screen_.setDevicePixelRatio(pr);
1244 QPaintDevice * GuiWorkArea::Private::screenDevice()
1246 if (use_backingstore_)
1249 return p->viewport();
1253 void GuiWorkArea::Private::updateScreen(QRectF const & rc)
1255 if (use_backingstore_) {
1256 QPainter qpain(p->viewport());
1257 double const pr = p->pixelRatio();
1258 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr,
1259 rc.width() * pr, rc.height() * pr);
1260 qpain.drawImage(rc, screen_, rcs);
1265 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1267 // Do not trigger the painting machinery if we are not ready (see
1268 // bug #10989). The second test triggers when in the middle of a
1269 // dispatch operation.
1270 if (view().busy() || d->buffer_view_->buffer().undo().activeUndoGroup()) {
1271 // Since macOS has turned the screen black at this point, our
1272 // backing store has to be copied to screen (this is a no-op
1273 // except on macOS).
1274 d->updateScreen(ev->rect());
1275 // Ignore this paint event, but request a new one for later.
1276 viewport()->update(ev->rect());
1281 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1282 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1284 if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_) {
1286 d->resizeBufferView();
1289 d->last_pixel_ratio_ = pixelRatio();
1291 GuiPainter pain(d->screenDevice(), pixelRatio(), d->lyx_view_->develMode());
1293 d->buffer_view_->draw(pain, d->caret_visible_);
1295 // The preedit text, if needed
1296 d->paintPreeditText(pain);
1299 // FIXME: the code would be a little bit simpler if caret geometry
1300 // was updated unconditionally. Some profiling is required to see
1301 // how expensive this is (especially when idle).
1302 if (d->caret_visible_) {
1303 if (d->needs_caret_geometry_update_)
1304 d->updateCaretGeometry();
1305 d->drawCaret(pain, d->buffer_view_->horizScrollOffset());
1308 d->updateScreen(ev->rect());
1314 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1316 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1317 << " commitString: " << e->commitString());
1319 // insert the processed text in the document (handles undo)
1320 if (!e->commitString().isEmpty()) {
1321 FuncRequest cmd(LFUN_SELF_INSERT,
1322 qstring_to_ucs4(e->commitString()),
1323 FuncRequest::KEYBOARD);
1325 // FIXME: this is supposed to remove traces from preedit
1326 // string. Can we avoid calling it explicitly?
1327 d->buffer_view_->updateMetrics();
1330 // Hide the caret during the test transformation.
1331 if (e->preeditString().isEmpty())
1332 startBlinkingCaret();
1334 stopBlinkingCaret();
1336 if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1342 // The preedit text and its attributes will be used in paintPreeditText
1343 d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1344 d->preedit_attr_ = e->attributes();
1347 // redraw area of preedit string.
1348 // int height = d->caret_->dim.height();
1349 // int cur_y = d->caret_->y;
1350 // viewport()->update(0, cur_y, viewport()->width(),
1351 // (height + 1) * d->preedit_lines_);
1352 viewport()->update();
1354 if (d->preedit_string_.empty()) {
1355 d->preedit_lines_ = 1;
1360 // Don't forget to accept the event!
1365 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1368 // this is the CJK-specific composition window position and
1369 // the context menu position when the menu key is pressed.
1370 #if (QT_VERSION < 0x050000)
1371 case Qt::ImMicroFocus: {
1373 case Qt::ImCursorRectangle: {
1375 CaretGeometry const & cg = bufferView().caretGeometry();
1376 return QRect(cg.left - 10 * (d->preedit_lines_ != 1),
1377 cg.top + cg.height() * d->preedit_lines_,
1378 cg.width(), cg.height());
1381 return QWidget::inputMethodQuery(query);
1386 void GuiWorkArea::updateWindowTitle()
1388 Buffer const & buf = bufferView().buffer();
1389 if (buf.fileName() != d->file_name_
1390 || buf.params().shell_escape != d->shell_escape_
1391 || buf.hasReadonlyFlag() != d->read_only_
1392 || buf.lyxvc().vcstatus() != d->vc_status_
1393 || buf.isClean() != d->clean_
1394 || buf.notifiesExternalModification() != d->externally_modified_) {
1395 d->file_name_ = buf.fileName();
1396 d->shell_escape_ = buf.params().shell_escape;
1397 d->read_only_ = buf.hasReadonlyFlag();
1398 d->vc_status_ = buf.lyxvc().vcstatus();
1399 d->clean_ = buf.isClean();
1400 d->externally_modified_ = buf.notifiesExternalModification();
1401 Q_EMIT titleChanged(this);
1406 bool GuiWorkArea::isFullScreen() const
1408 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1412 bool GuiWorkArea::inDialogMode() const
1414 return d->dialog_mode_;
1418 void GuiWorkArea::setDialogMode(bool mode)
1420 d->dialog_mode_ = mode;
1424 GuiCompleter & GuiWorkArea::completer()
1426 return *d->completer_;
1429 GuiView const & GuiWorkArea::view() const
1431 return *d->lyx_view_;
1435 GuiView & GuiWorkArea::view()
1437 return *d->lyx_view_;
1440 ////////////////////////////////////////////////////////////////////
1444 ////////////////////////////////////////////////////////////////////
1447 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1449 support::TempFile tempfile("embedded.internal");
1450 tempfile.setAutoRemove(false);
1451 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1452 buffer_->setUnnamed(true);
1453 buffer_->setFullyLoaded(true);
1454 setBuffer(*buffer_);
1455 setDialogMode(true);
1459 EmbeddedWorkArea::~EmbeddedWorkArea()
1461 // No need to destroy buffer and bufferview here, because it is done
1462 // in theBufferList() destruction loop at application exit
1466 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1469 GuiWorkArea::closeEvent(ev);
1473 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1476 GuiWorkArea::hideEvent(ev);
1480 QSize EmbeddedWorkArea::sizeHint () const
1483 // GuiWorkArea sets the size to the screen's viewport
1484 // by returning a value this gets overridden
1485 // EmbeddedWorkArea is now sized to fit in the layout
1486 // of the parent, and has a minimum size set in GuiWorkArea
1487 // which is what we return here
1488 return QSize(100, 70);
1492 void EmbeddedWorkArea::disable()
1494 stopBlinkingCaret();
1495 if (view().currentWorkArea() != this)
1497 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1498 // tolerates it and shows the background logo), what happens if
1499 // an EmbeddedWorkArea is closed after closing all document WAs
1500 view().setCurrentWorkArea(view().currentMainWorkArea());
1503 ////////////////////////////////////////////////////////////////////
1507 ////////////////////////////////////////////////////////////////////
1509 TabWorkArea::TabWorkArea(QWidget * parent)
1510 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1512 QPalette pal = palette();
1513 pal.setColor(QPalette::Active, QPalette::Button,
1514 pal.color(QPalette::Active, QPalette::Window));
1515 pal.setColor(QPalette::Disabled, QPalette::Button,
1516 pal.color(QPalette::Disabled, QPalette::Window));
1517 pal.setColor(QPalette::Inactive, QPalette::Button,
1518 pal.color(QPalette::Inactive, QPalette::Window));
1520 QObject::connect(this, SIGNAL(currentChanged(int)),
1521 this, SLOT(on_currentTabChanged(int)));
1523 closeBufferButton = new QToolButton(this);
1524 closeBufferButton->setPalette(pal);
1525 // FIXME: rename the icon to closebuffer.png
1526 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1527 closeBufferButton->setText("Close File");
1528 closeBufferButton->setAutoRaise(true);
1529 closeBufferButton->setCursor(Qt::ArrowCursor);
1530 closeBufferButton->setToolTip(qt_("Close File"));
1531 closeBufferButton->setEnabled(true);
1532 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1533 this, SLOT(closeCurrentBuffer()));
1534 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1536 // set TabBar behaviour
1537 QTabBar * tb = tabBar();
1538 tb->setTabsClosable(!lyxrc.single_close_tab_button);
1539 tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1540 tb->setElideMode(Qt::ElideNone);
1541 // allow dragging tabs
1542 tb->setMovable(true);
1543 // make us responsible for the context menu of the tabbar
1544 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1545 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1546 this, SLOT(showContextMenu(const QPoint &)));
1547 connect(tb, SIGNAL(tabCloseRequested(int)),
1548 this, SLOT(closeTab(int)));
1550 setUsesScrollButtons(true);
1552 // use document mode tabs
1553 setDocumentMode(true);
1558 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1560 if (me->button() == Qt::MiddleButton)
1561 midpressed_tab_ = tabBar()->tabAt(me->pos());
1563 QTabWidget::mousePressEvent(me);
1567 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1569 if (me->button() == Qt::MiddleButton) {
1570 int const midreleased_tab = tabBar()->tabAt(me->pos());
1571 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1572 closeTab(midreleased_tab);
1574 QTabWidget::mouseReleaseEvent(me);
1578 void TabWorkArea::paintEvent(QPaintEvent * event)
1580 if (tabBar()->isVisible()) {
1581 QTabWidget::paintEvent(event);
1583 // Prevent the selected tab to influence the
1584 // painting of the frame of the tab widget.
1585 // This is needed for gtk style in Qt.
1586 QStylePainter p(this);
1587 #if QT_VERSION < 0x050000
1588 QStyleOptionTabWidgetFrameV2 opt;
1590 QStyleOptionTabWidgetFrame opt;
1592 initStyleOption(&opt);
1593 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1595 opt.selectedTabRect = QRect();
1596 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1601 bool TabWorkArea::posIsTab(QPoint position)
1603 // tabAt returns -1 if tab does not covers position
1604 return tabBar()->tabAt(position) > -1;
1608 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1610 if (event->button() != Qt::LeftButton)
1613 // this code chunk is unnecessary because it seems the event only makes
1614 // it this far if it is not on a tab. I'm not sure why this is (maybe
1615 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1616 // this is true in all cases and if it will be true in the future so I
1617 // leave this code for now. (skostysh, 2016-07-21)
1619 // return early if double click on existing tabs
1620 if (posIsTab(event->pos()))
1623 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1627 void TabWorkArea::setFullScreen(bool full_screen)
1629 for (int i = 0; i != count(); ++i) {
1630 if (GuiWorkArea * wa = workArea(i))
1631 wa->setFullScreen(full_screen);
1634 if (lyxrc.full_screen_tabbar)
1635 showBar(!full_screen && count() > 1);
1637 showBar(count() > 1);
1641 void TabWorkArea::showBar(bool show)
1643 tabBar()->setEnabled(show);
1644 tabBar()->setVisible(show);
1645 if (documentMode()) {
1646 // avoid blank corner widget when documentMode(true) is used
1647 if (show && lyxrc.single_close_tab_button) {
1648 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1649 closeBufferButton->setVisible(true);
1651 // remove corner widget
1652 setCornerWidget(nullptr);
1654 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1655 setTabsClosable(!lyxrc.single_close_tab_button);
1659 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1661 QWidget * w = QTabWidget::widget(index);
1664 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1670 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1672 return widget(currentIndex());
1676 GuiWorkArea * TabWorkArea::workArea(int index) const
1678 GuiWorkAreaContainer * w = widget(index);
1681 return w->workArea();
1685 GuiWorkArea * TabWorkArea::currentWorkArea() const
1687 return workArea(currentIndex());
1691 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1693 // FIXME: this method doesn't work if we have more than one work area
1694 // showing the same buffer.
1695 for (int i = 0; i != count(); ++i) {
1696 GuiWorkArea * wa = workArea(i);
1697 LASSERT(wa, return nullptr);
1698 if (&wa->bufferView().buffer() == &buffer)
1705 void TabWorkArea::closeAll()
1708 QWidget * wac = widget(0);
1709 LASSERT(wac, return);
1716 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1718 for (int index = 0; index < count(); ++index)
1719 if (workArea(index) == w)
1725 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1727 LASSERT(work_area, return false);
1728 int index = indexOfWorkArea(work_area);
1732 if (index == currentIndex())
1733 // Make sure the work area is up to date.
1734 on_currentTabChanged(index);
1736 // Switch to the work area.
1737 setCurrentIndex(index);
1738 work_area->setFocus();
1744 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1746 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1747 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1748 wa->setUpdatesEnabled(false);
1749 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1750 // when hiding it again below).
1751 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1752 showBar(count() > 0);
1753 addTab(wac, wa->windowTitle());
1754 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1755 this, SLOT(updateTabTexts()));
1756 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1757 setFullScreen(true);
1759 // Hide tabbar if there's only one tab.
1760 showBar(count() > 1);
1768 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1770 LASSERT(work_area, return false);
1771 int index = indexOfWorkArea(work_area);
1775 work_area->setUpdatesEnabled(false);
1776 QWidget * wac = widget(index);
1781 // make sure the next work area is enabled.
1782 currentWidget()->setUpdatesEnabled(true);
1783 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1784 setFullScreen(true);
1786 // Show tabbar only if there's more than one tab.
1787 showBar(count() > 1);
1789 lastWorkAreaRemoved();
1797 void TabWorkArea::on_currentTabChanged(int i)
1799 // returns e.g. on application destruction
1802 GuiWorkArea * wa = workArea(i);
1803 LASSERT(wa, return);
1804 wa->setUpdatesEnabled(true);
1805 wa->scheduleRedraw(true);
1808 currentWorkAreaChanged(wa);
1810 LYXERR(Debug::GUI, "currentTabChanged " << i
1811 << " File: " << wa->bufferView().buffer().absFileName());
1815 void TabWorkArea::closeCurrentBuffer()
1818 if (clicked_tab_ == -1)
1819 wa = currentWorkArea();
1821 wa = workArea(clicked_tab_);
1822 LASSERT(wa, return);
1824 wa->view().closeWorkArea(wa);
1828 void TabWorkArea::hideCurrentTab()
1831 if (clicked_tab_ == -1)
1832 wa = currentWorkArea();
1834 wa = workArea(clicked_tab_);
1835 LASSERT(wa, return);
1837 wa->view().hideWorkArea(wa);
1841 void TabWorkArea::closeTab(int index)
1843 on_currentTabChanged(index);
1846 wa = currentWorkArea();
1848 wa = workArea(index);
1849 LASSERT(wa, return);
1851 wa->view().closeWorkArea(wa);
1858 /// make vector happy
1859 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1861 DisplayPath(int tab, FileName const & filename)
1864 // Recode URL encoded chars via fromPercentEncoding()
1865 string const fn = (filename.extension() == "lyx")
1866 ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
1867 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
1868 #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
1869 postfix_ = toqstr(filename.absoluteFilePath()).
1870 split("/", Qt::SkipEmptyParts);
1872 postfix_ = toqstr(filename.absoluteFilePath()).
1873 split("/", QString::SkipEmptyParts);
1875 postfix_.pop_back();
1876 abs_ = toqstr(filename.absoluteFilePath());
1877 dottedPrefix_ = false;
1880 /// Absolute path for debugging.
1885 /// Add the first segment from the postfix or three dots to the prefix.
1886 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1887 /// when really needed.
1888 void shiftPathSegment(bool dotted)
1890 if (postfix_.count() <= 0)
1894 if (dottedPrefix_ && !prefix_.isEmpty())
1895 prefix_ += ellipsisSlash_;
1896 prefix_ += postfix_.front() + "/";
1898 dottedPrefix_ = dotted && !prefix_.isEmpty();
1899 postfix_.pop_front();
1902 QString displayString() const
1904 if (prefix_.isEmpty())
1907 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1908 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1911 QString forecastPathString() const
1913 if (postfix_.count() == 0)
1914 return displayString();
1917 + (dottedPrefix_ ? ellipsisSlash_ : "")
1918 + postfix_.front() + "/";
1921 bool final() const { return postfix_.empty(); }
1923 int tab() const { return tab_; }
1927 static QString const ellipsisSlash_;
1931 QStringList postfix_;
1943 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1947 bool operator<(DisplayPath const & a, DisplayPath const & b)
1949 return a.displayString() < b.displayString();
1953 bool operator==(DisplayPath const & a, DisplayPath const & b)
1955 return a.displayString() == b.displayString();
1959 void TabWorkArea::updateTabTexts()
1961 int const n = count();
1964 std::list<DisplayPath> paths;
1965 typedef std::list<DisplayPath>::iterator It;
1967 // collect full names first: path into postfix, empty prefix and
1968 // filename without extension
1969 for (int i = 0; i < n; ++i) {
1970 GuiWorkArea * i_wa = workArea(i);
1971 FileName const fn = i_wa->bufferView().buffer().fileName();
1972 paths.push_back(DisplayPath(i, fn));
1975 // go through path segments and see if it helps to make the path more unique
1976 bool somethingChanged = true;
1977 bool allFinal = false;
1978 while (somethingChanged && !allFinal) {
1979 // adding path segments changes order
1982 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1983 somethingChanged = false;
1986 // find segments which are not unique (i.e. non-atomic)
1987 It it = paths.begin();
1989 QString segString = it->displayString();
1990 for (; it != paths.end(); ++it) {
1991 // look to the next item
1996 allFinal = allFinal && it->final();
1998 LYXERR(Debug::GUI, "it = " << it->abs()
1999 << " => " << it->displayString());
2001 // still the same segment?
2003 if ((next != paths.end()
2004 && (nextString = next->displayString()) == segString))
2006 LYXERR(Debug::GUI, "segment ended");
2008 // only a trivial one with one element?
2009 if (it == segStart) {
2010 // start new segment
2012 segString = nextString;
2016 // We found a non-atomic segment
2017 // We know that segStart <= it < next <= paths.end().
2018 // The assertion below tells coverity about it.
2019 LATTEST(segStart != paths.end());
2020 QString dspString = segStart->forecastPathString();
2021 LYXERR(Debug::GUI, "first forecast found for "
2022 << segStart->abs() << " => " << dspString);
2025 // Shift path segments and hope for the best
2026 // that it makes the path more unique.
2027 somethingChanged = true;
2028 bool moreUnique = false;
2029 for (; sit != next; ++sit) {
2030 if (sit->forecastPathString() != dspString) {
2031 LYXERR(Debug::GUI, "different forecast found for "
2032 << sit->abs() << " => " << sit->forecastPathString());
2036 LYXERR(Debug::GUI, "same forecast found for "
2037 << sit->abs() << " => " << dspString);
2040 // if the path segment helped, add it. Otherwise add dots
2041 bool dots = !moreUnique;
2042 LYXERR(Debug::GUI, "using dots = " << dots);
2043 for (sit = segStart; sit != next; ++sit) {
2044 sit->shiftPathSegment(dots);
2045 LYXERR(Debug::GUI, "shifting "
2046 << sit->abs() << " => " << sit->displayString());
2049 // start new segment
2051 segString = nextString;
2055 // set new tab titles
2056 for (It it = paths.begin(); it != paths.end(); ++it) {
2057 int const tab_index = it->tab();
2058 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2059 QString tab_text = it->displayString().replace("&", "&&");
2060 if (!buf.fileName().empty() && !buf.isClean())
2062 QString tab_tooltip = it->abs();
2063 if (buf.hasReadonlyFlag()) {
2065 QLabel * readOnlyButton = new QLabel();
2066 QIcon icon = QIcon(getPixmap("images/", "emblem-readonly", "svgz,png"));
2067 readOnlyButton->setPixmap(icon.pixmap(QSize(16, 16)));
2068 tabBar()->setTabButton(tab_index, QTabBar::RightSide, readOnlyButton);
2070 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2072 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2075 tabBar()->setTabButton(tab_index, QTabBar::RightSide, 0);
2077 setTabIcon(tab_index, QIcon());
2079 if (buf.notifiesExternalModification()) {
2080 QString const warn = qt_("%1 (modified externally)");
2081 tab_tooltip = warn.arg(tab_tooltip);
2082 tab_text += QChar(0x26a0);
2084 setTabText(tab_index, tab_text);
2085 setTabToolTip(tab_index, tab_tooltip);
2090 void TabWorkArea::showContextMenu(const QPoint & pos)
2093 clicked_tab_ = tabBar()->tabAt(pos);
2094 if (clicked_tab_ == -1)
2097 GuiWorkArea * wa = workArea(clicked_tab_);
2098 LASSERT(wa, return);
2102 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2103 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2105 // we want to show the 'close' option only if this is not a child buffer.
2106 Buffer const & buf = wa->bufferView().buffer();
2108 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2109 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2110 popup.exec(tabBar()->mapToGlobal(pos));
2116 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2118 QWidget * w = widget(fromIndex);
2119 QIcon icon = tabIcon(fromIndex);
2120 QString text = tabText(fromIndex);
2122 setCurrentIndex(fromIndex);
2123 removeTab(fromIndex);
2124 insertTab(toIndex, w, icon, text);
2125 setCurrentIndex(toIndex);
2129 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2130 : QWidget(parent), wa_(wa)
2132 LASSERT(wa, return);
2133 Ui::WorkAreaUi::setupUi(this);
2134 layout()->addWidget(wa);
2135 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2136 this, SLOT(updateDisplay()));
2137 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2138 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2139 setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2144 void GuiWorkAreaContainer::updateDisplay()
2146 Buffer const & buf = wa_->bufferView().buffer();
2147 notificationFrame->setHidden(!buf.notifiesExternalModification());
2148 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2149 .arg(toqstr(buf.fileName().displayName()));
2150 externalModificationLabel->setText(label);
2154 void GuiWorkAreaContainer::dispatch(FuncRequest const & f) const
2156 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2157 wa_->bufferView().buffer().absFileName()));
2162 void GuiWorkAreaContainer::reload() const
2164 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2168 void GuiWorkAreaContainer::ignore() const
2170 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2174 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2176 // prevent TabWorkArea from opening a new buffer on double click
2181 } // namespace frontend
2184 #include "moc_GuiWorkArea.cpp"