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>
56 #if (QT_VERSION < 0x050000)
57 #include <QInputContext>
62 #include <QProxyStyle>
64 #include <QMainWindow>
70 #include <QStyleOption>
71 #include <QStylePainter>
73 #include <QToolButton>
84 using namespace lyx::support;
89 /// return the LyX mouse button state from Qt's
90 static mouse_button::state q_button_state(Qt::MouseButton button)
92 mouse_button::state b = mouse_button::none;
95 b = mouse_button::button1;
97 case Qt::MiddleButton:
98 b = mouse_button::button2;
100 case Qt::RightButton:
101 b = mouse_button::button3;
110 /// return the LyX mouse button state from Qt's
111 mouse_button::state q_motion_state(Qt::MouseButtons state)
113 mouse_button::state b = mouse_button::none;
114 if (state & Qt::LeftButton)
115 b |= mouse_button::button1;
116 if (state & Qt::MiddleButton)
117 b |= mouse_button::button2;
118 if (state & Qt::RightButton)
119 b |= mouse_button::button3;
126 // This is a 'heartbeat' generating synthetic mouse move events when the
127 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
128 SyntheticMouseEvent::SyntheticMouseEvent()
129 : timeout(200), restart_timeout(true)
133 GuiWorkArea::Private::Private(GuiWorkArea * parent)
134 : p(parent), completer_(new GuiCompleter(p, p))
136 use_backingstore_ = lyxrc.draw_strategy == LyXRC::DS_BACKINGSTORE
137 || guiApp->needsBackingStore();
138 LYXERR(Debug::WORKAREA, "Drawing strategy is: "
139 << (use_backingstore_ ? "backingstore" : "partial"));
141 int const time = QApplication::cursorFlashTime() / 2;
143 caret_timeout_.setInterval(time);
144 caret_timeout_.start();
146 // let's initialize this just to be safe
147 caret_timeout_.setInterval(500);
152 GuiWorkArea::Private::~Private()
154 // If something is wrong with the buffer, we can ignore it safely
156 buffer_view_->buffer().workAreaManager().remove(p);
159 // Completer has a QObject parent and is thus automatically destroyed.
161 // delete completer_;
165 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
166 : d(new Private(this))
168 new CompressorProxy(this); // not a leak
172 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
173 : d(new Private(this))
175 new CompressorProxy(this); // not a leak
177 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
183 double GuiWorkArea::pixelRatio() const
185 #if QT_VERSION >= 0x050000
186 return qt_scale_factor * devicePixelRatio();
193 void GuiWorkArea::init()
196 connect(&d->caret_timeout_, SIGNAL(timeout()),
197 this, SLOT(toggleCaret()));
199 // This connection is closed at the same time as this is destroyed.
200 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
201 generateSyntheticMouseEvent();
205 // With Qt4.5 a mouse event will happen before the first paint event
206 // so make sure that the buffer view has an up to date metrics.
207 d->buffer_view_->resize(viewport()->width(), viewport()->height());
209 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
210 setAcceptDrops(true);
211 setMouseTracking(true);
212 setMinimumSize(100, 70);
213 setFrameStyle(QFrame::NoFrame);
216 d->updateCursorShape();
218 // we paint our own background
219 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
221 setFocusPolicy(Qt::StrongFocus);
223 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
224 << " viewport height: " << viewport()->height());
226 // Enables input methods for asian languages.
227 // Must be set when creating custom text editing widgets.
228 setAttribute(Qt::WA_InputMethodEnabled, true);
232 GuiWorkArea::~GuiWorkArea()
238 void GuiWorkArea::Private::updateCursorShape()
240 bool const clickable = buffer_view_ && buffer_view_->clickableInset();
241 p->viewport()->setCursor(clickable ? Qt::PointingHandCursor
246 void GuiWorkArea::setGuiView(GuiView & gv)
252 void GuiWorkArea::setBuffer(Buffer & buffer)
254 delete d->buffer_view_;
255 d->buffer_view_ = new BufferView(buffer);
256 buffer.workAreaManager().add(this);
258 // HACK: Prevents an additional redraw when the scrollbar pops up
259 // which regularly happens on documents with more than one page.
260 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
261 // Since we have no geometry information yet, we assume that
262 // a document needs a scrollbar if there is more then four
263 // paragraph in the outermost text.
264 if (buffer.text().paragraphs().size() > 4)
265 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
266 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
267 Q_EMIT bufferViewChanged();
271 void GuiWorkArea::fixVerticalScrollBar()
274 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
278 void GuiWorkArea::close()
280 d->lyx_view_->removeWorkArea(this);
284 void GuiWorkArea::setFullScreen(bool full_screen)
286 d->buffer_view_->setFullScreen(full_screen);
287 if (full_screen && lyxrc.full_screen_scrollbar)
288 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
290 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
294 BufferView & GuiWorkArea::bufferView()
296 return *d->buffer_view_;
300 BufferView const & GuiWorkArea::bufferView() const
302 return *d->buffer_view_;
306 void GuiWorkArea::stopBlinkingCaret()
308 d->caret_timeout_.stop();
313 void GuiWorkArea::startBlinkingCaret()
315 // do not show the cursor if the view is busy
319 // Don't start blinking if the cursor isn't on screen, unless we
320 // are not ready to know whether the cursor is on screen.
321 if (!d->buffer_view_->buffer().undo().activeUndoGroup()
322 && !d->buffer_view_->caretInView())
327 // Avoid blinking when debugging PAINTING, since it creates too much noise
328 if (!lyxerr.debugging(Debug::PAINTING)) {
329 // we are not supposed to cache this value.
330 int const time = QApplication::cursorFlashTime() / 2;
333 d->caret_timeout_.setInterval(time);
334 d->caret_timeout_.start();
339 void GuiWorkArea::toggleCaret()
341 if (d->caret_visible_)
348 void GuiWorkArea::scheduleRedraw(bool update_metrics)
351 // No need to redraw in this case.
354 // No need to do anything if this is the current view. The BufferView
355 // metrics are already up to date.
356 if (update_metrics || d->lyx_view_ != guiApp->currentView()
357 || d->lyx_view_->currentWorkArea() != this) {
358 // FIXME: it would be nice to optimize for the off-screen case.
359 d->buffer_view_->cursor().fixIfBroken();
360 d->buffer_view_->updateMetrics();
361 d->buffer_view_->cursor().fixIfBroken();
364 // update caret position, because otherwise it has to wait until
365 // the blinking interval is over
368 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
369 viewport()->update();
371 /// FIXME: is this still true now that paintEvent does the actual painting?
372 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
373 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
374 d->updateScrollbar();
375 d->lyx_view_->updateStatusBar();
377 if (lyxerr.debugging(Debug::WORKAREA))
378 d->buffer_view_->coordCache().dump();
382 d->updateCursorShape();
386 // Keep in sync with GuiWorkArea::processKeySym below
387 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
389 return guiApp->queryKeySym(key, mod);
393 // Keep in sync with GuiWorkArea::queryKeySym above
394 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
396 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
397 && lyxrc.full_screen_menubar) {
398 // FIXME HACK: we should not have to do this here. See related comment
399 // in GuiView::event() (QEvent::ShortcutOverride)
400 d->lyx_view_->menuBar()->hide();
403 // In order to avoid bad surprise in the middle of an operation,
404 // we better stop the blinking caret...
405 // the caret gets restarted in GuiView::restartCaret()
407 guiApp->processKeySym(key, mod);
411 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
414 if (cmd.action() == LFUN_FILE_OPEN) {
416 lyx_view_->dispatch(cmd, dr);
420 bool const notJustMovingTheMouse =
421 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
423 // In order to avoid bad surprise in the middle of an operation, we better stop
424 // the blinking caret.
425 if (notJustMovingTheMouse)
426 p->stopBlinkingCaret();
428 buffer_view_->mouseEventDispatch(cmd);
430 // Skip these when selecting
431 // FIXME: let GuiView take care of those.
432 if (notJustMovingTheMouse && !buffer_view_->mouseSelecting()) {
433 completer_->updateVisibility(false, false);
434 lyx_view_->updateDialogs();
435 lyx_view_->updateStatusBar();
438 // GUI tweaks except with mouse motion with no button pressed.
439 if (notJustMovingTheMouse) {
440 // Slight hack: this is only called currently when we
441 // clicked somewhere, so we force through the display
442 // of the new status here.
443 // FIXME: let GuiView take care of those.
444 lyx_view_->clearMessage();
446 // Show the caret immediately after any operation
447 p->startBlinkingCaret();
454 void GuiWorkArea::Private::resizeBufferView()
456 // WARNING: Please don't put any code that will trigger a repaint here!
457 // We are already inside a paint event.
458 p->stopBlinkingCaret();
459 // Warn our container (GuiView).
462 bool const caret_in_view = buffer_view_->caretInView();
463 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
465 buffer_view_->showCursor();
468 // Update scrollbars which might have changed due different
469 // BufferView dimension. This is especially important when the
470 // BufferView goes from zero-size to the real-size for the first time,
471 // as the scrollbar parameters are then set for the first time.
474 need_resize_ = false;
476 // Eventually, restart the caret after the resize event.
477 // We might be resizing even if the focus is on another widget so we only
478 // restart the caret if we have the focus.
480 QTimer::singleShot(50, p, SLOT(startBlinkingCaret()));
484 void GuiWorkArea::Private::resetCaret()
486 // Don't start blinking if the cursor isn't on screen.
487 if (!buffer_view_->caretInView())
490 // completion indicator
491 Cursor const & cur = buffer_view_->cursor();
492 bool const completable = cur.inset().showCompletionCursor()
493 && completer_->completionAvailable()
494 && !completer_->popupVisible()
495 && !completer_->inlineVisible();
497 buffer_view_->buildCaretGeometry(completable);
499 needs_caret_geometry_update_ = true;
500 caret_visible_ = true;
504 void GuiWorkArea::Private::updateCaretGeometry()
506 // we cannot update geometry if not ready and we do not need to if
507 // caret is not in view.
508 if (buffer_view_->buffer().undo().activeUndoGroup()
509 || !buffer_view_->caretInView())
513 needs_caret_geometry_update_ = false;
517 void GuiWorkArea::Private::showCaret()
523 p->viewport()->update();
527 void GuiWorkArea::Private::hideCaret()
532 caret_visible_ = false;
533 //if (!qApp->focusWidget())
534 p->viewport()->update();
538 /* Draw the caret. Parameter \c horiz_offset is not 0 when there
539 * has been horizontal scrolling in current row
541 void GuiWorkArea::Private::drawCaret(QPainter & painter, int horiz_offset) const
543 if (buffer_view_->caretGeometry().shapes.empty())
546 QColor const color = guiApp->colorCache().get(Color_cursor);
547 painter.setPen(color);
548 painter.setRenderHint(QPainter::Antialiasing, true);
549 for (auto const & shape : buffer_view_->caretGeometry().shapes) {
552 for (Point const & p : shape) {
554 path.moveTo(p.x_ - horiz_offset, p.y_);
557 path.lineTo(p.x_ - horiz_offset, p.y_);
559 painter.fillPath(path, color);
561 painter.setRenderHint(QPainter::Antialiasing, false);
565 void GuiWorkArea::Private::updateScrollbar()
567 // Prevent setRange() and setSliderPosition from causing recursive calls via
568 // the signal valueChanged. (#10311)
569 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
570 p, SLOT(scrollTo(int)));
571 ScrollbarParameters const & scroll = buffer_view_->scrollbarParameters();
572 p->verticalScrollBar()->setRange(scroll.min, scroll.max);
573 p->verticalScrollBar()->setPageStep(scroll.page_step);
574 p->verticalScrollBar()->setSingleStep(scroll.single_step);
575 p->verticalScrollBar()->setSliderPosition(0);
576 // Connect to the vertical scroll bar
577 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
578 p, SLOT(scrollTo(int)));
582 void GuiWorkArea::scrollTo(int value)
585 d->buffer_view_->scrollDocView(value, true);
587 if (lyxrc.cursor_follows_scrollbar) {
588 d->buffer_view_->setCursorFromScrollbar();
589 // FIXME: let GuiView take care of those.
590 d->lyx_view_->updateLayoutList();
592 // Show the caret immediately after any operation.
593 startBlinkingCaret();
596 QApplication::syncX();
601 bool GuiWorkArea::event(QEvent * e)
604 case QEvent::ToolTip: {
605 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
606 if (lyxrc.use_tooltip) {
607 QPoint pos = helpEvent->pos();
608 if (pos.x() < viewport()->width()) {
609 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
610 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
613 QToolTip::hideText();
615 // Don't forget to accept the event!
620 case QEvent::ShortcutOverride:
621 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
623 keyPressEvent(static_cast<QKeyEvent *>(e));
624 return e->isAccepted();
626 case QEvent::KeyPress: {
627 // We catch this event in order to catch the Tab or Shift+Tab key press
628 // which are otherwise reserved to focus switching between controls
630 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
631 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
632 || (ke->key() == Qt::Key_Backtab && (
633 ke->modifiers() == Qt::ShiftModifier
634 || ke->modifiers() == Qt::NoModifier))) {
638 return QAbstractScrollArea::event(e);
642 return QAbstractScrollArea::event(e);
648 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
651 if (e->reason() == QContextMenuEvent::Mouse)
652 // the menu name is set on mouse press
653 name = d->context_menu_name_;
655 QPoint pos = e->pos();
656 Cursor const & cur = d->buffer_view_->cursor();
657 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
658 // Do not access the context menu of math right in front of before
659 // the cursor. This does not work when the cursor is in text.
660 Inset * inset = cur.paragraph().getInset(cur.pos());
661 if (inset && inset->asInsetMath())
663 else if (cur.pos() > 0) {
664 inset = cur.paragraph().getInset(cur.pos() - 1);
669 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
676 // always show mnemonics when the keyboard is used to show the context menu
677 // FIXME: This should be fixed in Qt itself
678 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
679 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
684 // Position the menu to the right.
685 // FIXME: menu position should be different for RTL text.
686 menu->exec(e->globalPos());
691 void GuiWorkArea::focusInEvent(QFocusEvent * e)
693 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
694 if (d->lyx_view_->currentWorkArea() != this) {
695 d->lyx_view_->setCurrentWorkArea(this);
696 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
699 startBlinkingCaret();
700 QAbstractScrollArea::focusInEvent(e);
704 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
706 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
708 QAbstractScrollArea::focusOutEvent(e);
712 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
714 if (d->dc_event_.active && d->dc_event_ == *e) {
715 d->dc_event_.active = false;
716 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
717 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->position().x(), e->position().y(),
719 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
721 q_button_state(e->button()), q_key_state(e->modifiers()));
727 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
728 inputContext()->reset();
731 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
732 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->position().x(), e->position().y(),
734 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
736 q_button_state(e->button()), q_key_state(e->modifiers()));
739 // Save the context menu on mouse press, because also the mouse
740 // cursor is set on mouse press. Afterwards, we can either release
741 // the mousebutton somewhere else, or the cursor might have moved
742 // due to the DEPM. We need to do this after the mouse has been
743 // set in dispatch(), because the selection state might change.
744 if (e->button() == Qt::RightButton)
745 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
746 d->context_menu_name_ = d->buffer_view_->contextMenu(e->position().x(), e->position().y());
748 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
755 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
757 if (d->synthetic_mouse_event_.timeout.running())
758 d->synthetic_mouse_event_.timeout.stop();
760 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
761 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->position().x(), e->position().y(),
763 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
765 q_button_state(e->button()), q_key_state(e->modifiers()));
766 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
767 QT_VERSION < QT_VERSION_CHECK(5,15,1))
768 d->synthetic_mouse_event_.cmd = cmd; // QtBug QAbstractScrollArea::mouseMoveEvent
775 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
777 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
778 QT_VERSION < QT_VERSION_CHECK(5,15,1))
779 // cancel the event if the coordinates didn't change, this is due to QtBug
780 // QAbstractScrollArea::mouseMoveEvent, the event is triggered falsely when quickly
781 // double tapping a touchpad. To test: try to select a word by quickly double tapping
782 // on a touchpad while hovering the cursor over that word in the work area.
783 // This bug does not occur on Qt versions 5.10.1 and below. Only Windows seems to be affected.
784 // ML thread: https://www.mail-archive.com/lyx-devel@lists.lyx.org/msg211699.html
785 // Qt bugtracker: https://bugreports.qt.io/browse/QTBUG-85431
786 // Bug was fixed in Qt 5.15.1
787 if (e->x() == d->synthetic_mouse_event_.cmd.x() && // QtBug QAbstractScrollArea::mouseMoveEvent
788 e->y() == d->synthetic_mouse_event_.cmd.y()) // QtBug QAbstractScrollArea::mouseMoveEvent
789 return; // QtBug QAbstractScrollArea::mouseMoveEvent
792 // we kill the triple click if we move
793 doubleClickTimeout();
794 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
795 FuncRequest cmd(LFUN_MOUSE_MOTION, e->position().x(), e->position().y(),
797 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
799 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
803 // If we're above or below the work area...
804 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
805 if ((e->position().y() <= 20 || e->position().y() >= viewport()->height() - 20)
807 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
809 && e->buttons() == mouse_button::button1) {
810 // Make sure only a synthetic event can cause a page scroll,
811 // so they come at a steady rate:
812 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
813 if (e->position().y() <= 20)
814 // _Force_ a scroll up:
815 cmd.set_y(e->position().y() - 21);
817 cmd.set_y(e->position().y() + 21);
820 // _Force_ a scroll up:
821 cmd.set_y(e->y() - 21);
823 cmd.set_y(e->y() + 21);
825 // Store the event, to be handled when the timeout expires.
826 d->synthetic_mouse_event_.cmd = cmd;
828 if (d->synthetic_mouse_event_.timeout.running()) {
829 // Discard the event. Note that it _may_ be handled
830 // when the timeout expires if
831 // synthetic_mouse_event_.cmd has not been overwritten.
832 // Ie, when the timeout expires, we handle the
833 // most recent event but discard all others that
834 // occurred after the one used to start the timeout
835 // in the first place.
839 d->synthetic_mouse_event_.restart_timeout = true;
840 d->synthetic_mouse_event_.timeout.start();
841 // Fall through to handle this event...
843 } else if (d->synthetic_mouse_event_.timeout.running()) {
844 // Store the event, to be possibly handled when the timeout
846 // Once the timeout has expired, normal control is returned
847 // to mouseMoveEvent (restart_timeout = false).
848 // This results in a much smoother 'feel' when moving the
849 // mouse back into the work area.
850 d->synthetic_mouse_event_.cmd = cmd;
851 d->synthetic_mouse_event_.restart_timeout = false;
858 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
860 // Wheel rotation by one notch results in a delta() of 120 (see
861 // documentation of QWheelEvent)
862 // But first we have to ignore horizontal scroll events.
863 #if QT_VERSION < 0x050000
864 if (ev->orientation() == Qt::Horizontal) {
868 double const delta = ev->delta() / 120.0;
870 QPoint const aDelta = ev->angleDelta();
871 // skip horizontal wheel event
872 if (abs(aDelta.x()) > abs(aDelta.y())) {
876 double const delta = aDelta.y() / 120.0;
880 switch (lyxrc.scroll_wheel_zoom) {
881 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
882 zoom = ev->modifiers() & Qt::ControlModifier;
883 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
885 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
886 zoom = ev->modifiers() & Qt::ShiftModifier;
887 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
889 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
890 zoom = ev->modifiers() & Qt::AltModifier;
891 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
893 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
897 docstring arg = convert<docstring>(int(5 * delta));
898 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
902 // Take into account the desktop wide settings.
903 int const lines = qApp->wheelScrollLines();
904 int const page_step = verticalScrollBar()->pageStep();
905 // Test if the wheel mouse is set to one screen at a time.
906 // This is according to
907 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
909 min(lines * verticalScrollBar()->singleStep(), page_step);
911 // Take into account the rotation and the user preferences.
912 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
913 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
914 << " delta = " << delta << " scroll_value = " << scroll_value
915 << " page_step = " << page_step);
917 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
923 void GuiWorkArea::generateSyntheticMouseEvent()
925 int const e_y = d->synthetic_mouse_event_.cmd.y();
926 int const wh = d->buffer_view_->workHeight();
927 bool const up = e_y < 0;
928 bool const down = e_y > wh;
930 // Set things off to generate the _next_ 'pseudo' event.
932 if (d->synthetic_mouse_event_.restart_timeout) {
933 // This is some magic formulae to determine the speed
934 // of scrolling related to the position of the mouse.
937 int dist = up ? -e_y : e_y - wh;
938 time = max(min(200, 250000 / (dist * dist)), 1) ;
941 step = 80000 / (time * time);
945 d->synthetic_mouse_event_.timeout.setTimeout(time);
946 d->synthetic_mouse_event_.timeout.start();
949 // Can we scroll further ?
950 int const value = verticalScrollBar()->value();
951 if (value == verticalScrollBar()->maximum()
952 || value == verticalScrollBar()->minimum()) {
953 d->synthetic_mouse_event_.timeout.stop();
958 if (step <= 2 * wh) {
959 d->buffer_view_->scroll(up ? -step : step);
960 d->buffer_view_->updateMetrics();
962 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
965 // In which paragraph do we have to set the cursor ?
966 Cursor & cur = d->buffer_view_->cursor();
967 // FIXME: we don't know how to handle math.
968 Text * text = cur.text();
971 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
973 // Quit gracefully if there are no metrics, since otherwise next
974 // line would crash (bug #10324).
975 // This situation seems related to a (not yet understood) timing problem.
979 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
980 ParagraphMetrics const & pm = *pp.second;
981 pit_type const pit = pp.first;
983 if (pm.rows().empty())
986 // Find the row at which we set the cursor.
987 RowList::const_iterator rit = pm.rows().begin();
988 RowList::const_iterator rlast = pm.rows().end();
989 int yy = pm.position() - pm.ascent();
990 for (--rlast; rit != rlast; ++rit) {
991 int h = rit->height();
992 if ((up && yy + h > 0)
993 || (!up && yy + h > wh - defaultRowHeight()))
998 // Find the position of the cursor
1000 int x = d->synthetic_mouse_event_.cmd.x();
1001 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1006 cur.boundary(bound);
1008 d->buffer_view_->buffer().changed(false);
1012 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
1013 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
1015 qRegisterMetaType<KeySymbol>("KeySymbol");
1016 qRegisterMetaType<KeyModifier>("KeyModifier");
1017 connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
1018 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
1019 Qt::QueuedConnection);
1020 connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
1021 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1025 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1029 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1030 bool result = flag_;
1036 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1038 if (emitCheck(isAutoRepeat))
1039 Q_EMIT signal(sym, mod);
1041 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1045 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1047 // this is also called for ShortcutOverride events. In this case, one must
1048 // not act but simply accept the event explicitly.
1049 bool const act = (ev->type() != QEvent::ShortcutOverride);
1051 // Do not process here some keys if dialog_mode_ is set
1052 bool const for_dialog_mode = d->dialog_mode_
1053 && (ev->modifiers() == Qt::NoModifier
1054 || ev->modifiers() == Qt::ShiftModifier)
1055 && (ev->key() == Qt::Key_Escape
1056 || ev->key() == Qt::Key_Enter
1057 || ev->key() == Qt::Key_Return);
1058 // also do not use autoRepeat to input shortcuts
1059 bool const autoRepeat = ev->isAutoRepeat();
1061 if (for_dialog_mode || (!act && autoRepeat)) {
1066 // intercept some keys if completion popup is visible
1067 if (d->completer_->popupVisible()) {
1068 switch (ev->key()) {
1070 case Qt::Key_Return:
1072 d->completer_->activate();
1078 KeyModifier const m = q_key_state(ev->modifiers());
1080 if (act && lyxerr.debugging(Debug::KEY)) {
1082 if (m & ShiftModifier)
1084 if (m & ControlModifier)
1086 if (m & AltModifier)
1088 if (m & MetaModifier)
1090 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1091 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1092 << " keyState: " << str);
1096 setKeySymbol(&sym, ev);
1099 Q_EMIT compressKeySym(sym, m, autoRepeat);
1102 // here, !autoRepeat, as determined at the beginning
1103 ev->setAccepted(queryKeySym(sym, m));
1110 void GuiWorkArea::doubleClickTimeout()
1112 d->dc_event_.active = false;
1116 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1118 d->dc_event_ = DoubleClick(ev);
1119 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1120 SLOT(doubleClickTimeout()));
1121 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
1122 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->position().x(), ev->position().y(),
1124 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1126 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1132 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1134 QAbstractScrollArea::resizeEvent(ev);
1135 d->need_resize_ = true;
1140 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1142 if (preedit_string_.empty())
1145 // FIXME: shall we use real_current_font here? (see #10478)
1146 FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1147 FontMetrics const & fm = theFontMetrics(font);
1150 buffer_view_->caretPosAndDim(point, dim);
1151 int cur_x = point.x_;
1152 int cur_y = point.y_ + dim.height();
1154 // get attributes of input method cursor.
1155 // cursor_pos : cursor position in preedit string.
1156 size_t cursor_pos = 0;
1157 bool cursor_is_visible = false;
1158 for (auto const & attr : preedit_attr_) {
1159 if (attr.type == QInputMethodEvent::Cursor) {
1160 cursor_pos = size_t(attr.start);
1161 cursor_is_visible = attr.length != 0;
1166 size_t const preedit_length = preedit_string_.length();
1168 // get position of selection in input method.
1169 // FIXME: isn't there a simpler way to do this?
1170 // rStart : cursor position in selected string in IM.
1172 // rLength : selected string length in IM.
1174 if (cursor_pos < preedit_length) {
1175 for (auto const & attr : preedit_attr_) {
1176 if (attr.type == QInputMethodEvent::TextFormat) {
1177 if (attr.start <= int(cursor_pos)
1178 && int(cursor_pos) < attr.start + attr.length) {
1179 rStart = size_t(attr.start);
1180 rLength = size_t(attr.length);
1181 if (!cursor_is_visible)
1182 cursor_pos += rLength;
1189 rStart = cursor_pos;
1193 int const right_margin = buffer_view_->rightMargin();
1194 Painter::preedit_style ps;
1195 // Most often there would be only one line:
1197 for (size_t pos = 0; pos != preedit_length; ++pos) {
1198 char_type const typed_char = preedit_string_[pos];
1199 // reset preedit string style
1200 ps = Painter::preedit_default;
1202 // if we reached the right extremity of the screen, go to next line.
1203 if (cur_x + fm.width(typed_char) > p->viewport()->width() - right_margin) {
1204 cur_x = right_margin;
1205 cur_y += dim.height() + 1;
1208 // preedit strings are displayed with dashed underline
1209 // and partial strings are displayed white on black indicating
1210 // that we are in selecting mode in the input method.
1211 // FIXME: rLength == preedit_length is not a changing condition
1212 // FIXME: should be put out of the loop.
1214 && pos < rStart + rLength
1215 && !(cursor_pos < rLength && rLength == preedit_length))
1216 ps = Painter::preedit_selecting;
1218 if (pos == cursor_pos
1219 && (cursor_pos < rLength && rLength == preedit_length))
1220 ps = Painter::preedit_cursor;
1222 // draw one character and update cur_x.
1223 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1228 void GuiWorkArea::Private::resetScreen()
1230 if (use_backingstore_) {
1231 int const pr = p->pixelRatio();
1232 screen_ = QImage(pr * p->viewport()->width(),
1233 pr * p->viewport()->height(),
1234 QImage::Format_ARGB32_Premultiplied);
1235 # if QT_VERSION >= 0x050000
1236 screen_.setDevicePixelRatio(pr);
1242 QPaintDevice * GuiWorkArea::Private::screenDevice()
1244 if (use_backingstore_)
1247 return p->viewport();
1251 void GuiWorkArea::Private::updateScreen(QRectF const & rc)
1253 if (use_backingstore_) {
1254 QPainter qpain(p->viewport());
1255 double const pr = p->pixelRatio();
1256 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr,
1257 rc.width() * pr, rc.height() * pr);
1258 qpain.drawImage(rc, screen_, rcs);
1263 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1265 // Do not trigger the painting machinery if we are not ready (see
1266 // bug #10989). The second test triggers when in the middle of a
1267 // dispatch operation.
1268 if (view().busy() || d->buffer_view_->buffer().undo().activeUndoGroup()) {
1269 // Since macOS has turned the screen black at this point, our
1270 // backing store has to be copied to screen (this is a no-op
1271 // except on macOS).
1272 d->updateScreen(ev->rect());
1273 // Ignore this paint event, but request a new one for later.
1274 viewport()->update(ev->rect());
1279 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1280 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1282 if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_) {
1284 d->resizeBufferView();
1287 d->last_pixel_ratio_ = pixelRatio();
1289 GuiPainter pain(d->screenDevice(), pixelRatio(), d->lyx_view_->develMode());
1291 d->buffer_view_->draw(pain, d->caret_visible_);
1293 // The preedit text, if needed
1294 d->paintPreeditText(pain);
1297 // FIXME: the code would be a little bit simpler if caret geometry
1298 // was updated unconditionally. Some profiling is required to see
1299 // how expensive this is (especially when idle).
1300 if (d->caret_visible_) {
1301 if (d->needs_caret_geometry_update_)
1302 d->updateCaretGeometry();
1303 d->drawCaret(pain, d->buffer_view_->horizScrollOffset());
1306 d->updateScreen(ev->rect());
1312 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1314 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1315 << " commitString: " << e->commitString());
1317 if (!e->commitString().isEmpty()) {
1319 // take care of commit string assigned to a shortcut
1320 // e.g. quotation mark on international keyboard
1322 for (QChar const & ch : e->commitString()) {
1324 keysym.init(ch.unicode());
1325 keyseq.addkey(keysym, NoModifier);
1327 cmd = theTopLevelKeymap().getBinding(keyseq);
1329 if (cmd == FuncRequest::noaction || cmd == FuncRequest::unknown
1330 || cmd.action() == LFUN_SELF_INSERT)
1331 // insert the processed text in the document (handles undo)
1332 cmd = FuncRequest(LFUN_SELF_INSERT, qstring_to_ucs4(e->commitString()));
1334 cmd.setOrigin(FuncRequest::KEYBOARD);
1336 // FIXME: this is supposed to remove traces from preedit
1337 // string. Can we avoid calling it explicitly?
1338 d->buffer_view_->updateMetrics();
1341 // Hide the caret during the test transformation.
1342 if (e->preeditString().isEmpty())
1343 startBlinkingCaret();
1345 stopBlinkingCaret();
1347 if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1353 // The preedit text and its attributes will be used in paintPreeditText
1354 d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1355 d->preedit_attr_ = e->attributes();
1358 // redraw area of preedit string.
1359 // int height = d->caret_->dim.height();
1360 // int cur_y = d->caret_->y;
1361 // viewport()->update(0, cur_y, viewport()->width(),
1362 // (height + 1) * d->preedit_lines_);
1363 viewport()->update();
1365 if (d->preedit_string_.empty()) {
1366 d->preedit_lines_ = 1;
1371 // Don't forget to accept the event!
1376 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1379 // this is the CJK-specific composition window position and
1380 // the context menu position when the menu key is pressed.
1381 #if (QT_VERSION < 0x050000)
1382 case Qt::ImMicroFocus: {
1384 case Qt::ImCursorRectangle: {
1386 CaretGeometry const & cg = bufferView().caretGeometry();
1387 return QRect(cg.left - 10 * (d->preedit_lines_ != 1),
1388 cg.top + cg.height() * d->preedit_lines_,
1389 cg.width(), cg.height());
1392 return QWidget::inputMethodQuery(query);
1397 void GuiWorkArea::updateWindowTitle()
1399 Buffer const & buf = bufferView().buffer();
1400 if (buf.fileName() != d->file_name_
1401 || buf.params().shell_escape != d->shell_escape_
1402 || buf.hasReadonlyFlag() != d->read_only_
1403 || buf.lyxvc().vcstatus() != d->vc_status_
1404 || buf.isClean() != d->clean_
1405 || buf.notifiesExternalModification() != d->externally_modified_) {
1406 d->file_name_ = buf.fileName();
1407 d->shell_escape_ = buf.params().shell_escape;
1408 d->read_only_ = buf.hasReadonlyFlag();
1409 d->vc_status_ = buf.lyxvc().vcstatus();
1410 d->clean_ = buf.isClean();
1411 d->externally_modified_ = buf.notifiesExternalModification();
1412 Q_EMIT titleChanged(this);
1417 bool GuiWorkArea::isFullScreen() const
1419 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1423 bool GuiWorkArea::inDialogMode() const
1425 return d->dialog_mode_;
1429 void GuiWorkArea::setDialogMode(bool mode)
1431 d->dialog_mode_ = mode;
1435 GuiCompleter & GuiWorkArea::completer()
1437 return *d->completer_;
1440 GuiView const & GuiWorkArea::view() const
1442 return *d->lyx_view_;
1446 GuiView & GuiWorkArea::view()
1448 return *d->lyx_view_;
1451 ////////////////////////////////////////////////////////////////////
1455 ////////////////////////////////////////////////////////////////////
1458 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1460 support::TempFile tempfile("embedded.internal");
1461 tempfile.setAutoRemove(false);
1462 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1463 buffer_->setUnnamed(true);
1464 buffer_->setFullyLoaded(true);
1465 setBuffer(*buffer_);
1466 setDialogMode(true);
1470 EmbeddedWorkArea::~EmbeddedWorkArea()
1472 // No need to destroy buffer and bufferview here, because it is done
1473 // in theBufferList() destruction loop at application exit
1477 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1480 GuiWorkArea::closeEvent(ev);
1484 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1487 GuiWorkArea::hideEvent(ev);
1491 QSize EmbeddedWorkArea::sizeHint () const
1494 // GuiWorkArea sets the size to the screen's viewport
1495 // by returning a value this gets overridden
1496 // EmbeddedWorkArea is now sized to fit in the layout
1497 // of the parent, and has a minimum size set in GuiWorkArea
1498 // which is what we return here
1499 return QSize(100, 70);
1503 void EmbeddedWorkArea::disable()
1505 stopBlinkingCaret();
1506 if (view().currentWorkArea() != this)
1508 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1509 // tolerates it and shows the background logo), what happens if
1510 // an EmbeddedWorkArea is closed after closing all document WAs
1511 view().setCurrentWorkArea(view().currentMainWorkArea());
1514 ////////////////////////////////////////////////////////////////////
1518 ////////////////////////////////////////////////////////////////////
1520 TabWorkArea::TabWorkArea(QWidget * parent)
1521 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1523 QPalette pal = palette();
1524 pal.setColor(QPalette::Active, QPalette::Button,
1525 pal.color(QPalette::Active, QPalette::Window));
1526 pal.setColor(QPalette::Disabled, QPalette::Button,
1527 pal.color(QPalette::Disabled, QPalette::Window));
1528 pal.setColor(QPalette::Inactive, QPalette::Button,
1529 pal.color(QPalette::Inactive, QPalette::Window));
1531 QObject::connect(this, SIGNAL(currentChanged(int)),
1532 this, SLOT(on_currentTabChanged(int)));
1534 closeBufferButton = new QToolButton(this);
1535 closeBufferButton->setPalette(pal);
1536 // FIXME: rename the icon to closebuffer.png
1537 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1538 closeBufferButton->setText("Close File");
1539 closeBufferButton->setAutoRaise(true);
1540 closeBufferButton->setCursor(Qt::ArrowCursor);
1541 closeBufferButton->setToolTip(qt_("Close File"));
1542 closeBufferButton->setEnabled(true);
1543 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1544 this, SLOT(closeCurrentBuffer()));
1545 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1547 // set TabBar behaviour
1548 QTabBar * tb = tabBar();
1549 tb->setTabsClosable(!lyxrc.single_close_tab_button);
1550 tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1551 tb->setElideMode(Qt::ElideNone);
1552 // allow dragging tabs
1553 tb->setMovable(true);
1554 // make us responsible for the context menu of the tabbar
1555 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1556 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1557 this, SLOT(showContextMenu(const QPoint &)));
1558 connect(tb, SIGNAL(tabCloseRequested(int)),
1559 this, SLOT(closeTab(int)));
1561 setUsesScrollButtons(true);
1563 // use document mode tabs
1564 setDocumentMode(true);
1569 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1571 if (me->button() == Qt::MiddleButton)
1572 midpressed_tab_ = tabBar()->tabAt(me->pos());
1574 QTabWidget::mousePressEvent(me);
1578 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1580 if (me->button() == Qt::MiddleButton) {
1581 int const midreleased_tab = tabBar()->tabAt(me->pos());
1582 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1583 closeTab(midreleased_tab);
1585 QTabWidget::mouseReleaseEvent(me);
1589 void TabWorkArea::paintEvent(QPaintEvent * event)
1591 if (tabBar()->isVisible()) {
1592 QTabWidget::paintEvent(event);
1594 // Prevent the selected tab to influence the
1595 // painting of the frame of the tab widget.
1596 // This is needed for gtk style in Qt.
1597 QStylePainter p(this);
1598 #if QT_VERSION < 0x050000
1599 QStyleOptionTabWidgetFrameV2 opt;
1601 QStyleOptionTabWidgetFrame opt;
1603 initStyleOption(&opt);
1604 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1606 opt.selectedTabRect = QRect();
1607 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1612 bool TabWorkArea::posIsTab(QPoint position)
1614 // tabAt returns -1 if tab does not covers position
1615 return tabBar()->tabAt(position) > -1;
1619 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1621 if (event->button() != Qt::LeftButton)
1624 // this code chunk is unnecessary because it seems the event only makes
1625 // it this far if it is not on a tab. I'm not sure why this is (maybe
1626 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1627 // this is true in all cases and if it will be true in the future so I
1628 // leave this code for now. (skostysh, 2016-07-21)
1630 // return early if double click on existing tabs
1631 if (posIsTab(event->pos()))
1634 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1638 void TabWorkArea::setFullScreen(bool full_screen)
1640 for (int i = 0; i != count(); ++i) {
1641 if (GuiWorkArea * wa = workArea(i))
1642 wa->setFullScreen(full_screen);
1645 if (lyxrc.full_screen_tabbar)
1646 showBar(!full_screen && count() > 1);
1648 showBar(count() > 1);
1652 void TabWorkArea::showBar(bool show)
1654 tabBar()->setEnabled(show);
1655 tabBar()->setVisible(show);
1656 if (documentMode()) {
1657 // avoid blank corner widget when documentMode(true) is used
1658 if (show && lyxrc.single_close_tab_button) {
1659 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1660 closeBufferButton->setVisible(true);
1662 // remove corner widget
1663 setCornerWidget(nullptr);
1665 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1666 setTabsClosable(!lyxrc.single_close_tab_button);
1670 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1672 QWidget * w = QTabWidget::widget(index);
1675 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1681 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1683 return widget(currentIndex());
1687 GuiWorkArea * TabWorkArea::workArea(int index) const
1689 GuiWorkAreaContainer * w = widget(index);
1692 return w->workArea();
1696 GuiWorkArea * TabWorkArea::currentWorkArea() const
1698 return workArea(currentIndex());
1702 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1704 // FIXME: this method doesn't work if we have more than one work area
1705 // showing the same buffer.
1706 for (int i = 0; i != count(); ++i) {
1707 GuiWorkArea * wa = workArea(i);
1708 LASSERT(wa, return nullptr);
1709 if (&wa->bufferView().buffer() == &buffer)
1716 void TabWorkArea::closeAll()
1719 QWidget * wac = widget(0);
1720 LASSERT(wac, return);
1727 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1729 for (int index = 0; index < count(); ++index)
1730 if (workArea(index) == w)
1736 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1738 LASSERT(work_area, return false);
1739 int index = indexOfWorkArea(work_area);
1743 if (index == currentIndex())
1744 // Make sure the work area is up to date.
1745 on_currentTabChanged(index);
1747 // Switch to the work area.
1748 setCurrentIndex(index);
1749 work_area->setFocus();
1755 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1757 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1758 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1759 wa->setUpdatesEnabled(false);
1760 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1761 // when hiding it again below).
1762 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1763 showBar(count() > 0);
1764 addTab(wac, wa->windowTitle());
1765 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1766 this, SLOT(updateTabTexts()));
1767 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1768 setFullScreen(true);
1770 // Hide tabbar if there's only one tab.
1771 showBar(count() > 1);
1779 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1781 LASSERT(work_area, return false);
1782 int index = indexOfWorkArea(work_area);
1786 work_area->setUpdatesEnabled(false);
1787 QWidget * wac = widget(index);
1792 // make sure the next work area is enabled.
1793 currentWidget()->setUpdatesEnabled(true);
1794 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1795 setFullScreen(true);
1797 // Show tabbar only if there's more than one tab.
1798 showBar(count() > 1);
1800 lastWorkAreaRemoved();
1808 void TabWorkArea::on_currentTabChanged(int i)
1810 // returns e.g. on application destruction
1813 GuiWorkArea * wa = workArea(i);
1814 LASSERT(wa, return);
1815 wa->setUpdatesEnabled(true);
1816 wa->scheduleRedraw(true);
1819 currentWorkAreaChanged(wa);
1821 LYXERR(Debug::GUI, "currentTabChanged " << i
1822 << " File: " << wa->bufferView().buffer().absFileName());
1826 void TabWorkArea::closeCurrentBuffer()
1829 if (clicked_tab_ == -1)
1830 wa = currentWorkArea();
1832 wa = workArea(clicked_tab_);
1833 LASSERT(wa, return);
1835 wa->view().closeWorkArea(wa);
1839 void TabWorkArea::hideCurrentTab()
1842 if (clicked_tab_ == -1)
1843 wa = currentWorkArea();
1845 wa = workArea(clicked_tab_);
1846 LASSERT(wa, return);
1848 wa->view().hideWorkArea(wa);
1852 void TabWorkArea::closeTab(int index)
1854 on_currentTabChanged(index);
1857 wa = currentWorkArea();
1859 wa = workArea(index);
1860 LASSERT(wa, return);
1862 wa->view().closeWorkArea(wa);
1869 /// make vector happy
1870 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1872 DisplayPath(int tab, FileName const & filename)
1875 // Recode URL encoded chars via fromPercentEncoding()
1876 string const fn = (filename.extension() == "lyx")
1877 ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
1878 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
1879 #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
1880 postfix_ = toqstr(filename.absoluteFilePath()).
1881 split("/", Qt::SkipEmptyParts);
1883 postfix_ = toqstr(filename.absoluteFilePath()).
1884 split("/", QString::SkipEmptyParts);
1886 postfix_.pop_back();
1887 abs_ = toqstr(filename.absoluteFilePath());
1888 dottedPrefix_ = false;
1891 /// Absolute path for debugging.
1896 /// Add the first segment from the postfix or three dots to the prefix.
1897 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1898 /// when really needed.
1899 void shiftPathSegment(bool dotted)
1901 if (postfix_.count() <= 0)
1905 if (dottedPrefix_ && !prefix_.isEmpty())
1906 prefix_ += ellipsisSlash_;
1907 prefix_ += postfix_.front() + "/";
1909 dottedPrefix_ = dotted && !prefix_.isEmpty();
1910 postfix_.pop_front();
1913 QString displayString() const
1915 if (prefix_.isEmpty())
1918 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1919 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1922 QString forecastPathString() const
1924 if (postfix_.count() == 0)
1925 return displayString();
1928 + (dottedPrefix_ ? ellipsisSlash_ : "")
1929 + postfix_.front() + "/";
1932 bool final() const { return postfix_.empty(); }
1934 int tab() const { return tab_; }
1938 static QString const ellipsisSlash_;
1942 QStringList postfix_;
1954 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1958 bool operator<(DisplayPath const & a, DisplayPath const & b)
1960 return a.displayString() < b.displayString();
1964 bool operator==(DisplayPath const & a, DisplayPath const & b)
1966 return a.displayString() == b.displayString();
1970 void TabWorkArea::updateTabTexts()
1972 int const n = count();
1975 std::list<DisplayPath> paths;
1976 typedef std::list<DisplayPath>::iterator It;
1978 // collect full names first: path into postfix, empty prefix and
1979 // filename without extension
1980 for (int i = 0; i < n; ++i) {
1981 GuiWorkArea * i_wa = workArea(i);
1982 FileName const fn = i_wa->bufferView().buffer().fileName();
1983 paths.push_back(DisplayPath(i, fn));
1986 // go through path segments and see if it helps to make the path more unique
1987 bool somethingChanged = true;
1988 bool allFinal = false;
1989 while (somethingChanged && !allFinal) {
1990 // adding path segments changes order
1993 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1994 somethingChanged = false;
1997 // find segments which are not unique (i.e. non-atomic)
1998 It it = paths.begin();
2000 QString segString = it->displayString();
2001 for (; it != paths.end(); ++it) {
2002 // look to the next item
2007 allFinal = allFinal && it->final();
2009 LYXERR(Debug::GUI, "it = " << it->abs()
2010 << " => " << it->displayString());
2012 // still the same segment?
2014 if ((next != paths.end()
2015 && (nextString = next->displayString()) == segString))
2017 LYXERR(Debug::GUI, "segment ended");
2019 // only a trivial one with one element?
2020 if (it == segStart) {
2021 // start new segment
2023 segString = nextString;
2027 // We found a non-atomic segment
2028 // We know that segStart <= it < next <= paths.end().
2029 // The assertion below tells coverity about it.
2030 LATTEST(segStart != paths.end());
2031 QString dspString = segStart->forecastPathString();
2032 LYXERR(Debug::GUI, "first forecast found for "
2033 << segStart->abs() << " => " << dspString);
2036 // Shift path segments and hope for the best
2037 // that it makes the path more unique.
2038 somethingChanged = true;
2039 bool moreUnique = false;
2040 for (; sit != next; ++sit) {
2041 if (sit->forecastPathString() != dspString) {
2042 LYXERR(Debug::GUI, "different forecast found for "
2043 << sit->abs() << " => " << sit->forecastPathString());
2047 LYXERR(Debug::GUI, "same forecast found for "
2048 << sit->abs() << " => " << dspString);
2051 // if the path segment helped, add it. Otherwise add dots
2052 bool dots = !moreUnique;
2053 LYXERR(Debug::GUI, "using dots = " << dots);
2054 for (sit = segStart; sit != next; ++sit) {
2055 sit->shiftPathSegment(dots);
2056 LYXERR(Debug::GUI, "shifting "
2057 << sit->abs() << " => " << sit->displayString());
2060 // start new segment
2062 segString = nextString;
2066 // set new tab titles
2067 for (It it = paths.begin(); it != paths.end(); ++it) {
2068 int const tab_index = it->tab();
2069 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2070 QString tab_text = it->displayString().replace("&", "&&");
2071 if (!buf.fileName().empty() && !buf.isClean())
2073 QString tab_tooltip = it->abs();
2074 if (buf.hasReadonlyFlag()) {
2076 QLabel * readOnlyButton = new QLabel();
2077 QIcon icon = QIcon(getPixmap("images/", "emblem-readonly", "svgz,png"));
2078 readOnlyButton->setPixmap(icon.pixmap(QSize(16, 16)));
2079 tabBar()->setTabButton(tab_index, QTabBar::RightSide, readOnlyButton);
2081 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2083 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2086 tabBar()->setTabButton(tab_index, QTabBar::RightSide, 0);
2088 setTabIcon(tab_index, QIcon());
2090 if (buf.notifiesExternalModification()) {
2091 QString const warn = qt_("%1 (modified externally)");
2092 tab_tooltip = warn.arg(tab_tooltip);
2093 tab_text += QChar(0x26a0);
2095 setTabText(tab_index, tab_text);
2096 setTabToolTip(tab_index, tab_tooltip);
2101 void TabWorkArea::showContextMenu(const QPoint & pos)
2104 clicked_tab_ = tabBar()->tabAt(pos);
2105 if (clicked_tab_ == -1)
2108 GuiWorkArea * wa = workArea(clicked_tab_);
2109 LASSERT(wa, return);
2113 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2114 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2116 // we want to show the 'close' option only if this is not a child buffer.
2117 Buffer const & buf = wa->bufferView().buffer();
2119 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2120 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2121 popup.exec(tabBar()->mapToGlobal(pos));
2127 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2129 QWidget * w = widget(fromIndex);
2130 QIcon icon = tabIcon(fromIndex);
2131 QString text = tabText(fromIndex);
2133 setCurrentIndex(fromIndex);
2134 removeTab(fromIndex);
2135 insertTab(toIndex, w, icon, text);
2136 setCurrentIndex(toIndex);
2140 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2141 : QWidget(parent), wa_(wa)
2143 LASSERT(wa, return);
2144 Ui::WorkAreaUi::setupUi(this);
2145 layout()->addWidget(wa);
2146 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2147 this, SLOT(updateDisplay()));
2148 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2149 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2150 setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2155 void GuiWorkAreaContainer::updateDisplay()
2157 Buffer const & buf = wa_->bufferView().buffer();
2158 notificationFrame->setHidden(!buf.notifiesExternalModification());
2159 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2160 .arg(toqstr(buf.fileName().displayName()));
2161 externalModificationLabel->setText(label);
2165 void GuiWorkAreaContainer::dispatch(FuncRequest const & f) const
2167 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2168 wa_->bufferView().buffer().absFileName()));
2173 void GuiWorkAreaContainer::reload() const
2175 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2179 void GuiWorkAreaContainer::ignore() const
2181 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2185 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2187 // prevent TabWorkArea from opening a new buffer on double click
2192 } // namespace frontend
2195 #include "moc_GuiWorkArea.cpp"