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"
45 #include "support/convert.h"
46 #include "support/debug.h"
47 #include "support/lassert.h"
48 #include "support/TempFile.h"
50 #include "frontends/Application.h"
51 #include "frontends/CaretGeometry.h"
52 #include "frontends/FontMetrics.h"
53 #include "frontends/WorkAreaManager.h"
55 #include <QContextMenuEvent>
59 #include <QProxyStyle>
61 #include <QMainWindow>
67 #include <QStyleOption>
68 #include <QStylePainter>
70 #include <QToolButton>
81 using namespace lyx::support;
86 /// return the LyX mouse button state from Qt's
87 static mouse_button::state q_button_state(Qt::MouseButton button)
89 mouse_button::state b = mouse_button::none;
92 b = mouse_button::button1;
94 case Qt::MiddleButton:
95 b = mouse_button::button2;
98 b = mouse_button::button3;
107 /// return the LyX mouse button state from Qt's
108 mouse_button::state q_motion_state(Qt::MouseButtons state)
110 mouse_button::state b = mouse_button::none;
111 if (state & Qt::LeftButton)
112 b |= mouse_button::button1;
113 if (state & Qt::MiddleButton)
114 b |= mouse_button::button2;
115 if (state & Qt::RightButton)
116 b |= mouse_button::button3;
123 // This is a 'heartbeat' generating synthetic mouse move events when the
124 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
125 SyntheticMouseEvent::SyntheticMouseEvent()
126 : timeout(200), restart_timeout(true)
130 GuiWorkArea::Private::Private(GuiWorkArea * parent)
131 : p(parent), completer_(new GuiCompleter(p, p))
133 use_backingstore_ = lyxrc.draw_strategy == LyXRC::DS_BACKINGSTORE
134 || guiApp->needsBackingStore();
135 LYXERR(Debug::WORKAREA, "Drawing strategy is: "
136 << (use_backingstore_ ? "backingstore" : "partial"));
138 int const time = QApplication::cursorFlashTime() / 2;
140 caret_timeout_.setInterval(time);
141 caret_timeout_.start();
143 // let's initialize this just to be safe
144 caret_timeout_.setInterval(500);
149 GuiWorkArea::Private::~Private()
151 // If something is wrong with the buffer, we can ignore it safely
153 buffer_view_->buffer().workAreaManager().remove(p);
156 // Completer has a QObject parent and is thus automatically destroyed.
158 // delete completer_;
162 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
163 : d(new Private(this))
165 new CompressorProxy(this); // not a leak
169 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
170 : d(new Private(this))
172 new CompressorProxy(this); // not a leak
174 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
180 double GuiWorkArea::pixelRatio() const
182 return qt_scale_factor * devicePixelRatio();
186 void GuiWorkArea::init()
189 connect(&d->caret_timeout_, SIGNAL(timeout()),
190 this, SLOT(toggleCaret()));
192 // This connection is closed at the same time as this is destroyed.
193 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
194 generateSyntheticMouseEvent();
198 // A mouse event will happen before the first paint event,
199 // so make sure that the buffer view has an up to date metrics.
200 d->buffer_view_->resize(viewport()->width(), viewport()->height());
202 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
203 setAcceptDrops(true);
204 setMouseTracking(true);
205 setMinimumSize(100, 70);
206 setFrameStyle(QFrame::NoFrame);
209 d->updateCursorShape();
211 // we paint our own background
212 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
214 setFocusPolicy(Qt::StrongFocus);
216 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
217 << " viewport height: " << viewport()->height());
219 // Enables input methods for asian languages.
220 // Must be set when creating custom text editing widgets.
221 setAttribute(Qt::WA_InputMethodEnabled, true);
225 GuiWorkArea::~GuiWorkArea()
231 void GuiWorkArea::Private::updateCursorShape()
233 bool const clickable = buffer_view_ && buffer_view_->clickableInset();
234 p->viewport()->setCursor(clickable ? Qt::PointingHandCursor
239 void GuiWorkArea::setGuiView(GuiView & gv)
245 void GuiWorkArea::setBuffer(Buffer & buffer)
247 delete d->buffer_view_;
248 d->buffer_view_ = new BufferView(buffer);
249 buffer.workAreaManager().add(this);
251 // HACK: Prevents an additional redraw when the scrollbar pops up
252 // which regularly happens on documents with more than one page.
253 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
254 // Since we have no geometry information yet, we assume that
255 // a document needs a scrollbar if there is more then four
256 // paragraph in the outermost text.
257 if (buffer.text().paragraphs().size() > 4)
258 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
259 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
260 Q_EMIT bufferViewChanged();
264 void GuiWorkArea::fixVerticalScrollBar()
267 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
271 void GuiWorkArea::close()
273 d->lyx_view_->removeWorkArea(this);
277 void GuiWorkArea::setFullScreen(bool full_screen)
279 d->buffer_view_->setFullScreen(full_screen);
280 if (full_screen && lyxrc.full_screen_scrollbar)
281 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
283 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
287 BufferView & GuiWorkArea::bufferView()
289 return *d->buffer_view_;
293 BufferView const & GuiWorkArea::bufferView() const
295 return *d->buffer_view_;
299 void GuiWorkArea::stopBlinkingCaret()
301 d->caret_timeout_.stop();
306 void GuiWorkArea::startBlinkingCaret()
308 // do not show the cursor if the view is busy
312 // Don't start blinking if the cursor isn't on screen, unless we
313 // are not ready to know whether the cursor is on screen.
314 if (!d->buffer_view_->buffer().undo().activeUndoGroup()
315 && !d->buffer_view_->caretInView())
320 // Avoid blinking when debugging PAINTING, since it creates too much noise
321 if (!lyxerr.debugging(Debug::PAINTING)) {
322 // we are not supposed to cache this value.
323 int const time = QApplication::cursorFlashTime() / 2;
326 d->caret_timeout_.setInterval(time);
327 d->caret_timeout_.start();
332 void GuiWorkArea::toggleCaret()
334 if (d->caret_visible_)
341 void GuiWorkArea::scheduleRedraw(bool update_metrics)
344 // No need to redraw in this case.
347 // No need to do anything if this is the current view. The BufferView
348 // metrics are already up to date.
349 if (update_metrics || d->lyx_view_ != guiApp->currentView()
350 || d->lyx_view_->currentWorkArea() != this) {
351 // FIXME: it would be nice to optimize for the off-screen case.
352 d->buffer_view_->cursor().fixIfBroken();
353 d->buffer_view_->updateMetrics();
354 d->buffer_view_->cursor().fixIfBroken();
357 // update caret position, because otherwise it has to wait until
358 // the blinking interval is over
361 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
362 viewport()->update();
364 /// FIXME: is this still true now that paintEvent does the actual painting?
365 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
366 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
367 d->updateScrollbar();
368 d->lyx_view_->updateStatusBar();
370 if (lyxerr.debugging(Debug::WORKAREA))
371 d->buffer_view_->coordCache().dump();
375 d->updateCursorShape();
379 // Keep in sync with GuiWorkArea::processKeySym below
380 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
382 return guiApp->queryKeySym(key, mod);
386 // Keep in sync with GuiWorkArea::queryKeySym above
387 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
389 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
390 && lyxrc.full_screen_menubar) {
391 // FIXME HACK: we should not have to do this here. See related comment
392 // in GuiView::event() (QEvent::ShortcutOverride)
393 d->lyx_view_->menuBar()->hide();
396 // In order to avoid bad surprise in the middle of an operation,
397 // we better stop the blinking caret...
398 // the caret gets restarted in GuiView::restartCaret()
400 guiApp->processKeySym(key, mod);
404 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
407 if (cmd.action() == LFUN_FILE_OPEN) {
409 lyx_view_->dispatch(cmd, dr);
413 bool const notJustMovingTheMouse =
414 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
416 // In order to avoid bad surprise in the middle of an operation, we better stop
417 // the blinking caret.
418 if (notJustMovingTheMouse)
419 p->stopBlinkingCaret();
421 buffer_view_->mouseEventDispatch(cmd);
423 // Skip these when selecting
424 // FIXME: let GuiView take care of those.
425 if (notJustMovingTheMouse && !buffer_view_->mouseSelecting()) {
426 completer_->updateVisibility(false, false);
427 lyx_view_->updateDialogs();
428 lyx_view_->updateStatusBar();
431 // GUI tweaks except with mouse motion with no button pressed.
432 if (notJustMovingTheMouse) {
433 // Slight hack: this is only called currently when we
434 // clicked somewhere, so we force through the display
435 // of the new status here.
436 // FIXME: let GuiView take care of those.
437 lyx_view_->clearMessage();
439 // Show the caret immediately after any operation
440 p->startBlinkingCaret();
447 void GuiWorkArea::Private::resizeBufferView()
449 // WARNING: Please don't put any code that will trigger a repaint here!
450 // We are already inside a paint event.
451 p->stopBlinkingCaret();
452 // Warn our container (GuiView).
455 bool const caret_in_view = buffer_view_->caretInView();
456 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
458 buffer_view_->showCursor();
461 // Update scrollbars which might have changed due different
462 // BufferView dimension. This is especially important when the
463 // BufferView goes from zero-size to the real-size for the first time,
464 // as the scrollbar parameters are then set for the first time.
467 need_resize_ = false;
469 // Eventually, restart the caret after the resize event.
470 // We might be resizing even if the focus is on another widget so we only
471 // restart the caret if we have the focus.
473 QTimer::singleShot(50, p, SLOT(startBlinkingCaret()));
477 void GuiWorkArea::Private::resetCaret()
479 // Don't start blinking if the cursor isn't on screen.
480 if (!buffer_view_->caretInView())
483 // completion indicator
484 Cursor const & cur = buffer_view_->cursor();
485 bool const completable = cur.inset().showCompletionCursor()
486 && completer_->completionAvailable()
487 && !completer_->popupVisible()
488 && !completer_->inlineVisible();
490 buffer_view_->buildCaretGeometry(completable);
492 needs_caret_geometry_update_ = true;
493 caret_visible_ = true;
497 void GuiWorkArea::Private::updateCaretGeometry()
499 // we cannot update geometry if not ready and we do not need to if
500 // caret is not in view.
501 if (buffer_view_->buffer().undo().activeUndoGroup()
502 || !buffer_view_->caretInView())
506 needs_caret_geometry_update_ = false;
510 void GuiWorkArea::Private::showCaret()
516 p->viewport()->update();
520 void GuiWorkArea::Private::hideCaret()
525 caret_visible_ = false;
526 //if (!qApp->focusWidget())
527 p->viewport()->update();
531 /* Draw the caret. Parameter \c horiz_offset is not 0 when there
532 * has been horizontal scrolling in current row
534 void GuiWorkArea::Private::drawCaret(QPainter & painter, int horiz_offset) const
536 if (buffer_view_->caretGeometry().shapes.empty())
539 QColor const color = guiApp->colorCache().get(Color_cursor);
540 painter.setPen(color);
541 painter.setRenderHint(QPainter::Antialiasing, true);
542 for (auto const & shape : buffer_view_->caretGeometry().shapes) {
545 for (Point const & p : shape) {
547 path.moveTo(p.x_ - horiz_offset, p.y_);
550 path.lineTo(p.x_ - horiz_offset, p.y_);
552 painter.fillPath(path, color);
554 painter.setRenderHint(QPainter::Antialiasing, false);
558 void GuiWorkArea::Private::updateScrollbar()
560 // Prevent setRange() and setSliderPosition from causing recursive calls via
561 // the signal valueChanged. (#10311)
562 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
563 p, SLOT(scrollTo(int)));
564 ScrollbarParameters const & scroll = buffer_view_->scrollbarParameters();
565 p->verticalScrollBar()->setRange(scroll.min, scroll.max);
566 p->verticalScrollBar()->setPageStep(scroll.page_step);
567 p->verticalScrollBar()->setSingleStep(scroll.single_step);
568 p->verticalScrollBar()->setSliderPosition(0);
569 // Connect to the vertical scroll bar
570 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
571 p, SLOT(scrollTo(int)));
575 void GuiWorkArea::scrollTo(int value)
578 d->buffer_view_->scrollDocView(value, true);
580 if (lyxrc.cursor_follows_scrollbar) {
581 d->buffer_view_->setCursorFromScrollbar();
582 // FIXME: let GuiView take care of those.
583 d->lyx_view_->updateLayoutList();
585 // Show the caret immediately after any operation.
586 startBlinkingCaret();
590 bool GuiWorkArea::event(QEvent * e)
593 case QEvent::ToolTip: {
594 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
595 if (lyxrc.use_tooltip) {
596 QPoint pos = helpEvent->pos();
597 if (pos.x() < viewport()->width()) {
598 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
599 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
602 QToolTip::hideText();
604 // Don't forget to accept the event!
609 case QEvent::ShortcutOverride:
610 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
612 keyPressEvent(static_cast<QKeyEvent *>(e));
613 return e->isAccepted();
615 case QEvent::KeyPress: {
616 // We catch this event in order to catch the Tab or Shift+Tab key press
617 // which are otherwise reserved to focus switching between controls
619 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
620 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
621 || (ke->key() == Qt::Key_Backtab && (
622 ke->modifiers() == Qt::ShiftModifier
623 || ke->modifiers() == Qt::NoModifier))) {
627 return QAbstractScrollArea::event(e);
631 return QAbstractScrollArea::event(e);
637 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
640 if (e->reason() == QContextMenuEvent::Mouse)
641 // the menu name is set on mouse press
642 name = d->context_menu_name_;
644 QPoint pos = e->pos();
645 Cursor const & cur = d->buffer_view_->cursor();
646 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
647 // Do not access the context menu of math right in front of before
648 // the cursor. This does not work when the cursor is in text.
649 Inset * inset = cur.paragraph().getInset(cur.pos());
650 if (inset && inset->asInsetMath())
652 else if (cur.pos() > 0) {
653 inset = cur.paragraph().getInset(cur.pos() - 1);
658 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
665 // always show mnemonics when the keyboard is used to show the context menu
666 // FIXME: This should be fixed in Qt itself
667 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
668 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
673 // Position the menu to the right.
674 // FIXME: menu position should be different for RTL text.
675 menu->exec(e->globalPos());
680 void GuiWorkArea::focusInEvent(QFocusEvent * e)
682 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
683 if (d->lyx_view_->currentWorkArea() != this) {
684 d->lyx_view_->setCurrentWorkArea(this);
685 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
688 startBlinkingCaret();
689 QAbstractScrollArea::focusInEvent(e);
693 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
695 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
697 QAbstractScrollArea::focusOutEvent(e);
701 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
703 if (d->dc_event_.active && d->dc_event_ == *e) {
704 d->dc_event_.active = false;
705 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
706 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->position().x(), e->position().y(),
708 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
710 q_button_state(e->button()), q_key_state(e->modifiers()));
716 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
717 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->position().x(), e->position().y(),
719 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
721 q_button_state(e->button()), q_key_state(e->modifiers()));
724 // Save the context menu on mouse press, because also the mouse
725 // cursor is set on mouse press. Afterwards, we can either release
726 // the mousebutton somewhere else, or the cursor might have moved
727 // due to the DEPM. We need to do this after the mouse has been
728 // set in dispatch(), because the selection state might change.
729 if (e->button() == Qt::RightButton)
730 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
731 d->context_menu_name_ = d->buffer_view_->contextMenu(e->position().x(), e->position().y());
733 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
740 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
742 if (d->synthetic_mouse_event_.timeout.running())
743 d->synthetic_mouse_event_.timeout.stop();
745 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
746 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->position().x(), e->position().y(),
748 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
750 q_button_state(e->button()), q_key_state(e->modifiers()));
751 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
752 QT_VERSION < QT_VERSION_CHECK(5,15,1))
753 d->synthetic_mouse_event_.cmd = cmd; // QtBug QAbstractScrollArea::mouseMoveEvent
760 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
762 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
763 QT_VERSION < QT_VERSION_CHECK(5,15,1))
764 // cancel the event if the coordinates didn't change, this is due to QtBug
765 // QAbstractScrollArea::mouseMoveEvent, the event is triggered falsely when quickly
766 // double tapping a touchpad. To test: try to select a word by quickly double tapping
767 // on a touchpad while hovering the cursor over that word in the work area.
768 // This bug does not occur on Qt versions 5.10.1 and below. Only Windows seems to be affected.
769 // ML thread: https://www.mail-archive.com/lyx-devel@lists.lyx.org/msg211699.html
770 // Qt bugtracker: https://bugreports.qt.io/browse/QTBUG-85431
771 // Bug was fixed in Qt 5.15.1
772 if (e->x() == d->synthetic_mouse_event_.cmd.x() && // QtBug QAbstractScrollArea::mouseMoveEvent
773 e->y() == d->synthetic_mouse_event_.cmd.y()) // QtBug QAbstractScrollArea::mouseMoveEvent
774 return; // QtBug QAbstractScrollArea::mouseMoveEvent
777 // we kill the triple click if we move
778 doubleClickTimeout();
779 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
780 FuncRequest cmd(LFUN_MOUSE_MOTION, e->position().x(), e->position().y(),
782 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
784 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
788 // If we're above or below the work area...
789 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
790 if ((e->position().y() <= 20 || e->position().y() >= viewport()->height() - 20)
792 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
794 && e->buttons() == mouse_button::button1) {
795 // Make sure only a synthetic event can cause a page scroll,
796 // so they come at a steady rate:
797 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
798 if (e->position().y() <= 20)
799 // _Force_ a scroll up:
800 cmd.set_y(e->position().y() - 21);
802 cmd.set_y(e->position().y() + 21);
805 // _Force_ a scroll up:
806 cmd.set_y(e->y() - 21);
808 cmd.set_y(e->y() + 21);
810 // Store the event, to be handled when the timeout expires.
811 d->synthetic_mouse_event_.cmd = cmd;
813 if (d->synthetic_mouse_event_.timeout.running()) {
814 // Discard the event. Note that it _may_ be handled
815 // when the timeout expires if
816 // synthetic_mouse_event_.cmd has not been overwritten.
817 // Ie, when the timeout expires, we handle the
818 // most recent event but discard all others that
819 // occurred after the one used to start the timeout
820 // in the first place.
824 d->synthetic_mouse_event_.restart_timeout = true;
825 d->synthetic_mouse_event_.timeout.start();
826 // Fall through to handle this event...
828 } else if (d->synthetic_mouse_event_.timeout.running()) {
829 // Store the event, to be possibly handled when the timeout
831 // Once the timeout has expired, normal control is returned
832 // to mouseMoveEvent (restart_timeout = false).
833 // This results in a much smoother 'feel' when moving the
834 // mouse back into the work area.
835 d->synthetic_mouse_event_.cmd = cmd;
836 d->synthetic_mouse_event_.restart_timeout = false;
843 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
845 // Wheel rotation by one notch results in a delta() of 120 (see
846 // documentation of QWheelEvent)
847 // But first we have to ignore horizontal scroll events.
848 QPoint const aDelta = ev->angleDelta();
849 // skip horizontal wheel event
850 if (abs(aDelta.x()) > abs(aDelta.y())) {
854 double const delta = aDelta.y() / 120.0;
857 switch (lyxrc.scroll_wheel_zoom) {
858 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
859 zoom = ev->modifiers() & Qt::ControlModifier;
860 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
862 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
863 zoom = ev->modifiers() & Qt::ShiftModifier;
864 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
866 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
867 zoom = ev->modifiers() & Qt::AltModifier;
868 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
870 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
874 docstring arg = convert<docstring>(int(5 * delta));
875 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
879 // Take into account the desktop wide settings.
880 int const lines = qApp->wheelScrollLines();
881 int const page_step = verticalScrollBar()->pageStep();
882 // Test if the wheel mouse is set to one screen at a time.
883 // This is according to
884 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
886 min(lines * verticalScrollBar()->singleStep(), page_step);
888 // Take into account the rotation and the user preferences.
889 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
890 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
891 << " delta = " << delta << " scroll_value = " << scroll_value
892 << " page_step = " << page_step);
894 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
900 void GuiWorkArea::generateSyntheticMouseEvent()
902 int const e_y = d->synthetic_mouse_event_.cmd.y();
903 int const wh = d->buffer_view_->workHeight();
904 bool const up = e_y < 0;
905 bool const down = e_y > wh;
907 // Set things off to generate the _next_ 'pseudo' event.
909 if (d->synthetic_mouse_event_.restart_timeout) {
910 // This is some magic formulae to determine the speed
911 // of scrolling related to the position of the mouse.
914 int dist = up ? -e_y : e_y - wh;
915 time = max(min(200, 250000 / (dist * dist)), 1) ;
918 step = 80000 / (time * time);
922 d->synthetic_mouse_event_.timeout.setTimeout(time);
923 d->synthetic_mouse_event_.timeout.start();
926 // Can we scroll further ?
927 int const value = verticalScrollBar()->value();
928 if (value == verticalScrollBar()->maximum()
929 || value == verticalScrollBar()->minimum()) {
930 d->synthetic_mouse_event_.timeout.stop();
935 if (step <= 2 * wh) {
936 d->buffer_view_->scroll(up ? -step : step);
937 d->buffer_view_->updateMetrics();
939 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
942 // In which paragraph do we have to set the cursor ?
943 Cursor & cur = d->buffer_view_->cursor();
944 // FIXME: we don't know how to handle math.
945 Text * text = cur.text();
948 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
950 // Quit gracefully if there are no metrics, since otherwise next
951 // line would crash (bug #10324).
952 // This situation seems related to a (not yet understood) timing problem.
956 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
957 ParagraphMetrics const & pm = *pp.second;
958 pit_type const pit = pp.first;
960 if (pm.rows().empty())
963 // Find the row at which we set the cursor.
964 RowList::const_iterator rit = pm.rows().begin();
965 RowList::const_iterator rlast = pm.rows().end();
966 int yy = pm.position() - pm.ascent();
967 for (--rlast; rit != rlast; ++rit) {
968 int h = rit->height();
969 if ((up && yy + h > 0)
970 || (!up && yy + h > wh - defaultRowHeight()))
975 // Find the position of the cursor
977 int x = d->synthetic_mouse_event_.cmd.x();
978 pos_type const pos = tm.getPosNearX(*rit, x, bound);
985 d->buffer_view_->buffer().changed(false);
989 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
990 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
992 qRegisterMetaType<KeySymbol>("KeySymbol");
993 qRegisterMetaType<KeyModifier>("KeyModifier");
994 connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
995 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
996 Qt::QueuedConnection);
997 connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
998 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1002 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1006 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1007 bool result = flag_;
1013 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1015 if (emitCheck(isAutoRepeat))
1016 Q_EMIT signal(sym, mod);
1018 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1022 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1024 // this is also called for ShortcutOverride events. In this case, one must
1025 // not act but simply accept the event explicitly.
1026 bool const act = (ev->type() != QEvent::ShortcutOverride);
1028 // Do not process here some keys if dialog_mode_ is set
1029 bool const for_dialog_mode = d->dialog_mode_
1030 && (ev->modifiers() == Qt::NoModifier
1031 || ev->modifiers() == Qt::ShiftModifier)
1032 && (ev->key() == Qt::Key_Escape
1033 || ev->key() == Qt::Key_Enter
1034 || ev->key() == Qt::Key_Return);
1035 // also do not use autoRepeat to input shortcuts
1036 bool const autoRepeat = ev->isAutoRepeat();
1038 if (for_dialog_mode || (!act && autoRepeat)) {
1043 // intercept some keys if completion popup is visible
1044 if (d->completer_->popupVisible()) {
1045 switch (ev->key()) {
1047 case Qt::Key_Return:
1049 d->completer_->activate();
1055 KeyModifier const m = q_key_state(ev->modifiers());
1057 if (act && lyxerr.debugging(Debug::KEY)) {
1059 if (m & ShiftModifier)
1061 if (m & ControlModifier)
1063 if (m & AltModifier)
1065 if (m & MetaModifier)
1067 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1068 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1069 << " keyState: " << str);
1073 setKeySymbol(&sym, ev);
1076 Q_EMIT compressKeySym(sym, m, autoRepeat);
1079 // here, !autoRepeat, as determined at the beginning
1080 ev->setAccepted(queryKeySym(sym, m));
1087 void GuiWorkArea::doubleClickTimeout()
1089 d->dc_event_.active = false;
1093 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1095 d->dc_event_ = DoubleClick(ev);
1096 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1097 SLOT(doubleClickTimeout()));
1098 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
1099 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->position().x(), ev->position().y(),
1101 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1103 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1109 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1111 QAbstractScrollArea::resizeEvent(ev);
1112 d->need_resize_ = true;
1117 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1119 if (preedit_string_.empty())
1122 // FIXME: shall we use real_current_font here? (see #10478)
1123 FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1124 FontMetrics const & fm = theFontMetrics(font);
1127 buffer_view_->caretPosAndDim(point, dim);
1128 int cur_x = point.x_;
1129 int cur_y = point.y_ + dim.height();
1131 // get attributes of input method cursor.
1132 // cursor_pos : cursor position in preedit string.
1133 size_t cursor_pos = 0;
1134 bool cursor_is_visible = false;
1135 for (auto const & attr : preedit_attr_) {
1136 if (attr.type == QInputMethodEvent::Cursor) {
1137 cursor_pos = size_t(attr.start);
1138 cursor_is_visible = attr.length != 0;
1143 size_t const preedit_length = preedit_string_.length();
1145 // get position of selection in input method.
1146 // FIXME: isn't there a simpler way to do this?
1147 // rStart : cursor position in selected string in IM.
1149 // rLength : selected string length in IM.
1151 if (cursor_pos < preedit_length) {
1152 for (auto const & attr : preedit_attr_) {
1153 if (attr.type == QInputMethodEvent::TextFormat) {
1154 if (attr.start <= int(cursor_pos)
1155 && int(cursor_pos) < attr.start + attr.length) {
1156 rStart = size_t(attr.start);
1157 rLength = size_t(attr.length);
1158 if (!cursor_is_visible)
1159 cursor_pos += rLength;
1166 rStart = cursor_pos;
1170 int const right_margin = buffer_view_->rightMargin();
1171 Painter::preedit_style ps;
1172 // Most often there would be only one line:
1174 for (size_t pos = 0; pos != preedit_length; ++pos) {
1175 char_type const typed_char = preedit_string_[pos];
1176 // reset preedit string style
1177 ps = Painter::preedit_default;
1179 // if we reached the right extremity of the screen, go to next line.
1180 if (cur_x + fm.width(typed_char) > p->viewport()->width() - right_margin) {
1181 cur_x = right_margin;
1182 cur_y += dim.height() + 1;
1185 // preedit strings are displayed with dashed underline
1186 // and partial strings are displayed white on black indicating
1187 // that we are in selecting mode in the input method.
1188 // FIXME: rLength == preedit_length is not a changing condition
1189 // FIXME: should be put out of the loop.
1191 && pos < rStart + rLength
1192 && !(cursor_pos < rLength && rLength == preedit_length))
1193 ps = Painter::preedit_selecting;
1195 if (pos == cursor_pos
1196 && (cursor_pos < rLength && rLength == preedit_length))
1197 ps = Painter::preedit_cursor;
1199 // draw one character and update cur_x.
1200 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1205 void GuiWorkArea::Private::resetScreen()
1207 if (use_backingstore_) {
1208 int const pr = p->pixelRatio();
1209 screen_ = QImage(pr * p->viewport()->width(),
1210 pr * p->viewport()->height(),
1211 QImage::Format_ARGB32_Premultiplied);
1212 screen_.setDevicePixelRatio(pr);
1217 QPaintDevice * GuiWorkArea::Private::screenDevice()
1219 if (use_backingstore_)
1222 return p->viewport();
1226 void GuiWorkArea::Private::updateScreen(QRectF const & rc)
1228 if (use_backingstore_) {
1229 QPainter qpain(p->viewport());
1230 double const pr = p->pixelRatio();
1231 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr,
1232 rc.width() * pr, rc.height() * pr);
1233 qpain.drawImage(rc, screen_, rcs);
1238 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1240 // Do not trigger the painting machinery if we are not ready (see
1241 // bug #10989). The second test triggers when in the middle of a
1242 // dispatch operation.
1243 if (view().busy() || d->buffer_view_->buffer().undo().activeUndoGroup()) {
1244 // Since macOS has turned the screen black at this point, our
1245 // backing store has to be copied to screen (this is a no-op
1246 // except on macOS).
1247 d->updateScreen(ev->rect());
1248 // Ignore this paint event, but request a new one for later.
1249 viewport()->update(ev->rect());
1254 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1255 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1257 if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_) {
1259 d->resizeBufferView();
1262 d->last_pixel_ratio_ = pixelRatio();
1264 GuiPainter pain(d->screenDevice(), pixelRatio(), d->lyx_view_->develMode());
1266 d->buffer_view_->draw(pain, d->caret_visible_);
1268 // The preedit text, if needed
1269 d->paintPreeditText(pain);
1272 // FIXME: the code would be a little bit simpler if caret geometry
1273 // was updated unconditionally. Some profiling is required to see
1274 // how expensive this is (especially when idle).
1275 if (d->caret_visible_) {
1276 if (d->needs_caret_geometry_update_)
1277 d->updateCaretGeometry();
1278 d->drawCaret(pain, d->buffer_view_->horizScrollOffset());
1281 d->updateScreen(ev->rect());
1287 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1289 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1290 << " commitString: " << e->commitString());
1292 if (!e->commitString().isEmpty()) {
1294 // take care of commit string assigned to a shortcut
1295 // e.g. quotation mark on international keyboard
1297 for (QChar const & ch : e->commitString()) {
1299 keysym.init(ch.unicode());
1300 keyseq.addkey(keysym, NoModifier);
1302 cmd = theTopLevelKeymap().getBinding(keyseq);
1304 if (cmd == FuncRequest::noaction || cmd == FuncRequest::unknown
1305 || cmd.action() == LFUN_SELF_INSERT)
1306 // insert the processed text in the document (handles undo)
1307 cmd = FuncRequest(LFUN_SELF_INSERT, qstring_to_ucs4(e->commitString()));
1309 cmd.setOrigin(FuncRequest::KEYBOARD);
1311 // FIXME: this is supposed to remove traces from preedit
1312 // string. Can we avoid calling it explicitly?
1313 d->buffer_view_->updateMetrics();
1316 // Hide the caret during the test transformation.
1317 if (e->preeditString().isEmpty())
1318 startBlinkingCaret();
1320 stopBlinkingCaret();
1322 if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1328 // The preedit text and its attributes will be used in paintPreeditText
1329 d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1330 d->preedit_attr_ = e->attributes();
1333 // redraw area of preedit string.
1334 // int height = d->caret_->dim.height();
1335 // int cur_y = d->caret_->y;
1336 // viewport()->update(0, cur_y, viewport()->width(),
1337 // (height + 1) * d->preedit_lines_);
1338 viewport()->update();
1340 if (d->preedit_string_.empty()) {
1341 d->preedit_lines_ = 1;
1346 // Don't forget to accept the event!
1351 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1354 // this is the CJK-specific composition window position and
1355 // the context menu position when the menu key is pressed.
1356 case Qt::ImCursorRectangle: {
1357 CaretGeometry const & cg = bufferView().caretGeometry();
1358 return QRect(cg.left - 10 * (d->preedit_lines_ != 1),
1359 cg.top + cg.height() * d->preedit_lines_,
1360 cg.width(), cg.height());
1363 return QWidget::inputMethodQuery(query);
1368 void GuiWorkArea::updateWindowTitle()
1370 Buffer const & buf = bufferView().buffer();
1371 if (buf.fileName() != d->file_name_
1372 || buf.params().shell_escape != d->shell_escape_
1373 || buf.hasReadonlyFlag() != d->read_only_
1374 || buf.lyxvc().vcstatus() != d->vc_status_
1375 || buf.isClean() != d->clean_
1376 || buf.notifiesExternalModification() != d->externally_modified_) {
1377 d->file_name_ = buf.fileName();
1378 d->shell_escape_ = buf.params().shell_escape;
1379 d->read_only_ = buf.hasReadonlyFlag();
1380 d->vc_status_ = buf.lyxvc().vcstatus();
1381 d->clean_ = buf.isClean();
1382 d->externally_modified_ = buf.notifiesExternalModification();
1383 Q_EMIT titleChanged(this);
1388 bool GuiWorkArea::isFullScreen() const
1390 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1394 bool GuiWorkArea::inDialogMode() const
1396 return d->dialog_mode_;
1400 void GuiWorkArea::setDialogMode(bool mode)
1402 d->dialog_mode_ = mode;
1406 GuiCompleter & GuiWorkArea::completer()
1408 return *d->completer_;
1411 GuiView const & GuiWorkArea::view() const
1413 return *d->lyx_view_;
1417 GuiView & GuiWorkArea::view()
1419 return *d->lyx_view_;
1422 ////////////////////////////////////////////////////////////////////
1426 ////////////////////////////////////////////////////////////////////
1429 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1431 support::TempFile tempfile("embedded.internal");
1432 tempfile.setAutoRemove(false);
1433 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1434 buffer_->setUnnamed(true);
1435 buffer_->setFullyLoaded(true);
1436 setBuffer(*buffer_);
1437 setDialogMode(true);
1441 EmbeddedWorkArea::~EmbeddedWorkArea()
1443 // No need to destroy buffer and bufferview here, because it is done
1444 // in theBufferList() destruction loop at application exit
1448 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1451 GuiWorkArea::closeEvent(ev);
1455 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1458 GuiWorkArea::hideEvent(ev);
1462 QSize EmbeddedWorkArea::sizeHint () const
1465 // GuiWorkArea sets the size to the screen's viewport
1466 // by returning a value this gets overridden
1467 // EmbeddedWorkArea is now sized to fit in the layout
1468 // of the parent, and has a minimum size set in GuiWorkArea
1469 // which is what we return here
1470 return QSize(100, 70);
1474 void EmbeddedWorkArea::disable()
1476 stopBlinkingCaret();
1477 if (view().currentWorkArea() != this)
1479 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1480 // tolerates it and shows the background logo), what happens if
1481 // an EmbeddedWorkArea is closed after closing all document WAs
1482 view().setCurrentWorkArea(view().currentMainWorkArea());
1485 ////////////////////////////////////////////////////////////////////
1489 ////////////////////////////////////////////////////////////////////
1491 TabWorkArea::TabWorkArea(QWidget * parent)
1492 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1494 QPalette pal = palette();
1495 pal.setColor(QPalette::Active, QPalette::Button,
1496 pal.color(QPalette::Active, QPalette::Window));
1497 pal.setColor(QPalette::Disabled, QPalette::Button,
1498 pal.color(QPalette::Disabled, QPalette::Window));
1499 pal.setColor(QPalette::Inactive, QPalette::Button,
1500 pal.color(QPalette::Inactive, QPalette::Window));
1502 QObject::connect(this, SIGNAL(currentChanged(int)),
1503 this, SLOT(on_currentTabChanged(int)));
1505 closeBufferButton = new QToolButton(this);
1506 closeBufferButton->setPalette(pal);
1507 // FIXME: rename the icon to closebuffer.png
1508 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1509 closeBufferButton->setText("Close File");
1510 closeBufferButton->setAutoRaise(true);
1511 closeBufferButton->setCursor(Qt::ArrowCursor);
1512 closeBufferButton->setToolTip(qt_("Close File"));
1513 closeBufferButton->setEnabled(true);
1514 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1515 this, SLOT(closeCurrentBuffer()));
1516 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1518 // set TabBar behaviour
1519 QTabBar * tb = tabBar();
1520 tb->setTabsClosable(!lyxrc.single_close_tab_button);
1521 tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1522 tb->setElideMode(Qt::ElideNone);
1523 // allow dragging tabs
1524 tb->setMovable(true);
1525 // make us responsible for the context menu of the tabbar
1526 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1527 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1528 this, SLOT(showContextMenu(const QPoint &)));
1529 connect(tb, SIGNAL(tabCloseRequested(int)),
1530 this, SLOT(closeTab(int)));
1532 setUsesScrollButtons(true);
1534 // use document mode tabs
1535 setDocumentMode(true);
1540 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1542 if (me->button() == Qt::MiddleButton)
1543 midpressed_tab_ = tabBar()->tabAt(me->pos());
1545 QTabWidget::mousePressEvent(me);
1549 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1551 if (me->button() == Qt::MiddleButton) {
1552 int const midreleased_tab = tabBar()->tabAt(me->pos());
1553 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1554 closeTab(midreleased_tab);
1556 QTabWidget::mouseReleaseEvent(me);
1560 void TabWorkArea::paintEvent(QPaintEvent * event)
1562 if (tabBar()->isVisible()) {
1563 QTabWidget::paintEvent(event);
1565 // Prevent the selected tab to influence the
1566 // painting of the frame of the tab widget.
1567 // This is needed for gtk style in Qt.
1568 QStylePainter p(this);
1569 QStyleOptionTabWidgetFrame opt;
1570 initStyleOption(&opt);
1571 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1573 opt.selectedTabRect = QRect();
1574 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1579 bool TabWorkArea::posIsTab(QPoint position)
1581 // tabAt returns -1 if tab does not covers position
1582 return tabBar()->tabAt(position) > -1;
1586 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1588 if (event->button() != Qt::LeftButton)
1591 // this code chunk is unnecessary because it seems the event only makes
1592 // it this far if it is not on a tab. I'm not sure why this is (maybe
1593 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1594 // this is true in all cases and if it will be true in the future so I
1595 // leave this code for now. (skostysh, 2016-07-21)
1597 // return early if double click on existing tabs
1598 if (posIsTab(event->pos()))
1601 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1605 void TabWorkArea::setFullScreen(bool full_screen)
1607 for (int i = 0; i != count(); ++i) {
1608 if (GuiWorkArea * wa = workArea(i))
1609 wa->setFullScreen(full_screen);
1612 if (lyxrc.full_screen_tabbar)
1613 showBar(!full_screen && count() > 1);
1615 showBar(count() > 1);
1619 void TabWorkArea::showBar(bool show)
1621 tabBar()->setEnabled(show);
1622 tabBar()->setVisible(show);
1623 if (documentMode()) {
1624 // avoid blank corner widget when documentMode(true) is used
1625 if (show && lyxrc.single_close_tab_button) {
1626 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1627 closeBufferButton->setVisible(true);
1629 // remove corner widget
1630 setCornerWidget(nullptr);
1632 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1633 setTabsClosable(!lyxrc.single_close_tab_button);
1637 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1639 QWidget * w = QTabWidget::widget(index);
1642 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1648 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1650 return widget(currentIndex());
1654 GuiWorkArea * TabWorkArea::workArea(int index) const
1656 GuiWorkAreaContainer * w = widget(index);
1659 return w->workArea();
1663 GuiWorkArea * TabWorkArea::currentWorkArea() const
1665 return workArea(currentIndex());
1669 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1671 // FIXME: this method doesn't work if we have more than one work area
1672 // showing the same buffer.
1673 for (int i = 0; i != count(); ++i) {
1674 GuiWorkArea * wa = workArea(i);
1675 LASSERT(wa, return nullptr);
1676 if (&wa->bufferView().buffer() == &buffer)
1683 void TabWorkArea::closeAll()
1686 QWidget * wac = widget(0);
1687 LASSERT(wac, return);
1694 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1696 for (int index = 0; index < count(); ++index)
1697 if (workArea(index) == w)
1703 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1705 LASSERT(work_area, return false);
1706 int index = indexOfWorkArea(work_area);
1710 if (index == currentIndex())
1711 // Make sure the work area is up to date.
1712 on_currentTabChanged(index);
1714 // Switch to the work area.
1715 setCurrentIndex(index);
1716 work_area->setFocus();
1722 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1724 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1725 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1726 wa->setUpdatesEnabled(false);
1727 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1728 // when hiding it again below).
1729 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1730 showBar(count() > 0);
1731 addTab(wac, wa->windowTitle());
1732 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1733 this, SLOT(updateTabTexts()));
1734 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1735 setFullScreen(true);
1737 // Hide tabbar if there's only one tab.
1738 showBar(count() > 1);
1746 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1748 LASSERT(work_area, return false);
1749 int index = indexOfWorkArea(work_area);
1753 work_area->setUpdatesEnabled(false);
1754 QWidget * wac = widget(index);
1759 // make sure the next work area is enabled.
1760 currentWidget()->setUpdatesEnabled(true);
1761 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1762 setFullScreen(true);
1764 // Show tabbar only if there's more than one tab.
1765 showBar(count() > 1);
1767 lastWorkAreaRemoved();
1775 void TabWorkArea::on_currentTabChanged(int i)
1777 // returns e.g. on application destruction
1780 GuiWorkArea * wa = workArea(i);
1781 LASSERT(wa, return);
1782 wa->setUpdatesEnabled(true);
1783 wa->scheduleRedraw(true);
1786 currentWorkAreaChanged(wa);
1788 LYXERR(Debug::GUI, "currentTabChanged " << i
1789 << " File: " << wa->bufferView().buffer().absFileName());
1793 void TabWorkArea::closeCurrentBuffer()
1796 if (clicked_tab_ == -1)
1797 wa = currentWorkArea();
1799 wa = workArea(clicked_tab_);
1800 LASSERT(wa, return);
1802 wa->view().closeWorkArea(wa);
1806 void TabWorkArea::hideCurrentTab()
1809 if (clicked_tab_ == -1)
1810 wa = currentWorkArea();
1812 wa = workArea(clicked_tab_);
1813 LASSERT(wa, return);
1815 wa->view().hideWorkArea(wa);
1819 void TabWorkArea::closeTab(int index)
1821 on_currentTabChanged(index);
1824 wa = currentWorkArea();
1826 wa = workArea(index);
1827 LASSERT(wa, return);
1829 wa->view().closeWorkArea(wa);
1836 /// make vector happy
1837 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1839 DisplayPath(int tab, FileName const & filename)
1842 // Recode URL encoded chars via fromPercentEncoding()
1843 string const fn = (filename.extension() == "lyx")
1844 ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
1845 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
1846 #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
1847 postfix_ = toqstr(filename.absoluteFilePath()).
1848 split("/", Qt::SkipEmptyParts);
1850 postfix_ = toqstr(filename.absoluteFilePath()).
1851 split("/", QString::SkipEmptyParts);
1853 postfix_.pop_back();
1854 abs_ = toqstr(filename.absoluteFilePath());
1855 dottedPrefix_ = false;
1858 /// Absolute path for debugging.
1863 /// Add the first segment from the postfix or three dots to the prefix.
1864 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1865 /// when really needed.
1866 void shiftPathSegment(bool dotted)
1868 if (postfix_.count() <= 0)
1872 if (dottedPrefix_ && !prefix_.isEmpty())
1873 prefix_ += ellipsisSlash_;
1874 prefix_ += postfix_.front() + "/";
1876 dottedPrefix_ = dotted && !prefix_.isEmpty();
1877 postfix_.pop_front();
1880 QString displayString() const
1882 if (prefix_.isEmpty())
1885 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1886 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1889 QString forecastPathString() const
1891 if (postfix_.count() == 0)
1892 return displayString();
1895 + (dottedPrefix_ ? ellipsisSlash_ : "")
1896 + postfix_.front() + "/";
1899 bool final() const { return postfix_.empty(); }
1901 int tab() const { return tab_; }
1905 static QString const ellipsisSlash_;
1909 QStringList postfix_;
1921 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1925 bool operator<(DisplayPath const & a, DisplayPath const & b)
1927 return a.displayString() < b.displayString();
1931 bool operator==(DisplayPath const & a, DisplayPath const & b)
1933 return a.displayString() == b.displayString();
1937 void TabWorkArea::updateTabTexts()
1939 int const n = count();
1942 std::list<DisplayPath> paths;
1943 typedef std::list<DisplayPath>::iterator It;
1945 // collect full names first: path into postfix, empty prefix and
1946 // filename without extension
1947 for (int i = 0; i < n; ++i) {
1948 GuiWorkArea * i_wa = workArea(i);
1949 FileName const fn = i_wa->bufferView().buffer().fileName();
1950 paths.push_back(DisplayPath(i, fn));
1953 // go through path segments and see if it helps to make the path more unique
1954 bool somethingChanged = true;
1955 bool allFinal = false;
1956 while (somethingChanged && !allFinal) {
1957 // adding path segments changes order
1960 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1961 somethingChanged = false;
1964 // find segments which are not unique (i.e. non-atomic)
1965 It it = paths.begin();
1967 QString segString = it->displayString();
1968 for (; it != paths.end(); ++it) {
1969 // look to the next item
1974 allFinal = allFinal && it->final();
1976 LYXERR(Debug::GUI, "it = " << it->abs()
1977 << " => " << it->displayString());
1979 // still the same segment?
1981 if ((next != paths.end()
1982 && (nextString = next->displayString()) == segString))
1984 LYXERR(Debug::GUI, "segment ended");
1986 // only a trivial one with one element?
1987 if (it == segStart) {
1988 // start new segment
1990 segString = nextString;
1994 // We found a non-atomic segment
1995 // We know that segStart <= it < next <= paths.end().
1996 // The assertion below tells coverity about it.
1997 LATTEST(segStart != paths.end());
1998 QString dspString = segStart->forecastPathString();
1999 LYXERR(Debug::GUI, "first forecast found for "
2000 << segStart->abs() << " => " << dspString);
2003 // Shift path segments and hope for the best
2004 // that it makes the path more unique.
2005 somethingChanged = true;
2006 bool moreUnique = false;
2007 for (; sit != next; ++sit) {
2008 if (sit->forecastPathString() != dspString) {
2009 LYXERR(Debug::GUI, "different forecast found for "
2010 << sit->abs() << " => " << sit->forecastPathString());
2014 LYXERR(Debug::GUI, "same forecast found for "
2015 << sit->abs() << " => " << dspString);
2018 // if the path segment helped, add it. Otherwise add dots
2019 bool dots = !moreUnique;
2020 LYXERR(Debug::GUI, "using dots = " << dots);
2021 for (sit = segStart; sit != next; ++sit) {
2022 sit->shiftPathSegment(dots);
2023 LYXERR(Debug::GUI, "shifting "
2024 << sit->abs() << " => " << sit->displayString());
2027 // start new segment
2029 segString = nextString;
2033 // set new tab titles
2034 for (It it = paths.begin(); it != paths.end(); ++it) {
2035 int const tab_index = it->tab();
2036 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2037 QString tab_text = it->displayString().replace("&", "&&");
2038 if (!buf.fileName().empty() && !buf.isClean())
2040 QString tab_tooltip = it->abs();
2041 if (buf.hasReadonlyFlag()) {
2043 QLabel * readOnlyButton = new QLabel();
2044 QIcon icon = QIcon(getPixmap("images/", "emblem-readonly", "svgz,png"));
2045 readOnlyButton->setPixmap(icon.pixmap(QSize(16, 16)));
2046 tabBar()->setTabButton(tab_index, QTabBar::RightSide, readOnlyButton);
2048 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2050 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2053 tabBar()->setTabButton(tab_index, QTabBar::RightSide, 0);
2055 setTabIcon(tab_index, QIcon());
2057 if (buf.notifiesExternalModification()) {
2058 QString const warn = qt_("%1 (modified externally)");
2059 tab_tooltip = warn.arg(tab_tooltip);
2060 tab_text += QChar(0x26a0);
2062 setTabText(tab_index, tab_text);
2063 setTabToolTip(tab_index, tab_tooltip);
2068 void TabWorkArea::showContextMenu(const QPoint & pos)
2071 clicked_tab_ = tabBar()->tabAt(pos);
2072 if (clicked_tab_ == -1)
2075 GuiWorkArea * wa = workArea(clicked_tab_);
2076 LASSERT(wa, return);
2080 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2081 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2083 // we want to show the 'close' option only if this is not a child buffer.
2084 Buffer const & buf = wa->bufferView().buffer();
2086 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2087 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2088 popup.exec(tabBar()->mapToGlobal(pos));
2094 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2096 QWidget * w = widget(fromIndex);
2097 QIcon icon = tabIcon(fromIndex);
2098 QString text = tabText(fromIndex);
2100 setCurrentIndex(fromIndex);
2101 removeTab(fromIndex);
2102 insertTab(toIndex, w, icon, text);
2103 setCurrentIndex(toIndex);
2107 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2108 : QWidget(parent), wa_(wa)
2110 LASSERT(wa, return);
2111 Ui::WorkAreaUi::setupUi(this);
2112 layout()->addWidget(wa);
2113 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2114 this, SLOT(updateDisplay()));
2115 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2116 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2117 setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2122 void GuiWorkAreaContainer::updateDisplay()
2124 Buffer const & buf = wa_->bufferView().buffer();
2125 notificationFrame->setHidden(!buf.notifiesExternalModification());
2126 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2127 .arg(toqstr(buf.fileName().displayName()));
2128 externalModificationLabel->setText(label);
2132 void GuiWorkAreaContainer::dispatch(FuncRequest const & f) const
2134 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2135 wa_->bufferView().buffer().absFileName()));
2140 void GuiWorkAreaContainer::reload() const
2142 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2146 void GuiWorkAreaContainer::ignore() const
2148 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2152 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2154 // prevent TabWorkArea from opening a new buffer on double click
2159 } // namespace frontend
2162 #include "moc_GuiWorkArea.cpp"