2 * \file GuiWorkArea.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Abdelrazak Younes
9 * Full author contact details are available in file CREDITS.
14 #include "GuiWorkArea.h"
15 #include "GuiWorkArea_Private.h"
17 #include "ColorCache.h"
18 #include "GuiApplication.h"
19 #include "GuiCompleter.h"
20 #include "GuiKeySymbol.h"
21 #include "GuiPainter.h"
24 #include "qt_helpers.h"
27 #include "BufferList.h"
28 #include "BufferParams.h"
29 #include "BufferView.h"
30 #include "CoordCache.h"
33 #include "FuncRequest.h"
35 #include "KeySymbol.h"
36 #include "KeySequence.h"
41 #include "TextMetrics.h"
44 #include "support/convert.h"
45 #include "support/debug.h"
46 #include "support/lassert.h"
47 #include "support/TempFile.h"
49 #include "frontends/Application.h"
50 #include "frontends/CaretGeometry.h"
51 #include "frontends/FontMetrics.h"
52 #include "frontends/WorkAreaManager.h"
54 #include <QContextMenuEvent>
57 #include <QInputMethod>
59 #include <QProxyStyle>
61 #include <QMainWindow>
67 #include <QStyleOption>
68 #include <QStylePainter>
70 #include <QToolButton>
81 using namespace lyx::support;
86 /// return the LyX mouse button state from Qt's
87 static mouse_button::state q_button_state(Qt::MouseButton button)
89 mouse_button::state b = mouse_button::none;
92 b = mouse_button::button1;
94 case Qt::MiddleButton:
95 b = mouse_button::button2;
98 b = mouse_button::button3;
107 /// return the LyX mouse button state from Qt's
108 mouse_button::state q_motion_state(Qt::MouseButtons state)
110 mouse_button::state b = mouse_button::none;
111 if (state & Qt::LeftButton)
112 b |= mouse_button::button1;
113 if (state & Qt::MiddleButton)
114 b |= mouse_button::button2;
115 if (state & Qt::RightButton)
116 b |= mouse_button::button3;
123 // This is a 'heartbeat' generating synthetic mouse move events when the
124 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
125 SyntheticMouseEvent::SyntheticMouseEvent()
126 : timeout(200), restart_timeout(true)
130 GuiWorkArea::Private::Private(GuiWorkArea * parent)
131 : p(parent), completer_(new GuiCompleter(p, p))
133 use_backingstore_ = lyxrc.draw_strategy == LyXRC::DS_BACKINGSTORE
134 || guiApp->needsBackingStore();
135 LYXERR(Debug::WORKAREA, "Drawing strategy is: "
136 << (use_backingstore_ ? "backingstore" : "partial"));
138 int const time = QApplication::cursorFlashTime() / 2;
140 caret_timeout_.setInterval(time);
141 caret_timeout_.start();
143 // let's initialize this just to be safe
144 caret_timeout_.setInterval(500);
149 GuiWorkArea::Private::~Private()
151 // If something is wrong with the buffer, we can ignore it safely
153 buffer_view_->buffer().workAreaManager().remove(p);
156 // Completer has a QObject parent and is thus automatically destroyed.
158 // delete completer_;
162 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
163 : d(new Private(this))
165 new CompressorProxy(this); // not a leak
169 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
170 : d(new Private(this))
172 new CompressorProxy(this); // not a leak
174 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
180 double GuiWorkArea::pixelRatio() const
182 #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
183 return devicePixelRatioF();
185 return devicePixelRatio();
190 void GuiWorkArea::init()
193 connect(&d->caret_timeout_, SIGNAL(timeout()),
194 this, SLOT(toggleCaret()));
196 // This connection is closed at the same time as this is destroyed.
197 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
198 generateSyntheticMouseEvent();
202 // A mouse event will happen before the first paint event,
203 // so make sure that the buffer view has an up to date metrics.
204 d->buffer_view_->resize(viewport()->width(), viewport()->height());
206 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
207 setAcceptDrops(true);
208 setMouseTracking(true);
209 setMinimumSize(100, 70);
210 setFrameStyle(QFrame::NoFrame);
213 d->updateCursorShape();
215 // we paint our own background
216 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
218 setFocusPolicy(Qt::StrongFocus);
220 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
221 << " viewport height: " << viewport()->height());
223 // Enables input methods for asian languages.
224 // Must be set when creating custom text editing widgets.
225 setAttribute(Qt::WA_InputMethodEnabled, true);
226 // obtain transformation information to reset it when LyX gets refocus
227 d->im_item_trans_ = d->im_->inputItemTransform();
231 GuiWorkArea::~GuiWorkArea()
237 void GuiWorkArea::Private::updateCursorShape()
239 bool const clickable = buffer_view_ && buffer_view_->clickableInset();
240 p->viewport()->setCursor(clickable ? Qt::PointingHandCursor
245 void GuiWorkArea::setGuiView(GuiView & gv)
251 void GuiWorkArea::setBuffer(Buffer & buffer)
253 delete d->buffer_view_;
254 d->buffer_view_ = new BufferView(buffer);
255 buffer.workAreaManager().add(this);
257 // HACK: Prevents an additional redraw when the scrollbar pops up
258 // which regularly happens on documents with more than one page.
259 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
260 // Since we have no geometry information yet, we assume that
261 // a document needs a scrollbar if there is more then four
262 // paragraph in the outermost text.
263 if (buffer.text().paragraphs().size() > 4)
264 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
265 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
266 Q_EMIT bufferViewChanged();
270 void GuiWorkArea::fixVerticalScrollBar()
273 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
277 void GuiWorkArea::close()
279 d->lyx_view_->removeWorkArea(this);
283 void GuiWorkArea::setFullScreen(bool full_screen)
285 d->buffer_view_->setFullScreen(full_screen);
286 if (full_screen && lyxrc.full_screen_scrollbar)
287 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
289 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
293 BufferView & GuiWorkArea::bufferView()
295 return *d->buffer_view_;
299 BufferView const & GuiWorkArea::bufferView() const
301 return *d->buffer_view_;
305 void GuiWorkArea::stopBlinkingCaret()
307 d->caret_timeout_.stop();
312 void GuiWorkArea::startBlinkingCaret()
314 // do not show the cursor if the view is busy
318 // Don't start blinking if the cursor isn't on screen, unless we
319 // are not ready to know whether the cursor is on screen.
320 if (!d->buffer_view_->busy() && !d->buffer_view_->caretInView())
325 // Avoid blinking when debugging PAINTING, since it creates too much noise
326 if (!lyxerr.debugging(Debug::PAINTING)) {
327 // we are not supposed to cache this value.
328 int const time = QApplication::cursorFlashTime() / 2;
331 d->caret_timeout_.setInterval(time);
332 d->caret_timeout_.start();
337 void GuiWorkArea::toggleCaret()
339 if (d->caret_visible_)
346 void GuiWorkArea::scheduleRedraw(bool update_metrics)
349 // No need to redraw in this case.
352 // No need to do anything if this is the current view. The BufferView
353 // metrics are already up to date.
354 if (update_metrics || d->lyx_view_ != guiApp->currentView()
355 || d->lyx_view_->currentWorkArea() != this) {
356 // FIXME: it would be nice to optimize for the off-screen case.
357 d->buffer_view_->cursor().fixIfBroken();
358 d->buffer_view_->updateMetrics();
359 d->buffer_view_->cursor().fixIfBroken();
362 // update caret position, because otherwise it has to wait until
363 // the blinking interval is over
366 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
367 viewport()->update();
369 /// FIXME: is this still true now that paintEvent does the actual painting?
370 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
371 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
372 d->updateScrollbar();
373 d->lyx_view_->updateStatusBar();
375 if (lyxerr.debugging(Debug::WORKAREA))
376 d->buffer_view_->coordCache().dump();
380 d->updateCursorShape();
384 // Keep in sync with GuiWorkArea::processKeySym below
385 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
387 return guiApp->queryKeySym(key, mod);
391 // Keep in sync with GuiWorkArea::queryKeySym above
392 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
394 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
395 && lyxrc.full_screen_menubar) {
396 // FIXME HACK: we should not have to do this here. See related comment
397 // in GuiView::event() (QEvent::ShortcutOverride)
398 d->lyx_view_->menuBar()->hide();
401 // In order to avoid bad surprise in the middle of an operation,
402 // we better stop the blinking caret...
403 // the caret gets restarted in GuiView::restartCaret()
405 guiApp->processKeySym(key, mod);
409 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
412 if (cmd.action() == LFUN_FILE_OPEN) {
414 lyx_view_->dispatch(cmd, dr);
418 bool const notJustMovingTheMouse =
419 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
421 // In order to avoid bad surprise in the middle of an operation, we better stop
422 // the blinking caret.
423 if (notJustMovingTheMouse)
424 p->stopBlinkingCaret();
426 buffer_view_->mouseEventDispatch(cmd);
428 // Skip these when selecting
429 // FIXME: let GuiView take care of those.
430 if (notJustMovingTheMouse && !buffer_view_->mouseSelecting()) {
431 completer_->updateVisibility(false, false);
432 lyx_view_->updateDialogs();
433 lyx_view_->updateStatusBar();
436 // GUI tweaks except with mouse motion with no button pressed.
437 if (notJustMovingTheMouse) {
438 // Slight hack: this is only called currently when we
439 // clicked somewhere, so we force through the display
440 // of the new status here.
441 // FIXME: let GuiView take care of those.
442 lyx_view_->clearMessage();
444 // Show the caret immediately after any operation
445 p->startBlinkingCaret();
452 void GuiWorkArea::Private::resizeBufferView()
454 // WARNING: Please don't put any code that will trigger a repaint here!
455 // We are already inside a paint event.
456 p->stopBlinkingCaret();
457 // Warn our container (GuiView).
460 bool const caret_in_view = buffer_view_->caretInView();
461 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
463 buffer_view_->showCursor();
466 // Update scrollbars which might have changed due different
467 // BufferView dimension. This is especially important when the
468 // BufferView goes from zero-size to the real-size for the first time,
469 // as the scrollbar parameters are then set for the first time.
472 need_resize_ = false;
474 // Eventually, restart the caret after the resize event.
475 // We might be resizing even if the focus is on another widget so we only
476 // restart the caret if we have the focus.
478 QTimer::singleShot(50, p, SLOT(startBlinkingCaret()));
482 void GuiWorkArea::Private::resetCaret()
484 // Don't start blinking if the cursor isn't on screen or the window
485 // does not have focus
486 if (!buffer_view_->caretInView() || !p->hasFocus())
489 needs_caret_geometry_update_ = true;
490 caret_visible_ = true;
494 void GuiWorkArea::Private::updateCaretGeometry()
496 // we cannot update geometry if not ready and we do not need to if
497 // caret is not in view.
498 if (buffer_view_->busy() || !buffer_view_->caretInView())
501 // completion indicator
502 Cursor const & cur = buffer_view_->cursor();
503 bool const completable = cur.inset().showCompletionCursor()
504 && completer_->completionAvailable()
505 && !completer_->popupVisible()
506 && !completer_->inlineVisible();
508 buffer_view_->buildCaretGeometry(completable);
510 needs_caret_geometry_update_ = false;
514 void GuiWorkArea::Private::showCaret()
520 p->viewport()->update();
524 void GuiWorkArea::Private::hideCaret()
529 caret_visible_ = false;
530 //if (!qApp->focusWidget())
531 p->viewport()->update();
535 /* Draw the caret. Parameter \c horiz_offset is not 0 when there
536 * has been horizontal scrolling in current row
538 void GuiWorkArea::Private::drawCaret(QPainter & painter, int horiz_offset) const
540 if (buffer_view_->caretGeometry().shapes.empty())
543 QColor const color = guiApp->colorCache().get(Color_cursor);
544 painter.setPen(color);
545 painter.setRenderHint(QPainter::Antialiasing, true);
546 for (auto const & shape : buffer_view_->caretGeometry().shapes) {
549 for (Point const & p : shape) {
551 path.moveTo(p.x_ - horiz_offset, p.y_);
554 path.lineTo(p.x_ - horiz_offset, p.y_);
556 painter.fillPath(path, color);
558 painter.setRenderHint(QPainter::Antialiasing, false);
562 void GuiWorkArea::Private::updateScrollbar()
564 // Prevent setRange() and setSliderPosition from causing recursive calls via
565 // the signal valueChanged. (#10311)
566 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
567 p, SLOT(scrollTo(int)));
568 ScrollbarParameters const & scroll = buffer_view_->scrollbarParameters();
569 p->verticalScrollBar()->setRange(scroll.min, scroll.max);
570 p->verticalScrollBar()->setPageStep(scroll.page_step);
571 p->verticalScrollBar()->setSingleStep(scroll.single_step);
572 p->verticalScrollBar()->setSliderPosition(0);
573 // Connect to the vertical scroll bar
574 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
575 p, SLOT(scrollTo(int)));
579 void GuiWorkArea::scrollTo(int value)
582 d->buffer_view_->scrollDocView(value, true);
584 if (lyxrc.cursor_follows_scrollbar) {
585 d->buffer_view_->setCursorFromScrollbar();
586 // FIXME: let GuiView take care of those.
587 d->lyx_view_->updateLayoutList();
589 // Show the caret immediately after any operation.
590 startBlinkingCaret();
594 bool GuiWorkArea::event(QEvent * e)
597 case QEvent::ToolTip: {
598 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
599 if (lyxrc.use_tooltip) {
600 QPoint pos = helpEvent->pos();
601 if (pos.x() < viewport()->width()) {
602 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
603 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
606 QToolTip::hideText();
608 // Don't forget to accept the event!
613 case QEvent::ShortcutOverride:
614 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
616 keyPressEvent(static_cast<QKeyEvent *>(e));
617 return e->isAccepted();
619 case QEvent::KeyPress: {
620 // We catch this event in order to catch the Tab or Shift+Tab key press
621 // which are otherwise reserved to focus switching between controls
623 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
624 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
625 || (ke->key() == Qt::Key_Backtab && (
626 ke->modifiers() == Qt::ShiftModifier
627 || ke->modifiers() == Qt::NoModifier))) {
631 return QAbstractScrollArea::event(e);
635 return QAbstractScrollArea::event(e);
641 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
644 if (e->reason() == QContextMenuEvent::Mouse)
645 // the menu name is set on mouse press
646 name = d->context_menu_name_;
648 QPoint pos = e->pos();
649 Cursor const & cur = d->buffer_view_->cursor();
650 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
651 // Do not access the context menu of math right in front of before
652 // the cursor. This does not work when the cursor is in text.
653 Inset * inset = cur.paragraph().getInset(cur.pos());
654 if (inset && inset->asInsetMath())
656 else if (cur.pos() > 0) {
657 inset = cur.paragraph().getInset(cur.pos() - 1);
662 if (e->reason() == QContextMenuEvent::Keyboard)
663 // Subtract the top margin, see #12811
664 pos.setY(pos.y() - d->buffer_view_->topMargin());
666 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
673 // always show mnemonics when the keyboard is used to show the context menu
674 // FIXME: This should be fixed in Qt itself
675 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
676 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
681 // Position the menu to the right.
682 // FIXME: menu position should be different for RTL text.
683 menu->exec(e->globalPos());
688 void GuiWorkArea::focusInEvent(QFocusEvent * e)
690 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
691 if (d->lyx_view_->currentWorkArea() != this) {
692 d->lyx_view_->setCurrentWorkArea(this);
693 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
696 startBlinkingCaret();
697 QAbstractScrollArea::focusInEvent(e);
701 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
703 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
705 QAbstractScrollArea::focusOutEvent(e);
709 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
711 if (d->dc_event_.active && d->dc_event_ == *e) {
712 d->dc_event_.active = false;
713 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
714 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->position().x(), e->position().y(),
716 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
718 q_button_state(e->button()), q_key_state(e->modifiers()));
724 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
725 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->position().x(), e->position().y(),
727 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
729 q_button_state(e->button()), q_key_state(e->modifiers()));
732 // Save the context menu on mouse press, because also the mouse
733 // cursor is set on mouse press. Afterwards, we can either release
734 // the mousebutton somewhere else, or the cursor might have moved
735 // due to the DEPM. We need to do this after the mouse has been
736 // set in dispatch(), because the selection state might change.
737 if (e->button() == Qt::RightButton)
738 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
739 d->context_menu_name_ = d->buffer_view_->contextMenu(e->position().x(), e->position().y());
741 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
748 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
750 if (d->synthetic_mouse_event_.timeout.running())
751 d->synthetic_mouse_event_.timeout.stop();
753 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
754 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->position().x(), e->position().y(),
756 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
758 q_button_state(e->button()), q_key_state(e->modifiers()));
759 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
760 QT_VERSION < QT_VERSION_CHECK(5,15,1))
761 d->synthetic_mouse_event_.cmd = cmd; // QtBug QAbstractScrollArea::mouseMoveEvent
768 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
770 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
771 QT_VERSION < QT_VERSION_CHECK(5,15,1))
772 // cancel the event if the coordinates didn't change, this is due to QtBug
773 // QAbstractScrollArea::mouseMoveEvent, the event is triggered falsely when quickly
774 // double tapping a touchpad. To test: try to select a word by quickly double tapping
775 // on a touchpad while hovering the cursor over that word in the work area.
776 // This bug does not occur on Qt versions 5.10.1 and below. Only Windows seems to be affected.
777 // ML thread: https://www.mail-archive.com/lyx-devel@lists.lyx.org/msg211699.html
778 // Qt bugtracker: https://bugreports.qt.io/browse/QTBUG-85431
779 // Bug was fixed in Qt 5.15.1
780 if (e->x() == d->synthetic_mouse_event_.cmd.x() && // QtBug QAbstractScrollArea::mouseMoveEvent
781 e->y() == d->synthetic_mouse_event_.cmd.y()) // QtBug QAbstractScrollArea::mouseMoveEvent
782 return; // QtBug QAbstractScrollArea::mouseMoveEvent
785 // we kill the triple click if we move
786 doubleClickTimeout();
787 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
788 FuncRequest cmd(LFUN_MOUSE_MOTION, e->position().x(), e->position().y(),
790 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
792 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
796 // If we're above or below the work area...
797 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
798 if ((e->position().y() <= 20 || e->position().y() >= viewport()->height() - 20)
800 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
802 && e->buttons() == mouse_button::button1) {
803 // Make sure only a synthetic event can cause a page scroll,
804 // so they come at a steady rate:
805 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
806 if (e->position().y() <= 20)
807 // _Force_ a scroll up:
808 cmd.set_y(e->position().y() - 21);
810 cmd.set_y(e->position().y() + 21);
813 // _Force_ a scroll up:
814 cmd.set_y(e->y() - 21);
816 cmd.set_y(e->y() + 21);
818 // Store the event, to be handled when the timeout expires.
819 d->synthetic_mouse_event_.cmd = cmd;
821 if (d->synthetic_mouse_event_.timeout.running()) {
822 // Discard the event. Note that it _may_ be handled
823 // when the timeout expires if
824 // synthetic_mouse_event_.cmd has not been overwritten.
825 // Ie, when the timeout expires, we handle the
826 // most recent event but discard all others that
827 // occurred after the one used to start the timeout
828 // in the first place.
832 d->synthetic_mouse_event_.restart_timeout = true;
833 d->synthetic_mouse_event_.timeout.start();
834 // Fall through to handle this event...
836 } else if (d->synthetic_mouse_event_.timeout.running()) {
837 // Store the event, to be possibly handled when the timeout
839 // Once the timeout has expired, normal control is returned
840 // to mouseMoveEvent (restart_timeout = false).
841 // This results in a much smoother 'feel' when moving the
842 // mouse back into the work area.
843 d->synthetic_mouse_event_.cmd = cmd;
844 d->synthetic_mouse_event_.restart_timeout = false;
851 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
853 // Wheel rotation by one notch results in a delta() of 120 (see
854 // documentation of QWheelEvent)
855 // But first we have to ignore horizontal scroll events.
856 QPoint const aDelta = ev->angleDelta();
857 // skip horizontal wheel event
858 if (abs(aDelta.x()) > abs(aDelta.y())) {
862 double const delta = aDelta.y() / 120.0;
865 switch (lyxrc.scroll_wheel_zoom) {
866 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
867 zoom = ev->modifiers() & Qt::ControlModifier;
868 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
870 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
871 zoom = ev->modifiers() & Qt::ShiftModifier;
872 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
874 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
875 zoom = ev->modifiers() & Qt::AltModifier;
876 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
878 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
882 docstring arg = convert<docstring>(int(5 * delta));
883 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
887 // Take into account the desktop wide settings.
888 int const lines = qApp->wheelScrollLines();
889 int const page_step = verticalScrollBar()->pageStep();
890 // Test if the wheel mouse is set to one screen at a time.
891 // This is according to
892 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
894 min(lines * verticalScrollBar()->singleStep(), page_step);
896 // Take into account the rotation and the user preferences.
897 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
898 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
899 << " delta = " << delta << " scroll_value = " << scroll_value
900 << " page_step = " << page_step);
902 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
908 void GuiWorkArea::generateSyntheticMouseEvent()
910 int const e_y = d->synthetic_mouse_event_.cmd.y();
911 int const wh = d->buffer_view_->workHeight();
912 bool const up = e_y < 0;
913 bool const down = e_y > wh;
915 // Set things off to generate the _next_ 'pseudo' event.
917 if (d->synthetic_mouse_event_.restart_timeout) {
918 // This is some magic formulae to determine the speed
919 // of scrolling related to the position of the mouse.
922 int dist = up ? -e_y : e_y - wh;
923 time = max(min(200, 250000 / (dist * dist)), 1) ;
926 step = 80000 / (time * time);
930 d->synthetic_mouse_event_.timeout.setTimeout(time);
931 d->synthetic_mouse_event_.timeout.start();
934 // Can we scroll further ?
935 int const value = verticalScrollBar()->value();
936 if (value == verticalScrollBar()->maximum()
937 || value == verticalScrollBar()->minimum()) {
938 d->synthetic_mouse_event_.timeout.stop();
943 if (step <= 2 * wh) {
944 d->buffer_view_->scroll(up ? -step : step);
945 d->buffer_view_->updateMetrics();
947 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
950 // In which paragraph do we have to set the cursor ?
951 Cursor & cur = d->buffer_view_->cursor();
952 // FIXME: we don't know how to handle math.
953 Text * text = cur.text();
956 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
958 // Quit gracefully if there are no metrics, since otherwise next
959 // line would crash (bug #10324).
960 // This situation seems related to a (not yet understood) timing problem.
964 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
965 ParagraphMetrics const & pm = *pp.second;
966 pit_type const pit = pp.first;
968 if (pm.rows().empty())
971 // Find the row at which we set the cursor.
972 RowList::const_iterator rit = pm.rows().begin();
973 RowList::const_iterator rlast = pm.rows().end();
974 int yy = pm.position() - pm.ascent();
975 for (--rlast; rit != rlast; ++rit) {
976 int h = rit->height();
977 if ((up && yy + h > 0)
978 || (!up && yy + h > wh - defaultRowHeight()))
983 // Find the position of the cursor
985 int x = d->synthetic_mouse_event_.cmd.x();
986 pos_type const pos = tm.getPosNearX(*rit, x, bound);
993 d->buffer_view_->buffer().changed(false);
997 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
998 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
1000 qRegisterMetaType<KeySymbol>("KeySymbol");
1001 qRegisterMetaType<KeyModifier>("KeyModifier");
1002 connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
1003 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
1004 Qt::QueuedConnection);
1005 connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
1006 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1010 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1014 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1015 bool result = flag_;
1021 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1023 if (emitCheck(isAutoRepeat))
1024 Q_EMIT signal(sym, mod);
1026 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1030 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1032 // this is also called for ShortcutOverride events. In this case, one must
1033 // not act but simply accept the event explicitly.
1034 bool const act = (ev->type() != QEvent::ShortcutOverride);
1036 // Do not process here some keys if dialog_mode_ is set
1037 bool const for_dialog_mode = d->dialog_mode_
1038 && (ev->modifiers() == Qt::NoModifier
1039 || ev->modifiers() == Qt::ShiftModifier)
1040 && (ev->key() == Qt::Key_Escape
1041 || ev->key() == Qt::Key_Enter
1042 || ev->key() == Qt::Key_Return);
1043 // also do not use autoRepeat to input shortcuts
1044 bool const autoRepeat = ev->isAutoRepeat();
1046 if (for_dialog_mode || (!act && autoRepeat)) {
1051 // intercept some keys if completion popup is visible
1052 if (d->completer_->popupVisible()) {
1053 switch (ev->key()) {
1055 case Qt::Key_Return:
1057 d->completer_->activate();
1063 KeyModifier const m = q_key_state(ev->modifiers());
1065 if (act && lyxerr.debugging(Debug::KEY)) {
1067 if (m & ShiftModifier)
1069 if (m & ControlModifier)
1071 if (m & AltModifier)
1073 if (m & MetaModifier)
1075 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1076 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1077 << " keyState: " << str);
1081 setKeySymbol(&sym, ev);
1084 Q_EMIT compressKeySym(sym, m, autoRepeat);
1087 // here, !autoRepeat, as determined at the beginning
1088 ev->setAccepted(queryKeySym(sym, m));
1095 void GuiWorkArea::doubleClickTimeout()
1097 d->dc_event_.active = false;
1101 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1103 d->dc_event_ = DoubleClick(ev);
1104 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1105 SLOT(doubleClickTimeout()));
1106 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
1107 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->position().x(), ev->position().y(),
1109 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1111 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1117 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1119 QAbstractScrollArea::resizeEvent(ev);
1120 d->need_resize_ = true;
1125 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1127 if (preedit_string_.empty())
1130 // FIXME: shall we use real_current_font here? (see #10478)
1131 FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1132 FontMetrics const & fm = theFontMetrics(font);
1135 buffer_view_->caretPosAndDim(point, dim);
1136 int cur_x = point.x_ - dim.width();
1137 int cur_y = point.y_ + dim.height();
1138 // lower margin of the preedit area to separate the candidate window
1139 // report to IM the height of preedit rectangle larger than the actual by
1140 // preedit_lower_margin so that the conversion suggestion window does not
1141 // hide the underline of the preedit text
1142 int preedit_lower_margin = 3;
1143 // reset item transformation since it gets wrong after the item get
1144 // lost and regain focus.
1145 im_->setInputItemTransform(im_item_trans_);
1146 // force fulldraw to remove previous paint remaining on screen
1147 buffer_view_->processUpdateFlags(Update::ForceDraw);
1149 // get attributes of input method cursor.
1150 // cursor_pos : cursor position in preedit string.
1151 size_t cursor_pos = 0;
1152 bool cursor_is_visible = false;
1153 for (auto const & attr : preedit_attr_) {
1154 if (attr.type == QInputMethodEvent::Cursor) {
1155 cursor_pos = size_t(attr.start);
1156 cursor_is_visible = attr.length != 0;
1161 size_t const preedit_length = preedit_string_.length();
1163 // get position of selection in input method.
1164 // FIXME: isn't there a simpler way to do this?
1165 // rStart : cursor position in selected string in IM.
1167 // rLength : selected string length in IM.
1169 if (cursor_pos < preedit_length) {
1170 for (auto const & attr : preedit_attr_) {
1171 if (attr.type == QInputMethodEvent::TextFormat) {
1172 if (attr.start <= int(cursor_pos)
1173 && int(cursor_pos) < attr.start + attr.length) {
1174 rStart = size_t(attr.start);
1175 rLength = size_t(attr.length);
1176 if (!cursor_is_visible)
1177 cursor_pos += rLength;
1184 rStart = cursor_pos;
1188 int const text_width = p->viewport()->width() - buffer_view_->rightMargin()
1189 - buffer_view_->leftMargin();
1190 Painter::preedit_style ps;
1191 // Most often there would be only one line:
1193 for (size_t pos = 0; pos != preedit_length; ++pos) {
1194 char_type const typed_char = preedit_string_[pos];
1195 // reset preedit string style
1196 ps = Painter::preedit_default;
1198 // if we reached the right extremity of the screen, go to next line.
1199 if (cur_x + fm.width(typed_char) > p->viewport()->width() - buffer_view_->rightMargin()) {
1200 cur_x = buffer_view_->leftMargin();
1201 cur_y += dim.height() + 1;
1204 // preedit strings are displayed with dashed underline
1205 // and partial strings are displayed white on black indicating
1206 // that we are in selecting mode in the input method.
1207 // FIXME: rLength == preedit_length is not a changing condition
1208 // FIXME: should be put out of the loop.
1210 && pos < rStart + rLength
1211 && !(cursor_pos < rLength && rLength == preedit_length)) {
1212 ps = Painter::preedit_selecting;
1215 if (pos == cursor_pos
1216 && (cursor_pos < rLength && rLength == preedit_length))
1217 ps = Painter::preedit_cursor;
1219 // draw one character and update cur_x.
1220 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1223 // the selection candidate window follows the position of Qt::ImCursorRectangle
1224 // so we set it here in preparation for InputMethodQuery.
1226 // candidate selection mode
1227 div_t mod_cur, mod_anc;
1228 // width of preedit string in pixels
1229 int preedit_width = fm.width(preedit_string_);
1230 // calculate for modular so that its remainder and quotient become horizontal
1231 // and vertical adjustment factor respectively
1232 // FIXME: divider should be (text_width - font width of the end-of-line character)
1233 // however, since it's very rare that preedit becomes so long that it goes over
1234 // more than two lines, current error of position is more or less negligible
1235 mod_cur = div(text_width + cur_x - (preedit_width - fm.width(preedit_string_.substr(0, rStart))),
1237 mod_anc = div(text_width + cur_x - (preedit_width - fm.width(preedit_string_.substr(0, rStart + rLength))),
1239 // Obtain cursor and anchor rectangles to bind starting and ending points of selection.
1240 // Since the remainder of div moves from positive to negative as the line becomes longer
1241 // while its quotient repeats zero twice, we need to take it into account by conditioning.
1242 if (mod_cur.rem >= 0)
1243 im_cursor_rect_ = QRectF(mod_cur.rem,
1244 (cur_y - dim.height()) + (dim.height() + 1) * (mod_cur.quot - 1), 1,
1245 dim.height() + preedit_lower_margin);
1247 im_cursor_rect_ = QRectF(text_width + mod_cur.rem,
1248 (cur_y - dim.height()) + (dim.height() + 1) * (mod_cur.quot - 2), 1,
1249 dim.height() + preedit_lower_margin);
1250 if (mod_anc.rem >= 0)
1251 im_anchor_rect_ = QRectF(mod_anc.rem,
1252 point.y_ + (dim.height() + 1) * (mod_anc.quot - 1), 1,
1253 dim.height() + preedit_lower_margin );
1255 im_anchor_rect_ = QRectF(text_width + mod_anc.rem,
1256 point.y_ + (dim.height() + 1) * (mod_anc.quot - 2), 1,
1257 dim.height() + preedit_lower_margin );
1259 im_cursor_rect_ = QRectF(point.x_, point.y_, 1, dim.height() + preedit_lower_margin);
1260 im_anchor_rect_ = im_cursor_rect_;
1262 // Urge platform input method to make inputMethodQuery to check the values
1264 im_->update(Qt::ImQueryInput);
1268 void GuiWorkArea::Private::resetScreen()
1270 if (use_backingstore_) {
1271 double const pr = p->pixelRatio();
1272 screen_ = QImage(int(pr * p->viewport()->width()),
1273 int(pr * p->viewport()->height()),
1274 QImage::Format_ARGB32_Premultiplied);
1275 screen_.setDevicePixelRatio(pr);
1280 QPaintDevice * GuiWorkArea::Private::screenDevice()
1282 if (use_backingstore_)
1285 return p->viewport();
1289 void GuiWorkArea::Private::updateScreen(QRectF const & rc)
1291 if (use_backingstore_) {
1292 QPainter qpain(p->viewport());
1293 double const pr = p->pixelRatio();
1294 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr,
1295 rc.width() * pr, rc.height() * pr);
1296 qpain.drawImage(rc, screen_, rcs);
1301 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1303 // Do not trigger the painting machinery if we are not ready (see
1304 // bug #10989). The second test triggers when in the middle of a
1305 // dispatch operation.
1306 if (view().busy() || d->buffer_view_->busy()) {
1307 // Since the screen may have turned black at this point, our
1308 // backing store has to be copied to screen. This is a no-op
1309 // except when our drawing strategy is "backingstore" (macOS,
1310 // Wayland, or set in prefs).
1311 d->updateScreen(ev->rect());
1312 // Ignore this paint event, but request a new one for later.
1313 viewport()->update(ev->rect());
1318 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1319 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1321 if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_) {
1323 d->resizeBufferView();
1326 d->last_pixel_ratio_ = pixelRatio();
1328 GuiPainter pain(d->screenDevice(), pixelRatio(), d->lyx_view_->develMode());
1330 d->buffer_view_->draw(pain, d->caret_visible_);
1332 // The preedit text, if needed
1333 d->paintPreeditText(pain);
1336 // FIXME: the code would be a little bit simpler if caret geometry
1337 // was updated unconditionally. Some profiling is required to see
1338 // how expensive this is (especially when idle).
1339 if (d->caret_visible_) {
1340 if (d->needs_caret_geometry_update_)
1341 d->updateCaretGeometry();
1342 d->drawCaret(pain, d->buffer_view_->horizScrollOffset());
1345 d->updateScreen(ev->rect());
1351 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1353 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1354 << " commitString: " << e->commitString());
1356 if (!e->commitString().isEmpty()) {
1358 // take care of commit string assigned to a shortcut
1359 // e.g. quotation mark on international keyboard
1361 for (QChar const & ch : e->commitString()) {
1363 keysym.init(ch.unicode());
1364 keyseq.addkey(keysym, NoModifier);
1366 cmd = theTopLevelKeymap().getBinding(keyseq);
1368 if (cmd == FuncRequest::noaction || cmd == FuncRequest::unknown
1369 || cmd.action() == LFUN_SELF_INSERT)
1370 // insert the processed text in the document (handles undo)
1371 cmd = FuncRequest(LFUN_SELF_INSERT, qstring_to_ucs4(e->commitString()));
1373 cmd.setOrigin(FuncRequest::KEYBOARD);
1375 // FIXME: this is supposed to remove traces from preedit
1376 // string. Can we avoid calling it explicitly?
1377 d->buffer_view_->updateMetrics();
1380 // Hide the caret during the test transformation.
1381 if (e->preeditString().isEmpty())
1382 startBlinkingCaret();
1384 stopBlinkingCaret();
1386 if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1392 // The preedit text and its attributes will be used in paintPreeditText
1393 d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1394 d->preedit_attr_ = e->attributes();
1397 // redraw area of preedit string.
1398 // int height = d->caret_->dim.height();
1399 // int cur_y = d->caret_->y;
1400 // viewport()->update(0, cur_y, viewport()->width(),
1401 // (height + 1) * d->preedit_lines_);
1402 viewport()->update();
1404 if (d->preedit_string_.empty()) {
1405 d->preedit_lines_ = 1;
1410 // Don't forget to accept the event!
1415 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1417 LYXERR(Debug::INFO, "incoming InputMethodQuery Value: 0x" << std::hex << query);
1419 // this is the CJK-specific composition window position and
1420 // the context menu position when the menu key is pressed.
1421 case Qt::ImCursorRectangle: {
1422 return QVariant(d->im_cursor_rect_);
1425 #if QT_VERSION >= QT_VERSION_CHECK(5, 7, 0)
1426 case Qt::ImAnchorRectangle: {
1427 return QVariant(d->im_anchor_rect_);
1432 return QWidget::inputMethodQuery(query);
1437 void GuiWorkArea::updateWindowTitle()
1439 Buffer const & buf = bufferView().buffer();
1440 if (buf.fileName() != d->file_name_
1441 || buf.params().shell_escape != d->shell_escape_
1442 || buf.hasReadonlyFlag() != d->read_only_
1443 || buf.lyxvc().vcstatus() != d->vc_status_
1444 || buf.isClean() != d->clean_
1445 || buf.notifiesExternalModification() != d->externally_modified_) {
1446 d->file_name_ = buf.fileName();
1447 d->shell_escape_ = buf.params().shell_escape;
1448 d->read_only_ = buf.hasReadonlyFlag();
1449 d->vc_status_ = buf.lyxvc().vcstatus();
1450 d->clean_ = buf.isClean();
1451 d->externally_modified_ = buf.notifiesExternalModification();
1452 Q_EMIT titleChanged(this);
1457 bool GuiWorkArea::isFullScreen() const
1459 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1463 bool GuiWorkArea::inDialogMode() const
1465 return d->dialog_mode_;
1469 void GuiWorkArea::setDialogMode(bool mode)
1471 d->dialog_mode_ = mode;
1475 GuiCompleter & GuiWorkArea::completer()
1477 return *d->completer_;
1480 GuiView const & GuiWorkArea::view() const
1482 return *d->lyx_view_;
1486 GuiView & GuiWorkArea::view()
1488 return *d->lyx_view_;
1491 ////////////////////////////////////////////////////////////////////
1495 ////////////////////////////////////////////////////////////////////
1498 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1500 support::TempFile tempfile("embedded.internal");
1501 tempfile.setAutoRemove(false);
1502 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1503 buffer_->setUnnamed(true);
1504 buffer_->setFullyLoaded(true);
1505 setBuffer(*buffer_);
1506 setDialogMode(true);
1510 EmbeddedWorkArea::~EmbeddedWorkArea()
1512 // No need to destroy buffer and bufferview here, because it is done
1513 // in theBufferList() destruction loop at application exit
1517 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1520 GuiWorkArea::closeEvent(ev);
1524 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1527 GuiWorkArea::hideEvent(ev);
1531 QSize EmbeddedWorkArea::sizeHint () const
1534 // GuiWorkArea sets the size to the screen's viewport
1535 // by returning a value this gets overridden
1536 // EmbeddedWorkArea is now sized to fit in the layout
1537 // of the parent, and has a minimum size set in GuiWorkArea
1538 // which is what we return here
1539 return QSize(100, 70);
1543 void EmbeddedWorkArea::disable()
1545 stopBlinkingCaret();
1546 if (view().currentWorkArea() != this)
1548 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1549 // tolerates it and shows the background logo), what happens if
1550 // an EmbeddedWorkArea is closed after closing all document WAs
1551 view().setCurrentWorkArea(view().currentMainWorkArea());
1554 ////////////////////////////////////////////////////////////////////
1558 ////////////////////////////////////////////////////////////////////
1560 TabWorkArea::TabWorkArea(QWidget * parent)
1561 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1563 QPalette pal = palette();
1564 pal.setColor(QPalette::Active, QPalette::Button,
1565 pal.color(QPalette::Active, QPalette::Window));
1566 pal.setColor(QPalette::Disabled, QPalette::Button,
1567 pal.color(QPalette::Disabled, QPalette::Window));
1568 pal.setColor(QPalette::Inactive, QPalette::Button,
1569 pal.color(QPalette::Inactive, QPalette::Window));
1571 QObject::connect(this, SIGNAL(currentChanged(int)),
1572 this, SLOT(on_currentTabChanged(int)));
1574 QObject::connect(this, SIGNAL(tabBarClicked(int)),
1575 this, SLOT(on_currentTabChanged(int)));
1577 closeBufferButton = new QToolButton(this);
1578 closeBufferButton->setPalette(pal);
1579 // FIXME: rename the icon to closebuffer.png
1580 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1581 closeBufferButton->setText("Close File");
1582 closeBufferButton->setAutoRaise(true);
1583 closeBufferButton->setCursor(Qt::ArrowCursor);
1584 closeBufferButton->setToolTip(qt_("Close File"));
1585 closeBufferButton->setEnabled(true);
1586 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1587 this, SLOT(closeCurrentBuffer()));
1588 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1590 // set TabBar behaviour
1591 QTabBar * tb = tabBar();
1592 tb->setTabsClosable(!lyxrc.single_close_tab_button);
1593 tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1594 tb->setElideMode(Qt::ElideNone);
1595 // allow dragging tabs
1596 tb->setMovable(true);
1597 // make us responsible for the context menu of the tabbar
1598 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1599 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1600 this, SLOT(showContextMenu(const QPoint &)));
1601 connect(tb, SIGNAL(tabCloseRequested(int)),
1602 this, SLOT(closeTab(int)));
1604 setUsesScrollButtons(true);
1606 // use document mode tabs
1607 setDocumentMode(true);
1612 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1614 if (me->button() == Qt::MiddleButton)
1615 midpressed_tab_ = tabBar()->tabAt(me->pos());
1617 QTabWidget::mousePressEvent(me);
1621 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1623 if (me->button() == Qt::MiddleButton) {
1624 int const midreleased_tab = tabBar()->tabAt(me->pos());
1625 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1626 closeTab(midreleased_tab);
1628 QTabWidget::mouseReleaseEvent(me);
1632 void TabWorkArea::paintEvent(QPaintEvent * event)
1634 if (tabBar()->isVisible()) {
1635 QTabWidget::paintEvent(event);
1637 // Prevent the selected tab to influence the
1638 // painting of the frame of the tab widget.
1639 // This is needed for gtk style in Qt.
1640 QStylePainter p(this);
1641 QStyleOptionTabWidgetFrame opt;
1642 initStyleOption(&opt);
1643 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1645 opt.selectedTabRect = QRect();
1646 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1651 bool TabWorkArea::posIsTab(QPoint position)
1653 // tabAt returns -1 if tab does not covers position
1654 return tabBar()->tabAt(position) > -1;
1658 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1660 if (event->button() != Qt::LeftButton)
1663 // this code chunk is unnecessary because it seems the event only makes
1664 // it this far if it is not on a tab. I'm not sure why this is (maybe
1665 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1666 // this is true in all cases and if it will be true in the future so I
1667 // leave this code for now. (skostysh, 2016-07-21)
1669 // return early if double click on existing tabs
1670 if (posIsTab(event->pos()))
1673 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1677 void TabWorkArea::setFullScreen(bool full_screen)
1679 for (int i = 0; i != count(); ++i) {
1680 if (GuiWorkArea * wa = workArea(i))
1681 wa->setFullScreen(full_screen);
1684 if (lyxrc.full_screen_tabbar)
1685 showBar(!full_screen && count() > 1);
1687 showBar(count() > 1);
1691 void TabWorkArea::showBar(bool show)
1693 tabBar()->setEnabled(show);
1694 tabBar()->setVisible(show);
1695 if (documentMode()) {
1696 // avoid blank corner widget when documentMode(true) is used
1697 if (show && lyxrc.single_close_tab_button) {
1698 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1699 closeBufferButton->setVisible(true);
1701 // remove corner widget
1702 setCornerWidget(nullptr);
1704 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1705 setTabsClosable(!lyxrc.single_close_tab_button);
1709 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1711 QWidget * w = QTabWidget::widget(index);
1714 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1720 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1722 return widget(currentIndex());
1726 GuiWorkArea * TabWorkArea::workArea(int index) const
1728 GuiWorkAreaContainer * w = widget(index);
1731 return w->workArea();
1735 GuiWorkArea * TabWorkArea::currentWorkArea() const
1737 return workArea(currentIndex());
1741 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1743 // FIXME: this method doesn't work if we have more than one work area
1744 // showing the same buffer.
1745 for (int i = 0; i != count(); ++i) {
1746 GuiWorkArea * wa = workArea(i);
1747 LASSERT(wa, return nullptr);
1748 if (&wa->bufferView().buffer() == &buffer)
1755 void TabWorkArea::closeAll()
1758 QWidget * wac = widget(0);
1759 LASSERT(wac, return);
1766 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1768 for (int index = 0; index < count(); ++index)
1769 if (workArea(index) == w)
1775 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1777 LASSERT(work_area, return false);
1778 int index = indexOfWorkArea(work_area);
1782 if (index == currentIndex())
1783 // Make sure the work area is up to date.
1784 on_currentTabChanged(index);
1786 // Switch to the work area.
1787 setCurrentIndex(index);
1788 work_area->setFocus();
1794 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1796 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1797 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1798 wa->setUpdatesEnabled(false);
1799 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1800 // when hiding it again below).
1801 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1802 showBar(count() > 0);
1803 addTab(wac, wa->windowTitle());
1804 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1805 this, SLOT(updateTabTexts()));
1806 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1807 setFullScreen(true);
1809 // Hide tabbar if there's only one tab.
1810 showBar(count() > 1);
1818 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1820 LASSERT(work_area, return false);
1821 int index = indexOfWorkArea(work_area);
1825 work_area->setUpdatesEnabled(false);
1826 QWidget * wac = widget(index);
1831 // make sure the next work area is enabled.
1832 currentWidget()->setUpdatesEnabled(true);
1833 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1834 setFullScreen(true);
1836 // Show tabbar only if there's more than one tab.
1837 showBar(count() > 1);
1839 lastWorkAreaRemoved();
1847 void TabWorkArea::on_currentTabChanged(int i)
1849 // returns e.g. on application destruction
1852 GuiWorkArea * wa = workArea(i);
1853 LASSERT(wa, return);
1854 wa->setUpdatesEnabled(true);
1855 wa->scheduleRedraw(true);
1858 currentWorkAreaChanged(wa);
1860 LYXERR(Debug::GUI, "currentTabChanged " << i
1861 << " File: " << wa->bufferView().buffer().absFileName());
1865 void TabWorkArea::closeCurrentBuffer()
1868 if (clicked_tab_ == -1)
1869 wa = currentWorkArea();
1871 wa = workArea(clicked_tab_);
1872 LASSERT(wa, return);
1874 wa->view().closeWorkArea(wa);
1878 void TabWorkArea::hideCurrentTab()
1881 if (clicked_tab_ == -1)
1882 wa = currentWorkArea();
1884 wa = workArea(clicked_tab_);
1885 LASSERT(wa, return);
1887 wa->view().hideWorkArea(wa);
1891 void TabWorkArea::closeTab(int index)
1893 on_currentTabChanged(index);
1896 wa = currentWorkArea();
1898 wa = workArea(index);
1899 LASSERT(wa, return);
1901 wa->view().closeWorkArea(wa);
1908 /// make vector happy
1909 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1911 DisplayPath(int tab, FileName const & filename)
1914 // Recode URL encoded chars via fromPercentEncoding()
1915 string const fn = (filename.extension() == "lyx")
1916 ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
1917 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
1918 #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
1919 postfix_ = toqstr(filename.absoluteFilePath()).
1920 split("/", Qt::SkipEmptyParts);
1922 postfix_ = toqstr(filename.absoluteFilePath()).
1923 split("/", QString::SkipEmptyParts);
1925 postfix_.pop_back();
1926 abs_ = toqstr(filename.absoluteFilePath());
1927 dottedPrefix_ = false;
1930 /// Absolute path for debugging.
1935 /// Add the first segment from the postfix or three dots to the prefix.
1936 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1937 /// when really needed.
1938 void shiftPathSegment(bool dotted)
1940 if (postfix_.count() <= 0)
1944 if (dottedPrefix_ && !prefix_.isEmpty())
1945 prefix_ += ellipsisSlash_;
1946 prefix_ += postfix_.front() + "/";
1948 dottedPrefix_ = dotted && !prefix_.isEmpty();
1949 postfix_.pop_front();
1952 QString displayString() const
1954 if (prefix_.isEmpty())
1957 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1958 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1961 QString forecastPathString() const
1963 if (postfix_.count() == 0)
1964 return displayString();
1967 + (dottedPrefix_ ? ellipsisSlash_ : "")
1968 + postfix_.front() + "/";
1971 bool final() const { return postfix_.empty(); }
1973 int tab() const { return tab_; }
1977 static QString const ellipsisSlash_;
1981 QStringList postfix_;
1993 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1997 bool operator<(DisplayPath const & a, DisplayPath const & b)
1999 return a.displayString() < b.displayString();
2003 bool operator==(DisplayPath const & a, DisplayPath const & b)
2005 return a.displayString() == b.displayString();
2009 void TabWorkArea::updateTabTexts()
2011 int const n = count();
2014 std::list<DisplayPath> paths;
2015 typedef std::list<DisplayPath>::iterator It;
2017 // collect full names first: path into postfix, empty prefix and
2018 // filename without extension
2019 for (int i = 0; i < n; ++i) {
2020 GuiWorkArea * i_wa = workArea(i);
2021 FileName const fn = i_wa->bufferView().buffer().fileName();
2022 paths.push_back(DisplayPath(i, fn));
2025 // go through path segments and see if it helps to make the path more unique
2026 bool somethingChanged = true;
2027 bool allFinal = false;
2028 while (somethingChanged && !allFinal) {
2029 // adding path segments changes order
2032 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
2033 somethingChanged = false;
2036 // find segments which are not unique (i.e. non-atomic)
2037 It it = paths.begin();
2039 QString segString = it->displayString();
2040 for (; it != paths.end(); ++it) {
2041 // look to the next item
2046 allFinal = allFinal && it->final();
2048 LYXERR(Debug::GUI, "it = " << it->abs()
2049 << " => " << it->displayString());
2051 // still the same segment?
2053 if ((next != paths.end()
2054 && (nextString = next->displayString()) == segString))
2056 LYXERR(Debug::GUI, "segment ended");
2058 // only a trivial one with one element?
2059 if (it == segStart) {
2060 // start new segment
2062 segString = nextString;
2066 // We found a non-atomic segment
2067 // We know that segStart <= it < next <= paths.end().
2068 // The assertion below tells coverity about it.
2069 LATTEST(segStart != paths.end());
2070 QString dspString = segStart->forecastPathString();
2071 LYXERR(Debug::GUI, "first forecast found for "
2072 << segStart->abs() << " => " << dspString);
2075 // Shift path segments and hope for the best
2076 // that it makes the path more unique.
2077 somethingChanged = true;
2078 bool moreUnique = false;
2079 for (; sit != next; ++sit) {
2080 if (sit->forecastPathString() != dspString) {
2081 LYXERR(Debug::GUI, "different forecast found for "
2082 << sit->abs() << " => " << sit->forecastPathString());
2086 LYXERR(Debug::GUI, "same forecast found for "
2087 << sit->abs() << " => " << dspString);
2090 // if the path segment helped, add it. Otherwise add dots
2091 bool dots = !moreUnique;
2092 LYXERR(Debug::GUI, "using dots = " << dots);
2093 for (sit = segStart; sit != next; ++sit) {
2094 sit->shiftPathSegment(dots);
2095 LYXERR(Debug::GUI, "shifting "
2096 << sit->abs() << " => " << sit->displayString());
2099 // start new segment
2101 segString = nextString;
2105 // set new tab titles
2106 for (It it = paths.begin(); it != paths.end(); ++it) {
2107 int const tab_index = it->tab();
2108 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2109 QString tab_text = it->displayString().replace("&", "&&");
2110 if (!buf.fileName().empty() && !buf.isClean())
2112 QString tab_tooltip = it->abs();
2113 if (buf.hasReadonlyFlag()) {
2115 QLabel * readOnlyButton = new QLabel();
2116 QIcon icon = QIcon(getPixmap("images/", "emblem-readonly", "svgz,png"));
2117 readOnlyButton->setPixmap(icon.pixmap(QSize(16, 16)));
2118 tabBar()->setTabButton(tab_index, QTabBar::RightSide, readOnlyButton);
2120 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2122 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2125 tabBar()->setTabButton(tab_index, QTabBar::RightSide, 0);
2127 setTabIcon(tab_index, QIcon());
2129 if (buf.notifiesExternalModification()) {
2130 QString const warn = qt_("%1 (modified externally)");
2131 tab_tooltip = warn.arg(tab_tooltip);
2132 tab_text += QChar(0x26a0);
2134 setTabText(tab_index, tab_text);
2135 setTabToolTip(tab_index, tab_tooltip);
2140 void TabWorkArea::showContextMenu(const QPoint & pos)
2143 clicked_tab_ = tabBar()->tabAt(pos);
2144 if (clicked_tab_ == -1)
2147 GuiWorkArea * wa = workArea(clicked_tab_);
2148 LASSERT(wa, return);
2152 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2153 qt_("&Hide Tab"), this, SLOT(hideCurrentTab()));
2155 // we want to show the 'close' option only if this is not a child buffer.
2156 Buffer const & buf = wa->bufferView().buffer();
2158 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2159 qt_("&Close Tab"), this, SLOT(closeCurrentBuffer()));
2160 popup.exec(tabBar()->mapToGlobal(pos));
2166 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2168 QWidget * w = widget(fromIndex);
2169 QIcon icon = tabIcon(fromIndex);
2170 QString text = tabText(fromIndex);
2172 setCurrentIndex(fromIndex);
2173 removeTab(fromIndex);
2174 insertTab(toIndex, w, icon, text);
2175 setCurrentIndex(toIndex);
2179 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2180 : QWidget(parent), wa_(wa)
2182 LASSERT(wa, return);
2183 Ui::WorkAreaUi::setupUi(this);
2184 layout()->addWidget(wa);
2185 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2186 this, SLOT(updateDisplay()));
2187 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2188 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2189 setMessageColour({notificationFrame, externalModificationLabel},
2190 {reloadPB, ignorePB});
2195 void GuiWorkAreaContainer::updateDisplay()
2197 Buffer const & buf = wa_->bufferView().buffer();
2198 notificationFrame->setHidden(!buf.notifiesExternalModification());
2199 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2200 .arg(toqstr(buf.fileName().displayName()));
2201 externalModificationLabel->setText(label);
2205 void GuiWorkAreaContainer::dispatch(FuncRequest const & f) const
2207 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2208 wa_->bufferView().buffer().absFileName()));
2213 void GuiWorkAreaContainer::reload() const
2215 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2219 void GuiWorkAreaContainer::ignore() const
2221 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2225 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2227 // prevent TabWorkArea from opening a new buffer on double click
2232 } // namespace frontend
2235 #include "moc_GuiWorkArea.cpp"