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>
58 #include <QProxyStyle>
60 #include <QMainWindow>
66 #include <QStyleOption>
67 #include <QStylePainter>
69 #include <QToolButton>
80 using namespace lyx::support;
85 /// return the LyX mouse button state from Qt's
86 static mouse_button::state q_button_state(Qt::MouseButton button)
88 mouse_button::state b = mouse_button::none;
91 b = mouse_button::button1;
93 case Qt::MiddleButton:
94 b = mouse_button::button2;
97 b = mouse_button::button3;
106 /// return the LyX mouse button state from Qt's
107 mouse_button::state q_motion_state(Qt::MouseButtons state)
109 mouse_button::state b = mouse_button::none;
110 if (state & Qt::LeftButton)
111 b |= mouse_button::button1;
112 if (state & Qt::MiddleButton)
113 b |= mouse_button::button2;
114 if (state & Qt::RightButton)
115 b |= mouse_button::button3;
122 // This is a 'heartbeat' generating synthetic mouse move events when the
123 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
124 SyntheticMouseEvent::SyntheticMouseEvent()
125 : timeout(200), restart_timeout(true)
129 GuiWorkArea::Private::Private(GuiWorkArea * parent)
130 : p(parent), completer_(new GuiCompleter(p, p))
132 use_backingstore_ = lyxrc.draw_strategy == LyXRC::DS_BACKINGSTORE
133 || guiApp->needsBackingStore();
134 LYXERR(Debug::WORKAREA, "Drawing strategy is: "
135 << (use_backingstore_ ? "backingstore" : "partial"));
137 int const time = QApplication::cursorFlashTime() / 2;
139 caret_timeout_.setInterval(time);
140 caret_timeout_.start();
142 // let's initialize this just to be safe
143 caret_timeout_.setInterval(500);
148 GuiWorkArea::Private::~Private()
150 // If something is wrong with the buffer, we can ignore it safely
152 buffer_view_->buffer().workAreaManager().remove(p);
155 // Completer has a QObject parent and is thus automatically destroyed.
157 // delete completer_;
161 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
162 : d(new Private(this))
164 new CompressorProxy(this); // not a leak
168 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
169 : d(new Private(this))
171 new CompressorProxy(this); // not a leak
173 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
179 double GuiWorkArea::pixelRatio() const
181 return qt_scale_factor * devicePixelRatio();
185 void GuiWorkArea::init()
188 connect(&d->caret_timeout_, SIGNAL(timeout()),
189 this, SLOT(toggleCaret()));
191 // This connection is closed at the same time as this is destroyed.
192 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
193 generateSyntheticMouseEvent();
197 // A mouse event will happen before the first paint event,
198 // so make sure that the buffer view has an up to date metrics.
199 d->buffer_view_->resize(viewport()->width(), viewport()->height());
201 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
202 setAcceptDrops(true);
203 setMouseTracking(true);
204 setMinimumSize(100, 70);
205 setFrameStyle(QFrame::NoFrame);
208 d->updateCursorShape();
210 // we paint our own background
211 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
213 setFocusPolicy(Qt::StrongFocus);
215 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
216 << " viewport height: " << viewport()->height());
218 // Enables input methods for asian languages.
219 // Must be set when creating custom text editing widgets.
220 setAttribute(Qt::WA_InputMethodEnabled, true);
224 GuiWorkArea::~GuiWorkArea()
230 void GuiWorkArea::Private::updateCursorShape()
232 bool const clickable = buffer_view_ && buffer_view_->clickableInset();
233 p->viewport()->setCursor(clickable ? Qt::PointingHandCursor
238 void GuiWorkArea::setGuiView(GuiView & gv)
244 void GuiWorkArea::setBuffer(Buffer & buffer)
246 delete d->buffer_view_;
247 d->buffer_view_ = new BufferView(buffer);
248 buffer.workAreaManager().add(this);
250 // HACK: Prevents an additional redraw when the scrollbar pops up
251 // which regularly happens on documents with more than one page.
252 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
253 // Since we have no geometry information yet, we assume that
254 // a document needs a scrollbar if there is more then four
255 // paragraph in the outermost text.
256 if (buffer.text().paragraphs().size() > 4)
257 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
258 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
259 Q_EMIT bufferViewChanged();
263 void GuiWorkArea::fixVerticalScrollBar()
266 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
270 void GuiWorkArea::close()
272 d->lyx_view_->removeWorkArea(this);
276 void GuiWorkArea::setFullScreen(bool full_screen)
278 d->buffer_view_->setFullScreen(full_screen);
279 if (full_screen && lyxrc.full_screen_scrollbar)
280 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
282 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
286 BufferView & GuiWorkArea::bufferView()
288 return *d->buffer_view_;
292 BufferView const & GuiWorkArea::bufferView() const
294 return *d->buffer_view_;
298 void GuiWorkArea::stopBlinkingCaret()
300 d->caret_timeout_.stop();
305 void GuiWorkArea::startBlinkingCaret()
307 // do not show the cursor if the view is busy
311 // Don't start blinking if the cursor isn't on screen, unless we
312 // are not ready to know whether the cursor is on screen.
313 if (!d->buffer_view_->busy() && !d->buffer_view_->caretInView())
318 // Avoid blinking when debugging PAINTING, since it creates too much noise
319 if (!lyxerr.debugging(Debug::PAINTING)) {
320 // we are not supposed to cache this value.
321 int const time = QApplication::cursorFlashTime() / 2;
324 d->caret_timeout_.setInterval(time);
325 d->caret_timeout_.start();
330 void GuiWorkArea::toggleCaret()
332 if (d->caret_visible_)
339 void GuiWorkArea::scheduleRedraw(bool update_metrics)
342 // No need to redraw in this case.
345 // No need to do anything if this is the current view. The BufferView
346 // metrics are already up to date.
347 if (update_metrics || d->lyx_view_ != guiApp->currentView()
348 || d->lyx_view_->currentWorkArea() != this) {
349 // FIXME: it would be nice to optimize for the off-screen case.
350 d->buffer_view_->cursor().fixIfBroken();
351 d->buffer_view_->updateMetrics();
352 d->buffer_view_->cursor().fixIfBroken();
355 // update caret position, because otherwise it has to wait until
356 // the blinking interval is over
359 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
360 viewport()->update();
362 /// FIXME: is this still true now that paintEvent does the actual painting?
363 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
364 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
365 d->updateScrollbar();
366 d->lyx_view_->updateStatusBar();
368 if (lyxerr.debugging(Debug::WORKAREA))
369 d->buffer_view_->coordCache().dump();
373 d->updateCursorShape();
377 // Keep in sync with GuiWorkArea::processKeySym below
378 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
380 return guiApp->queryKeySym(key, mod);
384 // Keep in sync with GuiWorkArea::queryKeySym above
385 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
387 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
388 && lyxrc.full_screen_menubar) {
389 // FIXME HACK: we should not have to do this here. See related comment
390 // in GuiView::event() (QEvent::ShortcutOverride)
391 d->lyx_view_->menuBar()->hide();
394 // In order to avoid bad surprise in the middle of an operation,
395 // we better stop the blinking caret...
396 // the caret gets restarted in GuiView::restartCaret()
398 guiApp->processKeySym(key, mod);
402 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
405 if (cmd.action() == LFUN_FILE_OPEN) {
407 lyx_view_->dispatch(cmd, dr);
411 bool const notJustMovingTheMouse =
412 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
414 // In order to avoid bad surprise in the middle of an operation, we better stop
415 // the blinking caret.
416 if (notJustMovingTheMouse)
417 p->stopBlinkingCaret();
419 buffer_view_->mouseEventDispatch(cmd);
421 // Skip these when selecting
422 // FIXME: let GuiView take care of those.
423 if (notJustMovingTheMouse && !buffer_view_->mouseSelecting()) {
424 completer_->updateVisibility(false, false);
425 lyx_view_->updateDialogs();
426 lyx_view_->updateStatusBar();
429 // GUI tweaks except with mouse motion with no button pressed.
430 if (notJustMovingTheMouse) {
431 // Slight hack: this is only called currently when we
432 // clicked somewhere, so we force through the display
433 // of the new status here.
434 // FIXME: let GuiView take care of those.
435 lyx_view_->clearMessage();
437 // Show the caret immediately after any operation
438 p->startBlinkingCaret();
445 void GuiWorkArea::Private::resizeBufferView()
447 // WARNING: Please don't put any code that will trigger a repaint here!
448 // We are already inside a paint event.
449 p->stopBlinkingCaret();
450 // Warn our container (GuiView).
453 bool const caret_in_view = buffer_view_->caretInView();
454 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
456 buffer_view_->showCursor();
459 // Update scrollbars which might have changed due different
460 // BufferView dimension. This is especially important when the
461 // BufferView goes from zero-size to the real-size for the first time,
462 // as the scrollbar parameters are then set for the first time.
465 need_resize_ = false;
467 // Eventually, restart the caret after the resize event.
468 // We might be resizing even if the focus is on another widget so we only
469 // restart the caret if we have the focus.
471 QTimer::singleShot(50, p, SLOT(startBlinkingCaret()));
475 void GuiWorkArea::Private::resetCaret()
477 // Don't start blinking if the cursor isn't on screen or the window
478 // does not have focus
479 if (!buffer_view_->caretInView() || !p->hasFocus())
482 needs_caret_geometry_update_ = true;
483 caret_visible_ = true;
487 void GuiWorkArea::Private::updateCaretGeometry()
489 // we cannot update geometry if not ready and we do not need to if
490 // caret is not in view.
491 if (buffer_view_->busy() || !buffer_view_->caretInView())
494 // completion indicator
495 Cursor const & cur = buffer_view_->cursor();
496 bool const completable = cur.inset().showCompletionCursor()
497 && completer_->completionAvailable()
498 && !completer_->popupVisible()
499 && !completer_->inlineVisible();
501 buffer_view_->buildCaretGeometry(completable);
503 needs_caret_geometry_update_ = false;
507 void GuiWorkArea::Private::showCaret()
513 p->viewport()->update();
517 void GuiWorkArea::Private::hideCaret()
522 caret_visible_ = false;
523 //if (!qApp->focusWidget())
524 p->viewport()->update();
528 /* Draw the caret. Parameter \c horiz_offset is not 0 when there
529 * has been horizontal scrolling in current row
531 void GuiWorkArea::Private::drawCaret(QPainter & painter, int horiz_offset) const
533 if (buffer_view_->caretGeometry().shapes.empty())
536 QColor const color = guiApp->colorCache().get(Color_cursor);
537 painter.setPen(color);
538 painter.setRenderHint(QPainter::Antialiasing, true);
539 for (auto const & shape : buffer_view_->caretGeometry().shapes) {
542 for (Point const & p : shape) {
544 path.moveTo(p.x_ - horiz_offset, p.y_);
547 path.lineTo(p.x_ - horiz_offset, p.y_);
549 painter.fillPath(path, color);
551 painter.setRenderHint(QPainter::Antialiasing, false);
555 void GuiWorkArea::Private::updateScrollbar()
557 // Prevent setRange() and setSliderPosition from causing recursive calls via
558 // the signal valueChanged. (#10311)
559 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
560 p, SLOT(scrollTo(int)));
561 ScrollbarParameters const & scroll = buffer_view_->scrollbarParameters();
562 p->verticalScrollBar()->setRange(scroll.min, scroll.max);
563 p->verticalScrollBar()->setPageStep(scroll.page_step);
564 p->verticalScrollBar()->setSingleStep(scroll.single_step);
565 p->verticalScrollBar()->setSliderPosition(0);
566 // Connect to the vertical scroll bar
567 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
568 p, SLOT(scrollTo(int)));
572 void GuiWorkArea::scrollTo(int value)
575 d->buffer_view_->scrollDocView(value, true);
577 if (lyxrc.cursor_follows_scrollbar) {
578 d->buffer_view_->setCursorFromScrollbar();
579 // FIXME: let GuiView take care of those.
580 d->lyx_view_->updateLayoutList();
582 // Show the caret immediately after any operation.
583 startBlinkingCaret();
587 bool GuiWorkArea::event(QEvent * e)
590 case QEvent::ToolTip: {
591 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
592 if (lyxrc.use_tooltip) {
593 QPoint pos = helpEvent->pos();
594 if (pos.x() < viewport()->width()) {
595 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
596 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
599 QToolTip::hideText();
601 // Don't forget to accept the event!
606 case QEvent::ShortcutOverride:
607 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
609 keyPressEvent(static_cast<QKeyEvent *>(e));
610 return e->isAccepted();
612 case QEvent::KeyPress: {
613 // We catch this event in order to catch the Tab or Shift+Tab key press
614 // which are otherwise reserved to focus switching between controls
616 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
617 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
618 || (ke->key() == Qt::Key_Backtab && (
619 ke->modifiers() == Qt::ShiftModifier
620 || ke->modifiers() == Qt::NoModifier))) {
624 return QAbstractScrollArea::event(e);
628 return QAbstractScrollArea::event(e);
634 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
637 if (e->reason() == QContextMenuEvent::Mouse)
638 // the menu name is set on mouse press
639 name = d->context_menu_name_;
641 QPoint pos = e->pos();
642 Cursor const & cur = d->buffer_view_->cursor();
643 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
644 // Do not access the context menu of math right in front of before
645 // the cursor. This does not work when the cursor is in text.
646 Inset * inset = cur.paragraph().getInset(cur.pos());
647 if (inset && inset->asInsetMath())
649 else if (cur.pos() > 0) {
650 inset = cur.paragraph().getInset(cur.pos() - 1);
655 if (e->reason() == QContextMenuEvent::Keyboard)
656 // Subtract the top margin, see #12811
657 pos.setY(pos.y() - d->buffer_view_->topMargin());
659 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
666 // always show mnemonics when the keyboard is used to show the context menu
667 // FIXME: This should be fixed in Qt itself
668 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
669 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
674 // Position the menu to the right.
675 // FIXME: menu position should be different for RTL text.
676 menu->exec(e->globalPos());
681 void GuiWorkArea::focusInEvent(QFocusEvent * e)
683 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
684 if (d->lyx_view_->currentWorkArea() != this) {
685 d->lyx_view_->setCurrentWorkArea(this);
686 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
689 startBlinkingCaret();
690 QAbstractScrollArea::focusInEvent(e);
694 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
696 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
698 QAbstractScrollArea::focusOutEvent(e);
702 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
704 if (d->dc_event_.active && d->dc_event_ == *e) {
705 d->dc_event_.active = false;
706 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
707 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->position().x(), e->position().y(),
709 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
711 q_button_state(e->button()), q_key_state(e->modifiers()));
717 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
718 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->position().x(), e->position().y(),
720 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
722 q_button_state(e->button()), q_key_state(e->modifiers()));
725 // Save the context menu on mouse press, because also the mouse
726 // cursor is set on mouse press. Afterwards, we can either release
727 // the mousebutton somewhere else, or the cursor might have moved
728 // due to the DEPM. We need to do this after the mouse has been
729 // set in dispatch(), because the selection state might change.
730 if (e->button() == Qt::RightButton)
731 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
732 d->context_menu_name_ = d->buffer_view_->contextMenu(e->position().x(), e->position().y());
734 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
741 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
743 if (d->synthetic_mouse_event_.timeout.running())
744 d->synthetic_mouse_event_.timeout.stop();
746 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
747 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->position().x(), e->position().y(),
749 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
751 q_button_state(e->button()), q_key_state(e->modifiers()));
752 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
753 QT_VERSION < QT_VERSION_CHECK(5,15,1))
754 d->synthetic_mouse_event_.cmd = cmd; // QtBug QAbstractScrollArea::mouseMoveEvent
761 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
763 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
764 QT_VERSION < QT_VERSION_CHECK(5,15,1))
765 // cancel the event if the coordinates didn't change, this is due to QtBug
766 // QAbstractScrollArea::mouseMoveEvent, the event is triggered falsely when quickly
767 // double tapping a touchpad. To test: try to select a word by quickly double tapping
768 // on a touchpad while hovering the cursor over that word in the work area.
769 // This bug does not occur on Qt versions 5.10.1 and below. Only Windows seems to be affected.
770 // ML thread: https://www.mail-archive.com/lyx-devel@lists.lyx.org/msg211699.html
771 // Qt bugtracker: https://bugreports.qt.io/browse/QTBUG-85431
772 // Bug was fixed in Qt 5.15.1
773 if (e->x() == d->synthetic_mouse_event_.cmd.x() && // QtBug QAbstractScrollArea::mouseMoveEvent
774 e->y() == d->synthetic_mouse_event_.cmd.y()) // QtBug QAbstractScrollArea::mouseMoveEvent
775 return; // QtBug QAbstractScrollArea::mouseMoveEvent
778 // we kill the triple click if we move
779 doubleClickTimeout();
780 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
781 FuncRequest cmd(LFUN_MOUSE_MOTION, e->position().x(), e->position().y(),
783 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
785 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
789 // If we're above or below the work area...
790 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
791 if ((e->position().y() <= 20 || e->position().y() >= viewport()->height() - 20)
793 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
795 && e->buttons() == mouse_button::button1) {
796 // Make sure only a synthetic event can cause a page scroll,
797 // so they come at a steady rate:
798 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
799 if (e->position().y() <= 20)
800 // _Force_ a scroll up:
801 cmd.set_y(e->position().y() - 21);
803 cmd.set_y(e->position().y() + 21);
806 // _Force_ a scroll up:
807 cmd.set_y(e->y() - 21);
809 cmd.set_y(e->y() + 21);
811 // Store the event, to be handled when the timeout expires.
812 d->synthetic_mouse_event_.cmd = cmd;
814 if (d->synthetic_mouse_event_.timeout.running()) {
815 // Discard the event. Note that it _may_ be handled
816 // when the timeout expires if
817 // synthetic_mouse_event_.cmd has not been overwritten.
818 // Ie, when the timeout expires, we handle the
819 // most recent event but discard all others that
820 // occurred after the one used to start the timeout
821 // in the first place.
825 d->synthetic_mouse_event_.restart_timeout = true;
826 d->synthetic_mouse_event_.timeout.start();
827 // Fall through to handle this event...
829 } else if (d->synthetic_mouse_event_.timeout.running()) {
830 // Store the event, to be possibly handled when the timeout
832 // Once the timeout has expired, normal control is returned
833 // to mouseMoveEvent (restart_timeout = false).
834 // This results in a much smoother 'feel' when moving the
835 // mouse back into the work area.
836 d->synthetic_mouse_event_.cmd = cmd;
837 d->synthetic_mouse_event_.restart_timeout = false;
844 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
846 // Wheel rotation by one notch results in a delta() of 120 (see
847 // documentation of QWheelEvent)
848 // But first we have to ignore horizontal scroll events.
849 QPoint const aDelta = ev->angleDelta();
850 // skip horizontal wheel event
851 if (abs(aDelta.x()) > abs(aDelta.y())) {
855 double const delta = aDelta.y() / 120.0;
858 switch (lyxrc.scroll_wheel_zoom) {
859 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
860 zoom = ev->modifiers() & Qt::ControlModifier;
861 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
863 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
864 zoom = ev->modifiers() & Qt::ShiftModifier;
865 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
867 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
868 zoom = ev->modifiers() & Qt::AltModifier;
869 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
871 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
875 docstring arg = convert<docstring>(int(5 * delta));
876 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
880 // Take into account the desktop wide settings.
881 int const lines = qApp->wheelScrollLines();
882 int const page_step = verticalScrollBar()->pageStep();
883 // Test if the wheel mouse is set to one screen at a time.
884 // This is according to
885 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
887 min(lines * verticalScrollBar()->singleStep(), page_step);
889 // Take into account the rotation and the user preferences.
890 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
891 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
892 << " delta = " << delta << " scroll_value = " << scroll_value
893 << " page_step = " << page_step);
895 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
901 void GuiWorkArea::generateSyntheticMouseEvent()
903 int const e_y = d->synthetic_mouse_event_.cmd.y();
904 int const wh = d->buffer_view_->workHeight();
905 bool const up = e_y < 0;
906 bool const down = e_y > wh;
908 // Set things off to generate the _next_ 'pseudo' event.
910 if (d->synthetic_mouse_event_.restart_timeout) {
911 // This is some magic formulae to determine the speed
912 // of scrolling related to the position of the mouse.
915 int dist = up ? -e_y : e_y - wh;
916 time = max(min(200, 250000 / (dist * dist)), 1) ;
919 step = 80000 / (time * time);
923 d->synthetic_mouse_event_.timeout.setTimeout(time);
924 d->synthetic_mouse_event_.timeout.start();
927 // Can we scroll further ?
928 int const value = verticalScrollBar()->value();
929 if (value == verticalScrollBar()->maximum()
930 || value == verticalScrollBar()->minimum()) {
931 d->synthetic_mouse_event_.timeout.stop();
936 if (step <= 2 * wh) {
937 d->buffer_view_->scroll(up ? -step : step);
938 d->buffer_view_->updateMetrics();
940 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
943 // In which paragraph do we have to set the cursor ?
944 Cursor & cur = d->buffer_view_->cursor();
945 // FIXME: we don't know how to handle math.
946 Text * text = cur.text();
949 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
951 // Quit gracefully if there are no metrics, since otherwise next
952 // line would crash (bug #10324).
953 // This situation seems related to a (not yet understood) timing problem.
957 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
958 ParagraphMetrics const & pm = *pp.second;
959 pit_type const pit = pp.first;
961 if (pm.rows().empty())
964 // Find the row at which we set the cursor.
965 RowList::const_iterator rit = pm.rows().begin();
966 RowList::const_iterator rlast = pm.rows().end();
967 int yy = pm.position() - pm.ascent();
968 for (--rlast; rit != rlast; ++rit) {
969 int h = rit->height();
970 if ((up && yy + h > 0)
971 || (!up && yy + h > wh - defaultRowHeight()))
976 // Find the position of the cursor
978 int x = d->synthetic_mouse_event_.cmd.x();
979 pos_type const pos = tm.getPosNearX(*rit, x, bound);
986 d->buffer_view_->buffer().changed(false);
990 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
991 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
993 qRegisterMetaType<KeySymbol>("KeySymbol");
994 qRegisterMetaType<KeyModifier>("KeyModifier");
995 connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
996 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
997 Qt::QueuedConnection);
998 connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
999 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1003 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1007 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1008 bool result = flag_;
1014 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1016 if (emitCheck(isAutoRepeat))
1017 Q_EMIT signal(sym, mod);
1019 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1023 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1025 // this is also called for ShortcutOverride events. In this case, one must
1026 // not act but simply accept the event explicitly.
1027 bool const act = (ev->type() != QEvent::ShortcutOverride);
1029 // Do not process here some keys if dialog_mode_ is set
1030 bool const for_dialog_mode = d->dialog_mode_
1031 && (ev->modifiers() == Qt::NoModifier
1032 || ev->modifiers() == Qt::ShiftModifier)
1033 && (ev->key() == Qt::Key_Escape
1034 || ev->key() == Qt::Key_Enter
1035 || ev->key() == Qt::Key_Return);
1036 // also do not use autoRepeat to input shortcuts
1037 bool const autoRepeat = ev->isAutoRepeat();
1039 if (for_dialog_mode || (!act && autoRepeat)) {
1044 // intercept some keys if completion popup is visible
1045 if (d->completer_->popupVisible()) {
1046 switch (ev->key()) {
1048 case Qt::Key_Return:
1050 d->completer_->activate();
1056 KeyModifier const m = q_key_state(ev->modifiers());
1058 if (act && lyxerr.debugging(Debug::KEY)) {
1060 if (m & ShiftModifier)
1062 if (m & ControlModifier)
1064 if (m & AltModifier)
1066 if (m & MetaModifier)
1068 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1069 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1070 << " keyState: " << str);
1074 setKeySymbol(&sym, ev);
1077 Q_EMIT compressKeySym(sym, m, autoRepeat);
1080 // here, !autoRepeat, as determined at the beginning
1081 ev->setAccepted(queryKeySym(sym, m));
1088 void GuiWorkArea::doubleClickTimeout()
1090 d->dc_event_.active = false;
1094 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1096 d->dc_event_ = DoubleClick(ev);
1097 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1098 SLOT(doubleClickTimeout()));
1099 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
1100 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->position().x(), ev->position().y(),
1102 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1104 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1110 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1112 QAbstractScrollArea::resizeEvent(ev);
1113 d->need_resize_ = true;
1118 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1120 if (preedit_string_.empty())
1123 // FIXME: shall we use real_current_font here? (see #10478)
1124 FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1125 FontMetrics const & fm = theFontMetrics(font);
1128 buffer_view_->caretPosAndDim(point, dim);
1129 int cur_x = point.x_;
1130 int cur_y = point.y_ + dim.height();
1132 // get attributes of input method cursor.
1133 // cursor_pos : cursor position in preedit string.
1134 size_t cursor_pos = 0;
1135 bool cursor_is_visible = false;
1136 for (auto const & attr : preedit_attr_) {
1137 if (attr.type == QInputMethodEvent::Cursor) {
1138 cursor_pos = size_t(attr.start);
1139 cursor_is_visible = attr.length != 0;
1144 size_t const preedit_length = preedit_string_.length();
1146 // get position of selection in input method.
1147 // FIXME: isn't there a simpler way to do this?
1148 // rStart : cursor position in selected string in IM.
1150 // rLength : selected string length in IM.
1152 if (cursor_pos < preedit_length) {
1153 for (auto const & attr : preedit_attr_) {
1154 if (attr.type == QInputMethodEvent::TextFormat) {
1155 if (attr.start <= int(cursor_pos)
1156 && int(cursor_pos) < attr.start + attr.length) {
1157 rStart = size_t(attr.start);
1158 rLength = size_t(attr.length);
1159 if (!cursor_is_visible)
1160 cursor_pos += rLength;
1167 rStart = cursor_pos;
1171 int const right_margin = buffer_view_->rightMargin();
1172 Painter::preedit_style ps;
1173 // Most often there would be only one line:
1175 for (size_t pos = 0; pos != preedit_length; ++pos) {
1176 char_type const typed_char = preedit_string_[pos];
1177 // reset preedit string style
1178 ps = Painter::preedit_default;
1180 // if we reached the right extremity of the screen, go to next line.
1181 if (cur_x + fm.width(typed_char) > p->viewport()->width() - right_margin) {
1182 cur_x = right_margin;
1183 cur_y += dim.height() + 1;
1186 // preedit strings are displayed with dashed underline
1187 // and partial strings are displayed white on black indicating
1188 // that we are in selecting mode in the input method.
1189 // FIXME: rLength == preedit_length is not a changing condition
1190 // FIXME: should be put out of the loop.
1192 && pos < rStart + rLength
1193 && !(cursor_pos < rLength && rLength == preedit_length))
1194 ps = Painter::preedit_selecting;
1196 if (pos == cursor_pos
1197 && (cursor_pos < rLength && rLength == preedit_length))
1198 ps = Painter::preedit_cursor;
1200 // draw one character and update cur_x.
1201 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1206 void GuiWorkArea::Private::resetScreen()
1208 if (use_backingstore_) {
1209 int const pr = p->pixelRatio();
1210 screen_ = QImage(pr * p->viewport()->width(),
1211 pr * p->viewport()->height(),
1212 QImage::Format_ARGB32_Premultiplied);
1213 screen_.setDevicePixelRatio(pr);
1218 QPaintDevice * GuiWorkArea::Private::screenDevice()
1220 if (use_backingstore_)
1223 return p->viewport();
1227 void GuiWorkArea::Private::updateScreen(QRectF const & rc)
1229 if (use_backingstore_) {
1230 QPainter qpain(p->viewport());
1231 double const pr = p->pixelRatio();
1232 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr,
1233 rc.width() * pr, rc.height() * pr);
1234 qpain.drawImage(rc, screen_, rcs);
1239 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1241 // Do not trigger the painting machinery if we are not ready (see
1242 // bug #10989). The second test triggers when in the middle of a
1243 // dispatch operation.
1244 if (view().busy() || d->buffer_view_->busy()) {
1245 // Since the screen may have turned black at this point, our
1246 // backing store has to be copied to screen. This is a no-op
1247 // except when our drawing strategy is "backingstore" (macOS,
1248 // Wayland, or set in prefs).
1249 d->updateScreen(ev->rect());
1250 // Ignore this paint event, but request a new one for later.
1251 viewport()->update(ev->rect());
1256 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1257 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1259 if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_) {
1261 d->resizeBufferView();
1264 d->last_pixel_ratio_ = pixelRatio();
1266 GuiPainter pain(d->screenDevice(), pixelRatio(), d->lyx_view_->develMode());
1268 d->buffer_view_->draw(pain, d->caret_visible_);
1270 // The preedit text, if needed
1271 d->paintPreeditText(pain);
1274 // FIXME: the code would be a little bit simpler if caret geometry
1275 // was updated unconditionally. Some profiling is required to see
1276 // how expensive this is (especially when idle).
1277 if (d->caret_visible_) {
1278 if (d->needs_caret_geometry_update_)
1279 d->updateCaretGeometry();
1280 d->drawCaret(pain, d->buffer_view_->horizScrollOffset());
1283 d->updateScreen(ev->rect());
1289 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1291 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1292 << " commitString: " << e->commitString());
1294 if (!e->commitString().isEmpty()) {
1296 // take care of commit string assigned to a shortcut
1297 // e.g. quotation mark on international keyboard
1299 for (QChar const & ch : e->commitString()) {
1301 keysym.init(ch.unicode());
1302 keyseq.addkey(keysym, NoModifier);
1304 cmd = theTopLevelKeymap().getBinding(keyseq);
1306 if (cmd == FuncRequest::noaction || cmd == FuncRequest::unknown
1307 || cmd.action() == LFUN_SELF_INSERT)
1308 // insert the processed text in the document (handles undo)
1309 cmd = FuncRequest(LFUN_SELF_INSERT, qstring_to_ucs4(e->commitString()));
1311 cmd.setOrigin(FuncRequest::KEYBOARD);
1313 // FIXME: this is supposed to remove traces from preedit
1314 // string. Can we avoid calling it explicitly?
1315 d->buffer_view_->updateMetrics();
1318 // Hide the caret during the test transformation.
1319 if (e->preeditString().isEmpty())
1320 startBlinkingCaret();
1322 stopBlinkingCaret();
1324 if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1330 // The preedit text and its attributes will be used in paintPreeditText
1331 d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1332 d->preedit_attr_ = e->attributes();
1335 // redraw area of preedit string.
1336 // int height = d->caret_->dim.height();
1337 // int cur_y = d->caret_->y;
1338 // viewport()->update(0, cur_y, viewport()->width(),
1339 // (height + 1) * d->preedit_lines_);
1340 viewport()->update();
1342 if (d->preedit_string_.empty()) {
1343 d->preedit_lines_ = 1;
1348 // Don't forget to accept the event!
1353 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1356 // this is the CJK-specific composition window position and
1357 // the context menu position when the menu key is pressed.
1358 case Qt::ImCursorRectangle: {
1359 CaretGeometry const & cg = bufferView().caretGeometry();
1360 return QRect(cg.left - 10 * (d->preedit_lines_ != 1),
1361 cg.top + cg.height() * d->preedit_lines_,
1362 cg.width(), cg.height());
1365 return QWidget::inputMethodQuery(query);
1370 void GuiWorkArea::updateWindowTitle()
1372 Buffer const & buf = bufferView().buffer();
1373 if (buf.fileName() != d->file_name_
1374 || buf.params().shell_escape != d->shell_escape_
1375 || buf.hasReadonlyFlag() != d->read_only_
1376 || buf.lyxvc().vcstatus() != d->vc_status_
1377 || buf.isClean() != d->clean_
1378 || buf.notifiesExternalModification() != d->externally_modified_) {
1379 d->file_name_ = buf.fileName();
1380 d->shell_escape_ = buf.params().shell_escape;
1381 d->read_only_ = buf.hasReadonlyFlag();
1382 d->vc_status_ = buf.lyxvc().vcstatus();
1383 d->clean_ = buf.isClean();
1384 d->externally_modified_ = buf.notifiesExternalModification();
1385 Q_EMIT titleChanged(this);
1390 bool GuiWorkArea::isFullScreen() const
1392 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1396 bool GuiWorkArea::inDialogMode() const
1398 return d->dialog_mode_;
1402 void GuiWorkArea::setDialogMode(bool mode)
1404 d->dialog_mode_ = mode;
1408 GuiCompleter & GuiWorkArea::completer()
1410 return *d->completer_;
1413 GuiView const & GuiWorkArea::view() const
1415 return *d->lyx_view_;
1419 GuiView & GuiWorkArea::view()
1421 return *d->lyx_view_;
1424 ////////////////////////////////////////////////////////////////////
1428 ////////////////////////////////////////////////////////////////////
1431 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1433 support::TempFile tempfile("embedded.internal");
1434 tempfile.setAutoRemove(false);
1435 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1436 buffer_->setUnnamed(true);
1437 buffer_->setFullyLoaded(true);
1438 setBuffer(*buffer_);
1439 setDialogMode(true);
1443 EmbeddedWorkArea::~EmbeddedWorkArea()
1445 // No need to destroy buffer and bufferview here, because it is done
1446 // in theBufferList() destruction loop at application exit
1450 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1453 GuiWorkArea::closeEvent(ev);
1457 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1460 GuiWorkArea::hideEvent(ev);
1464 QSize EmbeddedWorkArea::sizeHint () const
1467 // GuiWorkArea sets the size to the screen's viewport
1468 // by returning a value this gets overridden
1469 // EmbeddedWorkArea is now sized to fit in the layout
1470 // of the parent, and has a minimum size set in GuiWorkArea
1471 // which is what we return here
1472 return QSize(100, 70);
1476 void EmbeddedWorkArea::disable()
1478 stopBlinkingCaret();
1479 if (view().currentWorkArea() != this)
1481 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1482 // tolerates it and shows the background logo), what happens if
1483 // an EmbeddedWorkArea is closed after closing all document WAs
1484 view().setCurrentWorkArea(view().currentMainWorkArea());
1487 ////////////////////////////////////////////////////////////////////
1491 ////////////////////////////////////////////////////////////////////
1493 TabWorkArea::TabWorkArea(QWidget * parent)
1494 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1496 QPalette pal = palette();
1497 pal.setColor(QPalette::Active, QPalette::Button,
1498 pal.color(QPalette::Active, QPalette::Window));
1499 pal.setColor(QPalette::Disabled, QPalette::Button,
1500 pal.color(QPalette::Disabled, QPalette::Window));
1501 pal.setColor(QPalette::Inactive, QPalette::Button,
1502 pal.color(QPalette::Inactive, QPalette::Window));
1504 QObject::connect(this, SIGNAL(currentChanged(int)),
1505 this, SLOT(on_currentTabChanged(int)));
1506 #if QT_VERSION >= 0x050200
1508 QObject::connect(this, SIGNAL(tabBarClicked(int)),
1509 this, SLOT(on_currentTabChanged(int)));
1512 closeBufferButton = new QToolButton(this);
1513 closeBufferButton->setPalette(pal);
1514 // FIXME: rename the icon to closebuffer.png
1515 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1516 closeBufferButton->setText("Close File");
1517 closeBufferButton->setAutoRaise(true);
1518 closeBufferButton->setCursor(Qt::ArrowCursor);
1519 closeBufferButton->setToolTip(qt_("Close File"));
1520 closeBufferButton->setEnabled(true);
1521 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1522 this, SLOT(closeCurrentBuffer()));
1523 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1525 // set TabBar behaviour
1526 QTabBar * tb = tabBar();
1527 tb->setTabsClosable(!lyxrc.single_close_tab_button);
1528 tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1529 tb->setElideMode(Qt::ElideNone);
1530 // allow dragging tabs
1531 tb->setMovable(true);
1532 // make us responsible for the context menu of the tabbar
1533 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1534 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1535 this, SLOT(showContextMenu(const QPoint &)));
1536 connect(tb, SIGNAL(tabCloseRequested(int)),
1537 this, SLOT(closeTab(int)));
1539 setUsesScrollButtons(true);
1541 // use document mode tabs
1542 setDocumentMode(true);
1547 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1549 if (me->button() == Qt::MiddleButton)
1550 midpressed_tab_ = tabBar()->tabAt(me->pos());
1552 QTabWidget::mousePressEvent(me);
1556 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1558 if (me->button() == Qt::MiddleButton) {
1559 int const midreleased_tab = tabBar()->tabAt(me->pos());
1560 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1561 closeTab(midreleased_tab);
1563 QTabWidget::mouseReleaseEvent(me);
1567 void TabWorkArea::paintEvent(QPaintEvent * event)
1569 if (tabBar()->isVisible()) {
1570 QTabWidget::paintEvent(event);
1572 // Prevent the selected tab to influence the
1573 // painting of the frame of the tab widget.
1574 // This is needed for gtk style in Qt.
1575 QStylePainter p(this);
1576 QStyleOptionTabWidgetFrame opt;
1577 initStyleOption(&opt);
1578 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1580 opt.selectedTabRect = QRect();
1581 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1586 bool TabWorkArea::posIsTab(QPoint position)
1588 // tabAt returns -1 if tab does not covers position
1589 return tabBar()->tabAt(position) > -1;
1593 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1595 if (event->button() != Qt::LeftButton)
1598 // this code chunk is unnecessary because it seems the event only makes
1599 // it this far if it is not on a tab. I'm not sure why this is (maybe
1600 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1601 // this is true in all cases and if it will be true in the future so I
1602 // leave this code for now. (skostysh, 2016-07-21)
1604 // return early if double click on existing tabs
1605 if (posIsTab(event->pos()))
1608 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1612 void TabWorkArea::setFullScreen(bool full_screen)
1614 for (int i = 0; i != count(); ++i) {
1615 if (GuiWorkArea * wa = workArea(i))
1616 wa->setFullScreen(full_screen);
1619 if (lyxrc.full_screen_tabbar)
1620 showBar(!full_screen && count() > 1);
1622 showBar(count() > 1);
1626 void TabWorkArea::showBar(bool show)
1628 tabBar()->setEnabled(show);
1629 tabBar()->setVisible(show);
1630 if (documentMode()) {
1631 // avoid blank corner widget when documentMode(true) is used
1632 if (show && lyxrc.single_close_tab_button) {
1633 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1634 closeBufferButton->setVisible(true);
1636 // remove corner widget
1637 setCornerWidget(nullptr);
1639 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1640 setTabsClosable(!lyxrc.single_close_tab_button);
1644 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1646 QWidget * w = QTabWidget::widget(index);
1649 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1655 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1657 return widget(currentIndex());
1661 GuiWorkArea * TabWorkArea::workArea(int index) const
1663 GuiWorkAreaContainer * w = widget(index);
1666 return w->workArea();
1670 GuiWorkArea * TabWorkArea::currentWorkArea() const
1672 return workArea(currentIndex());
1676 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1678 // FIXME: this method doesn't work if we have more than one work area
1679 // showing the same buffer.
1680 for (int i = 0; i != count(); ++i) {
1681 GuiWorkArea * wa = workArea(i);
1682 LASSERT(wa, return nullptr);
1683 if (&wa->bufferView().buffer() == &buffer)
1690 void TabWorkArea::closeAll()
1693 QWidget * wac = widget(0);
1694 LASSERT(wac, return);
1701 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1703 for (int index = 0; index < count(); ++index)
1704 if (workArea(index) == w)
1710 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1712 LASSERT(work_area, return false);
1713 int index = indexOfWorkArea(work_area);
1717 if (index == currentIndex())
1718 // Make sure the work area is up to date.
1719 on_currentTabChanged(index);
1721 // Switch to the work area.
1722 setCurrentIndex(index);
1723 work_area->setFocus();
1729 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1731 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1732 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1733 wa->setUpdatesEnabled(false);
1734 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1735 // when hiding it again below).
1736 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1737 showBar(count() > 0);
1738 addTab(wac, wa->windowTitle());
1739 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1740 this, SLOT(updateTabTexts()));
1741 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1742 setFullScreen(true);
1744 // Hide tabbar if there's only one tab.
1745 showBar(count() > 1);
1753 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1755 LASSERT(work_area, return false);
1756 int index = indexOfWorkArea(work_area);
1760 work_area->setUpdatesEnabled(false);
1761 QWidget * wac = widget(index);
1766 // make sure the next work area is enabled.
1767 currentWidget()->setUpdatesEnabled(true);
1768 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1769 setFullScreen(true);
1771 // Show tabbar only if there's more than one tab.
1772 showBar(count() > 1);
1774 lastWorkAreaRemoved();
1782 void TabWorkArea::on_currentTabChanged(int i)
1784 // returns e.g. on application destruction
1787 GuiWorkArea * wa = workArea(i);
1788 LASSERT(wa, return);
1789 wa->setUpdatesEnabled(true);
1790 wa->scheduleRedraw(true);
1793 currentWorkAreaChanged(wa);
1795 LYXERR(Debug::GUI, "currentTabChanged " << i
1796 << " File: " << wa->bufferView().buffer().absFileName());
1800 void TabWorkArea::closeCurrentBuffer()
1803 if (clicked_tab_ == -1)
1804 wa = currentWorkArea();
1806 wa = workArea(clicked_tab_);
1807 LASSERT(wa, return);
1809 wa->view().closeWorkArea(wa);
1813 void TabWorkArea::hideCurrentTab()
1816 if (clicked_tab_ == -1)
1817 wa = currentWorkArea();
1819 wa = workArea(clicked_tab_);
1820 LASSERT(wa, return);
1822 wa->view().hideWorkArea(wa);
1826 void TabWorkArea::closeTab(int index)
1828 on_currentTabChanged(index);
1831 wa = currentWorkArea();
1833 wa = workArea(index);
1834 LASSERT(wa, return);
1836 wa->view().closeWorkArea(wa);
1843 /// make vector happy
1844 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1846 DisplayPath(int tab, FileName const & filename)
1849 // Recode URL encoded chars via fromPercentEncoding()
1850 string const fn = (filename.extension() == "lyx")
1851 ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
1852 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
1853 #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
1854 postfix_ = toqstr(filename.absoluteFilePath()).
1855 split("/", Qt::SkipEmptyParts);
1857 postfix_ = toqstr(filename.absoluteFilePath()).
1858 split("/", QString::SkipEmptyParts);
1860 postfix_.pop_back();
1861 abs_ = toqstr(filename.absoluteFilePath());
1862 dottedPrefix_ = false;
1865 /// Absolute path for debugging.
1870 /// Add the first segment from the postfix or three dots to the prefix.
1871 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1872 /// when really needed.
1873 void shiftPathSegment(bool dotted)
1875 if (postfix_.count() <= 0)
1879 if (dottedPrefix_ && !prefix_.isEmpty())
1880 prefix_ += ellipsisSlash_;
1881 prefix_ += postfix_.front() + "/";
1883 dottedPrefix_ = dotted && !prefix_.isEmpty();
1884 postfix_.pop_front();
1887 QString displayString() const
1889 if (prefix_.isEmpty())
1892 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1893 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1896 QString forecastPathString() const
1898 if (postfix_.count() == 0)
1899 return displayString();
1902 + (dottedPrefix_ ? ellipsisSlash_ : "")
1903 + postfix_.front() + "/";
1906 bool final() const { return postfix_.empty(); }
1908 int tab() const { return tab_; }
1912 static QString const ellipsisSlash_;
1916 QStringList postfix_;
1928 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1932 bool operator<(DisplayPath const & a, DisplayPath const & b)
1934 return a.displayString() < b.displayString();
1938 bool operator==(DisplayPath const & a, DisplayPath const & b)
1940 return a.displayString() == b.displayString();
1944 void TabWorkArea::updateTabTexts()
1946 int const n = count();
1949 std::list<DisplayPath> paths;
1950 typedef std::list<DisplayPath>::iterator It;
1952 // collect full names first: path into postfix, empty prefix and
1953 // filename without extension
1954 for (int i = 0; i < n; ++i) {
1955 GuiWorkArea * i_wa = workArea(i);
1956 FileName const fn = i_wa->bufferView().buffer().fileName();
1957 paths.push_back(DisplayPath(i, fn));
1960 // go through path segments and see if it helps to make the path more unique
1961 bool somethingChanged = true;
1962 bool allFinal = false;
1963 while (somethingChanged && !allFinal) {
1964 // adding path segments changes order
1967 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1968 somethingChanged = false;
1971 // find segments which are not unique (i.e. non-atomic)
1972 It it = paths.begin();
1974 QString segString = it->displayString();
1975 for (; it != paths.end(); ++it) {
1976 // look to the next item
1981 allFinal = allFinal && it->final();
1983 LYXERR(Debug::GUI, "it = " << it->abs()
1984 << " => " << it->displayString());
1986 // still the same segment?
1988 if ((next != paths.end()
1989 && (nextString = next->displayString()) == segString))
1991 LYXERR(Debug::GUI, "segment ended");
1993 // only a trivial one with one element?
1994 if (it == segStart) {
1995 // start new segment
1997 segString = nextString;
2001 // We found a non-atomic segment
2002 // We know that segStart <= it < next <= paths.end().
2003 // The assertion below tells coverity about it.
2004 LATTEST(segStart != paths.end());
2005 QString dspString = segStart->forecastPathString();
2006 LYXERR(Debug::GUI, "first forecast found for "
2007 << segStart->abs() << " => " << dspString);
2010 // Shift path segments and hope for the best
2011 // that it makes the path more unique.
2012 somethingChanged = true;
2013 bool moreUnique = false;
2014 for (; sit != next; ++sit) {
2015 if (sit->forecastPathString() != dspString) {
2016 LYXERR(Debug::GUI, "different forecast found for "
2017 << sit->abs() << " => " << sit->forecastPathString());
2021 LYXERR(Debug::GUI, "same forecast found for "
2022 << sit->abs() << " => " << dspString);
2025 // if the path segment helped, add it. Otherwise add dots
2026 bool dots = !moreUnique;
2027 LYXERR(Debug::GUI, "using dots = " << dots);
2028 for (sit = segStart; sit != next; ++sit) {
2029 sit->shiftPathSegment(dots);
2030 LYXERR(Debug::GUI, "shifting "
2031 << sit->abs() << " => " << sit->displayString());
2034 // start new segment
2036 segString = nextString;
2040 // set new tab titles
2041 for (It it = paths.begin(); it != paths.end(); ++it) {
2042 int const tab_index = it->tab();
2043 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2044 QString tab_text = it->displayString().replace("&", "&&");
2045 if (!buf.fileName().empty() && !buf.isClean())
2047 QString tab_tooltip = it->abs();
2048 if (buf.hasReadonlyFlag()) {
2050 QLabel * readOnlyButton = new QLabel();
2051 QIcon icon = QIcon(getPixmap("images/", "emblem-readonly", "svgz,png"));
2052 readOnlyButton->setPixmap(icon.pixmap(QSize(16, 16)));
2053 tabBar()->setTabButton(tab_index, QTabBar::RightSide, readOnlyButton);
2055 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2057 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2060 tabBar()->setTabButton(tab_index, QTabBar::RightSide, 0);
2062 setTabIcon(tab_index, QIcon());
2064 if (buf.notifiesExternalModification()) {
2065 QString const warn = qt_("%1 (modified externally)");
2066 tab_tooltip = warn.arg(tab_tooltip);
2067 tab_text += QChar(0x26a0);
2069 setTabText(tab_index, tab_text);
2070 setTabToolTip(tab_index, tab_tooltip);
2075 void TabWorkArea::showContextMenu(const QPoint & pos)
2078 clicked_tab_ = tabBar()->tabAt(pos);
2079 if (clicked_tab_ == -1)
2082 GuiWorkArea * wa = workArea(clicked_tab_);
2083 LASSERT(wa, return);
2087 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2088 qt_("&Hide Tab"), this, SLOT(hideCurrentTab()));
2090 // we want to show the 'close' option only if this is not a child buffer.
2091 Buffer const & buf = wa->bufferView().buffer();
2093 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2094 qt_("&Close Tab"), this, SLOT(closeCurrentBuffer()));
2095 popup.exec(tabBar()->mapToGlobal(pos));
2101 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2103 QWidget * w = widget(fromIndex);
2104 QIcon icon = tabIcon(fromIndex);
2105 QString text = tabText(fromIndex);
2107 setCurrentIndex(fromIndex);
2108 removeTab(fromIndex);
2109 insertTab(toIndex, w, icon, text);
2110 setCurrentIndex(toIndex);
2114 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2115 : QWidget(parent), wa_(wa)
2117 LASSERT(wa, return);
2118 Ui::WorkAreaUi::setupUi(this);
2119 layout()->addWidget(wa);
2120 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2121 this, SLOT(updateDisplay()));
2122 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2123 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2124 setMessageColour({notificationFrame, externalModificationLabel},
2125 {reloadPB, ignorePB});
2130 void GuiWorkAreaContainer::updateDisplay()
2132 Buffer const & buf = wa_->bufferView().buffer();
2133 notificationFrame->setHidden(!buf.notifiesExternalModification());
2134 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2135 .arg(toqstr(buf.fileName().displayName()));
2136 externalModificationLabel->setText(label);
2140 void GuiWorkAreaContainer::dispatch(FuncRequest const & f) const
2142 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2143 wa_->bufferView().buffer().absFileName()));
2148 void GuiWorkAreaContainer::reload() const
2150 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2154 void GuiWorkAreaContainer::ignore() const
2156 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2160 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2162 // prevent TabWorkArea from opening a new buffer on double click
2167 } // namespace frontend
2170 #include "moc_GuiWorkArea.cpp"