2 * \file GuiWorkArea.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Abdelrazak Younes
9 * Full author contact details are available in file CREDITS.
14 #include "GuiWorkArea.h"
15 #include "GuiWorkArea_Private.h"
17 #include "ColorCache.h"
18 #include "GuiApplication.h"
19 #include "GuiCompleter.h"
20 #include "GuiKeySymbol.h"
21 #include "GuiPainter.h"
24 #include "qt_helpers.h"
27 #include "BufferList.h"
28 #include "BufferParams.h"
29 #include "BufferView.h"
30 #include "CoordCache.h"
33 #include "FuncRequest.h"
34 #include "KeySymbol.h"
39 #include "TextMetrics.h"
43 #include "graphics/GraphicsImage.h"
44 #include "graphics/GraphicsLoader.h"
46 #include "support/convert.h"
47 #include "support/debug.h"
48 #include "support/lassert.h"
49 #include "support/TempFile.h"
51 #include "frontends/Application.h"
52 #include "frontends/CaretGeometry.h"
54 #include "frontends/FontMetrics.h"
55 #include "frontends/WorkAreaManager.h"
57 #include <QContextMenuEvent>
58 #if (QT_VERSION < 0x050000)
59 #include <QInputContext>
64 #include <QProxyStyle>
66 #include <QMainWindow>
72 #include <QStyleOption>
73 #include <QStylePainter>
75 #include <QToolButton>
86 using namespace lyx::support;
91 /// return the LyX mouse button state from Qt's
92 static mouse_button::state q_button_state(Qt::MouseButton button)
94 mouse_button::state b = mouse_button::none;
97 b = mouse_button::button1;
100 b = mouse_button::button2;
102 case Qt::RightButton:
103 b = mouse_button::button3;
112 /// return the LyX mouse button state from Qt's
113 mouse_button::state q_motion_state(Qt::MouseButtons state)
115 mouse_button::state b = mouse_button::none;
116 if (state & Qt::LeftButton)
117 b |= mouse_button::button1;
118 if (state & Qt::MidButton)
119 b |= mouse_button::button2;
120 if (state & Qt::RightButton)
121 b |= mouse_button::button3;
128 // This is a 'heartbeat' generating synthetic mouse move events when the
129 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
130 SyntheticMouseEvent::SyntheticMouseEvent()
131 : timeout(200), restart_timeout(true)
135 GuiWorkArea::Private::Private(GuiWorkArea * parent)
136 : p(parent), buffer_view_(nullptr), lyx_view_(nullptr),
137 caret_visible_(false), need_resize_(false), preedit_lines_(1),
138 last_pixel_ratio_(1.0), completer_(new GuiCompleter(p, p)),
139 dialog_mode_(false), shell_escape_(false), read_only_(false),
140 clean_(true), externally_modified_(false), needs_caret_geometry_update_(true)
142 /* Qt on macOS and Wayland does not respect the
143 * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
144 * store at each update. Therefore, we use our own backing store in
145 * these two cases. */
146 #if QT_VERSION >= 0x050000
147 use_backingstore_ = guiApp->platformName() == "cocoa"
148 || guiApp->platformName().contains("wayland");
151 use_backingstore_ = true;
153 use_backingstore_ = false;
157 int const time = QApplication::cursorFlashTime() / 2;
159 caret_timeout_.setInterval(time);
160 caret_timeout_.start();
162 // let's initialize this just to be safe
163 caret_timeout_.setInterval(500);
168 GuiWorkArea::Private::~Private()
170 // If something is wrong with the buffer, we can ignore it safely
172 buffer_view_->buffer().workAreaManager().remove(p);
175 // Completer has a QObject parent and is thus automatically destroyed.
177 // delete completer_;
181 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
182 : d(new Private(this))
184 new CompressorProxy(this); // not a leak
188 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
189 : d(new Private(this))
191 new CompressorProxy(this); // not a leak
193 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
199 double GuiWorkArea::pixelRatio() const
201 #if QT_VERSION >= 0x050000
202 return qt_scale_factor * devicePixelRatio();
209 void GuiWorkArea::init()
212 connect(&d->caret_timeout_, SIGNAL(timeout()),
213 this, SLOT(toggleCaret()));
215 // This connection is closed at the same time as this is destroyed.
216 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
217 generateSyntheticMouseEvent();
221 // With Qt4.5 a mouse event will happen before the first paint event
222 // so make sure that the buffer view has an up to date metrics.
223 d->buffer_view_->resize(viewport()->width(), viewport()->height());
225 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
226 setAcceptDrops(true);
227 setMouseTracking(true);
228 setMinimumSize(100, 70);
229 setFrameStyle(QFrame::NoFrame);
232 d->updateCursorShape();
234 // we paint our own background
235 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
237 setFocusPolicy(Qt::StrongFocus);
239 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
240 << " viewport height: " << viewport()->height());
242 // Enables input methods for asian languages.
243 // Must be set when creating custom text editing widgets.
244 setAttribute(Qt::WA_InputMethodEnabled, true);
248 GuiWorkArea::~GuiWorkArea()
254 void GuiWorkArea::Private::updateCursorShape()
256 bool const clickable = buffer_view_ && buffer_view_->clickableInset();
257 p->viewport()->setCursor(clickable ? Qt::PointingHandCursor
262 void GuiWorkArea::setGuiView(GuiView & gv)
268 void GuiWorkArea::setBuffer(Buffer & buffer)
270 delete d->buffer_view_;
271 d->buffer_view_ = new BufferView(buffer);
272 buffer.workAreaManager().add(this);
274 // HACK: Prevents an additional redraw when the scrollbar pops up
275 // which regularly happens on documents with more than one page.
276 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
277 // Since we have no geometry information yet, we assume that
278 // a document needs a scrollbar if there is more then four
279 // paragraph in the outermost text.
280 if (buffer.text().paragraphs().size() > 4)
281 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
282 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
283 Q_EMIT bufferViewChanged();
287 void GuiWorkArea::fixVerticalScrollBar()
290 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
294 void GuiWorkArea::close()
296 d->lyx_view_->removeWorkArea(this);
300 void GuiWorkArea::setFullScreen(bool full_screen)
302 d->buffer_view_->setFullScreen(full_screen);
303 if (full_screen && lyxrc.full_screen_scrollbar)
304 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
306 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
310 BufferView & GuiWorkArea::bufferView()
312 return *d->buffer_view_;
316 BufferView const & GuiWorkArea::bufferView() const
318 return *d->buffer_view_;
322 void GuiWorkArea::stopBlinkingCaret()
324 d->caret_timeout_.stop();
329 void GuiWorkArea::startBlinkingCaret()
331 // do not show the cursor if the view is busy
335 // Don't start blinking if the cursor isn't on screen, unless we
336 // are not ready to know whether the cursor is on screen.
337 if (!d->buffer_view_->buffer().undo().activeUndoGroup()
338 && !d->buffer_view_->caretInView())
343 // Avoid blinking when debugging PAINTING, since it creates too much noise
344 if (!lyxerr.debugging(Debug::PAINTING)) {
345 // we are not supposed to cache this value.
346 int const time = QApplication::cursorFlashTime() / 2;
349 d->caret_timeout_.setInterval(time);
350 d->caret_timeout_.start();
355 void GuiWorkArea::toggleCaret()
357 if (d->caret_visible_)
364 void GuiWorkArea::scheduleRedraw(bool update_metrics)
367 // No need to redraw in this case.
370 // No need to do anything if this is the current view. The BufferView
371 // metrics are already up to date.
372 if (update_metrics || d->lyx_view_ != guiApp->currentView()
373 || d->lyx_view_->currentWorkArea() != this) {
374 // FIXME: it would be nice to optimize for the off-screen case.
375 d->buffer_view_->cursor().fixIfBroken();
376 d->buffer_view_->updateMetrics();
377 d->buffer_view_->cursor().fixIfBroken();
380 // update caret position, because otherwise it has to wait until
381 // the blinking interval is over
384 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
385 viewport()->update();
387 /// FIXME: is this still true now that paintEvent does the actual painting?
388 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
389 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
390 d->updateScrollbar();
391 d->lyx_view_->updateStatusBar();
393 if (lyxerr.debugging(Debug::WORKAREA))
394 d->buffer_view_->coordCache().dump();
398 d->updateCursorShape();
402 // Keep in sync with GuiWorkArea::processKeySym below
403 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
405 return guiApp->queryKeySym(key, mod);
409 // Keep in sync with GuiWorkArea::queryKeySym above
410 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
412 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
413 && lyxrc.full_screen_menubar) {
414 // FIXME HACK: we should not have to do this here. See related comment
415 // in GuiView::event() (QEvent::ShortcutOverride)
416 d->lyx_view_->menuBar()->hide();
419 // In order to avoid bad surprise in the middle of an operation,
420 // we better stop the blinking caret...
421 // the caret gets restarted in GuiView::restartCaret()
423 guiApp->processKeySym(key, mod);
427 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
430 if (cmd.action() == LFUN_FILE_OPEN) {
432 lyx_view_->dispatch(cmd, dr);
436 bool const notJustMovingTheMouse =
437 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
439 // In order to avoid bad surprise in the middle of an operation, we better stop
440 // the blinking caret.
441 if (notJustMovingTheMouse)
442 p->stopBlinkingCaret();
444 buffer_view_->mouseEventDispatch(cmd);
446 // Skip these when selecting
447 // FIXME: let GuiView take care of those.
448 if (cmd.action() != LFUN_MOUSE_MOTION) {
449 completer_->updateVisibility(false, false);
450 lyx_view_->updateDialogs();
451 lyx_view_->updateStatusBar();
454 // GUI tweaks except with mouse motion with no button pressed.
455 if (notJustMovingTheMouse) {
456 // Slight hack: this is only called currently when we
457 // clicked somewhere, so we force through the display
458 // of the new status here.
459 // FIXME: let GuiView take care of those.
460 lyx_view_->clearMessage();
462 // Show the caret immediately after any operation
463 p->startBlinkingCaret();
470 void GuiWorkArea::Private::resizeBufferView()
472 // WARNING: Please don't put any code that will trigger a repaint here!
473 // We are already inside a paint event.
474 p->stopBlinkingCaret();
475 // Warn our container (GuiView).
478 bool const caret_in_view = buffer_view_->caretInView();
479 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
481 buffer_view_->scrollToCursor();
484 // Update scrollbars which might have changed due different
485 // BufferView dimension. This is especially important when the
486 // BufferView goes from zero-size to the real-size for the first time,
487 // as the scrollbar parameters are then set for the first time.
490 need_resize_ = false;
492 // Eventually, restart the caret after the resize event.
493 // We might be resizing even if the focus is on another widget so we only
494 // restart the caret if we have the focus.
496 QTimer::singleShot(50, p, SLOT(startBlinkingCaret()));
500 void GuiWorkArea::Private::resetCaret()
502 // Don't start blinking if the cursor isn't on screen.
503 if (!buffer_view_->caretInView())
506 // completion indicator
507 Cursor const & cur = buffer_view_->cursor();
508 bool const completable = cur.inset().showCompletionCursor()
509 && completer_->completionAvailable()
510 && !completer_->popupVisible()
511 && !completer_->inlineVisible();
513 buffer_view_->buildCaretGeometry(completable);
515 needs_caret_geometry_update_ = true;
516 caret_visible_ = true;
520 void GuiWorkArea::Private::updateCaretGeometry()
522 // we cannot update geometry if not ready and we do not need to if
523 // caret is not in view.
524 if (buffer_view_->buffer().undo().activeUndoGroup()
525 || !buffer_view_->caretInView())
529 needs_caret_geometry_update_ = false;
533 void GuiWorkArea::Private::showCaret()
539 p->viewport()->update();
543 void GuiWorkArea::Private::hideCaret()
548 caret_visible_ = false;
549 //if (!qApp->focusWidget())
550 p->viewport()->update();
554 /* Draw the caret. Parameter \c horiz_offset is not 0 when there
555 * has been horizontal scrolling in current row
557 void GuiWorkArea::Private::drawCaret(QPainter & painter, int horiz_offset) const
559 if (buffer_view_->caretGeometry().shapes.empty())
562 QColor const color = guiApp->colorCache().get(Color_cursor);
563 painter.setPen(color);
564 painter.setRenderHint(QPainter::Antialiasing, true);
565 for (auto const & shape : buffer_view_->caretGeometry().shapes) {
568 for (Point const & p : shape) {
570 path.moveTo(p.x_ - horiz_offset, p.y_);
573 path.lineTo(p.x_ - horiz_offset, p.y_);
575 painter.fillPath(path, color);
577 painter.setRenderHint(QPainter::Antialiasing, false);
581 void GuiWorkArea::Private::updateScrollbar()
583 // Prevent setRange() and setSliderPosition from causing recursive calls via
584 // the signal valueChanged. (#10311)
585 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
586 p, SLOT(scrollTo(int)));
587 ScrollbarParameters const & scroll = buffer_view_->scrollbarParameters();
588 p->verticalScrollBar()->setRange(scroll.min, scroll.max);
589 p->verticalScrollBar()->setPageStep(scroll.page_step);
590 p->verticalScrollBar()->setSingleStep(scroll.single_step);
591 p->verticalScrollBar()->setSliderPosition(0);
592 // Connect to the vertical scroll bar
593 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
594 p, SLOT(scrollTo(int)));
598 void GuiWorkArea::scrollTo(int value)
601 d->buffer_view_->scrollDocView(value, true);
603 if (lyxrc.cursor_follows_scrollbar) {
604 d->buffer_view_->setCursorFromScrollbar();
605 // FIXME: let GuiView take care of those.
606 d->lyx_view_->updateLayoutList();
608 // Show the caret immediately after any operation.
609 startBlinkingCaret();
612 QApplication::syncX();
617 bool GuiWorkArea::event(QEvent * e)
620 case QEvent::ToolTip: {
621 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
622 if (lyxrc.use_tooltip) {
623 QPoint pos = helpEvent->pos();
624 if (pos.x() < viewport()->width()) {
625 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
626 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
629 QToolTip::hideText();
631 // Don't forget to accept the event!
636 case QEvent::ShortcutOverride:
637 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
639 keyPressEvent(static_cast<QKeyEvent *>(e));
640 return e->isAccepted();
642 case QEvent::KeyPress: {
643 // We catch this event in order to catch the Tab or Shift+Tab key press
644 // which are otherwise reserved to focus switching between controls
646 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
647 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
648 || (ke->key() == Qt::Key_Backtab && (
649 ke->modifiers() == Qt::ShiftModifier
650 || ke->modifiers() == Qt::NoModifier))) {
654 return QAbstractScrollArea::event(e);
658 return QAbstractScrollArea::event(e);
664 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
667 if (e->reason() == QContextMenuEvent::Mouse)
668 // the menu name is set on mouse press
669 name = d->context_menu_name_;
671 QPoint pos = e->pos();
672 Cursor const & cur = d->buffer_view_->cursor();
673 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
674 // Do not access the context menu of math right in front of before
675 // the cursor. This does not work when the cursor is in text.
676 Inset * inset = cur.paragraph().getInset(cur.pos());
677 if (inset && inset->asInsetMath())
679 else if (cur.pos() > 0) {
680 inset = cur.paragraph().getInset(cur.pos() - 1);
685 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
692 // always show mnemonics when the keyboard is used to show the context menu
693 // FIXME: This should be fixed in Qt itself
694 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
695 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
700 // Position the menu to the right.
701 // FIXME: menu position should be different for RTL text.
702 menu->exec(e->globalPos());
707 void GuiWorkArea::focusInEvent(QFocusEvent * e)
709 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
710 if (d->lyx_view_->currentWorkArea() != this) {
711 d->lyx_view_->setCurrentWorkArea(this);
712 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
715 startBlinkingCaret();
716 QAbstractScrollArea::focusInEvent(e);
720 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
722 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
724 QAbstractScrollArea::focusOutEvent(e);
728 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
730 if (d->dc_event_.active && d->dc_event_ == *e) {
731 d->dc_event_.active = false;
732 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
733 q_button_state(e->button()), q_key_state(e->modifiers()));
739 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
740 inputContext()->reset();
743 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
744 q_button_state(e->button()), q_key_state(e->modifiers()));
747 // Save the context menu on mouse press, because also the mouse
748 // cursor is set on mouse press. Afterwards, we can either release
749 // the mousebutton somewhere else, or the cursor might have moved
750 // due to the DEPM. We need to do this after the mouse has been
751 // set in dispatch(), because the selection state might change.
752 if (e->button() == Qt::RightButton)
753 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
759 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
761 if (d->synthetic_mouse_event_.timeout.running())
762 d->synthetic_mouse_event_.timeout.stop();
764 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 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
795 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
799 // If we're above or below the work area...
800 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
801 && e->buttons() == mouse_button::button1) {
802 // Make sure only a synthetic event can cause a page scroll,
803 // so they come at a steady rate:
805 // _Force_ a scroll up:
806 cmd.set_y(e->y() - 21);
808 cmd.set_y(e->y() + 21);
809 // Store the event, to be handled when the timeout expires.
810 d->synthetic_mouse_event_.cmd = cmd;
812 if (d->synthetic_mouse_event_.timeout.running()) {
813 // Discard the event. Note that it _may_ be handled
814 // when the timeout expires if
815 // synthetic_mouse_event_.cmd has not been overwritten.
816 // Ie, when the timeout expires, we handle the
817 // most recent event but discard all others that
818 // occurred after the one used to start the timeout
819 // in the first place.
823 d->synthetic_mouse_event_.restart_timeout = true;
824 d->synthetic_mouse_event_.timeout.start();
825 // Fall through to handle this event...
827 } else if (d->synthetic_mouse_event_.timeout.running()) {
828 // Store the event, to be possibly handled when the timeout
830 // Once the timeout has expired, normal control is returned
831 // to mouseMoveEvent (restart_timeout = false).
832 // This results in a much smoother 'feel' when moving the
833 // mouse back into the work area.
834 d->synthetic_mouse_event_.cmd = cmd;
835 d->synthetic_mouse_event_.restart_timeout = false;
842 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
844 // Wheel rotation by one notch results in a delta() of 120 (see
845 // documentation of QWheelEvent)
846 // But first we have to ignore horizontal scroll events.
847 #if QT_VERSION < 0x050000
848 if (ev->orientation() == Qt::Horizontal) {
852 double const delta = ev->delta() / 120.0;
854 QPoint const aDelta = ev->angleDelta();
855 // skip horizontal wheel event
856 if (abs(aDelta.x()) > abs(aDelta.y())) {
860 double const delta = aDelta.y() / 120.0;
864 switch (lyxrc.scroll_wheel_zoom) {
865 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
866 zoom = ev->modifiers() & Qt::ControlModifier;
867 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
869 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
870 zoom = ev->modifiers() & Qt::ShiftModifier;
871 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
873 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
874 zoom = ev->modifiers() & Qt::AltModifier;
875 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
877 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
881 docstring arg = convert<docstring>(int(5 * delta));
882 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
886 // Take into account the desktop wide settings.
887 int const lines = qApp->wheelScrollLines();
888 int const page_step = verticalScrollBar()->pageStep();
889 // Test if the wheel mouse is set to one screen at a time.
890 // This is according to
891 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
893 min(lines * verticalScrollBar()->singleStep(), page_step);
895 // Take into account the rotation and the user preferences.
896 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
897 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
898 << " delta = " << delta << " scroll_value = " << scroll_value
899 << " page_step = " << page_step);
901 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
907 void GuiWorkArea::generateSyntheticMouseEvent()
909 int const e_y = d->synthetic_mouse_event_.cmd.y();
910 int const wh = d->buffer_view_->workHeight();
911 bool const up = e_y < 0;
912 bool const down = e_y > wh;
914 // Set things off to generate the _next_ 'pseudo' event.
916 if (d->synthetic_mouse_event_.restart_timeout) {
917 // This is some magic formulae to determine the speed
918 // of scrolling related to the position of the mouse.
921 int dist = up ? -e_y : e_y - wh;
922 time = max(min(200, 250000 / (dist * dist)), 1) ;
925 step = 80000 / (time * time);
929 d->synthetic_mouse_event_.timeout.setTimeout(time);
930 d->synthetic_mouse_event_.timeout.start();
933 // Can we scroll further ?
934 int const value = verticalScrollBar()->value();
935 if (value == verticalScrollBar()->maximum()
936 || value == verticalScrollBar()->minimum()) {
937 d->synthetic_mouse_event_.timeout.stop();
942 if (step <= 2 * wh) {
943 d->buffer_view_->scroll(up ? -step : step);
944 d->buffer_view_->updateMetrics();
946 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
949 // In which paragraph do we have to set the cursor ?
950 Cursor & cur = d->buffer_view_->cursor();
951 // FIXME: we don't know how to handle math.
952 Text * text = cur.text();
955 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
957 // Quit gracefully if there are no metrics, since otherwise next
958 // line would crash (bug #10324).
959 // This situation seems related to a (not yet understood) timing problem.
963 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
964 ParagraphMetrics const & pm = *pp.second;
965 pit_type const pit = pp.first;
967 if (pm.rows().empty())
970 // Find the row at which we set the cursor.
971 RowList::const_iterator rit = pm.rows().begin();
972 RowList::const_iterator rlast = pm.rows().end();
973 int yy = pm.position() - pm.ascent();
974 for (--rlast; rit != rlast; ++rit) {
975 int h = rit->height();
976 if ((up && yy + h > 0)
977 || (!up && yy + h > wh - defaultRowHeight()))
982 // Find the position of the cursor
984 int x = d->synthetic_mouse_event_.cmd.x();
985 pos_type const pos = tm.getPosNearX(*rit, x, bound);
992 d->buffer_view_->buffer().changed(false);
996 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
997 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
999 qRegisterMetaType<KeySymbol>("KeySymbol");
1000 qRegisterMetaType<KeyModifier>("KeyModifier");
1001 connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
1002 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
1003 Qt::QueuedConnection);
1004 connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
1005 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1009 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1013 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1014 bool result = flag_;
1020 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1022 if (emitCheck(isAutoRepeat))
1023 Q_EMIT signal(sym, mod);
1025 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1029 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1031 // this is also called for ShortcutOverride events. In this case, one must
1032 // not act but simply accept the event explicitly.
1033 bool const act = (ev->type() != QEvent::ShortcutOverride);
1035 // Do not process here some keys if dialog_mode_ is set
1036 bool const for_dialog_mode = d->dialog_mode_
1037 && (ev->modifiers() == Qt::NoModifier
1038 || ev->modifiers() == Qt::ShiftModifier)
1039 && (ev->key() == Qt::Key_Escape
1040 || ev->key() == Qt::Key_Enter
1041 || ev->key() == Qt::Key_Return);
1042 // also do not use autoRepeat to input shortcuts
1043 bool const autoRepeat = ev->isAutoRepeat();
1045 if (for_dialog_mode || (!act && autoRepeat)) {
1050 // intercept some keys if completion popup is visible
1051 if (d->completer_->popupVisible()) {
1052 switch (ev->key()) {
1054 case Qt::Key_Return:
1056 d->completer_->activate();
1062 KeyModifier const m = q_key_state(ev->modifiers());
1064 if (act && lyxerr.debugging(Debug::KEY)) {
1066 if (m & ShiftModifier)
1068 if (m & ControlModifier)
1070 if (m & AltModifier)
1072 if (m & MetaModifier)
1074 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1075 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1076 << " keyState: " << str);
1080 setKeySymbol(&sym, ev);
1083 Q_EMIT compressKeySym(sym, m, autoRepeat);
1086 // here, !autoRepeat, as determined at the beginning
1087 ev->setAccepted(queryKeySym(sym, m));
1094 void GuiWorkArea::doubleClickTimeout()
1096 d->dc_event_.active = false;
1100 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1102 d->dc_event_ = DoubleClick(ev);
1103 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1104 SLOT(doubleClickTimeout()));
1105 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1106 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1112 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1114 QAbstractScrollArea::resizeEvent(ev);
1115 d->need_resize_ = true;
1120 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1122 if (preedit_string_.empty())
1125 // FIXME: shall we use real_current_font here? (see #10478)
1126 FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1127 FontMetrics const & fm = theFontMetrics(font);
1130 buffer_view_->caretPosAndDim(point, dim);
1131 int cur_x = point.x_;
1132 int cur_y = point.y_ + dim.height();
1134 // get attributes of input method cursor.
1135 // cursor_pos : cursor position in preedit string.
1136 size_t cursor_pos = 0;
1137 bool cursor_is_visible = false;
1138 for (auto const & attr : preedit_attr_) {
1139 if (attr.type == QInputMethodEvent::Cursor) {
1140 cursor_pos = size_t(attr.start);
1141 cursor_is_visible = attr.length != 0;
1146 size_t const preedit_length = preedit_string_.length();
1148 // get position of selection in input method.
1149 // FIXME: isn't there a simpler way to do this?
1150 // rStart : cursor position in selected string in IM.
1152 // rLength : selected string length in IM.
1154 if (cursor_pos < preedit_length) {
1155 for (auto const & attr : preedit_attr_) {
1156 if (attr.type == QInputMethodEvent::TextFormat) {
1157 if (attr.start <= int(cursor_pos)
1158 && int(cursor_pos) < attr.start + attr.length) {
1159 rStart = size_t(attr.start);
1160 rLength = size_t(attr.length);
1161 if (!cursor_is_visible)
1162 cursor_pos += rLength;
1169 rStart = cursor_pos;
1173 int const right_margin = buffer_view_->rightMargin();
1174 Painter::preedit_style ps;
1175 // Most often there would be only one line:
1177 for (size_t pos = 0; pos != preedit_length; ++pos) {
1178 char_type const typed_char = preedit_string_[pos];
1179 // reset preedit string style
1180 ps = Painter::preedit_default;
1182 // if we reached the right extremity of the screen, go to next line.
1183 if (cur_x + fm.width(typed_char) > p->viewport()->width() - right_margin) {
1184 cur_x = right_margin;
1185 cur_y += dim.height() + 1;
1188 // preedit strings are displayed with dashed underline
1189 // and partial strings are displayed white on black indicating
1190 // that we are in selecting mode in the input method.
1191 // FIXME: rLength == preedit_length is not a changing condition
1192 // FIXME: should be put out of the loop.
1194 && pos < rStart + rLength
1195 && !(cursor_pos < rLength && rLength == preedit_length))
1196 ps = Painter::preedit_selecting;
1198 if (pos == cursor_pos
1199 && (cursor_pos < rLength && rLength == preedit_length))
1200 ps = Painter::preedit_cursor;
1202 // draw one character and update cur_x.
1203 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1208 void GuiWorkArea::Private::resetScreen()
1210 if (use_backingstore_) {
1211 int const pr = p->pixelRatio();
1212 screen_ = QImage(static_cast<int>(pr * p->viewport()->width()),
1213 static_cast<int>(pr * p->viewport()->height()),
1214 QImage::Format_ARGB32_Premultiplied);
1215 # if QT_VERSION >= 0x050000
1216 screen_.setDevicePixelRatio(pr);
1222 QPaintDevice * GuiWorkArea::Private::screenDevice()
1224 if (use_backingstore_)
1227 return p->viewport();
1231 void GuiWorkArea::Private::updateScreen(QRectF const & rc)
1233 if (use_backingstore_) {
1234 QPainter qpain(p->viewport());
1235 double const pr = p->pixelRatio();
1236 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr,
1237 rc.width() * pr, rc.height() * pr);
1238 qpain.drawImage(rc, screen_, rcs);
1243 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1245 // Do not trigger the painting machinery if we are not ready (see
1246 // bug #10989). The second test triggers when in the middle of a
1247 // dispatch operation.
1248 if (view().busy() || d->buffer_view_->buffer().undo().activeUndoGroup()) {
1249 // Since macOS has turned the screen black at this point, our
1250 // backing store has to be copied to screen (this is a no-op
1251 // except on macOS).
1252 d->updateScreen(ev->rect());
1253 // Ignore this paint event, but request a new one for later.
1254 viewport()->update(ev->rect());
1259 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1260 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1262 if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_) {
1264 d->resizeBufferView();
1267 d->last_pixel_ratio_ = pixelRatio();
1269 GuiPainter pain(d->screenDevice(), pixelRatio(), d->lyx_view_->develMode());
1271 d->buffer_view_->draw(pain, d->caret_visible_);
1273 // The preedit text, if needed
1274 d->paintPreeditText(pain);
1277 // FIXME: the code would be a little bit simpler if caret geometry
1278 // was updated unconditionally. Some profiling is required to see
1279 // how expensive this is (especially when idle).
1280 if (d->caret_visible_) {
1281 if (d->needs_caret_geometry_update_)
1282 d->updateCaretGeometry();
1283 d->drawCaret(pain, d->buffer_view_->horizScrollOffset());
1286 d->updateScreen(ev->rect());
1292 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1294 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1295 << " commitString: " << e->commitString());
1297 // insert the processed text in the document (handles undo)
1298 if (!e->commitString().isEmpty()) {
1299 FuncRequest cmd(LFUN_SELF_INSERT,
1300 qstring_to_ucs4(e->commitString()),
1301 FuncRequest::KEYBOARD);
1303 // FIXME: this is supposed to remove traces from preedit
1304 // string. Can we avoid calling it explicitly?
1305 d->buffer_view_->updateMetrics();
1308 // Hide the caret during the test transformation.
1309 if (e->preeditString().isEmpty())
1310 startBlinkingCaret();
1312 stopBlinkingCaret();
1314 if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1320 // The preedit text and its attributes will be used in paintPreeditText
1321 d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1322 d->preedit_attr_ = e->attributes();
1325 // redraw area of preedit string.
1326 // int height = d->caret_->dim.height();
1327 // int cur_y = d->caret_->y;
1328 // viewport()->update(0, cur_y, viewport()->width(),
1329 // (height + 1) * d->preedit_lines_);
1330 viewport()->update();
1332 if (d->preedit_string_.empty()) {
1333 d->preedit_lines_ = 1;
1338 // Don't forget to accept the event!
1343 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1346 // this is the CJK-specific composition window position and
1347 // the context menu position when the menu key is pressed.
1348 case Qt::ImMicroFocus: {
1349 CaretGeometry const & cg = bufferView().caretGeometry();
1350 return QRect(cg.left - 10 * (d->preedit_lines_ != 1),
1351 cg.top + cg.height() * d->preedit_lines_,
1352 cg.width(), cg.height());
1355 return QWidget::inputMethodQuery(query);
1360 void GuiWorkArea::updateWindowTitle()
1362 Buffer const & buf = bufferView().buffer();
1363 if (buf.fileName() != d->file_name_
1364 || buf.params().shell_escape != d->shell_escape_
1365 || buf.hasReadonlyFlag() != d->read_only_
1366 || buf.lyxvc().vcstatus() != d->vc_status_
1367 || buf.isClean() != d->clean_
1368 || buf.notifiesExternalModification() != d->externally_modified_) {
1369 d->file_name_ = buf.fileName();
1370 d->shell_escape_ = buf.params().shell_escape;
1371 d->read_only_ = buf.hasReadonlyFlag();
1372 d->vc_status_ = buf.lyxvc().vcstatus();
1373 d->clean_ = buf.isClean();
1374 d->externally_modified_ = buf.notifiesExternalModification();
1375 Q_EMIT titleChanged(this);
1380 bool GuiWorkArea::isFullScreen() const
1382 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1386 bool GuiWorkArea::inDialogMode() const
1388 return d->dialog_mode_;
1392 void GuiWorkArea::setDialogMode(bool mode)
1394 d->dialog_mode_ = mode;
1398 GuiCompleter & GuiWorkArea::completer()
1400 return *d->completer_;
1403 GuiView const & GuiWorkArea::view() const
1405 return *d->lyx_view_;
1409 GuiView & GuiWorkArea::view()
1411 return *d->lyx_view_;
1414 ////////////////////////////////////////////////////////////////////
1418 ////////////////////////////////////////////////////////////////////
1421 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1423 support::TempFile tempfile("embedded.internal");
1424 tempfile.setAutoRemove(false);
1425 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1426 buffer_->setUnnamed(true);
1427 buffer_->setFullyLoaded(true);
1428 setBuffer(*buffer_);
1429 setDialogMode(true);
1433 EmbeddedWorkArea::~EmbeddedWorkArea()
1435 // No need to destroy buffer and bufferview here, because it is done
1436 // in theBufferList() destruction loop at application exit
1440 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1443 GuiWorkArea::closeEvent(ev);
1447 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1450 GuiWorkArea::hideEvent(ev);
1454 QSize EmbeddedWorkArea::sizeHint () const
1457 // GuiWorkArea sets the size to the screen's viewport
1458 // by returning a value this gets overridden
1459 // EmbeddedWorkArea is now sized to fit in the layout
1460 // of the parent, and has a minimum size set in GuiWorkArea
1461 // which is what we return here
1462 return QSize(100, 70);
1466 void EmbeddedWorkArea::disable()
1468 stopBlinkingCaret();
1469 if (view().currentWorkArea() != this)
1471 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1472 // tolerates it and shows the background logo), what happens if
1473 // an EmbeddedWorkArea is closed after closing all document WAs
1474 view().setCurrentWorkArea(view().currentMainWorkArea());
1477 ////////////////////////////////////////////////////////////////////
1481 ////////////////////////////////////////////////////////////////////
1484 class NoTabFrameMacStyle : public QProxyStyle {
1487 QRect subElementRect(SubElement element, const QStyleOption * option,
1488 const QWidget * widget = 0) const
1490 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1491 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1493 // The Qt Mac style puts the contents into a 3 pixel wide box
1494 // which looks very ugly and not like other Mac applications.
1495 // Hence we remove this here, and moreover the 16 pixel round
1496 // frame above if the tab bar is hidden.
1497 if (element == QStyle::SE_TabWidgetTabContents) {
1498 rect.adjust(- rect.left(), 0, rect.left(), 0);
1507 NoTabFrameMacStyle noTabFrameMacStyle;
1511 TabWorkArea::TabWorkArea(QWidget * parent)
1512 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1515 setStyle(&noTabFrameMacStyle);
1518 QPalette pal = palette();
1519 pal.setColor(QPalette::Active, QPalette::Button,
1520 pal.color(QPalette::Active, QPalette::Window));
1521 pal.setColor(QPalette::Disabled, QPalette::Button,
1522 pal.color(QPalette::Disabled, QPalette::Window));
1523 pal.setColor(QPalette::Inactive, QPalette::Button,
1524 pal.color(QPalette::Inactive, QPalette::Window));
1526 QObject::connect(this, SIGNAL(currentChanged(int)),
1527 this, SLOT(on_currentTabChanged(int)));
1529 closeBufferButton = new QToolButton(this);
1530 closeBufferButton->setPalette(pal);
1531 // FIXME: rename the icon to closebuffer.png
1532 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1533 closeBufferButton->setText("Close File");
1534 closeBufferButton->setAutoRaise(true);
1535 closeBufferButton->setCursor(Qt::ArrowCursor);
1536 closeBufferButton->setToolTip(qt_("Close File"));
1537 closeBufferButton->setEnabled(true);
1538 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1539 this, SLOT(closeCurrentBuffer()));
1540 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1542 // set TabBar behaviour
1543 QTabBar * tb = tabBar();
1544 tb->setTabsClosable(!lyxrc.single_close_tab_button);
1545 tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1546 tb->setElideMode(Qt::ElideNone);
1547 // allow dragging tabs
1548 tb->setMovable(true);
1549 // make us responsible for the context menu of the tabbar
1550 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1551 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1552 this, SLOT(showContextMenu(const QPoint &)));
1553 connect(tb, SIGNAL(tabCloseRequested(int)),
1554 this, SLOT(closeTab(int)));
1556 setUsesScrollButtons(true);
1560 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1562 if (me->button() == Qt::MidButton)
1563 midpressed_tab_ = tabBar()->tabAt(me->pos());
1565 QTabWidget::mousePressEvent(me);
1569 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1571 if (me->button() == Qt::MidButton) {
1572 int const midreleased_tab = tabBar()->tabAt(me->pos());
1573 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1574 closeTab(midreleased_tab);
1576 QTabWidget::mouseReleaseEvent(me);
1580 void TabWorkArea::paintEvent(QPaintEvent * event)
1582 if (tabBar()->isVisible()) {
1583 QTabWidget::paintEvent(event);
1585 // Prevent the selected tab to influence the
1586 // painting of the frame of the tab widget.
1587 // This is needed for gtk style in Qt.
1588 QStylePainter p(this);
1589 #if QT_VERSION < 0x050000
1590 QStyleOptionTabWidgetFrameV2 opt;
1592 QStyleOptionTabWidgetFrame opt;
1594 initStyleOption(&opt);
1595 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1597 opt.selectedTabRect = QRect();
1598 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1603 bool TabWorkArea::posIsTab(QPoint position)
1605 // tabAt returns -1 if tab does not covers position
1606 return tabBar()->tabAt(position) > -1;
1610 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1612 if (event->button() != Qt::LeftButton)
1615 // this code chunk is unnecessary because it seems the event only makes
1616 // it this far if it is not on a tab. I'm not sure why this is (maybe
1617 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1618 // this is true in all cases and if it will be true in the future so I
1619 // leave this code for now. (skostysh, 2016-07-21)
1621 // return early if double click on existing tabs
1622 if (posIsTab(event->pos()))
1625 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1629 void TabWorkArea::setFullScreen(bool full_screen)
1631 for (int i = 0; i != count(); ++i) {
1632 if (GuiWorkArea * wa = workArea(i))
1633 wa->setFullScreen(full_screen);
1636 if (lyxrc.full_screen_tabbar)
1637 showBar(!full_screen && count() > 1);
1639 showBar(count() > 1);
1643 void TabWorkArea::showBar(bool show)
1645 tabBar()->setEnabled(show);
1646 tabBar()->setVisible(show);
1647 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1648 setTabsClosable(!lyxrc.single_close_tab_button);
1652 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1654 QWidget * w = QTabWidget::widget(index);
1657 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1663 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1665 return widget(currentIndex());
1669 GuiWorkArea * TabWorkArea::workArea(int index) const
1671 GuiWorkAreaContainer * w = widget(index);
1674 return w->workArea();
1678 GuiWorkArea * TabWorkArea::currentWorkArea() const
1680 return workArea(currentIndex());
1684 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1686 // FIXME: this method doesn't work if we have more than one work area
1687 // showing the same buffer.
1688 for (int i = 0; i != count(); ++i) {
1689 GuiWorkArea * wa = workArea(i);
1690 LASSERT(wa, return nullptr);
1691 if (&wa->bufferView().buffer() == &buffer)
1698 void TabWorkArea::closeAll()
1701 QWidget * wac = widget(0);
1702 LASSERT(wac, return);
1709 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1711 for (int index = 0; index < count(); ++index)
1712 if (workArea(index) == w)
1718 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1720 LASSERT(work_area, return false);
1721 int index = indexOfWorkArea(work_area);
1725 if (index == currentIndex())
1726 // Make sure the work area is up to date.
1727 on_currentTabChanged(index);
1729 // Switch to the work area.
1730 setCurrentIndex(index);
1731 work_area->setFocus();
1737 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1739 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1740 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1741 wa->setUpdatesEnabled(false);
1742 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1743 // when hiding it again below).
1744 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1745 showBar(count() > 0);
1746 addTab(wac, wa->windowTitle());
1747 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1748 this, SLOT(updateTabTexts()));
1749 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1750 setFullScreen(true);
1752 // Hide tabbar if there's only one tab.
1753 showBar(count() > 1);
1761 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1763 LASSERT(work_area, return false);
1764 int index = indexOfWorkArea(work_area);
1768 work_area->setUpdatesEnabled(false);
1769 QWidget * wac = widget(index);
1774 // make sure the next work area is enabled.
1775 currentWidget()->setUpdatesEnabled(true);
1776 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1777 setFullScreen(true);
1779 // Show tabbar only if there's more than one tab.
1780 showBar(count() > 1);
1782 lastWorkAreaRemoved();
1790 void TabWorkArea::on_currentTabChanged(int i)
1792 // returns e.g. on application destruction
1795 GuiWorkArea * wa = workArea(i);
1796 LASSERT(wa, return);
1797 wa->setUpdatesEnabled(true);
1798 wa->scheduleRedraw(true);
1801 currentWorkAreaChanged(wa);
1803 LYXERR(Debug::GUI, "currentTabChanged " << i
1804 << " File: " << wa->bufferView().buffer().absFileName());
1808 void TabWorkArea::closeCurrentBuffer()
1811 if (clicked_tab_ == -1)
1812 wa = currentWorkArea();
1814 wa = workArea(clicked_tab_);
1815 LASSERT(wa, return);
1817 wa->view().closeWorkArea(wa);
1821 void TabWorkArea::hideCurrentTab()
1824 if (clicked_tab_ == -1)
1825 wa = currentWorkArea();
1827 wa = workArea(clicked_tab_);
1828 LASSERT(wa, return);
1830 wa->view().hideWorkArea(wa);
1834 void TabWorkArea::closeTab(int index)
1836 on_currentTabChanged(index);
1839 wa = currentWorkArea();
1841 wa = workArea(index);
1842 LASSERT(wa, return);
1844 wa->view().closeWorkArea(wa);
1851 /// make vector happy
1852 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1854 DisplayPath(int tab, FileName const & filename)
1857 // Recode URL encoded chars via fromPercentEncoding()
1858 string const fn = (filename.extension() == "lyx")
1859 ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
1860 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
1861 postfix_ = toqstr(filename.absoluteFilePath()).
1862 split("/", QString::SkipEmptyParts);
1863 postfix_.pop_back();
1864 abs_ = toqstr(filename.absoluteFilePath());
1865 dottedPrefix_ = false;
1868 /// Absolute path for debugging.
1873 /// Add the first segment from the postfix or three dots to the prefix.
1874 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1875 /// when really needed.
1876 void shiftPathSegment(bool dotted)
1878 if (postfix_.count() <= 0)
1882 if (dottedPrefix_ && !prefix_.isEmpty())
1883 prefix_ += ellipsisSlash_;
1884 prefix_ += postfix_.front() + "/";
1886 dottedPrefix_ = dotted && !prefix_.isEmpty();
1887 postfix_.pop_front();
1890 QString displayString() const
1892 if (prefix_.isEmpty())
1895 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1896 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1899 QString forecastPathString() const
1901 if (postfix_.count() == 0)
1902 return displayString();
1905 + (dottedPrefix_ ? ellipsisSlash_ : "")
1906 + postfix_.front() + "/";
1909 bool final() const { return postfix_.empty(); }
1911 int tab() const { return tab_; }
1915 static QString const ellipsisSlash_;
1919 QStringList postfix_;
1931 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1935 bool operator<(DisplayPath const & a, DisplayPath const & b)
1937 return a.displayString() < b.displayString();
1941 bool operator==(DisplayPath const & a, DisplayPath const & b)
1943 return a.displayString() == b.displayString();
1947 void TabWorkArea::updateTabTexts()
1949 int const n = count();
1952 std::list<DisplayPath> paths;
1953 typedef std::list<DisplayPath>::iterator It;
1955 // collect full names first: path into postfix, empty prefix and
1956 // filename without extension
1957 for (int i = 0; i < n; ++i) {
1958 GuiWorkArea * i_wa = workArea(i);
1959 FileName const fn = i_wa->bufferView().buffer().fileName();
1960 paths.push_back(DisplayPath(i, fn));
1963 // go through path segments and see if it helps to make the path more unique
1964 bool somethingChanged = true;
1965 bool allFinal = false;
1966 while (somethingChanged && !allFinal) {
1967 // adding path segments changes order
1970 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1971 somethingChanged = false;
1974 // find segments which are not unique (i.e. non-atomic)
1975 It it = paths.begin();
1977 QString segString = it->displayString();
1978 for (; it != paths.end(); ++it) {
1979 // look to the next item
1984 allFinal = allFinal && it->final();
1986 LYXERR(Debug::GUI, "it = " << it->abs()
1987 << " => " << it->displayString());
1989 // still the same segment?
1991 if ((next != paths.end()
1992 && (nextString = next->displayString()) == segString))
1994 LYXERR(Debug::GUI, "segment ended");
1996 // only a trivial one with one element?
1997 if (it == segStart) {
1998 // start new segment
2000 segString = nextString;
2004 // We found a non-atomic segment
2005 // We know that segStart <= it < next <= paths.end().
2006 // The assertion below tells coverity about it.
2007 LATTEST(segStart != paths.end());
2008 QString dspString = segStart->forecastPathString();
2009 LYXERR(Debug::GUI, "first forecast found for "
2010 << segStart->abs() << " => " << dspString);
2013 // Shift path segments and hope for the best
2014 // that it makes the path more unique.
2015 somethingChanged = true;
2016 bool moreUnique = false;
2017 for (; sit != next; ++sit) {
2018 if (sit->forecastPathString() != dspString) {
2019 LYXERR(Debug::GUI, "different forecast found for "
2020 << sit->abs() << " => " << sit->forecastPathString());
2024 LYXERR(Debug::GUI, "same forecast found for "
2025 << sit->abs() << " => " << dspString);
2028 // if the path segment helped, add it. Otherwise add dots
2029 bool dots = !moreUnique;
2030 LYXERR(Debug::GUI, "using dots = " << dots);
2031 for (sit = segStart; sit != next; ++sit) {
2032 sit->shiftPathSegment(dots);
2033 LYXERR(Debug::GUI, "shifting "
2034 << sit->abs() << " => " << sit->displayString());
2037 // start new segment
2039 segString = nextString;
2043 // set new tab titles
2044 for (It it = paths.begin(); it != paths.end(); ++it) {
2045 int const tab_index = it->tab();
2046 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2047 QString tab_text = it->displayString().replace("&", "&&");
2048 if (!buf.fileName().empty() && !buf.isClean())
2050 QString tab_tooltip = it->abs();
2051 if (buf.hasReadonlyFlag()) {
2052 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2053 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2055 setTabIcon(tab_index, QIcon());
2056 if (buf.notifiesExternalModification()) {
2057 QString const warn = qt_("%1 (modified externally)");
2058 tab_tooltip = warn.arg(tab_tooltip);
2059 tab_text += QChar(0x26a0);
2061 setTabText(tab_index, tab_text);
2062 setTabToolTip(tab_index, tab_tooltip);
2067 void TabWorkArea::showContextMenu(const QPoint & pos)
2070 clicked_tab_ = tabBar()->tabAt(pos);
2071 if (clicked_tab_ == -1)
2074 GuiWorkArea * wa = workArea(clicked_tab_);
2075 LASSERT(wa, return);
2079 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2080 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2082 // we want to show the 'close' option only if this is not a child buffer.
2083 Buffer const & buf = wa->bufferView().buffer();
2085 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2086 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2087 popup.exec(tabBar()->mapToGlobal(pos));
2093 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2095 QWidget * w = widget(fromIndex);
2096 QIcon icon = tabIcon(fromIndex);
2097 QString text = tabText(fromIndex);
2099 setCurrentIndex(fromIndex);
2100 removeTab(fromIndex);
2101 insertTab(toIndex, w, icon, text);
2102 setCurrentIndex(toIndex);
2106 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2107 : QWidget(parent), wa_(wa)
2109 LASSERT(wa, return);
2110 Ui::WorkAreaUi::setupUi(this);
2111 layout()->addWidget(wa);
2112 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2113 this, SLOT(updateDisplay()));
2114 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2115 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2116 setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2121 void GuiWorkAreaContainer::updateDisplay()
2123 Buffer const & buf = wa_->bufferView().buffer();
2124 notificationFrame->setHidden(!buf.notifiesExternalModification());
2125 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2126 .arg(toqstr(buf.fileName().displayName()));
2127 externalModificationLabel->setText(label);
2131 void GuiWorkAreaContainer::dispatch(FuncRequest const & f) const
2133 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2134 wa_->bufferView().buffer().absFileName()));
2139 void GuiWorkAreaContainer::reload() const
2141 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2145 void GuiWorkAreaContainer::ignore() const
2147 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2151 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2153 // prevent TabWorkArea from opening a new buffer on double click
2158 } // namespace frontend
2161 #include "moc_GuiWorkArea.cpp"