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 "support/convert.h"
44 #include "support/debug.h"
45 #include "support/lassert.h"
46 #include "support/TempFile.h"
48 #include "frontends/Application.h"
49 #include "frontends/CaretGeometry.h"
51 #include "frontends/FontMetrics.h"
52 #include "frontends/WorkAreaManager.h"
54 #include <QContextMenuEvent>
55 #if (QT_VERSION < 0x050000)
56 #include <QInputContext>
61 #include <QProxyStyle>
63 #include <QMainWindow>
69 #include <QStyleOption>
70 #include <QStylePainter>
72 #include <QToolButton>
83 using namespace lyx::support;
88 /// return the LyX mouse button state from Qt's
89 static mouse_button::state q_button_state(Qt::MouseButton button)
91 mouse_button::state b = mouse_button::none;
94 b = mouse_button::button1;
97 b = mouse_button::button2;
100 b = mouse_button::button3;
109 /// return the LyX mouse button state from Qt's
110 mouse_button::state q_motion_state(Qt::MouseButtons state)
112 mouse_button::state b = mouse_button::none;
113 if (state & Qt::LeftButton)
114 b |= mouse_button::button1;
115 if (state & Qt::MidButton)
116 b |= mouse_button::button2;
117 if (state & Qt::RightButton)
118 b |= mouse_button::button3;
125 // This is a 'heartbeat' generating synthetic mouse move events when the
126 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
127 SyntheticMouseEvent::SyntheticMouseEvent()
128 : timeout(200), restart_timeout(true)
132 GuiWorkArea::Private::Private(GuiWorkArea * parent)
133 : p(parent), buffer_view_(nullptr), lyx_view_(nullptr),
134 caret_visible_(false), need_resize_(false), preedit_lines_(1),
135 last_pixel_ratio_(1.0), completer_(new GuiCompleter(p, p)),
136 dialog_mode_(false), shell_escape_(false), read_only_(false),
137 clean_(true), externally_modified_(false), needs_caret_geometry_update_(true)
139 /* Qt on macOS and Wayland does not respect the
140 * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
141 * store at each update. Therefore, we use our own backing store in
142 * these two cases. */
143 #if QT_VERSION >= 0x050000
144 use_backingstore_ = guiApp->platformName() == "cocoa"
145 || guiApp->platformName().contains("wayland");
148 use_backingstore_ = true;
150 use_backingstore_ = false;
154 int const time = QApplication::cursorFlashTime() / 2;
156 caret_timeout_.setInterval(time);
157 caret_timeout_.start();
159 // let's initialize this just to be safe
160 caret_timeout_.setInterval(500);
165 GuiWorkArea::Private::~Private()
167 // If something is wrong with the buffer, we can ignore it safely
169 buffer_view_->buffer().workAreaManager().remove(p);
172 // Completer has a QObject parent and is thus automatically destroyed.
174 // delete completer_;
178 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
179 : d(new Private(this))
181 new CompressorProxy(this); // not a leak
185 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
186 : d(new Private(this))
188 new CompressorProxy(this); // not a leak
190 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
196 double GuiWorkArea::pixelRatio() const
198 #if QT_VERSION >= 0x050000
199 return qt_scale_factor * devicePixelRatio();
206 void GuiWorkArea::init()
209 connect(&d->caret_timeout_, SIGNAL(timeout()),
210 this, SLOT(toggleCaret()));
212 // This connection is closed at the same time as this is destroyed.
213 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
214 generateSyntheticMouseEvent();
218 // With Qt4.5 a mouse event will happen before the first paint event
219 // so make sure that the buffer view has an up to date metrics.
220 d->buffer_view_->resize(viewport()->width(), viewport()->height());
222 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
223 setAcceptDrops(true);
224 setMouseTracking(true);
225 setMinimumSize(100, 70);
226 setFrameStyle(QFrame::NoFrame);
229 d->updateCursorShape();
231 // we paint our own background
232 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
234 setFocusPolicy(Qt::StrongFocus);
236 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
237 << " viewport height: " << viewport()->height());
239 // Enables input methods for asian languages.
240 // Must be set when creating custom text editing widgets.
241 setAttribute(Qt::WA_InputMethodEnabled, true);
245 GuiWorkArea::~GuiWorkArea()
251 void GuiWorkArea::Private::updateCursorShape()
253 bool const clickable = buffer_view_ && buffer_view_->clickableInset();
254 p->viewport()->setCursor(clickable ? Qt::PointingHandCursor
259 void GuiWorkArea::setGuiView(GuiView & gv)
265 void GuiWorkArea::setBuffer(Buffer & buffer)
267 delete d->buffer_view_;
268 d->buffer_view_ = new BufferView(buffer);
269 buffer.workAreaManager().add(this);
271 // HACK: Prevents an additional redraw when the scrollbar pops up
272 // which regularly happens on documents with more than one page.
273 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
274 // Since we have no geometry information yet, we assume that
275 // a document needs a scrollbar if there is more then four
276 // paragraph in the outermost text.
277 if (buffer.text().paragraphs().size() > 4)
278 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
279 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
280 Q_EMIT bufferViewChanged();
284 void GuiWorkArea::fixVerticalScrollBar()
287 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
291 void GuiWorkArea::close()
293 d->lyx_view_->removeWorkArea(this);
297 void GuiWorkArea::setFullScreen(bool full_screen)
299 d->buffer_view_->setFullScreen(full_screen);
300 if (full_screen && lyxrc.full_screen_scrollbar)
301 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
303 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
307 BufferView & GuiWorkArea::bufferView()
309 return *d->buffer_view_;
313 BufferView const & GuiWorkArea::bufferView() const
315 return *d->buffer_view_;
319 void GuiWorkArea::stopBlinkingCaret()
321 d->caret_timeout_.stop();
326 void GuiWorkArea::startBlinkingCaret()
328 // do not show the cursor if the view is busy
332 // Don't start blinking if the cursor isn't on screen, unless we
333 // are not ready to know whether the cursor is on screen.
334 if (!d->buffer_view_->buffer().undo().activeUndoGroup()
335 && !d->buffer_view_->caretInView())
340 // Avoid blinking when debugging PAINTING, since it creates too much noise
341 if (!lyxerr.debugging(Debug::PAINTING)) {
342 // we are not supposed to cache this value.
343 int const time = QApplication::cursorFlashTime() / 2;
346 d->caret_timeout_.setInterval(time);
347 d->caret_timeout_.start();
352 void GuiWorkArea::toggleCaret()
354 if (d->caret_visible_)
361 void GuiWorkArea::scheduleRedraw(bool update_metrics)
364 // No need to redraw in this case.
367 // No need to do anything if this is the current view. The BufferView
368 // metrics are already up to date.
369 if (update_metrics || d->lyx_view_ != guiApp->currentView()
370 || d->lyx_view_->currentWorkArea() != this) {
371 // FIXME: it would be nice to optimize for the off-screen case.
372 d->buffer_view_->cursor().fixIfBroken();
373 d->buffer_view_->updateMetrics();
374 d->buffer_view_->cursor().fixIfBroken();
377 // update caret position, because otherwise it has to wait until
378 // the blinking interval is over
381 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
382 viewport()->update();
384 /// FIXME: is this still true now that paintEvent does the actual painting?
385 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
386 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
387 d->updateScrollbar();
388 d->lyx_view_->updateStatusBar();
390 if (lyxerr.debugging(Debug::WORKAREA))
391 d->buffer_view_->coordCache().dump();
395 d->updateCursorShape();
399 // Keep in sync with GuiWorkArea::processKeySym below
400 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
402 return guiApp->queryKeySym(key, mod);
406 // Keep in sync with GuiWorkArea::queryKeySym above
407 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
409 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
410 && lyxrc.full_screen_menubar) {
411 // FIXME HACK: we should not have to do this here. See related comment
412 // in GuiView::event() (QEvent::ShortcutOverride)
413 d->lyx_view_->menuBar()->hide();
416 // In order to avoid bad surprise in the middle of an operation,
417 // we better stop the blinking caret...
418 // the caret gets restarted in GuiView::restartCaret()
420 guiApp->processKeySym(key, mod);
424 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
427 if (cmd.action() == LFUN_FILE_OPEN) {
429 lyx_view_->dispatch(cmd, dr);
433 bool const notJustMovingTheMouse =
434 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
436 // In order to avoid bad surprise in the middle of an operation, we better stop
437 // the blinking caret.
438 if (notJustMovingTheMouse)
439 p->stopBlinkingCaret();
441 buffer_view_->mouseEventDispatch(cmd);
443 // Skip these when selecting
444 // FIXME: let GuiView take care of those.
445 if (cmd.action() != LFUN_MOUSE_MOTION) {
446 completer_->updateVisibility(false, false);
447 lyx_view_->updateDialogs();
448 lyx_view_->updateStatusBar();
451 // GUI tweaks except with mouse motion with no button pressed.
452 if (notJustMovingTheMouse) {
453 // Slight hack: this is only called currently when we
454 // clicked somewhere, so we force through the display
455 // of the new status here.
456 // FIXME: let GuiView take care of those.
457 lyx_view_->clearMessage();
459 // Show the caret immediately after any operation
460 p->startBlinkingCaret();
467 void GuiWorkArea::Private::resizeBufferView()
469 // WARNING: Please don't put any code that will trigger a repaint here!
470 // We are already inside a paint event.
471 p->stopBlinkingCaret();
472 // Warn our container (GuiView).
475 bool const caret_in_view = buffer_view_->caretInView();
476 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
478 buffer_view_->scrollToCursor();
481 // Update scrollbars which might have changed due different
482 // BufferView dimension. This is especially important when the
483 // BufferView goes from zero-size to the real-size for the first time,
484 // as the scrollbar parameters are then set for the first time.
487 need_resize_ = false;
489 // Eventually, restart the caret after the resize event.
490 // We might be resizing even if the focus is on another widget so we only
491 // restart the caret if we have the focus.
493 QTimer::singleShot(50, p, SLOT(startBlinkingCaret()));
497 void GuiWorkArea::Private::resetCaret()
499 // Don't start blinking if the cursor isn't on screen.
500 if (!buffer_view_->caretInView())
503 // completion indicator
504 Cursor const & cur = buffer_view_->cursor();
505 bool const completable = cur.inset().showCompletionCursor()
506 && completer_->completionAvailable()
507 && !completer_->popupVisible()
508 && !completer_->inlineVisible();
510 buffer_view_->buildCaretGeometry(completable);
512 needs_caret_geometry_update_ = true;
513 caret_visible_ = true;
517 void GuiWorkArea::Private::updateCaretGeometry()
519 // we cannot update geometry if not ready and we do not need to if
520 // caret is not in view.
521 if (buffer_view_->buffer().undo().activeUndoGroup()
522 || !buffer_view_->caretInView())
526 needs_caret_geometry_update_ = false;
530 void GuiWorkArea::Private::showCaret()
536 p->viewport()->update();
540 void GuiWorkArea::Private::hideCaret()
545 caret_visible_ = false;
546 //if (!qApp->focusWidget())
547 p->viewport()->update();
551 /* Draw the caret. Parameter \c horiz_offset is not 0 when there
552 * has been horizontal scrolling in current row
554 void GuiWorkArea::Private::drawCaret(QPainter & painter, int horiz_offset) const
556 if (buffer_view_->caretGeometry().shapes.empty())
559 QColor const color = guiApp->colorCache().get(Color_cursor);
560 painter.setPen(color);
561 painter.setRenderHint(QPainter::Antialiasing, true);
562 for (auto const & shape : buffer_view_->caretGeometry().shapes) {
565 for (Point const & p : shape) {
567 path.moveTo(p.x_ - horiz_offset, p.y_);
570 path.lineTo(p.x_ - horiz_offset, p.y_);
572 painter.fillPath(path, color);
574 painter.setRenderHint(QPainter::Antialiasing, false);
578 void GuiWorkArea::Private::updateScrollbar()
580 // Prevent setRange() and setSliderPosition from causing recursive calls via
581 // the signal valueChanged. (#10311)
582 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
583 p, SLOT(scrollTo(int)));
584 ScrollbarParameters const & scroll = buffer_view_->scrollbarParameters();
585 p->verticalScrollBar()->setRange(scroll.min, scroll.max);
586 p->verticalScrollBar()->setPageStep(scroll.page_step);
587 p->verticalScrollBar()->setSingleStep(scroll.single_step);
588 p->verticalScrollBar()->setSliderPosition(0);
589 // Connect to the vertical scroll bar
590 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
591 p, SLOT(scrollTo(int)));
595 void GuiWorkArea::scrollTo(int value)
598 d->buffer_view_->scrollDocView(value, true);
600 if (lyxrc.cursor_follows_scrollbar) {
601 d->buffer_view_->setCursorFromScrollbar();
602 // FIXME: let GuiView take care of those.
603 d->lyx_view_->updateLayoutList();
605 // Show the caret immediately after any operation.
606 startBlinkingCaret();
609 QApplication::syncX();
614 bool GuiWorkArea::event(QEvent * e)
617 case QEvent::ToolTip: {
618 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
619 if (lyxrc.use_tooltip) {
620 QPoint pos = helpEvent->pos();
621 if (pos.x() < viewport()->width()) {
622 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
623 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
626 QToolTip::hideText();
628 // Don't forget to accept the event!
633 case QEvent::ShortcutOverride:
634 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
636 keyPressEvent(static_cast<QKeyEvent *>(e));
637 return e->isAccepted();
639 case QEvent::KeyPress: {
640 // We catch this event in order to catch the Tab or Shift+Tab key press
641 // which are otherwise reserved to focus switching between controls
643 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
644 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
645 || (ke->key() == Qt::Key_Backtab && (
646 ke->modifiers() == Qt::ShiftModifier
647 || ke->modifiers() == Qt::NoModifier))) {
651 return QAbstractScrollArea::event(e);
655 return QAbstractScrollArea::event(e);
661 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
664 if (e->reason() == QContextMenuEvent::Mouse)
665 // the menu name is set on mouse press
666 name = d->context_menu_name_;
668 QPoint pos = e->pos();
669 Cursor const & cur = d->buffer_view_->cursor();
670 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
671 // Do not access the context menu of math right in front of before
672 // the cursor. This does not work when the cursor is in text.
673 Inset * inset = cur.paragraph().getInset(cur.pos());
674 if (inset && inset->asInsetMath())
676 else if (cur.pos() > 0) {
677 inset = cur.paragraph().getInset(cur.pos() - 1);
682 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
689 // always show mnemonics when the keyboard is used to show the context menu
690 // FIXME: This should be fixed in Qt itself
691 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
692 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
697 // Position the menu to the right.
698 // FIXME: menu position should be different for RTL text.
699 menu->exec(e->globalPos());
704 void GuiWorkArea::focusInEvent(QFocusEvent * e)
706 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
707 if (d->lyx_view_->currentWorkArea() != this) {
708 d->lyx_view_->setCurrentWorkArea(this);
709 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
712 startBlinkingCaret();
713 QAbstractScrollArea::focusInEvent(e);
717 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
719 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
721 QAbstractScrollArea::focusOutEvent(e);
725 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
727 if (d->dc_event_.active && d->dc_event_ == *e) {
728 d->dc_event_.active = false;
729 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
730 q_button_state(e->button()), q_key_state(e->modifiers()));
736 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
737 inputContext()->reset();
740 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
741 q_button_state(e->button()), q_key_state(e->modifiers()));
744 // Save the context menu on mouse press, because also the mouse
745 // cursor is set on mouse press. Afterwards, we can either release
746 // the mousebutton somewhere else, or the cursor might have moved
747 // due to the DEPM. We need to do this after the mouse has been
748 // set in dispatch(), because the selection state might change.
749 if (e->button() == Qt::RightButton)
750 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
756 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
758 if (d->synthetic_mouse_event_.timeout.running())
759 d->synthetic_mouse_event_.timeout.stop();
761 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
762 q_button_state(e->button()), q_key_state(e->modifiers()));
763 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
764 QT_VERSION < QT_VERSION_CHECK(5,15,1))
765 d->synthetic_mouse_event_.cmd = cmd; // QtBug QAbstractScrollArea::mouseMoveEvent
772 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
774 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
775 QT_VERSION < QT_VERSION_CHECK(5,15,1))
776 // cancel the event if the coordinates didn't change, this is due to QtBug
777 // QAbstractScrollArea::mouseMoveEvent, the event is triggered falsely when quickly
778 // double tapping a touchpad. To test: try to select a word by quickly double tapping
779 // on a touchpad while hovering the cursor over that word in the work area.
780 // This bug does not occur on Qt versions 5.10.1 and below. Only Windows seems to be affected.
781 // ML thread: https://www.mail-archive.com/lyx-devel@lists.lyx.org/msg211699.html
782 // Qt bugtracker: https://bugreports.qt.io/browse/QTBUG-85431
783 // Bug was fixed in Qt 5.15.1
784 if (e->x() == d->synthetic_mouse_event_.cmd.x() && // QtBug QAbstractScrollArea::mouseMoveEvent
785 e->y() == d->synthetic_mouse_event_.cmd.y()) // QtBug QAbstractScrollArea::mouseMoveEvent
786 return; // QtBug QAbstractScrollArea::mouseMoveEvent
789 // we kill the triple click if we move
790 doubleClickTimeout();
791 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
792 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
796 // If we're above or below the work area...
797 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
798 && e->buttons() == mouse_button::button1) {
799 // Make sure only a synthetic event can cause a page scroll,
800 // so they come at a steady rate:
802 // _Force_ a scroll up:
803 cmd.set_y(e->y() - 21);
805 cmd.set_y(e->y() + 21);
806 // Store the event, to be handled when the timeout expires.
807 d->synthetic_mouse_event_.cmd = cmd;
809 if (d->synthetic_mouse_event_.timeout.running()) {
810 // Discard the event. Note that it _may_ be handled
811 // when the timeout expires if
812 // synthetic_mouse_event_.cmd has not been overwritten.
813 // Ie, when the timeout expires, we handle the
814 // most recent event but discard all others that
815 // occurred after the one used to start the timeout
816 // in the first place.
820 d->synthetic_mouse_event_.restart_timeout = true;
821 d->synthetic_mouse_event_.timeout.start();
822 // Fall through to handle this event...
824 } else if (d->synthetic_mouse_event_.timeout.running()) {
825 // Store the event, to be possibly handled when the timeout
827 // Once the timeout has expired, normal control is returned
828 // to mouseMoveEvent (restart_timeout = false).
829 // This results in a much smoother 'feel' when moving the
830 // mouse back into the work area.
831 d->synthetic_mouse_event_.cmd = cmd;
832 d->synthetic_mouse_event_.restart_timeout = false;
839 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
841 // Wheel rotation by one notch results in a delta() of 120 (see
842 // documentation of QWheelEvent)
843 // But first we have to ignore horizontal scroll events.
844 #if QT_VERSION < 0x050000
845 if (ev->orientation() == Qt::Horizontal) {
849 double const delta = ev->delta() / 120.0;
851 QPoint const aDelta = ev->angleDelta();
852 // skip horizontal wheel event
853 if (abs(aDelta.x()) > abs(aDelta.y())) {
857 double const delta = aDelta.y() / 120.0;
861 switch (lyxrc.scroll_wheel_zoom) {
862 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
863 zoom = ev->modifiers() & Qt::ControlModifier;
864 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
866 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
867 zoom = ev->modifiers() & Qt::ShiftModifier;
868 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
870 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
871 zoom = ev->modifiers() & Qt::AltModifier;
872 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
874 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
878 docstring arg = convert<docstring>(int(5 * delta));
879 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
883 // Take into account the desktop wide settings.
884 int const lines = qApp->wheelScrollLines();
885 int const page_step = verticalScrollBar()->pageStep();
886 // Test if the wheel mouse is set to one screen at a time.
887 // This is according to
888 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
890 min(lines * verticalScrollBar()->singleStep(), page_step);
892 // Take into account the rotation and the user preferences.
893 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
894 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
895 << " delta = " << delta << " scroll_value = " << scroll_value
896 << " page_step = " << page_step);
898 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
904 void GuiWorkArea::generateSyntheticMouseEvent()
906 int const e_y = d->synthetic_mouse_event_.cmd.y();
907 int const wh = d->buffer_view_->workHeight();
908 bool const up = e_y < 0;
909 bool const down = e_y > wh;
911 // Set things off to generate the _next_ 'pseudo' event.
913 if (d->synthetic_mouse_event_.restart_timeout) {
914 // This is some magic formulae to determine the speed
915 // of scrolling related to the position of the mouse.
918 int dist = up ? -e_y : e_y - wh;
919 time = max(min(200, 250000 / (dist * dist)), 1) ;
922 step = 80000 / (time * time);
926 d->synthetic_mouse_event_.timeout.setTimeout(time);
927 d->synthetic_mouse_event_.timeout.start();
930 // Can we scroll further ?
931 int const value = verticalScrollBar()->value();
932 if (value == verticalScrollBar()->maximum()
933 || value == verticalScrollBar()->minimum()) {
934 d->synthetic_mouse_event_.timeout.stop();
939 if (step <= 2 * wh) {
940 d->buffer_view_->scroll(up ? -step : step);
941 d->buffer_view_->updateMetrics();
943 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
946 // In which paragraph do we have to set the cursor ?
947 Cursor & cur = d->buffer_view_->cursor();
948 // FIXME: we don't know how to handle math.
949 Text * text = cur.text();
952 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
954 // Quit gracefully if there are no metrics, since otherwise next
955 // line would crash (bug #10324).
956 // This situation seems related to a (not yet understood) timing problem.
960 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
961 ParagraphMetrics const & pm = *pp.second;
962 pit_type const pit = pp.first;
964 if (pm.rows().empty())
967 // Find the row at which we set the cursor.
968 RowList::const_iterator rit = pm.rows().begin();
969 RowList::const_iterator rlast = pm.rows().end();
970 int yy = pm.position() - pm.ascent();
971 for (--rlast; rit != rlast; ++rit) {
972 int h = rit->height();
973 if ((up && yy + h > 0)
974 || (!up && yy + h > wh - defaultRowHeight()))
979 // Find the position of the cursor
981 int x = d->synthetic_mouse_event_.cmd.x();
982 pos_type const pos = tm.getPosNearX(*rit, x, bound);
989 d->buffer_view_->buffer().changed(false);
993 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
994 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
996 qRegisterMetaType<KeySymbol>("KeySymbol");
997 qRegisterMetaType<KeyModifier>("KeyModifier");
998 connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
999 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
1000 Qt::QueuedConnection);
1001 connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
1002 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1006 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1010 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1011 bool result = flag_;
1017 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1019 if (emitCheck(isAutoRepeat))
1020 Q_EMIT signal(sym, mod);
1022 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1026 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1028 // this is also called for ShortcutOverride events. In this case, one must
1029 // not act but simply accept the event explicitly.
1030 bool const act = (ev->type() != QEvent::ShortcutOverride);
1032 // Do not process here some keys if dialog_mode_ is set
1033 bool const for_dialog_mode = d->dialog_mode_
1034 && (ev->modifiers() == Qt::NoModifier
1035 || ev->modifiers() == Qt::ShiftModifier)
1036 && (ev->key() == Qt::Key_Escape
1037 || ev->key() == Qt::Key_Enter
1038 || ev->key() == Qt::Key_Return);
1039 // also do not use autoRepeat to input shortcuts
1040 bool const autoRepeat = ev->isAutoRepeat();
1042 if (for_dialog_mode || (!act && autoRepeat)) {
1047 // intercept some keys if completion popup is visible
1048 if (d->completer_->popupVisible()) {
1049 switch (ev->key()) {
1051 case Qt::Key_Return:
1053 d->completer_->activate();
1059 KeyModifier const m = q_key_state(ev->modifiers());
1061 if (act && lyxerr.debugging(Debug::KEY)) {
1063 if (m & ShiftModifier)
1065 if (m & ControlModifier)
1067 if (m & AltModifier)
1069 if (m & MetaModifier)
1071 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1072 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1073 << " keyState: " << str);
1077 setKeySymbol(&sym, ev);
1080 Q_EMIT compressKeySym(sym, m, autoRepeat);
1083 // here, !autoRepeat, as determined at the beginning
1084 ev->setAccepted(queryKeySym(sym, m));
1091 void GuiWorkArea::doubleClickTimeout()
1093 d->dc_event_.active = false;
1097 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1099 d->dc_event_ = DoubleClick(ev);
1100 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1101 SLOT(doubleClickTimeout()));
1102 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1103 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1109 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1111 QAbstractScrollArea::resizeEvent(ev);
1112 d->need_resize_ = true;
1117 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1119 if (preedit_string_.empty())
1122 // FIXME: shall we use real_current_font here? (see #10478)
1123 FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1124 FontMetrics const & fm = theFontMetrics(font);
1127 buffer_view_->caretPosAndDim(point, dim);
1128 int cur_x = point.x_;
1129 int cur_y = point.y_ + dim.height();
1131 // get attributes of input method cursor.
1132 // cursor_pos : cursor position in preedit string.
1133 size_t cursor_pos = 0;
1134 bool cursor_is_visible = false;
1135 for (auto const & attr : preedit_attr_) {
1136 if (attr.type == QInputMethodEvent::Cursor) {
1137 cursor_pos = size_t(attr.start);
1138 cursor_is_visible = attr.length != 0;
1143 size_t const preedit_length = preedit_string_.length();
1145 // get position of selection in input method.
1146 // FIXME: isn't there a simpler way to do this?
1147 // rStart : cursor position in selected string in IM.
1149 // rLength : selected string length in IM.
1151 if (cursor_pos < preedit_length) {
1152 for (auto const & attr : preedit_attr_) {
1153 if (attr.type == QInputMethodEvent::TextFormat) {
1154 if (attr.start <= int(cursor_pos)
1155 && int(cursor_pos) < attr.start + attr.length) {
1156 rStart = size_t(attr.start);
1157 rLength = size_t(attr.length);
1158 if (!cursor_is_visible)
1159 cursor_pos += rLength;
1166 rStart = cursor_pos;
1170 int const right_margin = buffer_view_->rightMargin();
1171 Painter::preedit_style ps;
1172 // Most often there would be only one line:
1174 for (size_t pos = 0; pos != preedit_length; ++pos) {
1175 char_type const typed_char = preedit_string_[pos];
1176 // reset preedit string style
1177 ps = Painter::preedit_default;
1179 // if we reached the right extremity of the screen, go to next line.
1180 if (cur_x + fm.width(typed_char) > p->viewport()->width() - right_margin) {
1181 cur_x = right_margin;
1182 cur_y += dim.height() + 1;
1185 // preedit strings are displayed with dashed underline
1186 // and partial strings are displayed white on black indicating
1187 // that we are in selecting mode in the input method.
1188 // FIXME: rLength == preedit_length is not a changing condition
1189 // FIXME: should be put out of the loop.
1191 && pos < rStart + rLength
1192 && !(cursor_pos < rLength && rLength == preedit_length))
1193 ps = Painter::preedit_selecting;
1195 if (pos == cursor_pos
1196 && (cursor_pos < rLength && rLength == preedit_length))
1197 ps = Painter::preedit_cursor;
1199 // draw one character and update cur_x.
1200 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1205 void GuiWorkArea::Private::resetScreen()
1207 if (use_backingstore_) {
1208 int const pr = p->pixelRatio();
1209 screen_ = QImage(static_cast<int>(pr * p->viewport()->width()),
1210 static_cast<int>(pr * p->viewport()->height()),
1211 QImage::Format_ARGB32_Premultiplied);
1212 # if QT_VERSION >= 0x050000
1213 screen_.setDevicePixelRatio(pr);
1219 QPaintDevice * GuiWorkArea::Private::screenDevice()
1221 if (use_backingstore_)
1224 return p->viewport();
1228 void GuiWorkArea::Private::updateScreen(QRectF const & rc)
1230 if (use_backingstore_) {
1231 QPainter qpain(p->viewport());
1232 double const pr = p->pixelRatio();
1233 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr,
1234 rc.width() * pr, rc.height() * pr);
1235 qpain.drawImage(rc, screen_, rcs);
1240 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1242 // Do not trigger the painting machinery if we are not ready (see
1243 // bug #10989). The second test triggers when in the middle of a
1244 // dispatch operation.
1245 if (view().busy() || d->buffer_view_->buffer().undo().activeUndoGroup()) {
1246 // Since macOS has turned the screen black at this point, our
1247 // backing store has to be copied to screen (this is a no-op
1248 // except on macOS).
1249 d->updateScreen(ev->rect());
1250 // Ignore this paint event, but request a new one for later.
1251 viewport()->update(ev->rect());
1256 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1257 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1259 if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_) {
1261 d->resizeBufferView();
1264 d->last_pixel_ratio_ = pixelRatio();
1266 GuiPainter pain(d->screenDevice(), pixelRatio(), d->lyx_view_->develMode());
1268 d->buffer_view_->draw(pain, d->caret_visible_);
1270 // The preedit text, if needed
1271 d->paintPreeditText(pain);
1274 // FIXME: the code would be a little bit simpler if caret geometry
1275 // was updated unconditionally. Some profiling is required to see
1276 // how expensive this is (especially when idle).
1277 if (d->caret_visible_) {
1278 if (d->needs_caret_geometry_update_)
1279 d->updateCaretGeometry();
1280 d->drawCaret(pain, d->buffer_view_->horizScrollOffset());
1283 d->updateScreen(ev->rect());
1289 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1291 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1292 << " commitString: " << e->commitString());
1294 // insert the processed text in the document (handles undo)
1295 if (!e->commitString().isEmpty()) {
1296 FuncRequest cmd(LFUN_SELF_INSERT,
1297 qstring_to_ucs4(e->commitString()),
1298 FuncRequest::KEYBOARD);
1300 // FIXME: this is supposed to remove traces from preedit
1301 // string. Can we avoid calling it explicitly?
1302 d->buffer_view_->updateMetrics();
1305 // Hide the caret during the test transformation.
1306 if (e->preeditString().isEmpty())
1307 startBlinkingCaret();
1309 stopBlinkingCaret();
1311 if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1317 // The preedit text and its attributes will be used in paintPreeditText
1318 d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1319 d->preedit_attr_ = e->attributes();
1322 // redraw area of preedit string.
1323 // int height = d->caret_->dim.height();
1324 // int cur_y = d->caret_->y;
1325 // viewport()->update(0, cur_y, viewport()->width(),
1326 // (height + 1) * d->preedit_lines_);
1327 viewport()->update();
1329 if (d->preedit_string_.empty()) {
1330 d->preedit_lines_ = 1;
1335 // Don't forget to accept the event!
1340 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1343 // this is the CJK-specific composition window position and
1344 // the context menu position when the menu key is pressed.
1345 #if (QT_VERSION < 0x050000)
1346 case Qt::ImMicroFocus: {
1348 case Qt::ImCursorRectangle: {
1350 CaretGeometry const & cg = bufferView().caretGeometry();
1351 return QRect(cg.left - 10 * (d->preedit_lines_ != 1),
1352 cg.top + cg.height() * d->preedit_lines_,
1353 cg.width(), cg.height());
1356 return QWidget::inputMethodQuery(query);
1361 void GuiWorkArea::updateWindowTitle()
1363 Buffer const & buf = bufferView().buffer();
1364 if (buf.fileName() != d->file_name_
1365 || buf.params().shell_escape != d->shell_escape_
1366 || buf.hasReadonlyFlag() != d->read_only_
1367 || buf.lyxvc().vcstatus() != d->vc_status_
1368 || buf.isClean() != d->clean_
1369 || buf.notifiesExternalModification() != d->externally_modified_) {
1370 d->file_name_ = buf.fileName();
1371 d->shell_escape_ = buf.params().shell_escape;
1372 d->read_only_ = buf.hasReadonlyFlag();
1373 d->vc_status_ = buf.lyxvc().vcstatus();
1374 d->clean_ = buf.isClean();
1375 d->externally_modified_ = buf.notifiesExternalModification();
1376 Q_EMIT titleChanged(this);
1381 bool GuiWorkArea::isFullScreen() const
1383 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1387 bool GuiWorkArea::inDialogMode() const
1389 return d->dialog_mode_;
1393 void GuiWorkArea::setDialogMode(bool mode)
1395 d->dialog_mode_ = mode;
1399 GuiCompleter & GuiWorkArea::completer()
1401 return *d->completer_;
1404 GuiView const & GuiWorkArea::view() const
1406 return *d->lyx_view_;
1410 GuiView & GuiWorkArea::view()
1412 return *d->lyx_view_;
1415 ////////////////////////////////////////////////////////////////////
1419 ////////////////////////////////////////////////////////////////////
1422 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1424 support::TempFile tempfile("embedded.internal");
1425 tempfile.setAutoRemove(false);
1426 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1427 buffer_->setUnnamed(true);
1428 buffer_->setFullyLoaded(true);
1429 setBuffer(*buffer_);
1430 setDialogMode(true);
1434 EmbeddedWorkArea::~EmbeddedWorkArea()
1436 // No need to destroy buffer and bufferview here, because it is done
1437 // in theBufferList() destruction loop at application exit
1441 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1444 GuiWorkArea::closeEvent(ev);
1448 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1451 GuiWorkArea::hideEvent(ev);
1455 QSize EmbeddedWorkArea::sizeHint () const
1458 // GuiWorkArea sets the size to the screen's viewport
1459 // by returning a value this gets overridden
1460 // EmbeddedWorkArea is now sized to fit in the layout
1461 // of the parent, and has a minimum size set in GuiWorkArea
1462 // which is what we return here
1463 return QSize(100, 70);
1467 void EmbeddedWorkArea::disable()
1469 stopBlinkingCaret();
1470 if (view().currentWorkArea() != this)
1472 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1473 // tolerates it and shows the background logo), what happens if
1474 // an EmbeddedWorkArea is closed after closing all document WAs
1475 view().setCurrentWorkArea(view().currentMainWorkArea());
1478 ////////////////////////////////////////////////////////////////////
1482 ////////////////////////////////////////////////////////////////////
1485 class NoTabFrameMacStyle : public QProxyStyle {
1488 QRect subElementRect(SubElement element, const QStyleOption * option,
1489 const QWidget * widget = 0) const
1491 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1492 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1494 // The Qt Mac style puts the contents into a 3 pixel wide box
1495 // which looks very ugly and not like other Mac applications.
1496 // Hence we remove this here, and moreover the 16 pixel round
1497 // frame above if the tab bar is hidden.
1498 if (element == QStyle::SE_TabWidgetTabContents) {
1499 rect.adjust(- rect.left(), 0, rect.left(), 0);
1508 NoTabFrameMacStyle noTabFrameMacStyle;
1512 TabWorkArea::TabWorkArea(QWidget * parent)
1513 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1516 setStyle(&noTabFrameMacStyle);
1519 QPalette pal = palette();
1520 pal.setColor(QPalette::Active, QPalette::Button,
1521 pal.color(QPalette::Active, QPalette::Window));
1522 pal.setColor(QPalette::Disabled, QPalette::Button,
1523 pal.color(QPalette::Disabled, QPalette::Window));
1524 pal.setColor(QPalette::Inactive, QPalette::Button,
1525 pal.color(QPalette::Inactive, QPalette::Window));
1527 QObject::connect(this, SIGNAL(currentChanged(int)),
1528 this, SLOT(on_currentTabChanged(int)));
1530 closeBufferButton = new QToolButton(this);
1531 closeBufferButton->setPalette(pal);
1532 // FIXME: rename the icon to closebuffer.png
1533 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1534 closeBufferButton->setText("Close File");
1535 closeBufferButton->setAutoRaise(true);
1536 closeBufferButton->setCursor(Qt::ArrowCursor);
1537 closeBufferButton->setToolTip(qt_("Close File"));
1538 closeBufferButton->setEnabled(true);
1539 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1540 this, SLOT(closeCurrentBuffer()));
1541 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1543 // set TabBar behaviour
1544 QTabBar * tb = tabBar();
1545 tb->setTabsClosable(!lyxrc.single_close_tab_button);
1546 tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1547 tb->setElideMode(Qt::ElideNone);
1548 // allow dragging tabs
1549 tb->setMovable(true);
1550 // make us responsible for the context menu of the tabbar
1551 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1552 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1553 this, SLOT(showContextMenu(const QPoint &)));
1554 connect(tb, SIGNAL(tabCloseRequested(int)),
1555 this, SLOT(closeTab(int)));
1557 setUsesScrollButtons(true);
1561 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1563 if (me->button() == Qt::MidButton)
1564 midpressed_tab_ = tabBar()->tabAt(me->pos());
1566 QTabWidget::mousePressEvent(me);
1570 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1572 if (me->button() == Qt::MidButton) {
1573 int const midreleased_tab = tabBar()->tabAt(me->pos());
1574 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1575 closeTab(midreleased_tab);
1577 QTabWidget::mouseReleaseEvent(me);
1581 void TabWorkArea::paintEvent(QPaintEvent * event)
1583 if (tabBar()->isVisible()) {
1584 QTabWidget::paintEvent(event);
1586 // Prevent the selected tab to influence the
1587 // painting of the frame of the tab widget.
1588 // This is needed for gtk style in Qt.
1589 QStylePainter p(this);
1590 #if QT_VERSION < 0x050000
1591 QStyleOptionTabWidgetFrameV2 opt;
1593 QStyleOptionTabWidgetFrame opt;
1595 initStyleOption(&opt);
1596 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1598 opt.selectedTabRect = QRect();
1599 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1604 bool TabWorkArea::posIsTab(QPoint position)
1606 // tabAt returns -1 if tab does not covers position
1607 return tabBar()->tabAt(position) > -1;
1611 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1613 if (event->button() != Qt::LeftButton)
1616 // this code chunk is unnecessary because it seems the event only makes
1617 // it this far if it is not on a tab. I'm not sure why this is (maybe
1618 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1619 // this is true in all cases and if it will be true in the future so I
1620 // leave this code for now. (skostysh, 2016-07-21)
1622 // return early if double click on existing tabs
1623 if (posIsTab(event->pos()))
1626 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1630 void TabWorkArea::setFullScreen(bool full_screen)
1632 for (int i = 0; i != count(); ++i) {
1633 if (GuiWorkArea * wa = workArea(i))
1634 wa->setFullScreen(full_screen);
1637 if (lyxrc.full_screen_tabbar)
1638 showBar(!full_screen && count() > 1);
1640 showBar(count() > 1);
1644 void TabWorkArea::showBar(bool show)
1646 tabBar()->setEnabled(show);
1647 tabBar()->setVisible(show);
1648 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1649 setTabsClosable(!lyxrc.single_close_tab_button);
1653 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1655 QWidget * w = QTabWidget::widget(index);
1658 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1664 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1666 return widget(currentIndex());
1670 GuiWorkArea * TabWorkArea::workArea(int index) const
1672 GuiWorkAreaContainer * w = widget(index);
1675 return w->workArea();
1679 GuiWorkArea * TabWorkArea::currentWorkArea() const
1681 return workArea(currentIndex());
1685 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1687 // FIXME: this method doesn't work if we have more than one work area
1688 // showing the same buffer.
1689 for (int i = 0; i != count(); ++i) {
1690 GuiWorkArea * wa = workArea(i);
1691 LASSERT(wa, return nullptr);
1692 if (&wa->bufferView().buffer() == &buffer)
1699 void TabWorkArea::closeAll()
1702 QWidget * wac = widget(0);
1703 LASSERT(wac, return);
1710 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1712 for (int index = 0; index < count(); ++index)
1713 if (workArea(index) == w)
1719 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1721 LASSERT(work_area, return false);
1722 int index = indexOfWorkArea(work_area);
1726 if (index == currentIndex())
1727 // Make sure the work area is up to date.
1728 on_currentTabChanged(index);
1730 // Switch to the work area.
1731 setCurrentIndex(index);
1732 work_area->setFocus();
1738 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1740 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1741 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1742 wa->setUpdatesEnabled(false);
1743 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1744 // when hiding it again below).
1745 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1746 showBar(count() > 0);
1747 addTab(wac, wa->windowTitle());
1748 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1749 this, SLOT(updateTabTexts()));
1750 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1751 setFullScreen(true);
1753 // Hide tabbar if there's only one tab.
1754 showBar(count() > 1);
1762 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1764 LASSERT(work_area, return false);
1765 int index = indexOfWorkArea(work_area);
1769 work_area->setUpdatesEnabled(false);
1770 QWidget * wac = widget(index);
1775 // make sure the next work area is enabled.
1776 currentWidget()->setUpdatesEnabled(true);
1777 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1778 setFullScreen(true);
1780 // Show tabbar only if there's more than one tab.
1781 showBar(count() > 1);
1783 lastWorkAreaRemoved();
1791 void TabWorkArea::on_currentTabChanged(int i)
1793 // returns e.g. on application destruction
1796 GuiWorkArea * wa = workArea(i);
1797 LASSERT(wa, return);
1798 wa->setUpdatesEnabled(true);
1799 wa->scheduleRedraw(true);
1802 currentWorkAreaChanged(wa);
1804 LYXERR(Debug::GUI, "currentTabChanged " << i
1805 << " File: " << wa->bufferView().buffer().absFileName());
1809 void TabWorkArea::closeCurrentBuffer()
1812 if (clicked_tab_ == -1)
1813 wa = currentWorkArea();
1815 wa = workArea(clicked_tab_);
1816 LASSERT(wa, return);
1818 wa->view().closeWorkArea(wa);
1822 void TabWorkArea::hideCurrentTab()
1825 if (clicked_tab_ == -1)
1826 wa = currentWorkArea();
1828 wa = workArea(clicked_tab_);
1829 LASSERT(wa, return);
1831 wa->view().hideWorkArea(wa);
1835 void TabWorkArea::closeTab(int index)
1837 on_currentTabChanged(index);
1840 wa = currentWorkArea();
1842 wa = workArea(index);
1843 LASSERT(wa, return);
1845 wa->view().closeWorkArea(wa);
1852 /// make vector happy
1853 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1855 DisplayPath(int tab, FileName const & filename)
1858 // Recode URL encoded chars via fromPercentEncoding()
1859 string const fn = (filename.extension() == "lyx")
1860 ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
1861 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
1862 postfix_ = toqstr(filename.absoluteFilePath()).
1863 split("/", QString::SkipEmptyParts);
1864 postfix_.pop_back();
1865 abs_ = toqstr(filename.absoluteFilePath());
1866 dottedPrefix_ = false;
1869 /// Absolute path for debugging.
1874 /// Add the first segment from the postfix or three dots to the prefix.
1875 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1876 /// when really needed.
1877 void shiftPathSegment(bool dotted)
1879 if (postfix_.count() <= 0)
1883 if (dottedPrefix_ && !prefix_.isEmpty())
1884 prefix_ += ellipsisSlash_;
1885 prefix_ += postfix_.front() + "/";
1887 dottedPrefix_ = dotted && !prefix_.isEmpty();
1888 postfix_.pop_front();
1891 QString displayString() const
1893 if (prefix_.isEmpty())
1896 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1897 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1900 QString forecastPathString() const
1902 if (postfix_.count() == 0)
1903 return displayString();
1906 + (dottedPrefix_ ? ellipsisSlash_ : "")
1907 + postfix_.front() + "/";
1910 bool final() const { return postfix_.empty(); }
1912 int tab() const { return tab_; }
1916 static QString const ellipsisSlash_;
1920 QStringList postfix_;
1932 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1936 bool operator<(DisplayPath const & a, DisplayPath const & b)
1938 return a.displayString() < b.displayString();
1942 bool operator==(DisplayPath const & a, DisplayPath const & b)
1944 return a.displayString() == b.displayString();
1948 void TabWorkArea::updateTabTexts()
1950 int const n = count();
1953 std::list<DisplayPath> paths;
1954 typedef std::list<DisplayPath>::iterator It;
1956 // collect full names first: path into postfix, empty prefix and
1957 // filename without extension
1958 for (int i = 0; i < n; ++i) {
1959 GuiWorkArea * i_wa = workArea(i);
1960 FileName const fn = i_wa->bufferView().buffer().fileName();
1961 paths.push_back(DisplayPath(i, fn));
1964 // go through path segments and see if it helps to make the path more unique
1965 bool somethingChanged = true;
1966 bool allFinal = false;
1967 while (somethingChanged && !allFinal) {
1968 // adding path segments changes order
1971 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1972 somethingChanged = false;
1975 // find segments which are not unique (i.e. non-atomic)
1976 It it = paths.begin();
1978 QString segString = it->displayString();
1979 for (; it != paths.end(); ++it) {
1980 // look to the next item
1985 allFinal = allFinal && it->final();
1987 LYXERR(Debug::GUI, "it = " << it->abs()
1988 << " => " << it->displayString());
1990 // still the same segment?
1992 if ((next != paths.end()
1993 && (nextString = next->displayString()) == segString))
1995 LYXERR(Debug::GUI, "segment ended");
1997 // only a trivial one with one element?
1998 if (it == segStart) {
1999 // start new segment
2001 segString = nextString;
2005 // We found a non-atomic segment
2006 // We know that segStart <= it < next <= paths.end().
2007 // The assertion below tells coverity about it.
2008 LATTEST(segStart != paths.end());
2009 QString dspString = segStart->forecastPathString();
2010 LYXERR(Debug::GUI, "first forecast found for "
2011 << segStart->abs() << " => " << dspString);
2014 // Shift path segments and hope for the best
2015 // that it makes the path more unique.
2016 somethingChanged = true;
2017 bool moreUnique = false;
2018 for (; sit != next; ++sit) {
2019 if (sit->forecastPathString() != dspString) {
2020 LYXERR(Debug::GUI, "different forecast found for "
2021 << sit->abs() << " => " << sit->forecastPathString());
2025 LYXERR(Debug::GUI, "same forecast found for "
2026 << sit->abs() << " => " << dspString);
2029 // if the path segment helped, add it. Otherwise add dots
2030 bool dots = !moreUnique;
2031 LYXERR(Debug::GUI, "using dots = " << dots);
2032 for (sit = segStart; sit != next; ++sit) {
2033 sit->shiftPathSegment(dots);
2034 LYXERR(Debug::GUI, "shifting "
2035 << sit->abs() << " => " << sit->displayString());
2038 // start new segment
2040 segString = nextString;
2044 // set new tab titles
2045 for (It it = paths.begin(); it != paths.end(); ++it) {
2046 int const tab_index = it->tab();
2047 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2048 QString tab_text = it->displayString().replace("&", "&&");
2049 if (!buf.fileName().empty() && !buf.isClean())
2051 QString tab_tooltip = it->abs();
2052 if (buf.hasReadonlyFlag()) {
2053 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2054 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2056 setTabIcon(tab_index, QIcon());
2057 if (buf.notifiesExternalModification()) {
2058 QString const warn = qt_("%1 (modified externally)");
2059 tab_tooltip = warn.arg(tab_tooltip);
2060 tab_text += QChar(0x26a0);
2062 setTabText(tab_index, tab_text);
2063 setTabToolTip(tab_index, tab_tooltip);
2068 void TabWorkArea::showContextMenu(const QPoint & pos)
2071 clicked_tab_ = tabBar()->tabAt(pos);
2072 if (clicked_tab_ == -1)
2075 GuiWorkArea * wa = workArea(clicked_tab_);
2076 LASSERT(wa, return);
2080 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2081 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2083 // we want to show the 'close' option only if this is not a child buffer.
2084 Buffer const & buf = wa->bufferView().buffer();
2086 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2087 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2088 popup.exec(tabBar()->mapToGlobal(pos));
2094 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2096 QWidget * w = widget(fromIndex);
2097 QIcon icon = tabIcon(fromIndex);
2098 QString text = tabText(fromIndex);
2100 setCurrentIndex(fromIndex);
2101 removeTab(fromIndex);
2102 insertTab(toIndex, w, icon, text);
2103 setCurrentIndex(toIndex);
2107 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2108 : QWidget(parent), wa_(wa)
2110 LASSERT(wa, return);
2111 Ui::WorkAreaUi::setupUi(this);
2112 layout()->addWidget(wa);
2113 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2114 this, SLOT(updateDisplay()));
2115 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2116 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2117 setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2122 void GuiWorkAreaContainer::updateDisplay()
2124 Buffer const & buf = wa_->bufferView().buffer();
2125 notificationFrame->setHidden(!buf.notifiesExternalModification());
2126 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2127 .arg(toqstr(buf.fileName().displayName()));
2128 externalModificationLabel->setText(label);
2132 void GuiWorkAreaContainer::dispatch(FuncRequest const & f) const
2134 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2135 wa_->bufferView().buffer().absFileName()));
2140 void GuiWorkAreaContainer::reload() const
2142 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2146 void GuiWorkAreaContainer::ignore() const
2148 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2152 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2154 // prevent TabWorkArea from opening a new buffer on double click
2159 } // namespace frontend
2162 #include "moc_GuiWorkArea.cpp"