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 #if (QT_VERSION < 0x050000)
1349 case Qt::ImMicroFocus: {
1351 case Qt::ImCursorRectangle: {
1353 CaretGeometry const & cg = bufferView().caretGeometry();
1354 return QRect(cg.left - 10 * (d->preedit_lines_ != 1),
1355 cg.top + cg.height() * d->preedit_lines_,
1356 cg.width(), cg.height());
1359 return QWidget::inputMethodQuery(query);
1364 void GuiWorkArea::updateWindowTitle()
1366 Buffer const & buf = bufferView().buffer();
1367 if (buf.fileName() != d->file_name_
1368 || buf.params().shell_escape != d->shell_escape_
1369 || buf.hasReadonlyFlag() != d->read_only_
1370 || buf.lyxvc().vcstatus() != d->vc_status_
1371 || buf.isClean() != d->clean_
1372 || buf.notifiesExternalModification() != d->externally_modified_) {
1373 d->file_name_ = buf.fileName();
1374 d->shell_escape_ = buf.params().shell_escape;
1375 d->read_only_ = buf.hasReadonlyFlag();
1376 d->vc_status_ = buf.lyxvc().vcstatus();
1377 d->clean_ = buf.isClean();
1378 d->externally_modified_ = buf.notifiesExternalModification();
1379 Q_EMIT titleChanged(this);
1384 bool GuiWorkArea::isFullScreen() const
1386 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1390 bool GuiWorkArea::inDialogMode() const
1392 return d->dialog_mode_;
1396 void GuiWorkArea::setDialogMode(bool mode)
1398 d->dialog_mode_ = mode;
1402 GuiCompleter & GuiWorkArea::completer()
1404 return *d->completer_;
1407 GuiView const & GuiWorkArea::view() const
1409 return *d->lyx_view_;
1413 GuiView & GuiWorkArea::view()
1415 return *d->lyx_view_;
1418 ////////////////////////////////////////////////////////////////////
1422 ////////////////////////////////////////////////////////////////////
1425 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1427 support::TempFile tempfile("embedded.internal");
1428 tempfile.setAutoRemove(false);
1429 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1430 buffer_->setUnnamed(true);
1431 buffer_->setFullyLoaded(true);
1432 setBuffer(*buffer_);
1433 setDialogMode(true);
1437 EmbeddedWorkArea::~EmbeddedWorkArea()
1439 // No need to destroy buffer and bufferview here, because it is done
1440 // in theBufferList() destruction loop at application exit
1444 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1447 GuiWorkArea::closeEvent(ev);
1451 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1454 GuiWorkArea::hideEvent(ev);
1458 QSize EmbeddedWorkArea::sizeHint () const
1461 // GuiWorkArea sets the size to the screen's viewport
1462 // by returning a value this gets overridden
1463 // EmbeddedWorkArea is now sized to fit in the layout
1464 // of the parent, and has a minimum size set in GuiWorkArea
1465 // which is what we return here
1466 return QSize(100, 70);
1470 void EmbeddedWorkArea::disable()
1472 stopBlinkingCaret();
1473 if (view().currentWorkArea() != this)
1475 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1476 // tolerates it and shows the background logo), what happens if
1477 // an EmbeddedWorkArea is closed after closing all document WAs
1478 view().setCurrentWorkArea(view().currentMainWorkArea());
1481 ////////////////////////////////////////////////////////////////////
1485 ////////////////////////////////////////////////////////////////////
1488 class NoTabFrameMacStyle : public QProxyStyle {
1491 QRect subElementRect(SubElement element, const QStyleOption * option,
1492 const QWidget * widget = 0) const
1494 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1495 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1497 // The Qt Mac style puts the contents into a 3 pixel wide box
1498 // which looks very ugly and not like other Mac applications.
1499 // Hence we remove this here, and moreover the 16 pixel round
1500 // frame above if the tab bar is hidden.
1501 if (element == QStyle::SE_TabWidgetTabContents) {
1502 rect.adjust(- rect.left(), 0, rect.left(), 0);
1511 NoTabFrameMacStyle noTabFrameMacStyle;
1515 TabWorkArea::TabWorkArea(QWidget * parent)
1516 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1519 setStyle(&noTabFrameMacStyle);
1522 QPalette pal = palette();
1523 pal.setColor(QPalette::Active, QPalette::Button,
1524 pal.color(QPalette::Active, QPalette::Window));
1525 pal.setColor(QPalette::Disabled, QPalette::Button,
1526 pal.color(QPalette::Disabled, QPalette::Window));
1527 pal.setColor(QPalette::Inactive, QPalette::Button,
1528 pal.color(QPalette::Inactive, QPalette::Window));
1530 QObject::connect(this, SIGNAL(currentChanged(int)),
1531 this, SLOT(on_currentTabChanged(int)));
1533 closeBufferButton = new QToolButton(this);
1534 closeBufferButton->setPalette(pal);
1535 // FIXME: rename the icon to closebuffer.png
1536 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1537 closeBufferButton->setText("Close File");
1538 closeBufferButton->setAutoRaise(true);
1539 closeBufferButton->setCursor(Qt::ArrowCursor);
1540 closeBufferButton->setToolTip(qt_("Close File"));
1541 closeBufferButton->setEnabled(true);
1542 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1543 this, SLOT(closeCurrentBuffer()));
1544 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1546 // set TabBar behaviour
1547 QTabBar * tb = tabBar();
1548 tb->setTabsClosable(!lyxrc.single_close_tab_button);
1549 tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1550 tb->setElideMode(Qt::ElideNone);
1551 // allow dragging tabs
1552 tb->setMovable(true);
1553 // make us responsible for the context menu of the tabbar
1554 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1555 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1556 this, SLOT(showContextMenu(const QPoint &)));
1557 connect(tb, SIGNAL(tabCloseRequested(int)),
1558 this, SLOT(closeTab(int)));
1560 setUsesScrollButtons(true);
1564 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1566 if (me->button() == Qt::MidButton)
1567 midpressed_tab_ = tabBar()->tabAt(me->pos());
1569 QTabWidget::mousePressEvent(me);
1573 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1575 if (me->button() == Qt::MidButton) {
1576 int const midreleased_tab = tabBar()->tabAt(me->pos());
1577 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1578 closeTab(midreleased_tab);
1580 QTabWidget::mouseReleaseEvent(me);
1584 void TabWorkArea::paintEvent(QPaintEvent * event)
1586 if (tabBar()->isVisible()) {
1587 QTabWidget::paintEvent(event);
1589 // Prevent the selected tab to influence the
1590 // painting of the frame of the tab widget.
1591 // This is needed for gtk style in Qt.
1592 QStylePainter p(this);
1593 #if QT_VERSION < 0x050000
1594 QStyleOptionTabWidgetFrameV2 opt;
1596 QStyleOptionTabWidgetFrame opt;
1598 initStyleOption(&opt);
1599 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1601 opt.selectedTabRect = QRect();
1602 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1607 bool TabWorkArea::posIsTab(QPoint position)
1609 // tabAt returns -1 if tab does not covers position
1610 return tabBar()->tabAt(position) > -1;
1614 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1616 if (event->button() != Qt::LeftButton)
1619 // this code chunk is unnecessary because it seems the event only makes
1620 // it this far if it is not on a tab. I'm not sure why this is (maybe
1621 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1622 // this is true in all cases and if it will be true in the future so I
1623 // leave this code for now. (skostysh, 2016-07-21)
1625 // return early if double click on existing tabs
1626 if (posIsTab(event->pos()))
1629 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1633 void TabWorkArea::setFullScreen(bool full_screen)
1635 for (int i = 0; i != count(); ++i) {
1636 if (GuiWorkArea * wa = workArea(i))
1637 wa->setFullScreen(full_screen);
1640 if (lyxrc.full_screen_tabbar)
1641 showBar(!full_screen && count() > 1);
1643 showBar(count() > 1);
1647 void TabWorkArea::showBar(bool show)
1649 tabBar()->setEnabled(show);
1650 tabBar()->setVisible(show);
1651 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1652 setTabsClosable(!lyxrc.single_close_tab_button);
1656 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1658 QWidget * w = QTabWidget::widget(index);
1661 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1667 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1669 return widget(currentIndex());
1673 GuiWorkArea * TabWorkArea::workArea(int index) const
1675 GuiWorkAreaContainer * w = widget(index);
1678 return w->workArea();
1682 GuiWorkArea * TabWorkArea::currentWorkArea() const
1684 return workArea(currentIndex());
1688 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1690 // FIXME: this method doesn't work if we have more than one work area
1691 // showing the same buffer.
1692 for (int i = 0; i != count(); ++i) {
1693 GuiWorkArea * wa = workArea(i);
1694 LASSERT(wa, return nullptr);
1695 if (&wa->bufferView().buffer() == &buffer)
1702 void TabWorkArea::closeAll()
1705 QWidget * wac = widget(0);
1706 LASSERT(wac, return);
1713 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1715 for (int index = 0; index < count(); ++index)
1716 if (workArea(index) == w)
1722 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1724 LASSERT(work_area, return false);
1725 int index = indexOfWorkArea(work_area);
1729 if (index == currentIndex())
1730 // Make sure the work area is up to date.
1731 on_currentTabChanged(index);
1733 // Switch to the work area.
1734 setCurrentIndex(index);
1735 work_area->setFocus();
1741 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1743 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1744 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1745 wa->setUpdatesEnabled(false);
1746 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1747 // when hiding it again below).
1748 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1749 showBar(count() > 0);
1750 addTab(wac, wa->windowTitle());
1751 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1752 this, SLOT(updateTabTexts()));
1753 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1754 setFullScreen(true);
1756 // Hide tabbar if there's only one tab.
1757 showBar(count() > 1);
1765 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1767 LASSERT(work_area, return false);
1768 int index = indexOfWorkArea(work_area);
1772 work_area->setUpdatesEnabled(false);
1773 QWidget * wac = widget(index);
1778 // make sure the next work area is enabled.
1779 currentWidget()->setUpdatesEnabled(true);
1780 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1781 setFullScreen(true);
1783 // Show tabbar only if there's more than one tab.
1784 showBar(count() > 1);
1786 lastWorkAreaRemoved();
1794 void TabWorkArea::on_currentTabChanged(int i)
1796 // returns e.g. on application destruction
1799 GuiWorkArea * wa = workArea(i);
1800 LASSERT(wa, return);
1801 wa->setUpdatesEnabled(true);
1802 wa->scheduleRedraw(true);
1805 currentWorkAreaChanged(wa);
1807 LYXERR(Debug::GUI, "currentTabChanged " << i
1808 << " File: " << wa->bufferView().buffer().absFileName());
1812 void TabWorkArea::closeCurrentBuffer()
1815 if (clicked_tab_ == -1)
1816 wa = currentWorkArea();
1818 wa = workArea(clicked_tab_);
1819 LASSERT(wa, return);
1821 wa->view().closeWorkArea(wa);
1825 void TabWorkArea::hideCurrentTab()
1828 if (clicked_tab_ == -1)
1829 wa = currentWorkArea();
1831 wa = workArea(clicked_tab_);
1832 LASSERT(wa, return);
1834 wa->view().hideWorkArea(wa);
1838 void TabWorkArea::closeTab(int index)
1840 on_currentTabChanged(index);
1843 wa = currentWorkArea();
1845 wa = workArea(index);
1846 LASSERT(wa, return);
1848 wa->view().closeWorkArea(wa);
1855 /// make vector happy
1856 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1858 DisplayPath(int tab, FileName const & filename)
1861 // Recode URL encoded chars via fromPercentEncoding()
1862 string const fn = (filename.extension() == "lyx")
1863 ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
1864 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
1865 postfix_ = toqstr(filename.absoluteFilePath()).
1866 split("/", QString::SkipEmptyParts);
1867 postfix_.pop_back();
1868 abs_ = toqstr(filename.absoluteFilePath());
1869 dottedPrefix_ = false;
1872 /// Absolute path for debugging.
1877 /// Add the first segment from the postfix or three dots to the prefix.
1878 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1879 /// when really needed.
1880 void shiftPathSegment(bool dotted)
1882 if (postfix_.count() <= 0)
1886 if (dottedPrefix_ && !prefix_.isEmpty())
1887 prefix_ += ellipsisSlash_;
1888 prefix_ += postfix_.front() + "/";
1890 dottedPrefix_ = dotted && !prefix_.isEmpty();
1891 postfix_.pop_front();
1894 QString displayString() const
1896 if (prefix_.isEmpty())
1899 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1900 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1903 QString forecastPathString() const
1905 if (postfix_.count() == 0)
1906 return displayString();
1909 + (dottedPrefix_ ? ellipsisSlash_ : "")
1910 + postfix_.front() + "/";
1913 bool final() const { return postfix_.empty(); }
1915 int tab() const { return tab_; }
1919 static QString const ellipsisSlash_;
1923 QStringList postfix_;
1935 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1939 bool operator<(DisplayPath const & a, DisplayPath const & b)
1941 return a.displayString() < b.displayString();
1945 bool operator==(DisplayPath const & a, DisplayPath const & b)
1947 return a.displayString() == b.displayString();
1951 void TabWorkArea::updateTabTexts()
1953 int const n = count();
1956 std::list<DisplayPath> paths;
1957 typedef std::list<DisplayPath>::iterator It;
1959 // collect full names first: path into postfix, empty prefix and
1960 // filename without extension
1961 for (int i = 0; i < n; ++i) {
1962 GuiWorkArea * i_wa = workArea(i);
1963 FileName const fn = i_wa->bufferView().buffer().fileName();
1964 paths.push_back(DisplayPath(i, fn));
1967 // go through path segments and see if it helps to make the path more unique
1968 bool somethingChanged = true;
1969 bool allFinal = false;
1970 while (somethingChanged && !allFinal) {
1971 // adding path segments changes order
1974 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1975 somethingChanged = false;
1978 // find segments which are not unique (i.e. non-atomic)
1979 It it = paths.begin();
1981 QString segString = it->displayString();
1982 for (; it != paths.end(); ++it) {
1983 // look to the next item
1988 allFinal = allFinal && it->final();
1990 LYXERR(Debug::GUI, "it = " << it->abs()
1991 << " => " << it->displayString());
1993 // still the same segment?
1995 if ((next != paths.end()
1996 && (nextString = next->displayString()) == segString))
1998 LYXERR(Debug::GUI, "segment ended");
2000 // only a trivial one with one element?
2001 if (it == segStart) {
2002 // start new segment
2004 segString = nextString;
2008 // We found a non-atomic segment
2009 // We know that segStart <= it < next <= paths.end().
2010 // The assertion below tells coverity about it.
2011 LATTEST(segStart != paths.end());
2012 QString dspString = segStart->forecastPathString();
2013 LYXERR(Debug::GUI, "first forecast found for "
2014 << segStart->abs() << " => " << dspString);
2017 // Shift path segments and hope for the best
2018 // that it makes the path more unique.
2019 somethingChanged = true;
2020 bool moreUnique = false;
2021 for (; sit != next; ++sit) {
2022 if (sit->forecastPathString() != dspString) {
2023 LYXERR(Debug::GUI, "different forecast found for "
2024 << sit->abs() << " => " << sit->forecastPathString());
2028 LYXERR(Debug::GUI, "same forecast found for "
2029 << sit->abs() << " => " << dspString);
2032 // if the path segment helped, add it. Otherwise add dots
2033 bool dots = !moreUnique;
2034 LYXERR(Debug::GUI, "using dots = " << dots);
2035 for (sit = segStart; sit != next; ++sit) {
2036 sit->shiftPathSegment(dots);
2037 LYXERR(Debug::GUI, "shifting "
2038 << sit->abs() << " => " << sit->displayString());
2041 // start new segment
2043 segString = nextString;
2047 // set new tab titles
2048 for (It it = paths.begin(); it != paths.end(); ++it) {
2049 int const tab_index = it->tab();
2050 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2051 QString tab_text = it->displayString().replace("&", "&&");
2052 if (!buf.fileName().empty() && !buf.isClean())
2054 QString tab_tooltip = it->abs();
2055 if (buf.hasReadonlyFlag()) {
2056 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2057 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2059 setTabIcon(tab_index, QIcon());
2060 if (buf.notifiesExternalModification()) {
2061 QString const warn = qt_("%1 (modified externally)");
2062 tab_tooltip = warn.arg(tab_tooltip);
2063 tab_text += QChar(0x26a0);
2065 setTabText(tab_index, tab_text);
2066 setTabToolTip(tab_index, tab_tooltip);
2071 void TabWorkArea::showContextMenu(const QPoint & pos)
2074 clicked_tab_ = tabBar()->tabAt(pos);
2075 if (clicked_tab_ == -1)
2078 GuiWorkArea * wa = workArea(clicked_tab_);
2079 LASSERT(wa, return);
2083 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2084 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2086 // we want to show the 'close' option only if this is not a child buffer.
2087 Buffer const & buf = wa->bufferView().buffer();
2089 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2090 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2091 popup.exec(tabBar()->mapToGlobal(pos));
2097 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2099 QWidget * w = widget(fromIndex);
2100 QIcon icon = tabIcon(fromIndex);
2101 QString text = tabText(fromIndex);
2103 setCurrentIndex(fromIndex);
2104 removeTab(fromIndex);
2105 insertTab(toIndex, w, icon, text);
2106 setCurrentIndex(toIndex);
2110 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2111 : QWidget(parent), wa_(wa)
2113 LASSERT(wa, return);
2114 Ui::WorkAreaUi::setupUi(this);
2115 layout()->addWidget(wa);
2116 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2117 this, SLOT(updateDisplay()));
2118 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2119 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2120 setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2125 void GuiWorkAreaContainer::updateDisplay()
2127 Buffer const & buf = wa_->bufferView().buffer();
2128 notificationFrame->setHidden(!buf.notifiesExternalModification());
2129 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2130 .arg(toqstr(buf.fileName().displayName()));
2131 externalModificationLabel->setText(label);
2135 void GuiWorkAreaContainer::dispatch(FuncRequest const & f) const
2137 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2138 wa_->bufferView().buffer().absFileName()));
2143 void GuiWorkAreaContainer::reload() const
2145 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2149 void GuiWorkAreaContainer::ignore() const
2151 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2155 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2157 // prevent TabWorkArea from opening a new buffer on double click
2162 } // namespace frontend
2165 #include "moc_GuiWorkArea.cpp"