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 "FontLoader.h"
19 #include "GuiApplication.h"
20 #include "GuiCompleter.h"
21 #include "GuiKeySymbol.h"
22 #include "GuiPainter.h"
25 #include "qt_helpers.h"
28 #include "BufferList.h"
29 #include "BufferParams.h"
30 #include "BufferView.h"
31 #include "CoordCache.h"
34 #include "FuncRequest.h"
35 #include "KeySymbol.h"
41 #include "TextMetrics.h"
45 #include "graphics/GraphicsImage.h"
46 #include "graphics/GraphicsLoader.h"
48 #include "support/convert.h"
49 #include "support/debug.h"
50 #include "support/lassert.h"
51 #include "support/TempFile.h"
53 #include "frontends/Application.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;
130 CaretWidget() : dir(1), l_shape(false), completable(false),
134 /* Draw the caret. Parameter \c horiz_offset is not 0 when there
135 * has been horizontal scrolling in current row
137 void draw(QPainter & painter, int horiz_offset)
141 // correction for horizontal scrolling
142 int const xx = x - horiz_offset;
143 int const lx = dim.height() / 3;
146 painter.setPen(color);
148 path.moveTo(xx + dim.asc * slope, y);
149 path.lineTo(xx - dim.des * slope, y + dim.height());
150 path.lineTo(xx + dir * dim.wid - dim.des * slope, y + dim.height());
151 path.lineTo(xx + dir * dim.wid + dim.asc * slope, y);
152 painter.setRenderHint(QPainter::Antialiasing, true);
153 painter.fillPath(path, color);
154 painter.setRenderHint(QPainter::Antialiasing, false);
156 // draw RTL/LTR indication
158 painter.fillRect(xx - dim.des * slope,
159 y + dim.height() - dim.wid + 1,
160 dir * (dim.wid + lx - 1), dim.wid, color);
162 // draw completion triangle
164 int const m = y + dim.height() / 2;
165 int const d = dim.height() / 8;
166 // offset for slanted carret
167 int const sx = (dim.asc - (dim.height() / 2 - d)) * slope;
168 painter.setPen(QPen(color, dim.width()));
169 painter.drawLine(xx + dir * dim.wid + sx, m - d,
170 xx + dir * (dim.wid + d) + sx, m);
171 painter.drawLine(xx + dir * dim.wid + sx, m + d,
172 xx + dir * (dim.wid + d) + sx, m);
176 void update(BufferView const * bv, bool complet) {
177 // Cursor size and position
179 bv->caretPosAndDim(point, dim);
182 completable = complet;
184 Cursor const & cur = bv->cursor();
185 Font const & realfont = cur.real_current_font;
186 FontMetrics const & fm = theFontMetrics(realfont.fontInfo());
187 BufferParams const & bp = bv->buffer().params();
188 bool const samelang = realfont.language() == bp.language;
189 bool const isrtl = realfont.isVisibleRightToLeft();
190 dir = isrtl ? -1 : 1;
192 l_shape = (!samelang || isrtl != bp.language->rightToLeft())
193 && realfont.language() != latex_language;
195 // use slanted caret for italics in text edit mode
196 // except for selections because the selection rect does not slant
197 bool const slant = fm.italic() && cur.inTexted() && !cur.selection();
198 slope = slant ? fm.italicSlope() : 0;
200 color = guiApp->colorCache().get(Color_cursor);
203 /// text direction (1 for LtR, -1 for RtL)
205 /// indication for language change
207 /// triangle to show that a completion is available
211 /// dimension uf base caret
213 /// x position (were the vertical line is drawn)
215 /// y position (the top of the caret)
217 /// the slope for drawing slanted caret
222 // This is a 'heartbeat' generating synthetic mouse move events when the
223 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
224 SyntheticMouseEvent::SyntheticMouseEvent()
225 : timeout(200), restart_timeout(true)
229 GuiWorkArea::Private::Private(GuiWorkArea * parent)
230 : p(parent), buffer_view_(nullptr), lyx_view_(nullptr), caret_(nullptr),
231 caret_visible_(false), need_resize_(false), preedit_lines_(1),
232 last_pixel_ratio_(1.0), completer_(new GuiCompleter(p, p)),
233 dialog_mode_(false), shell_escape_(false), read_only_(false),
234 clean_(true), externally_modified_(false), needs_caret_geometry_update_(true)
236 /* Qt on macOS and Wayland does not respect the
237 * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
238 * store at each update. Therefore, we use our own backing store in
239 * these two cases. */
240 #if QT_VERSION >= 0x050000
241 use_backingstore_ = guiApp->platformName() == "cocoa"
242 || guiApp->platformName().contains("wayland");
245 use_backingstore_ = true;
247 use_backingstore_ = false;
251 int const time = QApplication::cursorFlashTime() / 2;
253 caret_timeout_.setInterval(time);
254 caret_timeout_.start();
256 // let's initialize this just to be safe
257 caret_timeout_.setInterval(500);
262 GuiWorkArea::Private::~Private()
264 // If something is wrong with the buffer, we can ignore it safely
266 buffer_view_->buffer().workAreaManager().remove(p);
270 // Completer has a QObject parent and is thus automatically destroyed.
272 // delete completer_;
276 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
277 : d(new Private(this))
279 new CompressorProxy(this); // not a leak
283 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
284 : d(new Private(this))
286 new CompressorProxy(this); // not a leak
288 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
294 double GuiWorkArea::pixelRatio() const
296 #if QT_VERSION >= 0x050000
297 return qt_scale_factor * devicePixelRatio();
304 void GuiWorkArea::init()
307 connect(&d->caret_timeout_, SIGNAL(timeout()),
308 this, SLOT(toggleCaret()));
310 // This connection is closed at the same time as this is destroyed.
311 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
312 generateSyntheticMouseEvent();
316 // With Qt4.5 a mouse event will happen before the first paint event
317 // so make sure that the buffer view has an up to date metrics.
318 d->buffer_view_->resize(viewport()->width(), viewport()->height());
319 d->caret_ = new frontend::CaretWidget();
321 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
322 setAcceptDrops(true);
323 setMouseTracking(true);
324 setMinimumSize(100, 70);
325 setFrameStyle(QFrame::NoFrame);
328 d->updateCursorShape();
330 // we paint our own background
331 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
333 setFocusPolicy(Qt::StrongFocus);
335 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
336 << " viewport height: " << viewport()->height());
338 // Enables input methods for asian languages.
339 // Must be set when creating custom text editing widgets.
340 setAttribute(Qt::WA_InputMethodEnabled, true);
344 GuiWorkArea::~GuiWorkArea()
350 void GuiWorkArea::Private::updateCursorShape()
352 bool const clickable = buffer_view_ && buffer_view_->clickableInset();
353 p->viewport()->setCursor(clickable ? Qt::PointingHandCursor
358 void GuiWorkArea::setGuiView(GuiView & gv)
364 void GuiWorkArea::setBuffer(Buffer & buffer)
366 delete d->buffer_view_;
367 d->buffer_view_ = new BufferView(buffer);
368 buffer.workAreaManager().add(this);
370 // HACK: Prevents an additional redraw when the scrollbar pops up
371 // which regularly happens on documents with more than one page.
372 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
373 // Since we have no geometry information yet, we assume that
374 // a document needs a scrollbar if there is more then four
375 // paragraph in the outermost text.
376 if (buffer.text().paragraphs().size() > 4)
377 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
378 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
379 Q_EMIT bufferViewChanged();
383 void GuiWorkArea::fixVerticalScrollBar()
386 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
390 void GuiWorkArea::close()
392 d->lyx_view_->removeWorkArea(this);
396 void GuiWorkArea::setFullScreen(bool full_screen)
398 d->buffer_view_->setFullScreen(full_screen);
399 if (full_screen && lyxrc.full_screen_scrollbar)
400 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
402 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
406 BufferView & GuiWorkArea::bufferView()
408 return *d->buffer_view_;
412 BufferView const & GuiWorkArea::bufferView() const
414 return *d->buffer_view_;
418 void GuiWorkArea::stopBlinkingCaret()
420 d->caret_timeout_.stop();
425 void GuiWorkArea::startBlinkingCaret()
427 // do not show the cursor if the view is busy
431 // Don't start blinking if the cursor isn't on screen, unless we
432 // are not ready to know whether the cursor is on screen.
433 if (!d->buffer_view_->buffer().undo().activeUndoGroup()
434 && !d->buffer_view_->caretInView())
439 // Avoid blinking when debugging PAINTING, since it creates too much noise
440 if (!lyxerr.debugging(Debug::PAINTING)) {
441 // we are not supposed to cache this value.
442 int const time = QApplication::cursorFlashTime() / 2;
445 d->caret_timeout_.setInterval(time);
446 d->caret_timeout_.start();
451 void GuiWorkArea::toggleCaret()
453 if (d->caret_visible_)
460 void GuiWorkArea::scheduleRedraw(bool update_metrics)
463 // No need to redraw in this case.
466 // No need to do anything if this is the current view. The BufferView
467 // metrics are already up to date.
468 if (update_metrics || d->lyx_view_ != guiApp->currentView()
469 || d->lyx_view_->currentWorkArea() != this) {
470 // FIXME: it would be nice to optimize for the off-screen case.
471 d->buffer_view_->cursor().fixIfBroken();
472 d->buffer_view_->updateMetrics();
473 d->buffer_view_->cursor().fixIfBroken();
476 // update caret position, because otherwise it has to wait until
477 // the blinking interval is over
480 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
481 viewport()->update();
483 /// FIXME: is this still true now that paintEvent does the actual painting?
484 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
485 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
486 d->updateScrollbar();
487 d->lyx_view_->updateStatusBar();
489 if (lyxerr.debugging(Debug::WORKAREA))
490 d->buffer_view_->coordCache().dump();
494 d->updateCursorShape();
498 // Keep in sync with GuiWorkArea::processKeySym below
499 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
501 return guiApp->queryKeySym(key, mod);
505 // Keep in sync with GuiWorkArea::queryKeySym above
506 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
508 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
509 && lyxrc.full_screen_menubar) {
510 // FIXME HACK: we should not have to do this here. See related comment
511 // in GuiView::event() (QEvent::ShortcutOverride)
512 d->lyx_view_->menuBar()->hide();
515 // In order to avoid bad surprise in the middle of an operation,
516 // we better stop the blinking caret...
517 // the caret gets restarted in GuiView::restartCaret()
519 guiApp->processKeySym(key, mod);
523 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
526 if (cmd.action() == LFUN_FILE_OPEN) {
528 lyx_view_->dispatch(cmd, dr);
532 bool const notJustMovingTheMouse =
533 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
535 // In order to avoid bad surprise in the middle of an operation, we better stop
536 // the blinking caret.
537 if (notJustMovingTheMouse)
538 p->stopBlinkingCaret();
540 buffer_view_->mouseEventDispatch(cmd);
542 // Skip these when selecting
543 // FIXME: let GuiView take care of those.
544 if (cmd.action() != LFUN_MOUSE_MOTION) {
545 completer_->updateVisibility(false, false);
546 lyx_view_->updateDialogs();
547 lyx_view_->updateStatusBar();
550 // GUI tweaks except with mouse motion with no button pressed.
551 if (notJustMovingTheMouse) {
552 // Slight hack: this is only called currently when we
553 // clicked somewhere, so we force through the display
554 // of the new status here.
555 // FIXME: let GuiView take care of those.
556 lyx_view_->clearMessage();
558 // Show the caret immediately after any operation
559 p->startBlinkingCaret();
566 void GuiWorkArea::Private::resizeBufferView()
568 // WARNING: Please don't put any code that will trigger a repaint here!
569 // We are already inside a paint event.
570 p->stopBlinkingCaret();
571 // Warn our container (GuiView).
574 bool const caret_in_view = buffer_view_->caretInView();
575 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
577 buffer_view_->scrollToCursor();
580 // Update scrollbars which might have changed due different
581 // BufferView dimension. This is especially important when the
582 // BufferView goes from zero-size to the real-size for the first time,
583 // as the scrollbar parameters are then set for the first time.
586 need_resize_ = false;
588 // Eventually, restart the caret after the resize event.
589 // We might be resizing even if the focus is on another widget so we only
590 // restart the caret if we have the focus.
592 QTimer::singleShot(50, p, SLOT(startBlinkingCaret()));
596 void GuiWorkArea::Private::resetCaret()
598 // Don't start blinking if the cursor isn't on screen.
599 if (!buffer_view_->caretInView())
602 // completion indicator
603 Cursor const & cur = buffer_view_->cursor();
604 bool const completable = cur.inset().showCompletionCursor()
605 && completer_->completionAvailable()
606 && !completer_->popupVisible()
607 && !completer_->inlineVisible();
609 caret_->update(buffer_view_, completable);
611 needs_caret_geometry_update_ = true;
612 caret_visible_ = true;
616 void GuiWorkArea::Private::updateCaretGeometry()
618 // we cannot update geometry if not ready and we do not need to if
619 // caret is not in view.
620 if (buffer_view_->buffer().undo().activeUndoGroup()
621 || !buffer_view_->caretInView())
625 needs_caret_geometry_update_ = false;
629 void GuiWorkArea::Private::showCaret()
635 p->viewport()->update();
639 void GuiWorkArea::Private::hideCaret()
644 caret_visible_ = false;
645 //if (!qApp->focusWidget())
646 p->viewport()->update();
650 void GuiWorkArea::Private::updateScrollbar()
652 // Prevent setRange() and setSliderPosition from causing recursive calls via
653 // the signal valueChanged. (#10311)
654 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
655 p, SLOT(scrollTo(int)));
656 ScrollbarParameters const & scroll = buffer_view_->scrollbarParameters();
657 p->verticalScrollBar()->setRange(scroll.min, scroll.max);
658 p->verticalScrollBar()->setPageStep(scroll.page_step);
659 p->verticalScrollBar()->setSingleStep(scroll.single_step);
660 p->verticalScrollBar()->setSliderPosition(0);
661 // Connect to the vertical scroll bar
662 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
663 p, SLOT(scrollTo(int)));
667 void GuiWorkArea::scrollTo(int value)
670 d->buffer_view_->scrollDocView(value, true);
672 if (lyxrc.cursor_follows_scrollbar) {
673 d->buffer_view_->setCursorFromScrollbar();
674 // FIXME: let GuiView take care of those.
675 d->lyx_view_->updateLayoutList();
677 // Show the caret immediately after any operation.
678 startBlinkingCaret();
681 QApplication::syncX();
686 bool GuiWorkArea::event(QEvent * e)
689 case QEvent::ToolTip: {
690 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
691 if (lyxrc.use_tooltip) {
692 QPoint pos = helpEvent->pos();
693 if (pos.x() < viewport()->width()) {
694 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
695 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
698 QToolTip::hideText();
700 // Don't forget to accept the event!
705 case QEvent::ShortcutOverride:
706 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
708 keyPressEvent(static_cast<QKeyEvent *>(e));
709 return e->isAccepted();
711 case QEvent::KeyPress: {
712 // We catch this event in order to catch the Tab or Shift+Tab key press
713 // which are otherwise reserved to focus switching between controls
715 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
716 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
717 || (ke->key() == Qt::Key_Backtab && (
718 ke->modifiers() == Qt::ShiftModifier
719 || ke->modifiers() == Qt::NoModifier))) {
723 return QAbstractScrollArea::event(e);
727 return QAbstractScrollArea::event(e);
733 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
736 if (e->reason() == QContextMenuEvent::Mouse)
737 // the menu name is set on mouse press
738 name = d->context_menu_name_;
740 QPoint pos = e->pos();
741 Cursor const & cur = d->buffer_view_->cursor();
742 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
743 // Do not access the context menu of math right in front of before
744 // the cursor. This does not work when the cursor is in text.
745 Inset * inset = cur.paragraph().getInset(cur.pos());
746 if (inset && inset->asInsetMath())
748 else if (cur.pos() > 0) {
749 inset = cur.paragraph().getInset(cur.pos() - 1);
754 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
761 // always show mnemonics when the keyboard is used to show the context menu
762 // FIXME: This should be fixed in Qt itself
763 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
764 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
769 // Position the menu to the right.
770 // FIXME: menu position should be different for RTL text.
771 menu->exec(e->globalPos());
776 void GuiWorkArea::focusInEvent(QFocusEvent * e)
778 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
779 if (d->lyx_view_->currentWorkArea() != this) {
780 d->lyx_view_->setCurrentWorkArea(this);
781 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
784 startBlinkingCaret();
785 QAbstractScrollArea::focusInEvent(e);
789 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
791 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
793 QAbstractScrollArea::focusOutEvent(e);
797 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
799 if (d->dc_event_.active && d->dc_event_ == *e) {
800 d->dc_event_.active = false;
801 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
802 q_button_state(e->button()), q_key_state(e->modifiers()));
808 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
809 inputContext()->reset();
812 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
813 q_button_state(e->button()), q_key_state(e->modifiers()));
816 // Save the context menu on mouse press, because also the mouse
817 // cursor is set on mouse press. Afterwards, we can either release
818 // the mousebutton somewhere else, or the cursor might have moved
819 // due to the DEPM. We need to do this after the mouse has been
820 // set in dispatch(), because the selection state might change.
821 if (e->button() == Qt::RightButton)
822 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
828 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
830 if (d->synthetic_mouse_event_.timeout.running())
831 d->synthetic_mouse_event_.timeout.stop();
833 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
834 q_button_state(e->button()), q_key_state(e->modifiers()));
835 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
836 QT_VERSION < QT_VERSION_CHECK(5,15,1))
837 d->synthetic_mouse_event_.cmd = cmd; // QtBug QAbstractScrollArea::mouseMoveEvent
844 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
846 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
847 QT_VERSION < QT_VERSION_CHECK(5,15,1))
848 // cancel the event if the coordinates didn't change, this is due to QtBug
849 // QAbstractScrollArea::mouseMoveEvent, the event is triggered falsely when quickly
850 // double tapping a touchpad. To test: try to select a word by quickly double tapping
851 // on a touchpad while hovering the cursor over that word in the work area.
852 // This bug does not occur on Qt versions 5.10.1 and below. Only Windows seems to be affected.
853 // ML thread: https://www.mail-archive.com/lyx-devel@lists.lyx.org/msg211699.html
854 // Qt bugtracker: https://bugreports.qt.io/browse/QTBUG-85431
855 // Bug was fixed in Qt 5.15.1
856 if (e->x() == d->synthetic_mouse_event_.cmd.x() && // QtBug QAbstractScrollArea::mouseMoveEvent
857 e->y() == d->synthetic_mouse_event_.cmd.y()) // QtBug QAbstractScrollArea::mouseMoveEvent
858 return; // QtBug QAbstractScrollArea::mouseMoveEvent
861 // we kill the triple click if we move
862 doubleClickTimeout();
863 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
864 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
868 // If we're above or below the work area...
869 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
870 && e->buttons() == mouse_button::button1) {
871 // Make sure only a synthetic event can cause a page scroll,
872 // so they come at a steady rate:
874 // _Force_ a scroll up:
875 cmd.set_y(e->y() - 21);
877 cmd.set_y(e->y() + 21);
878 // Store the event, to be handled when the timeout expires.
879 d->synthetic_mouse_event_.cmd = cmd;
881 if (d->synthetic_mouse_event_.timeout.running()) {
882 // Discard the event. Note that it _may_ be handled
883 // when the timeout expires if
884 // synthetic_mouse_event_.cmd has not been overwritten.
885 // Ie, when the timeout expires, we handle the
886 // most recent event but discard all others that
887 // occurred after the one used to start the timeout
888 // in the first place.
892 d->synthetic_mouse_event_.restart_timeout = true;
893 d->synthetic_mouse_event_.timeout.start();
894 // Fall through to handle this event...
896 } else if (d->synthetic_mouse_event_.timeout.running()) {
897 // Store the event, to be possibly handled when the timeout
899 // Once the timeout has expired, normal control is returned
900 // to mouseMoveEvent (restart_timeout = false).
901 // This results in a much smoother 'feel' when moving the
902 // mouse back into the work area.
903 d->synthetic_mouse_event_.cmd = cmd;
904 d->synthetic_mouse_event_.restart_timeout = false;
911 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
913 // Wheel rotation by one notch results in a delta() of 120 (see
914 // documentation of QWheelEvent)
915 // But first we have to ignore horizontal scroll events.
916 #if QT_VERSION < 0x050000
917 if (ev->orientation() == Qt::Horizontal) {
921 double const delta = ev->delta() / 120.0;
923 QPoint const aDelta = ev->angleDelta();
924 // skip horizontal wheel event
925 if (abs(aDelta.x()) > abs(aDelta.y())) {
929 double const delta = aDelta.y() / 120.0;
933 switch (lyxrc.scroll_wheel_zoom) {
934 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
935 zoom = ev->modifiers() & Qt::ControlModifier;
936 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
938 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
939 zoom = ev->modifiers() & Qt::ShiftModifier;
940 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
942 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
943 zoom = ev->modifiers() & Qt::AltModifier;
944 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
946 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
950 docstring arg = convert<docstring>(int(5 * delta));
951 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
955 // Take into account the desktop wide settings.
956 int const lines = qApp->wheelScrollLines();
957 int const page_step = verticalScrollBar()->pageStep();
958 // Test if the wheel mouse is set to one screen at a time.
959 // This is according to
960 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
962 min(lines * verticalScrollBar()->singleStep(), page_step);
964 // Take into account the rotation and the user preferences.
965 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
966 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
967 << " delta = " << delta << " scroll_value = " << scroll_value
968 << " page_step = " << page_step);
970 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
976 void GuiWorkArea::generateSyntheticMouseEvent()
978 int const e_y = d->synthetic_mouse_event_.cmd.y();
979 int const wh = d->buffer_view_->workHeight();
980 bool const up = e_y < 0;
981 bool const down = e_y > wh;
983 // Set things off to generate the _next_ 'pseudo' event.
985 if (d->synthetic_mouse_event_.restart_timeout) {
986 // This is some magic formulae to determine the speed
987 // of scrolling related to the position of the mouse.
990 int dist = up ? -e_y : e_y - wh;
991 time = max(min(200, 250000 / (dist * dist)), 1) ;
994 step = 80000 / (time * time);
998 d->synthetic_mouse_event_.timeout.setTimeout(time);
999 d->synthetic_mouse_event_.timeout.start();
1002 // Can we scroll further ?
1003 int const value = verticalScrollBar()->value();
1004 if (value == verticalScrollBar()->maximum()
1005 || value == verticalScrollBar()->minimum()) {
1006 d->synthetic_mouse_event_.timeout.stop();
1011 if (step <= 2 * wh) {
1012 d->buffer_view_->scroll(up ? -step : step);
1013 d->buffer_view_->updateMetrics();
1015 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
1018 // In which paragraph do we have to set the cursor ?
1019 Cursor & cur = d->buffer_view_->cursor();
1020 // FIXME: we don't know how to handle math.
1021 Text * text = cur.text();
1024 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
1026 // Quit gracefully if there are no metrics, since otherwise next
1027 // line would crash (bug #10324).
1028 // This situation seems related to a (not yet understood) timing problem.
1032 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
1033 ParagraphMetrics const & pm = *pp.second;
1034 pit_type const pit = pp.first;
1036 if (pm.rows().empty())
1039 // Find the row at which we set the cursor.
1040 RowList::const_iterator rit = pm.rows().begin();
1041 RowList::const_iterator rlast = pm.rows().end();
1042 int yy = pm.position() - pm.ascent();
1043 for (--rlast; rit != rlast; ++rit) {
1044 int h = rit->height();
1045 if ((up && yy + h > 0)
1046 || (!up && yy + h > wh - defaultRowHeight()))
1051 // Find the position of the cursor
1053 int x = d->synthetic_mouse_event_.cmd.x();
1054 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1059 cur.boundary(bound);
1061 d->buffer_view_->buffer().changed(false);
1065 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
1066 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
1068 qRegisterMetaType<KeySymbol>("KeySymbol");
1069 qRegisterMetaType<KeyModifier>("KeyModifier");
1070 connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
1071 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
1072 Qt::QueuedConnection);
1073 connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
1074 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1078 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1082 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1083 bool result = flag_;
1089 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1091 if (emitCheck(isAutoRepeat))
1092 Q_EMIT signal(sym, mod);
1094 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1098 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1100 // this is also called for ShortcutOverride events. In this case, one must
1101 // not act but simply accept the event explicitly.
1102 bool const act = (ev->type() != QEvent::ShortcutOverride);
1104 // Do not process here some keys if dialog_mode_ is set
1105 bool const for_dialog_mode = d->dialog_mode_
1106 && (ev->modifiers() == Qt::NoModifier
1107 || ev->modifiers() == Qt::ShiftModifier)
1108 && (ev->key() == Qt::Key_Escape
1109 || ev->key() == Qt::Key_Enter
1110 || ev->key() == Qt::Key_Return);
1111 // also do not use autoRepeat to input shortcuts
1112 bool const autoRepeat = ev->isAutoRepeat();
1114 if (for_dialog_mode || (!act && autoRepeat)) {
1119 // intercept some keys if completion popup is visible
1120 if (d->completer_->popupVisible()) {
1121 switch (ev->key()) {
1123 case Qt::Key_Return:
1125 d->completer_->activate();
1131 KeyModifier const m = q_key_state(ev->modifiers());
1133 if (act && lyxerr.debugging(Debug::KEY)) {
1135 if (m & ShiftModifier)
1137 if (m & ControlModifier)
1139 if (m & AltModifier)
1141 if (m & MetaModifier)
1143 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1144 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1145 << " keyState: " << str);
1149 setKeySymbol(&sym, ev);
1152 Q_EMIT compressKeySym(sym, m, autoRepeat);
1155 // here, !autoRepeat, as determined at the beginning
1156 ev->setAccepted(queryKeySym(sym, m));
1163 void GuiWorkArea::doubleClickTimeout()
1165 d->dc_event_.active = false;
1169 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1171 d->dc_event_ = DoubleClick(ev);
1172 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1173 SLOT(doubleClickTimeout()));
1174 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1175 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1181 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1183 QAbstractScrollArea::resizeEvent(ev);
1184 d->need_resize_ = true;
1189 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1191 if (preedit_string_.empty())
1194 // FIXME: shall we use real_current_font here? (see #10478)
1195 FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1196 FontMetrics const & fm = theFontMetrics(font);
1197 int const height = fm.maxHeight();
1198 int cur_x = caret_->x;
1199 int cur_y = caret_->y + height;
1201 // get attributes of input method cursor.
1202 // cursor_pos : cursor position in preedit string.
1203 size_t cursor_pos = 0;
1204 bool cursor_is_visible = false;
1205 for (auto const & attr : preedit_attr_) {
1206 if (attr.type == QInputMethodEvent::Cursor) {
1207 cursor_pos = size_t(attr.start);
1208 cursor_is_visible = attr.length != 0;
1213 size_t const preedit_length = preedit_string_.length();
1215 // get position of selection in input method.
1216 // FIXME: isn't there a simpler way to do this?
1217 // rStart : cursor position in selected string in IM.
1219 // rLength : selected string length in IM.
1221 if (cursor_pos < preedit_length) {
1222 for (auto const & attr : preedit_attr_) {
1223 if (attr.type == QInputMethodEvent::TextFormat) {
1224 if (attr.start <= int(cursor_pos)
1225 && int(cursor_pos) < attr.start + attr.length) {
1226 rStart = size_t(attr.start);
1227 rLength = size_t(attr.length);
1228 if (!cursor_is_visible)
1229 cursor_pos += rLength;
1236 rStart = cursor_pos;
1240 int const right_margin = buffer_view_->rightMargin();
1241 Painter::preedit_style ps;
1242 // Most often there would be only one line:
1244 for (size_t pos = 0; pos != preedit_length; ++pos) {
1245 char_type const typed_char = preedit_string_[pos];
1246 // reset preedit string style
1247 ps = Painter::preedit_default;
1249 // if we reached the right extremity of the screen, go to next line.
1250 if (cur_x + fm.width(typed_char) > p->viewport()->width() - right_margin) {
1251 cur_x = right_margin;
1252 cur_y += height + 1;
1255 // preedit strings are displayed with dashed underline
1256 // and partial strings are displayed white on black indicating
1257 // that we are in selecting mode in the input method.
1258 // FIXME: rLength == preedit_length is not a changing condition
1259 // FIXME: should be put out of the loop.
1261 && pos < rStart + rLength
1262 && !(cursor_pos < rLength && rLength == preedit_length))
1263 ps = Painter::preedit_selecting;
1265 if (pos == cursor_pos
1266 && (cursor_pos < rLength && rLength == preedit_length))
1267 ps = Painter::preedit_cursor;
1269 // draw one character and update cur_x.
1270 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1275 void GuiWorkArea::Private::resetScreen()
1277 if (use_backingstore_) {
1278 int const pr = p->pixelRatio();
1279 screen_ = QImage(static_cast<int>(pr * p->viewport()->width()),
1280 static_cast<int>(pr * p->viewport()->height()),
1281 QImage::Format_ARGB32_Premultiplied);
1282 # if QT_VERSION >= 0x050000
1283 screen_.setDevicePixelRatio(pr);
1289 QPaintDevice * GuiWorkArea::Private::screenDevice()
1291 if (use_backingstore_)
1294 return p->viewport();
1298 void GuiWorkArea::Private::updateScreen(QRectF const & rc)
1300 if (use_backingstore_) {
1301 QPainter qpain(p->viewport());
1302 double const pr = p->pixelRatio();
1303 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr,
1304 rc.width() * pr, rc.height() * pr);
1305 qpain.drawImage(rc, screen_, rcs);
1310 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1312 // Do not trigger the painting machinery if we are not ready (see
1313 // bug #10989). The second test triggers when in the middle of a
1314 // dispatch operation.
1315 if (view().busy() || d->buffer_view_->buffer().undo().activeUndoGroup()) {
1316 // Since macOS has turned the screen black at this point, our
1317 // backing store has to be copied to screen (this is a no-op
1318 // except on macOS).
1319 d->updateScreen(ev->rect());
1320 // Ignore this paint event, but request a new one for later.
1321 viewport()->update(ev->rect());
1326 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1327 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1329 if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_) {
1331 d->resizeBufferView();
1334 d->last_pixel_ratio_ = pixelRatio();
1336 GuiPainter pain(d->screenDevice(), pixelRatio(), d->lyx_view_->develMode());
1338 d->buffer_view_->draw(pain, d->caret_visible_);
1340 // The preedit text, if needed
1341 d->paintPreeditText(pain);
1344 // FIXME: the code would be a little bit simpler if caret geometry
1345 // was updated unconditionally. Some profiling is required to see
1346 // how expensive this is (especially when idle).
1347 if (d->caret_visible_) {
1348 if (d->needs_caret_geometry_update_)
1349 d->updateCaretGeometry();
1350 d->caret_->draw(pain, d->buffer_view_->horizScrollOffset());
1353 d->updateScreen(ev->rect());
1359 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1361 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1362 << " commitString: " << e->commitString());
1364 // insert the processed text in the document (handles undo)
1365 if (!e->commitString().isEmpty()) {
1366 FuncRequest cmd(LFUN_SELF_INSERT,
1367 qstring_to_ucs4(e->commitString()),
1368 FuncRequest::KEYBOARD);
1370 // FIXME: this is supposed to remove traces from preedit
1371 // string. Can we avoid calling it explicitly?
1372 d->buffer_view_->updateMetrics();
1375 // Hide the caret during the test transformation.
1376 if (e->preeditString().isEmpty())
1377 startBlinkingCaret();
1379 stopBlinkingCaret();
1381 if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1387 // The preedit text and its attributes will be used in paintPreeditText
1388 d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1389 d->preedit_attr_ = e->attributes();
1392 // redraw area of preedit string.
1393 int height = d->caret_->dim.height();
1394 int cur_y = d->caret_->y;
1395 viewport()->update(0, cur_y, viewport()->width(),
1396 (height + 1) * d->preedit_lines_);
1398 if (d->preedit_string_.empty()) {
1399 d->preedit_lines_ = 1;
1404 // Don't forget to accept the event!
1409 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1412 // this is the CJK-specific composition window position and
1413 // the context menu position when the menu key is pressed.
1414 case Qt::ImMicroFocus:
1415 return QRect(d->caret_->x - 10 * (d->preedit_lines_ != 1),
1416 d->caret_->y + d->caret_->dim.height() * d->preedit_lines_,
1417 d->caret_->dim.width(), d->caret_->dim.height());
1419 return QWidget::inputMethodQuery(query);
1424 void GuiWorkArea::updateWindowTitle()
1426 Buffer const & buf = bufferView().buffer();
1427 if (buf.fileName() != d->file_name_
1428 || buf.params().shell_escape != d->shell_escape_
1429 || buf.hasReadonlyFlag() != d->read_only_
1430 || buf.lyxvc().vcstatus() != d->vc_status_
1431 || buf.isClean() != d->clean_
1432 || buf.notifiesExternalModification() != d->externally_modified_) {
1433 d->file_name_ = buf.fileName();
1434 d->shell_escape_ = buf.params().shell_escape;
1435 d->read_only_ = buf.hasReadonlyFlag();
1436 d->vc_status_ = buf.lyxvc().vcstatus();
1437 d->clean_ = buf.isClean();
1438 d->externally_modified_ = buf.notifiesExternalModification();
1439 Q_EMIT titleChanged(this);
1444 bool GuiWorkArea::isFullScreen() const
1446 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1450 bool GuiWorkArea::inDialogMode() const
1452 return d->dialog_mode_;
1456 void GuiWorkArea::setDialogMode(bool mode)
1458 d->dialog_mode_ = mode;
1462 GuiCompleter & GuiWorkArea::completer()
1464 return *d->completer_;
1467 GuiView const & GuiWorkArea::view() const
1469 return *d->lyx_view_;
1473 GuiView & GuiWorkArea::view()
1475 return *d->lyx_view_;
1478 ////////////////////////////////////////////////////////////////////
1482 ////////////////////////////////////////////////////////////////////
1485 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1487 support::TempFile tempfile("embedded.internal");
1488 tempfile.setAutoRemove(false);
1489 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1490 buffer_->setUnnamed(true);
1491 buffer_->setFullyLoaded(true);
1492 setBuffer(*buffer_);
1493 setDialogMode(true);
1497 EmbeddedWorkArea::~EmbeddedWorkArea()
1499 // No need to destroy buffer and bufferview here, because it is done
1500 // in theBufferList() destruction loop at application exit
1504 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1507 GuiWorkArea::closeEvent(ev);
1511 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1514 GuiWorkArea::hideEvent(ev);
1518 QSize EmbeddedWorkArea::sizeHint () const
1521 // GuiWorkArea sets the size to the screen's viewport
1522 // by returning a value this gets overridden
1523 // EmbeddedWorkArea is now sized to fit in the layout
1524 // of the parent, and has a minimum size set in GuiWorkArea
1525 // which is what we return here
1526 return QSize(100, 70);
1530 void EmbeddedWorkArea::disable()
1532 stopBlinkingCaret();
1533 if (view().currentWorkArea() != this)
1535 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1536 // tolerates it and shows the background logo), what happens if
1537 // an EmbeddedWorkArea is closed after closing all document WAs
1538 view().setCurrentWorkArea(view().currentMainWorkArea());
1541 ////////////////////////////////////////////////////////////////////
1545 ////////////////////////////////////////////////////////////////////
1548 class NoTabFrameMacStyle : public QProxyStyle {
1551 QRect subElementRect(SubElement element, const QStyleOption * option,
1552 const QWidget * widget = 0) const
1554 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1555 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1557 // The Qt Mac style puts the contents into a 3 pixel wide box
1558 // which looks very ugly and not like other Mac applications.
1559 // Hence we remove this here, and moreover the 16 pixel round
1560 // frame above if the tab bar is hidden.
1561 if (element == QStyle::SE_TabWidgetTabContents) {
1562 rect.adjust(- rect.left(), 0, rect.left(), 0);
1571 NoTabFrameMacStyle noTabFrameMacStyle;
1575 TabWorkArea::TabWorkArea(QWidget * parent)
1576 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1579 setStyle(&noTabFrameMacStyle);
1582 QPalette pal = palette();
1583 pal.setColor(QPalette::Active, QPalette::Button,
1584 pal.color(QPalette::Active, QPalette::Window));
1585 pal.setColor(QPalette::Disabled, QPalette::Button,
1586 pal.color(QPalette::Disabled, QPalette::Window));
1587 pal.setColor(QPalette::Inactive, QPalette::Button,
1588 pal.color(QPalette::Inactive, QPalette::Window));
1590 QObject::connect(this, SIGNAL(currentChanged(int)),
1591 this, SLOT(on_currentTabChanged(int)));
1593 closeBufferButton = new QToolButton(this);
1594 closeBufferButton->setPalette(pal);
1595 // FIXME: rename the icon to closebuffer.png
1596 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1597 closeBufferButton->setText("Close File");
1598 closeBufferButton->setAutoRaise(true);
1599 closeBufferButton->setCursor(Qt::ArrowCursor);
1600 closeBufferButton->setToolTip(qt_("Close File"));
1601 closeBufferButton->setEnabled(true);
1602 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1603 this, SLOT(closeCurrentBuffer()));
1604 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1606 // set TabBar behaviour
1607 QTabBar * tb = tabBar();
1608 tb->setTabsClosable(!lyxrc.single_close_tab_button);
1609 tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1610 tb->setElideMode(Qt::ElideNone);
1611 // allow dragging tabs
1612 tb->setMovable(true);
1613 // make us responsible for the context menu of the tabbar
1614 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1615 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1616 this, SLOT(showContextMenu(const QPoint &)));
1617 connect(tb, SIGNAL(tabCloseRequested(int)),
1618 this, SLOT(closeTab(int)));
1620 setUsesScrollButtons(true);
1624 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1626 if (me->button() == Qt::MidButton)
1627 midpressed_tab_ = tabBar()->tabAt(me->pos());
1629 QTabWidget::mousePressEvent(me);
1633 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1635 if (me->button() == Qt::MidButton) {
1636 int const midreleased_tab = tabBar()->tabAt(me->pos());
1637 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1638 closeTab(midreleased_tab);
1640 QTabWidget::mouseReleaseEvent(me);
1644 void TabWorkArea::paintEvent(QPaintEvent * event)
1646 if (tabBar()->isVisible()) {
1647 QTabWidget::paintEvent(event);
1649 // Prevent the selected tab to influence the
1650 // painting of the frame of the tab widget.
1651 // This is needed for gtk style in Qt.
1652 QStylePainter p(this);
1653 #if QT_VERSION < 0x050000
1654 QStyleOptionTabWidgetFrameV2 opt;
1656 QStyleOptionTabWidgetFrame opt;
1658 initStyleOption(&opt);
1659 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1661 opt.selectedTabRect = QRect();
1662 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1667 bool TabWorkArea::posIsTab(QPoint position)
1669 // tabAt returns -1 if tab does not covers position
1670 return tabBar()->tabAt(position) > -1;
1674 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1676 if (event->button() != Qt::LeftButton)
1679 // this code chunk is unnecessary because it seems the event only makes
1680 // it this far if it is not on a tab. I'm not sure why this is (maybe
1681 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1682 // this is true in all cases and if it will be true in the future so I
1683 // leave this code for now. (skostysh, 2016-07-21)
1685 // return early if double click on existing tabs
1686 if (posIsTab(event->pos()))
1689 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1693 void TabWorkArea::setFullScreen(bool full_screen)
1695 for (int i = 0; i != count(); ++i) {
1696 if (GuiWorkArea * wa = workArea(i))
1697 wa->setFullScreen(full_screen);
1700 if (lyxrc.full_screen_tabbar)
1701 showBar(!full_screen && count() > 1);
1703 showBar(count() > 1);
1707 void TabWorkArea::showBar(bool show)
1709 tabBar()->setEnabled(show);
1710 tabBar()->setVisible(show);
1711 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1712 setTabsClosable(!lyxrc.single_close_tab_button);
1716 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1718 QWidget * w = QTabWidget::widget(index);
1721 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1727 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1729 return widget(currentIndex());
1733 GuiWorkArea * TabWorkArea::workArea(int index) const
1735 GuiWorkAreaContainer * w = widget(index);
1738 return w->workArea();
1742 GuiWorkArea * TabWorkArea::currentWorkArea() const
1744 return workArea(currentIndex());
1748 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1750 // FIXME: this method doesn't work if we have more than one work area
1751 // showing the same buffer.
1752 for (int i = 0; i != count(); ++i) {
1753 GuiWorkArea * wa = workArea(i);
1754 LASSERT(wa, return nullptr);
1755 if (&wa->bufferView().buffer() == &buffer)
1762 void TabWorkArea::closeAll()
1765 QWidget * wac = widget(0);
1766 LASSERT(wac, return);
1773 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1775 for (int index = 0; index < count(); ++index)
1776 if (workArea(index) == w)
1782 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1784 LASSERT(work_area, return false);
1785 int index = indexOfWorkArea(work_area);
1789 if (index == currentIndex())
1790 // Make sure the work area is up to date.
1791 on_currentTabChanged(index);
1793 // Switch to the work area.
1794 setCurrentIndex(index);
1795 work_area->setFocus();
1801 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1803 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1804 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1805 wa->setUpdatesEnabled(false);
1806 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1807 // when hiding it again below).
1808 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1809 showBar(count() > 0);
1810 addTab(wac, wa->windowTitle());
1811 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1812 this, SLOT(updateTabTexts()));
1813 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1814 setFullScreen(true);
1816 // Hide tabbar if there's only one tab.
1817 showBar(count() > 1);
1825 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1827 LASSERT(work_area, return false);
1828 int index = indexOfWorkArea(work_area);
1832 work_area->setUpdatesEnabled(false);
1833 QWidget * wac = widget(index);
1838 // make sure the next work area is enabled.
1839 currentWidget()->setUpdatesEnabled(true);
1840 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1841 setFullScreen(true);
1843 // Show tabbar only if there's more than one tab.
1844 showBar(count() > 1);
1846 lastWorkAreaRemoved();
1854 void TabWorkArea::on_currentTabChanged(int i)
1856 // returns e.g. on application destruction
1859 GuiWorkArea * wa = workArea(i);
1860 LASSERT(wa, return);
1861 wa->setUpdatesEnabled(true);
1862 wa->scheduleRedraw(true);
1865 currentWorkAreaChanged(wa);
1867 LYXERR(Debug::GUI, "currentTabChanged " << i
1868 << " File: " << wa->bufferView().buffer().absFileName());
1872 void TabWorkArea::closeCurrentBuffer()
1875 if (clicked_tab_ == -1)
1876 wa = currentWorkArea();
1878 wa = workArea(clicked_tab_);
1879 LASSERT(wa, return);
1881 wa->view().closeWorkArea(wa);
1885 void TabWorkArea::hideCurrentTab()
1888 if (clicked_tab_ == -1)
1889 wa = currentWorkArea();
1891 wa = workArea(clicked_tab_);
1892 LASSERT(wa, return);
1894 wa->view().hideWorkArea(wa);
1898 void TabWorkArea::closeTab(int index)
1900 on_currentTabChanged(index);
1903 wa = currentWorkArea();
1905 wa = workArea(index);
1906 LASSERT(wa, return);
1908 wa->view().closeWorkArea(wa);
1915 /// make vector happy
1916 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1918 DisplayPath(int tab, FileName const & filename)
1921 // Recode URL encoded chars via fromPercentEncoding()
1922 string const fn = (filename.extension() == "lyx")
1923 ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
1924 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
1925 postfix_ = toqstr(filename.absoluteFilePath()).
1926 split("/", QString::SkipEmptyParts);
1927 postfix_.pop_back();
1928 abs_ = toqstr(filename.absoluteFilePath());
1929 dottedPrefix_ = false;
1932 /// Absolute path for debugging.
1937 /// Add the first segment from the postfix or three dots to the prefix.
1938 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1939 /// when really needed.
1940 void shiftPathSegment(bool dotted)
1942 if (postfix_.count() <= 0)
1946 if (dottedPrefix_ && !prefix_.isEmpty())
1947 prefix_ += ellipsisSlash_;
1948 prefix_ += postfix_.front() + "/";
1950 dottedPrefix_ = dotted && !prefix_.isEmpty();
1951 postfix_.pop_front();
1954 QString displayString() const
1956 if (prefix_.isEmpty())
1959 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1960 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1963 QString forecastPathString() const
1965 if (postfix_.count() == 0)
1966 return displayString();
1969 + (dottedPrefix_ ? ellipsisSlash_ : "")
1970 + postfix_.front() + "/";
1973 bool final() const { return postfix_.empty(); }
1975 int tab() const { return tab_; }
1979 static QString const ellipsisSlash_;
1983 QStringList postfix_;
1995 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1999 bool operator<(DisplayPath const & a, DisplayPath const & b)
2001 return a.displayString() < b.displayString();
2005 bool operator==(DisplayPath const & a, DisplayPath const & b)
2007 return a.displayString() == b.displayString();
2011 void TabWorkArea::updateTabTexts()
2013 int const n = count();
2016 std::list<DisplayPath> paths;
2017 typedef std::list<DisplayPath>::iterator It;
2019 // collect full names first: path into postfix, empty prefix and
2020 // filename without extension
2021 for (int i = 0; i < n; ++i) {
2022 GuiWorkArea * i_wa = workArea(i);
2023 FileName const fn = i_wa->bufferView().buffer().fileName();
2024 paths.push_back(DisplayPath(i, fn));
2027 // go through path segments and see if it helps to make the path more unique
2028 bool somethingChanged = true;
2029 bool allFinal = false;
2030 while (somethingChanged && !allFinal) {
2031 // adding path segments changes order
2034 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
2035 somethingChanged = false;
2038 // find segments which are not unique (i.e. non-atomic)
2039 It it = paths.begin();
2041 QString segString = it->displayString();
2042 for (; it != paths.end(); ++it) {
2043 // look to the next item
2048 allFinal = allFinal && it->final();
2050 LYXERR(Debug::GUI, "it = " << it->abs()
2051 << " => " << it->displayString());
2053 // still the same segment?
2055 if ((next != paths.end()
2056 && (nextString = next->displayString()) == segString))
2058 LYXERR(Debug::GUI, "segment ended");
2060 // only a trivial one with one element?
2061 if (it == segStart) {
2062 // start new segment
2064 segString = nextString;
2068 // We found a non-atomic segment
2069 // We know that segStart <= it < next <= paths.end().
2070 // The assertion below tells coverity about it.
2071 LATTEST(segStart != paths.end());
2072 QString dspString = segStart->forecastPathString();
2073 LYXERR(Debug::GUI, "first forecast found for "
2074 << segStart->abs() << " => " << dspString);
2077 // Shift path segments and hope for the best
2078 // that it makes the path more unique.
2079 somethingChanged = true;
2080 bool moreUnique = false;
2081 for (; sit != next; ++sit) {
2082 if (sit->forecastPathString() != dspString) {
2083 LYXERR(Debug::GUI, "different forecast found for "
2084 << sit->abs() << " => " << sit->forecastPathString());
2088 LYXERR(Debug::GUI, "same forecast found for "
2089 << sit->abs() << " => " << dspString);
2092 // if the path segment helped, add it. Otherwise add dots
2093 bool dots = !moreUnique;
2094 LYXERR(Debug::GUI, "using dots = " << dots);
2095 for (sit = segStart; sit != next; ++sit) {
2096 sit->shiftPathSegment(dots);
2097 LYXERR(Debug::GUI, "shifting "
2098 << sit->abs() << " => " << sit->displayString());
2101 // start new segment
2103 segString = nextString;
2107 // set new tab titles
2108 for (It it = paths.begin(); it != paths.end(); ++it) {
2109 int const tab_index = it->tab();
2110 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2111 QString tab_text = it->displayString().replace("&", "&&");
2112 if (!buf.fileName().empty() && !buf.isClean())
2114 QString tab_tooltip = it->abs();
2115 if (buf.hasReadonlyFlag()) {
2116 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2117 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2119 setTabIcon(tab_index, QIcon());
2120 if (buf.notifiesExternalModification()) {
2121 QString const warn = qt_("%1 (modified externally)");
2122 tab_tooltip = warn.arg(tab_tooltip);
2123 tab_text += QChar(0x26a0);
2125 setTabText(tab_index, tab_text);
2126 setTabToolTip(tab_index, tab_tooltip);
2131 void TabWorkArea::showContextMenu(const QPoint & pos)
2134 clicked_tab_ = tabBar()->tabAt(pos);
2135 if (clicked_tab_ == -1)
2138 GuiWorkArea * wa = workArea(clicked_tab_);
2139 LASSERT(wa, return);
2143 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2144 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2146 // we want to show the 'close' option only if this is not a child buffer.
2147 Buffer const & buf = wa->bufferView().buffer();
2149 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2150 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2151 popup.exec(tabBar()->mapToGlobal(pos));
2157 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2159 QWidget * w = widget(fromIndex);
2160 QIcon icon = tabIcon(fromIndex);
2161 QString text = tabText(fromIndex);
2163 setCurrentIndex(fromIndex);
2164 removeTab(fromIndex);
2165 insertTab(toIndex, w, icon, text);
2166 setCurrentIndex(toIndex);
2170 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2171 : QWidget(parent), wa_(wa)
2173 LASSERT(wa, return);
2174 Ui::WorkAreaUi::setupUi(this);
2175 layout()->addWidget(wa);
2176 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2177 this, SLOT(updateDisplay()));
2178 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2179 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2180 setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2185 void GuiWorkAreaContainer::updateDisplay()
2187 Buffer const & buf = wa_->bufferView().buffer();
2188 notificationFrame->setHidden(!buf.notifiesExternalModification());
2189 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2190 .arg(toqstr(buf.fileName().displayName()));
2191 externalModificationLabel->setText(label);
2195 void GuiWorkAreaContainer::dispatch(FuncRequest const & f) const
2197 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2198 wa_->bufferView().buffer().absFileName()));
2203 void GuiWorkAreaContainer::reload() const
2205 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2209 void GuiWorkAreaContainer::ignore() const
2211 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2215 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2217 // prevent TabWorkArea from opening a new buffer on double click
2222 } // namespace frontend
2225 #include "moc_GuiWorkArea.cpp"