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>
82 int const TabIndicatorWidth = 3;
88 using namespace lyx::support;
93 /// return the LyX mouse button state from Qt's
94 static mouse_button::state q_button_state(Qt::MouseButton button)
96 mouse_button::state b = mouse_button::none;
99 b = mouse_button::button1;
102 b = mouse_button::button2;
104 case Qt::RightButton:
105 b = mouse_button::button3;
114 /// return the LyX mouse button state from Qt's
115 mouse_button::state q_motion_state(Qt::MouseButtons state)
117 mouse_button::state b = mouse_button::none;
118 if (state & Qt::LeftButton)
119 b |= mouse_button::button1;
120 if (state & Qt::MidButton)
121 b |= mouse_button::button2;
122 if (state & Qt::RightButton)
123 b |= mouse_button::button3;
132 CaretWidget() : rtl_(false), l_shape_(false), completable_(false),
133 x_(0), caret_width_(0), slant_(false), ascent_(0)
136 /* Draw the caret. Parameter \c horiz_offset is not 0 when there
137 * has been horizontal scrolling in current row
139 void draw(QPainter & painter, int horiz_offset)
141 if (!rect_.isValid())
144 int const x = x_ - horiz_offset;
145 int const y = rect_.top();
146 int const lx = rtl_ ? x_ - rect_.left() : rect_.right() - x_;
147 int const bot = rect_.bottom();
148 int const dir = rtl_ ? -1 : 1;
149 // this is almost equal to tan(14 * PI / 180)
150 qreal const slope = 0.25;
153 if (slant_ && !rtl_) {
154 // slanted (14 degree angle)
156 path.moveTo(x + ascent_ * slope, y);
157 path.lineTo(x - (rect_.height() - ascent_) * slope, y + rect_.height());
158 path.lineTo(x + dir * caret_width_ - (rect_.height() - ascent_) * slope,
160 path.lineTo(x + dir * caret_width_ + ascent_ * slope, y);
161 painter.setRenderHint(QPainter::Antialiasing, true);
162 painter.fillPath(path, color_);
163 painter.setRenderHint(QPainter::Antialiasing, false);
166 painter.fillRect(x, y, dir * caret_width_, rect_.height(), color_);
168 // draw RTL/LTR indication
169 painter.setPen(color_);
171 painter.drawLine(x, bot, x + dir * (caret_width_ + lx - 1), bot);
174 // draw completion triangle
176 int const m = y + rect_.height() / 2;
177 int const d = TabIndicatorWidth - 1;
178 // offset for slanted carret
179 int const sx = (slant_ && !rtl_) ? (ascent_ - (rect_.height() / 2 - d)) * slope : 0;
180 painter.drawLine(x + dir * (caret_width_ + 1) + sx, m - d,
181 x + dir * (caret_width_ + d + 1) + sx, m);
182 painter.drawLine(x + dir * (caret_width_ + 1) + sx, m + d,
183 x + dir * (caret_width_ + d + 1) + sx, m);
187 void update(int x, int y, int h, bool l_shape,
188 bool rtl, bool completable, bool slant, int ascent)
190 color_ = guiApp->colorCache().get(Color_cursor);
193 completable_ = completable;
198 // extension to left and right
202 // RTL/LTR indication
210 // completion triangle
213 l = max(l, TabIndicatorWidth);
215 r = max(r, TabIndicatorWidth);
218 //FIXME: LyXRC::cursor_width should be caret_width
219 caret_width_ = lyxrc.cursor_width
221 : 1 + int((lyxrc.currentZoom + 50) / 200.0);
223 // compute overall rectangle
224 rect_ = QRect(x - l, y, caret_width_ + r + l, h);
227 QRect const & rect() { return rect_; }
230 /// caret is in RTL or LTR text
232 /// indication for RTL or LTR
234 /// triangle to show that a completion is available
238 /// rectangle, possibly with l_shape and completion triangle
240 /// x position (were the vertical line is drawn)
242 /// the width of the vertical blinking bar
244 /// caret is in slanted text
246 /// the fontmetrics ascent for drawing slanted caret
251 // This is a 'heartbeat' generating synthetic mouse move events when the
252 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
253 SyntheticMouseEvent::SyntheticMouseEvent()
254 : timeout(200), restart_timeout(true)
258 GuiWorkArea::Private::Private(GuiWorkArea * parent)
259 : p(parent), buffer_view_(nullptr), lyx_view_(nullptr), caret_(nullptr),
260 caret_visible_(false), need_resize_(false), preedit_lines_(1),
261 last_pixel_ratio_(1.0), completer_(new GuiCompleter(p, p)),
262 dialog_mode_(false), shell_escape_(false), read_only_(false),
263 clean_(true), externally_modified_(false), needs_caret_geometry_update_(true)
265 /* Qt on macOS and Wayland does not respect the
266 * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
267 * store at each update. Therefore, we use our own backing store in
268 * these two cases. */
269 #if QT_VERSION >= 0x050000
270 use_backingstore_ = guiApp->platformName() == "cocoa"
271 || guiApp->platformName().contains("wayland");
274 use_backingstore_ = true;
276 use_backingstore_ = false;
280 int const time = QApplication::cursorFlashTime() / 2;
282 caret_timeout_.setInterval(time);
283 caret_timeout_.start();
285 // let's initialize this just to be safe
286 caret_timeout_.setInterval(500);
291 GuiWorkArea::Private::~Private()
293 // If something is wrong with the buffer, we can ignore it safely
295 buffer_view_->buffer().workAreaManager().remove(p);
299 // Completer has a QObject parent and is thus automatically destroyed.
301 // delete completer_;
305 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
306 : d(new Private(this))
308 new CompressorProxy(this); // not a leak
312 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
313 : d(new Private(this))
315 new CompressorProxy(this); // not a leak
317 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
323 double GuiWorkArea::pixelRatio() const
325 #if QT_VERSION >= 0x050000
326 return qt_scale_factor * devicePixelRatio();
333 void GuiWorkArea::init()
336 connect(&d->caret_timeout_, SIGNAL(timeout()),
337 this, SLOT(toggleCaret()));
339 // This connection is closed at the same time as this is destroyed.
340 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
341 generateSyntheticMouseEvent();
345 // With Qt4.5 a mouse event will happen before the first paint event
346 // so make sure that the buffer view has an up to date metrics.
347 d->buffer_view_->resize(viewport()->width(), viewport()->height());
348 d->caret_ = new frontend::CaretWidget();
350 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
351 setAcceptDrops(true);
352 setMouseTracking(true);
353 setMinimumSize(100, 70);
354 setFrameStyle(QFrame::NoFrame);
357 d->updateCursorShape();
359 // we paint our own background
360 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
362 setFocusPolicy(Qt::StrongFocus);
364 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
365 << " viewport height: " << viewport()->height());
367 // Enables input methods for asian languages.
368 // Must be set when creating custom text editing widgets.
369 setAttribute(Qt::WA_InputMethodEnabled, true);
373 GuiWorkArea::~GuiWorkArea()
379 void GuiWorkArea::Private::updateCursorShape()
381 bool const clickable = buffer_view_ && buffer_view_->clickableInset();
382 p->viewport()->setCursor(clickable ? Qt::PointingHandCursor
387 void GuiWorkArea::setGuiView(GuiView & gv)
393 void GuiWorkArea::setBuffer(Buffer & buffer)
395 delete d->buffer_view_;
396 d->buffer_view_ = new BufferView(buffer);
397 buffer.workAreaManager().add(this);
399 // HACK: Prevents an additional redraw when the scrollbar pops up
400 // which regularly happens on documents with more than one page.
401 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
402 // Since we have no geometry information yet, we assume that
403 // a document needs a scrollbar if there is more then four
404 // paragraph in the outermost text.
405 if (buffer.text().paragraphs().size() > 4)
406 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
407 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
408 Q_EMIT bufferViewChanged();
412 void GuiWorkArea::fixVerticalScrollBar()
415 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
419 void GuiWorkArea::close()
421 d->lyx_view_->removeWorkArea(this);
425 void GuiWorkArea::setFullScreen(bool full_screen)
427 d->buffer_view_->setFullScreen(full_screen);
428 if (full_screen && lyxrc.full_screen_scrollbar)
429 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
431 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
435 BufferView & GuiWorkArea::bufferView()
437 return *d->buffer_view_;
441 BufferView const & GuiWorkArea::bufferView() const
443 return *d->buffer_view_;
447 void GuiWorkArea::stopBlinkingCaret()
449 d->caret_timeout_.stop();
454 void GuiWorkArea::startBlinkingCaret()
456 // do not show the cursor if the view is busy
460 // Don't start blinking if the cursor isn't on screen, unless we
461 // are not ready to know whether the cursor is on screen.
462 if (!d->buffer_view_->buffer().undo().activeUndoGroup()
463 && !d->buffer_view_->caretInView())
468 // Avoid blinking when debugging PAINTING, since it creates too much noise
469 if (!lyxerr.debugging(Debug::PAINTING)) {
470 // we are not supposed to cache this value.
471 int const time = QApplication::cursorFlashTime() / 2;
474 d->caret_timeout_.setInterval(time);
475 d->caret_timeout_.start();
480 void GuiWorkArea::toggleCaret()
482 if (d->caret_visible_)
489 void GuiWorkArea::scheduleRedraw(bool update_metrics)
492 // No need to redraw in this case.
495 // No need to do anything if this is the current view. The BufferView
496 // metrics are already up to date.
497 if (update_metrics || d->lyx_view_ != guiApp->currentView()
498 || d->lyx_view_->currentWorkArea() != this) {
499 // FIXME: it would be nice to optimize for the off-screen case.
500 d->buffer_view_->cursor().fixIfBroken();
501 d->buffer_view_->updateMetrics();
502 d->buffer_view_->cursor().fixIfBroken();
505 // update caret position, because otherwise it has to wait until
506 // the blinking interval is over
509 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
510 viewport()->update();
512 /// FIXME: is this still true now that paintEvent does the actual painting?
513 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
514 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
515 d->updateScrollbar();
516 d->lyx_view_->updateStatusBar();
518 if (lyxerr.debugging(Debug::WORKAREA))
519 d->buffer_view_->coordCache().dump();
523 d->updateCursorShape();
527 // Keep in sync with GuiWorkArea::processKeySym below
528 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
530 return guiApp->queryKeySym(key, mod);
534 // Keep in sync with GuiWorkArea::queryKeySym above
535 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
537 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
538 && lyxrc.full_screen_menubar) {
539 // FIXME HACK: we should not have to do this here. See related comment
540 // in GuiView::event() (QEvent::ShortcutOverride)
541 d->lyx_view_->menuBar()->hide();
544 // In order to avoid bad surprise in the middle of an operation,
545 // we better stop the blinking caret...
546 // the caret gets restarted in GuiView::restartCaret()
548 guiApp->processKeySym(key, mod);
552 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
555 if (cmd.action() == LFUN_FILE_OPEN) {
557 lyx_view_->dispatch(cmd, dr);
561 bool const notJustMovingTheMouse =
562 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
564 // In order to avoid bad surprise in the middle of an operation, we better stop
565 // the blinking caret.
566 if (notJustMovingTheMouse)
567 p->stopBlinkingCaret();
569 buffer_view_->mouseEventDispatch(cmd);
571 // Skip these when selecting
572 // FIXME: let GuiView take care of those.
573 if (cmd.action() != LFUN_MOUSE_MOTION) {
574 completer_->updateVisibility(false, false);
575 lyx_view_->updateDialogs();
576 lyx_view_->updateStatusBar();
579 // GUI tweaks except with mouse motion with no button pressed.
580 if (notJustMovingTheMouse) {
581 // Slight hack: this is only called currently when we
582 // clicked somewhere, so we force through the display
583 // of the new status here.
584 // FIXME: let GuiView take care of those.
585 lyx_view_->clearMessage();
587 // Show the caret immediately after any operation
588 p->startBlinkingCaret();
595 void GuiWorkArea::Private::resizeBufferView()
597 // WARNING: Please don't put any code that will trigger a repaint here!
598 // We are already inside a paint event.
599 p->stopBlinkingCaret();
600 // Warn our container (GuiView).
603 bool const caret_in_view = buffer_view_->caretInView();
604 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
606 buffer_view_->scrollToCursor();
609 // Update scrollbars which might have changed due different
610 // BufferView dimension. This is especially important when the
611 // BufferView goes from zero-size to the real-size for the first time,
612 // as the scrollbar parameters are then set for the first time.
615 need_resize_ = false;
617 // Eventually, restart the caret after the resize event.
618 // We might be resizing even if the focus is on another widget so we only
619 // restart the caret if we have the focus.
621 QTimer::singleShot(50, p, SLOT(startBlinkingCaret()));
625 void GuiWorkArea::Private::resetCaret()
627 // Don't start blinking if the cursor isn't on screen.
628 if (!buffer_view_->caretInView())
631 needs_caret_geometry_update_ = true;
632 caret_visible_ = true;
636 void GuiWorkArea::Private::updateCaretGeometry()
638 // we cannot update geometry if not ready and we do not need to if
639 // caret is not in view.
640 if (buffer_view_->buffer().undo().activeUndoGroup()
641 || !buffer_view_->caretInView())
646 buffer_view_->caretPosAndHeight(point, h);
649 bool l_shape = false;
650 Font const & realfont = buffer_view_->cursor().real_current_font;
651 FontMetrics const & fm = theFontMetrics(realfont.fontInfo());
652 BufferParams const & bp = buffer_view_->buffer().params();
653 bool const samelang = realfont.language() == bp.language;
654 bool const isrtl = realfont.isVisibleRightToLeft();
656 if (!samelang || isrtl != bp.language->rightToLeft())
659 // The ERT language hack needs fixing up
660 if (realfont.language() == latex_language)
663 // show caret on screen
664 Cursor & cur = buffer_view_->cursor();
665 bool completable = cur.inset().showCompletionCursor()
666 && completer_->completionAvailable()
667 && !completer_->popupVisible()
668 && !completer_->inlineVisible();
670 caret_->update(point.x_, point.y_, h, l_shape, isrtl, completable,
671 // use slanted caret for italics in text edit mode
672 fm.italic() && buffer_view_->cursor().inTexted()
673 // except for selections because the selection rect does not slant
674 && !buffer_view_->cursor().selection(), fm.maxAscent());
675 needs_caret_geometry_update_ = false;
680 void GuiWorkArea::Private::showCaret()
686 p->viewport()->update();
690 void GuiWorkArea::Private::hideCaret()
695 caret_visible_ = false;
696 //if (!qApp->focusWidget())
697 p->viewport()->update();
701 void GuiWorkArea::Private::updateScrollbar()
703 // Prevent setRange() and setSliderPosition from causing recursive calls via
704 // the signal valueChanged. (#10311)
705 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
706 p, SLOT(scrollTo(int)));
707 ScrollbarParameters const & scroll = buffer_view_->scrollbarParameters();
708 p->verticalScrollBar()->setRange(scroll.min, scroll.max);
709 p->verticalScrollBar()->setPageStep(scroll.page_step);
710 p->verticalScrollBar()->setSingleStep(scroll.single_step);
711 p->verticalScrollBar()->setSliderPosition(0);
712 // Connect to the vertical scroll bar
713 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
714 p, SLOT(scrollTo(int)));
718 void GuiWorkArea::scrollTo(int value)
721 d->buffer_view_->scrollDocView(value, true);
723 if (lyxrc.cursor_follows_scrollbar) {
724 d->buffer_view_->setCursorFromScrollbar();
725 // FIXME: let GuiView take care of those.
726 d->lyx_view_->updateLayoutList();
728 // Show the caret immediately after any operation.
729 startBlinkingCaret();
732 QApplication::syncX();
737 bool GuiWorkArea::event(QEvent * e)
740 case QEvent::ToolTip: {
741 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
742 if (lyxrc.use_tooltip) {
743 QPoint pos = helpEvent->pos();
744 if (pos.x() < viewport()->width()) {
745 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
746 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
749 QToolTip::hideText();
751 // Don't forget to accept the event!
756 case QEvent::ShortcutOverride:
757 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
759 keyPressEvent(static_cast<QKeyEvent *>(e));
760 return e->isAccepted();
762 case QEvent::KeyPress: {
763 // We catch this event in order to catch the Tab or Shift+Tab key press
764 // which are otherwise reserved to focus switching between controls
766 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
767 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
768 || (ke->key() == Qt::Key_Backtab && (
769 ke->modifiers() == Qt::ShiftModifier
770 || ke->modifiers() == Qt::NoModifier))) {
774 return QAbstractScrollArea::event(e);
778 return QAbstractScrollArea::event(e);
784 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
787 if (e->reason() == QContextMenuEvent::Mouse)
788 // the menu name is set on mouse press
789 name = d->context_menu_name_;
791 QPoint pos = e->pos();
792 Cursor const & cur = d->buffer_view_->cursor();
793 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
794 // Do not access the context menu of math right in front of before
795 // the cursor. This does not work when the cursor is in text.
796 Inset * inset = cur.paragraph().getInset(cur.pos());
797 if (inset && inset->asInsetMath())
799 else if (cur.pos() > 0) {
800 inset = cur.paragraph().getInset(cur.pos() - 1);
805 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
812 // always show mnemonics when the keyboard is used to show the context menu
813 // FIXME: This should be fixed in Qt itself
814 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
815 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
820 // Position the menu to the right.
821 // FIXME: menu position should be different for RTL text.
822 menu->exec(e->globalPos());
827 void GuiWorkArea::focusInEvent(QFocusEvent * e)
829 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
830 if (d->lyx_view_->currentWorkArea() != this) {
831 d->lyx_view_->setCurrentWorkArea(this);
832 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
835 startBlinkingCaret();
836 QAbstractScrollArea::focusInEvent(e);
840 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
842 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
844 QAbstractScrollArea::focusOutEvent(e);
848 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
850 if (d->dc_event_.active && d->dc_event_ == *e) {
851 d->dc_event_.active = false;
852 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
853 q_button_state(e->button()), q_key_state(e->modifiers()));
859 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
860 inputContext()->reset();
863 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
864 q_button_state(e->button()), q_key_state(e->modifiers()));
867 // Save the context menu on mouse press, because also the mouse
868 // cursor is set on mouse press. Afterwards, we can either release
869 // the mousebutton somewhere else, or the cursor might have moved
870 // due to the DEPM. We need to do this after the mouse has been
871 // set in dispatch(), because the selection state might change.
872 if (e->button() == Qt::RightButton)
873 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
879 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
881 if (d->synthetic_mouse_event_.timeout.running())
882 d->synthetic_mouse_event_.timeout.stop();
884 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
885 q_button_state(e->button()), q_key_state(e->modifiers()));
886 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
887 QT_VERSION < QT_VERSION_CHECK(5,15,1))
888 d->synthetic_mouse_event_.cmd = cmd; // QtBug QAbstractScrollArea::mouseMoveEvent
895 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
897 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
898 QT_VERSION < QT_VERSION_CHECK(5,15,1))
899 // cancel the event if the coordinates didn't change, this is due to QtBug
900 // QAbstractScrollArea::mouseMoveEvent, the event is triggered falsely when quickly
901 // double tapping a touchpad. To test: try to select a word by quickly double tapping
902 // on a touchpad while hovering the cursor over that word in the work area.
903 // This bug does not occur on Qt versions 5.10.1 and below. Only Windows seems to be affected.
904 // ML thread: https://www.mail-archive.com/lyx-devel@lists.lyx.org/msg211699.html
905 // Qt bugtracker: https://bugreports.qt.io/browse/QTBUG-85431
906 // Bug was fixed in Qt 5.15.1
907 if (e->x() == d->synthetic_mouse_event_.cmd.x() && // QtBug QAbstractScrollArea::mouseMoveEvent
908 e->y() == d->synthetic_mouse_event_.cmd.y()) // QtBug QAbstractScrollArea::mouseMoveEvent
909 return; // QtBug QAbstractScrollArea::mouseMoveEvent
912 // we kill the triple click if we move
913 doubleClickTimeout();
914 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
915 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
919 // If we're above or below the work area...
920 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
921 && e->buttons() == mouse_button::button1) {
922 // Make sure only a synthetic event can cause a page scroll,
923 // so they come at a steady rate:
925 // _Force_ a scroll up:
926 cmd.set_y(e->y() - 21);
928 cmd.set_y(e->y() + 21);
929 // Store the event, to be handled when the timeout expires.
930 d->synthetic_mouse_event_.cmd = cmd;
932 if (d->synthetic_mouse_event_.timeout.running()) {
933 // Discard the event. Note that it _may_ be handled
934 // when the timeout expires if
935 // synthetic_mouse_event_.cmd has not been overwritten.
936 // Ie, when the timeout expires, we handle the
937 // most recent event but discard all others that
938 // occurred after the one used to start the timeout
939 // in the first place.
943 d->synthetic_mouse_event_.restart_timeout = true;
944 d->synthetic_mouse_event_.timeout.start();
945 // Fall through to handle this event...
947 } else if (d->synthetic_mouse_event_.timeout.running()) {
948 // Store the event, to be possibly handled when the timeout
950 // Once the timeout has expired, normal control is returned
951 // to mouseMoveEvent (restart_timeout = false).
952 // This results in a much smoother 'feel' when moving the
953 // mouse back into the work area.
954 d->synthetic_mouse_event_.cmd = cmd;
955 d->synthetic_mouse_event_.restart_timeout = false;
962 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
964 // Wheel rotation by one notch results in a delta() of 120 (see
965 // documentation of QWheelEvent)
966 // But first we have to ignore horizontal scroll events.
967 #if QT_VERSION < 0x050000
968 if (ev->orientation() == Qt::Horizontal) {
972 double const delta = ev->delta() / 120.0;
974 QPoint const aDelta = ev->angleDelta();
975 // skip horizontal wheel event
976 if (abs(aDelta.x()) > abs(aDelta.y())) {
980 double const delta = aDelta.y() / 120.0;
984 switch (lyxrc.scroll_wheel_zoom) {
985 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
986 zoom = ev->modifiers() & Qt::ControlModifier;
987 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
989 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
990 zoom = ev->modifiers() & Qt::ShiftModifier;
991 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
993 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
994 zoom = ev->modifiers() & Qt::AltModifier;
995 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
997 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
1001 docstring arg = convert<docstring>(int(5 * delta));
1002 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
1006 // Take into account the desktop wide settings.
1007 int const lines = qApp->wheelScrollLines();
1008 int const page_step = verticalScrollBar()->pageStep();
1009 // Test if the wheel mouse is set to one screen at a time.
1010 // This is according to
1011 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
1013 min(lines * verticalScrollBar()->singleStep(), page_step);
1015 // Take into account the rotation and the user preferences.
1016 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
1017 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
1018 << " delta = " << delta << " scroll_value = " << scroll_value
1019 << " page_step = " << page_step);
1021 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
1027 void GuiWorkArea::generateSyntheticMouseEvent()
1029 int const e_y = d->synthetic_mouse_event_.cmd.y();
1030 int const wh = d->buffer_view_->workHeight();
1031 bool const up = e_y < 0;
1032 bool const down = e_y > wh;
1034 // Set things off to generate the _next_ 'pseudo' event.
1036 if (d->synthetic_mouse_event_.restart_timeout) {
1037 // This is some magic formulae to determine the speed
1038 // of scrolling related to the position of the mouse.
1041 int dist = up ? -e_y : e_y - wh;
1042 time = max(min(200, 250000 / (dist * dist)), 1) ;
1045 step = 80000 / (time * time);
1049 d->synthetic_mouse_event_.timeout.setTimeout(time);
1050 d->synthetic_mouse_event_.timeout.start();
1053 // Can we scroll further ?
1054 int const value = verticalScrollBar()->value();
1055 if (value == verticalScrollBar()->maximum()
1056 || value == verticalScrollBar()->minimum()) {
1057 d->synthetic_mouse_event_.timeout.stop();
1062 if (step <= 2 * wh) {
1063 d->buffer_view_->scroll(up ? -step : step);
1064 d->buffer_view_->updateMetrics();
1066 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
1069 // In which paragraph do we have to set the cursor ?
1070 Cursor & cur = d->buffer_view_->cursor();
1071 // FIXME: we don't know how to handle math.
1072 Text * text = cur.text();
1075 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
1077 // Quit gracefully if there are no metrics, since otherwise next
1078 // line would crash (bug #10324).
1079 // This situation seems related to a (not yet understood) timing problem.
1083 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
1084 ParagraphMetrics const & pm = *pp.second;
1085 pit_type const pit = pp.first;
1087 if (pm.rows().empty())
1090 // Find the row at which we set the cursor.
1091 RowList::const_iterator rit = pm.rows().begin();
1092 RowList::const_iterator rlast = pm.rows().end();
1093 int yy = pm.position() - pm.ascent();
1094 for (--rlast; rit != rlast; ++rit) {
1095 int h = rit->height();
1096 if ((up && yy + h > 0)
1097 || (!up && yy + h > wh - defaultRowHeight()))
1102 // Find the position of the cursor
1104 int x = d->synthetic_mouse_event_.cmd.x();
1105 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1110 cur.boundary(bound);
1112 d->buffer_view_->buffer().changed(false);
1117 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
1118 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
1120 qRegisterMetaType<KeySymbol>("KeySymbol");
1121 qRegisterMetaType<KeyModifier>("KeyModifier");
1122 connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
1123 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
1124 Qt::QueuedConnection);
1125 connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
1126 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1130 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1134 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1135 bool result = flag_;
1141 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1143 if (emitCheck(isAutoRepeat))
1144 Q_EMIT signal(sym, mod);
1146 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1150 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1152 // this is also called for ShortcutOverride events. In this case, one must
1153 // not act but simply accept the event explicitly.
1154 bool const act = (ev->type() != QEvent::ShortcutOverride);
1156 // Do not process here some keys if dialog_mode_ is set
1157 bool const for_dialog_mode = d->dialog_mode_
1158 && (ev->modifiers() == Qt::NoModifier
1159 || ev->modifiers() == Qt::ShiftModifier)
1160 && (ev->key() == Qt::Key_Escape
1161 || ev->key() == Qt::Key_Enter
1162 || ev->key() == Qt::Key_Return);
1163 // also do not use autoRepeat to input shortcuts
1164 bool const autoRepeat = ev->isAutoRepeat();
1166 if (for_dialog_mode || (!act && autoRepeat)) {
1171 // intercept some keys if completion popup is visible
1172 if (d->completer_->popupVisible()) {
1173 switch (ev->key()) {
1175 case Qt::Key_Return:
1177 d->completer_->activate();
1183 KeyModifier const m = q_key_state(ev->modifiers());
1185 if (act && lyxerr.debugging(Debug::KEY)) {
1187 if (m & ShiftModifier)
1189 if (m & ControlModifier)
1191 if (m & AltModifier)
1193 if (m & MetaModifier)
1195 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1196 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1197 << " keyState: " << str);
1201 setKeySymbol(&sym, ev);
1204 Q_EMIT compressKeySym(sym, m, autoRepeat);
1207 // here, !autoRepeat, as determined at the beginning
1208 ev->setAccepted(queryKeySym(sym, m));
1215 void GuiWorkArea::doubleClickTimeout()
1217 d->dc_event_.active = false;
1221 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1223 d->dc_event_ = DoubleClick(ev);
1224 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1225 SLOT(doubleClickTimeout()));
1226 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1227 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1233 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1235 QAbstractScrollArea::resizeEvent(ev);
1236 d->need_resize_ = true;
1241 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1243 if (preedit_string_.empty())
1246 // FIXME: shall we use real_current_font here? (see #10478)
1247 FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1248 FontMetrics const & fm = theFontMetrics(font);
1249 int const height = fm.maxHeight();
1250 int cur_x = caret_->rect().left();
1251 int cur_y = caret_->rect().bottom();
1253 // get attributes of input method cursor.
1254 // cursor_pos : cursor position in preedit string.
1255 size_t cursor_pos = 0;
1256 bool cursor_is_visible = false;
1257 for (auto const & attr : preedit_attr_) {
1258 if (attr.type == QInputMethodEvent::Cursor) {
1259 cursor_pos = size_t(attr.start);
1260 cursor_is_visible = attr.length != 0;
1265 size_t const preedit_length = preedit_string_.length();
1267 // get position of selection in input method.
1268 // FIXME: isn't there a simpler way to do this?
1269 // rStart : cursor position in selected string in IM.
1271 // rLength : selected string length in IM.
1273 if (cursor_pos < preedit_length) {
1274 for (auto const & attr : preedit_attr_) {
1275 if (attr.type == QInputMethodEvent::TextFormat) {
1276 if (attr.start <= int(cursor_pos)
1277 && int(cursor_pos) < attr.start + attr.length) {
1278 rStart = size_t(attr.start);
1279 rLength = size_t(attr.length);
1280 if (!cursor_is_visible)
1281 cursor_pos += rLength;
1288 rStart = cursor_pos;
1292 int const right_margin = buffer_view_->rightMargin();
1293 Painter::preedit_style ps;
1294 // Most often there would be only one line:
1296 for (size_t pos = 0; pos != preedit_length; ++pos) {
1297 char_type const typed_char = preedit_string_[pos];
1298 // reset preedit string style
1299 ps = Painter::preedit_default;
1301 // if we reached the right extremity of the screen, go to next line.
1302 if (cur_x + fm.width(typed_char) > p->viewport()->width() - right_margin) {
1303 cur_x = right_margin;
1304 cur_y += height + 1;
1307 // preedit strings are displayed with dashed underline
1308 // and partial strings are displayed white on black indicating
1309 // that we are in selecting mode in the input method.
1310 // FIXME: rLength == preedit_length is not a changing condition
1311 // FIXME: should be put out of the loop.
1313 && pos < rStart + rLength
1314 && !(cursor_pos < rLength && rLength == preedit_length))
1315 ps = Painter::preedit_selecting;
1317 if (pos == cursor_pos
1318 && (cursor_pos < rLength && rLength == preedit_length))
1319 ps = Painter::preedit_cursor;
1321 // draw one character and update cur_x.
1322 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1327 void GuiWorkArea::Private::resetScreen()
1329 if (use_backingstore_) {
1330 int const pr = p->pixelRatio();
1331 screen_ = QImage(static_cast<int>(pr * p->viewport()->width()),
1332 static_cast<int>(pr * p->viewport()->height()),
1333 QImage::Format_ARGB32_Premultiplied);
1334 # if QT_VERSION >= 0x050000
1335 screen_.setDevicePixelRatio(pr);
1341 QPaintDevice * GuiWorkArea::Private::screenDevice()
1343 if (use_backingstore_)
1346 return p->viewport();
1350 void GuiWorkArea::Private::updateScreen(QRectF const & rc)
1352 if (use_backingstore_) {
1353 QPainter qpain(p->viewport());
1354 double const pr = p->pixelRatio();
1355 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr,
1356 rc.width() * pr, rc.height() * pr);
1357 qpain.drawImage(rc, screen_, rcs);
1362 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1364 // Do not trigger the painting machinery if we are not ready (see
1365 // bug #10989). The second test triggers when in the middle of a
1366 // dispatch operation.
1367 if (view().busy() || d->buffer_view_->buffer().undo().activeUndoGroup()) {
1368 // Since macOS has turned the screen black at this point, our
1369 // backing store has to be copied to screen (this is a no-op
1370 // except on macOS).
1371 d->updateScreen(ev->rect());
1372 // Ignore this paint event, but request a new one for later.
1373 viewport()->update(ev->rect());
1378 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1379 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1381 if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_) {
1383 d->resizeBufferView();
1386 d->last_pixel_ratio_ = pixelRatio();
1388 GuiPainter pain(d->screenDevice(), pixelRatio(), d->lyx_view_->develMode());
1390 d->buffer_view_->draw(pain, d->caret_visible_);
1392 // The preedit text, if needed
1393 d->paintPreeditText(pain);
1396 // FIXME: the code would be a little bit simpler if caret geometry
1397 // was updated unconditionally. Some profiling is required to see
1398 // how expensive this is (especially when idle).
1399 if (d->caret_visible_) {
1400 if (d->needs_caret_geometry_update_)
1401 d->updateCaretGeometry();
1402 d->caret_->draw(pain, d->buffer_view_->horizScrollOffset());
1405 d->updateScreen(ev->rect());
1411 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1413 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1414 << " commitString: " << e->commitString());
1416 // insert the processed text in the document (handles undo)
1417 if (!e->commitString().isEmpty()) {
1418 FuncRequest cmd(LFUN_SELF_INSERT,
1419 qstring_to_ucs4(e->commitString()),
1420 FuncRequest::KEYBOARD);
1422 // FIXME: this is supposed to remove traces from preedit
1423 // string. Can we avoid calling it explicitly?
1424 d->buffer_view_->updateMetrics();
1427 // Hide the caret during the test transformation.
1428 if (e->preeditString().isEmpty())
1429 startBlinkingCaret();
1431 stopBlinkingCaret();
1433 if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1439 // The preedit text and its attributes will be used in paintPreeditText
1440 d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1441 d->preedit_attr_ = e->attributes();
1444 // redraw area of preedit string.
1445 int height = d->caret_->rect().height();
1446 int cur_y = d->caret_->rect().bottom();
1447 viewport()->update(0, cur_y - height, viewport()->width(),
1448 (height + 1) * d->preedit_lines_);
1450 if (d->preedit_string_.empty()) {
1451 d->preedit_lines_ = 1;
1456 // Don't forget to accept the event!
1461 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1463 QRect cur_r(0, 0, 0, 0);
1465 // this is the CJK-specific composition window position and
1466 // the context menu position when the menu key is pressed.
1467 case Qt::ImMicroFocus:
1468 cur_r = d->caret_->rect();
1469 if (d->preedit_lines_ != 1)
1471 cur_r.moveBottom(cur_r.bottom()
1472 + cur_r.height() * (d->preedit_lines_ - 1));
1473 // return lower right of caret in LyX.
1476 return QWidget::inputMethodQuery(query);
1481 void GuiWorkArea::updateWindowTitle()
1483 Buffer const & buf = bufferView().buffer();
1484 if (buf.fileName() != d->file_name_
1485 || buf.params().shell_escape != d->shell_escape_
1486 || buf.hasReadonlyFlag() != d->read_only_
1487 || buf.lyxvc().vcstatus() != d->vc_status_
1488 || buf.isClean() != d->clean_
1489 || buf.notifiesExternalModification() != d->externally_modified_) {
1490 d->file_name_ = buf.fileName();
1491 d->shell_escape_ = buf.params().shell_escape;
1492 d->read_only_ = buf.hasReadonlyFlag();
1493 d->vc_status_ = buf.lyxvc().vcstatus();
1494 d->clean_ = buf.isClean();
1495 d->externally_modified_ = buf.notifiesExternalModification();
1496 Q_EMIT titleChanged(this);
1501 bool GuiWorkArea::isFullScreen() const
1503 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1507 bool GuiWorkArea::inDialogMode() const
1509 return d->dialog_mode_;
1513 void GuiWorkArea::setDialogMode(bool mode)
1515 d->dialog_mode_ = mode;
1519 GuiCompleter & GuiWorkArea::completer()
1521 return *d->completer_;
1524 GuiView const & GuiWorkArea::view() const
1526 return *d->lyx_view_;
1530 GuiView & GuiWorkArea::view()
1532 return *d->lyx_view_;
1535 ////////////////////////////////////////////////////////////////////
1539 ////////////////////////////////////////////////////////////////////
1542 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1544 support::TempFile tempfile("embedded.internal");
1545 tempfile.setAutoRemove(false);
1546 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1547 buffer_->setUnnamed(true);
1548 buffer_->setFullyLoaded(true);
1549 setBuffer(*buffer_);
1550 setDialogMode(true);
1554 EmbeddedWorkArea::~EmbeddedWorkArea()
1556 // No need to destroy buffer and bufferview here, because it is done
1557 // in theBufferList() destruction loop at application exit
1561 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1564 GuiWorkArea::closeEvent(ev);
1568 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1571 GuiWorkArea::hideEvent(ev);
1575 QSize EmbeddedWorkArea::sizeHint () const
1578 // GuiWorkArea sets the size to the screen's viewport
1579 // by returning a value this gets overridden
1580 // EmbeddedWorkArea is now sized to fit in the layout
1581 // of the parent, and has a minimum size set in GuiWorkArea
1582 // which is what we return here
1583 return QSize(100, 70);
1587 void EmbeddedWorkArea::disable()
1589 stopBlinkingCaret();
1590 if (view().currentWorkArea() != this)
1592 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1593 // tolerates it and shows the background logo), what happens if
1594 // an EmbeddedWorkArea is closed after closing all document WAs
1595 view().setCurrentWorkArea(view().currentMainWorkArea());
1598 ////////////////////////////////////////////////////////////////////
1602 ////////////////////////////////////////////////////////////////////
1605 class NoTabFrameMacStyle : public QProxyStyle {
1608 QRect subElementRect(SubElement element, const QStyleOption * option,
1609 const QWidget * widget = 0) const
1611 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1612 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1614 // The Qt Mac style puts the contents into a 3 pixel wide box
1615 // which looks very ugly and not like other Mac applications.
1616 // Hence we remove this here, and moreover the 16 pixel round
1617 // frame above if the tab bar is hidden.
1618 if (element == QStyle::SE_TabWidgetTabContents) {
1619 rect.adjust(- rect.left(), 0, rect.left(), 0);
1628 NoTabFrameMacStyle noTabFrameMacStyle;
1632 TabWorkArea::TabWorkArea(QWidget * parent)
1633 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1636 setStyle(&noTabFrameMacStyle);
1639 QPalette pal = palette();
1640 pal.setColor(QPalette::Active, QPalette::Button,
1641 pal.color(QPalette::Active, QPalette::Window));
1642 pal.setColor(QPalette::Disabled, QPalette::Button,
1643 pal.color(QPalette::Disabled, QPalette::Window));
1644 pal.setColor(QPalette::Inactive, QPalette::Button,
1645 pal.color(QPalette::Inactive, QPalette::Window));
1647 QObject::connect(this, SIGNAL(currentChanged(int)),
1648 this, SLOT(on_currentTabChanged(int)));
1650 closeBufferButton = new QToolButton(this);
1651 closeBufferButton->setPalette(pal);
1652 // FIXME: rename the icon to closebuffer.png
1653 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1654 closeBufferButton->setText("Close File");
1655 closeBufferButton->setAutoRaise(true);
1656 closeBufferButton->setCursor(Qt::ArrowCursor);
1657 closeBufferButton->setToolTip(qt_("Close File"));
1658 closeBufferButton->setEnabled(true);
1659 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1660 this, SLOT(closeCurrentBuffer()));
1661 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1663 // set TabBar behaviour
1664 QTabBar * tb = tabBar();
1665 tb->setTabsClosable(!lyxrc.single_close_tab_button);
1666 tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1667 tb->setElideMode(Qt::ElideNone);
1668 // allow dragging tabs
1669 tb->setMovable(true);
1670 // make us responsible for the context menu of the tabbar
1671 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1672 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1673 this, SLOT(showContextMenu(const QPoint &)));
1674 connect(tb, SIGNAL(tabCloseRequested(int)),
1675 this, SLOT(closeTab(int)));
1677 setUsesScrollButtons(true);
1681 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1683 if (me->button() == Qt::MidButton)
1684 midpressed_tab_ = tabBar()->tabAt(me->pos());
1686 QTabWidget::mousePressEvent(me);
1690 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1692 if (me->button() == Qt::MidButton) {
1693 int const midreleased_tab = tabBar()->tabAt(me->pos());
1694 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1695 closeTab(midreleased_tab);
1697 QTabWidget::mouseReleaseEvent(me);
1701 void TabWorkArea::paintEvent(QPaintEvent * event)
1703 if (tabBar()->isVisible()) {
1704 QTabWidget::paintEvent(event);
1706 // Prevent the selected tab to influence the
1707 // painting of the frame of the tab widget.
1708 // This is needed for gtk style in Qt.
1709 QStylePainter p(this);
1710 #if QT_VERSION < 0x050000
1711 QStyleOptionTabWidgetFrameV2 opt;
1713 QStyleOptionTabWidgetFrame opt;
1715 initStyleOption(&opt);
1716 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1718 opt.selectedTabRect = QRect();
1719 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1724 bool TabWorkArea::posIsTab(QPoint position)
1726 // tabAt returns -1 if tab does not covers position
1727 return tabBar()->tabAt(position) > -1;
1731 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1733 if (event->button() != Qt::LeftButton)
1736 // this code chunk is unnecessary because it seems the event only makes
1737 // it this far if it is not on a tab. I'm not sure why this is (maybe
1738 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1739 // this is true in all cases and if it will be true in the future so I
1740 // leave this code for now. (skostysh, 2016-07-21)
1742 // return early if double click on existing tabs
1743 if (posIsTab(event->pos()))
1746 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1750 void TabWorkArea::setFullScreen(bool full_screen)
1752 for (int i = 0; i != count(); ++i) {
1753 if (GuiWorkArea * wa = workArea(i))
1754 wa->setFullScreen(full_screen);
1757 if (lyxrc.full_screen_tabbar)
1758 showBar(!full_screen && count() > 1);
1760 showBar(count() > 1);
1764 void TabWorkArea::showBar(bool show)
1766 tabBar()->setEnabled(show);
1767 tabBar()->setVisible(show);
1768 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1769 setTabsClosable(!lyxrc.single_close_tab_button);
1773 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1775 QWidget * w = QTabWidget::widget(index);
1778 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1784 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1786 return widget(currentIndex());
1790 GuiWorkArea * TabWorkArea::workArea(int index) const
1792 GuiWorkAreaContainer * w = widget(index);
1795 return w->workArea();
1799 GuiWorkArea * TabWorkArea::currentWorkArea() const
1801 return workArea(currentIndex());
1805 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1807 // FIXME: this method doesn't work if we have more than one work area
1808 // showing the same buffer.
1809 for (int i = 0; i != count(); ++i) {
1810 GuiWorkArea * wa = workArea(i);
1811 LASSERT(wa, return nullptr);
1812 if (&wa->bufferView().buffer() == &buffer)
1819 void TabWorkArea::closeAll()
1822 QWidget * wac = widget(0);
1823 LASSERT(wac, return);
1830 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1832 for (int index = 0; index < count(); ++index)
1833 if (workArea(index) == w)
1839 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1841 LASSERT(work_area, return false);
1842 int index = indexOfWorkArea(work_area);
1846 if (index == currentIndex())
1847 // Make sure the work area is up to date.
1848 on_currentTabChanged(index);
1850 // Switch to the work area.
1851 setCurrentIndex(index);
1852 work_area->setFocus();
1858 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1860 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1861 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1862 wa->setUpdatesEnabled(false);
1863 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1864 // when hiding it again below).
1865 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1866 showBar(count() > 0);
1867 addTab(wac, wa->windowTitle());
1868 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1869 this, SLOT(updateTabTexts()));
1870 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1871 setFullScreen(true);
1873 // Hide tabbar if there's only one tab.
1874 showBar(count() > 1);
1882 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1884 LASSERT(work_area, return false);
1885 int index = indexOfWorkArea(work_area);
1889 work_area->setUpdatesEnabled(false);
1890 QWidget * wac = widget(index);
1895 // make sure the next work area is enabled.
1896 currentWidget()->setUpdatesEnabled(true);
1897 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1898 setFullScreen(true);
1900 // Show tabbar only if there's more than one tab.
1901 showBar(count() > 1);
1903 lastWorkAreaRemoved();
1911 void TabWorkArea::on_currentTabChanged(int i)
1913 // returns e.g. on application destruction
1916 GuiWorkArea * wa = workArea(i);
1917 LASSERT(wa, return);
1918 wa->setUpdatesEnabled(true);
1919 wa->scheduleRedraw(true);
1922 currentWorkAreaChanged(wa);
1924 LYXERR(Debug::GUI, "currentTabChanged " << i
1925 << " File: " << wa->bufferView().buffer().absFileName());
1929 void TabWorkArea::closeCurrentBuffer()
1932 if (clicked_tab_ == -1)
1933 wa = currentWorkArea();
1935 wa = workArea(clicked_tab_);
1936 LASSERT(wa, return);
1938 wa->view().closeWorkArea(wa);
1942 void TabWorkArea::hideCurrentTab()
1945 if (clicked_tab_ == -1)
1946 wa = currentWorkArea();
1948 wa = workArea(clicked_tab_);
1949 LASSERT(wa, return);
1951 wa->view().hideWorkArea(wa);
1955 void TabWorkArea::closeTab(int index)
1957 on_currentTabChanged(index);
1960 wa = currentWorkArea();
1962 wa = workArea(index);
1963 LASSERT(wa, return);
1965 wa->view().closeWorkArea(wa);
1972 /// make vector happy
1973 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1975 DisplayPath(int tab, FileName const & filename)
1978 // Recode URL encoded chars via fromPercentEncoding()
1979 string const fn = (filename.extension() == "lyx")
1980 ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
1981 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
1982 postfix_ = toqstr(filename.absoluteFilePath()).
1983 split("/", QString::SkipEmptyParts);
1984 postfix_.pop_back();
1985 abs_ = toqstr(filename.absoluteFilePath());
1986 dottedPrefix_ = false;
1989 /// Absolute path for debugging.
1994 /// Add the first segment from the postfix or three dots to the prefix.
1995 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1996 /// when really needed.
1997 void shiftPathSegment(bool dotted)
1999 if (postfix_.count() <= 0)
2003 if (dottedPrefix_ && !prefix_.isEmpty())
2004 prefix_ += ellipsisSlash_;
2005 prefix_ += postfix_.front() + "/";
2007 dottedPrefix_ = dotted && !prefix_.isEmpty();
2008 postfix_.pop_front();
2011 QString displayString() const
2013 if (prefix_.isEmpty())
2016 bool dots = dottedPrefix_ || !postfix_.isEmpty();
2017 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
2020 QString forecastPathString() const
2022 if (postfix_.count() == 0)
2023 return displayString();
2026 + (dottedPrefix_ ? ellipsisSlash_ : "")
2027 + postfix_.front() + "/";
2030 bool final() const { return postfix_.empty(); }
2032 int tab() const { return tab_; }
2036 static QString const ellipsisSlash_;
2040 QStringList postfix_;
2052 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
2056 bool operator<(DisplayPath const & a, DisplayPath const & b)
2058 return a.displayString() < b.displayString();
2062 bool operator==(DisplayPath const & a, DisplayPath const & b)
2064 return a.displayString() == b.displayString();
2068 void TabWorkArea::updateTabTexts()
2070 int const n = count();
2073 std::list<DisplayPath> paths;
2074 typedef std::list<DisplayPath>::iterator It;
2076 // collect full names first: path into postfix, empty prefix and
2077 // filename without extension
2078 for (int i = 0; i < n; ++i) {
2079 GuiWorkArea * i_wa = workArea(i);
2080 FileName const fn = i_wa->bufferView().buffer().fileName();
2081 paths.push_back(DisplayPath(i, fn));
2084 // go through path segments and see if it helps to make the path more unique
2085 bool somethingChanged = true;
2086 bool allFinal = false;
2087 while (somethingChanged && !allFinal) {
2088 // adding path segments changes order
2091 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
2092 somethingChanged = false;
2095 // find segments which are not unique (i.e. non-atomic)
2096 It it = paths.begin();
2098 QString segString = it->displayString();
2099 for (; it != paths.end(); ++it) {
2100 // look to the next item
2105 allFinal = allFinal && it->final();
2107 LYXERR(Debug::GUI, "it = " << it->abs()
2108 << " => " << it->displayString());
2110 // still the same segment?
2112 if ((next != paths.end()
2113 && (nextString = next->displayString()) == segString))
2115 LYXERR(Debug::GUI, "segment ended");
2117 // only a trivial one with one element?
2118 if (it == segStart) {
2119 // start new segment
2121 segString = nextString;
2125 // We found a non-atomic segment
2126 // We know that segStart <= it < next <= paths.end().
2127 // The assertion below tells coverity about it.
2128 LATTEST(segStart != paths.end());
2129 QString dspString = segStart->forecastPathString();
2130 LYXERR(Debug::GUI, "first forecast found for "
2131 << segStart->abs() << " => " << dspString);
2134 // Shift path segments and hope for the best
2135 // that it makes the path more unique.
2136 somethingChanged = true;
2137 bool moreUnique = false;
2138 for (; sit != next; ++sit) {
2139 if (sit->forecastPathString() != dspString) {
2140 LYXERR(Debug::GUI, "different forecast found for "
2141 << sit->abs() << " => " << sit->forecastPathString());
2145 LYXERR(Debug::GUI, "same forecast found for "
2146 << sit->abs() << " => " << dspString);
2149 // if the path segment helped, add it. Otherwise add dots
2150 bool dots = !moreUnique;
2151 LYXERR(Debug::GUI, "using dots = " << dots);
2152 for (sit = segStart; sit != next; ++sit) {
2153 sit->shiftPathSegment(dots);
2154 LYXERR(Debug::GUI, "shifting "
2155 << sit->abs() << " => " << sit->displayString());
2158 // start new segment
2160 segString = nextString;
2164 // set new tab titles
2165 for (It it = paths.begin(); it != paths.end(); ++it) {
2166 int const tab_index = it->tab();
2167 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2168 QString tab_text = it->displayString().replace("&", "&&");
2169 if (!buf.fileName().empty() && !buf.isClean())
2171 QString tab_tooltip = it->abs();
2172 if (buf.hasReadonlyFlag()) {
2173 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2174 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2176 setTabIcon(tab_index, QIcon());
2177 if (buf.notifiesExternalModification()) {
2178 QString const warn = qt_("%1 (modified externally)");
2179 tab_tooltip = warn.arg(tab_tooltip);
2180 tab_text += QChar(0x26a0);
2182 setTabText(tab_index, tab_text);
2183 setTabToolTip(tab_index, tab_tooltip);
2188 void TabWorkArea::showContextMenu(const QPoint & pos)
2191 clicked_tab_ = tabBar()->tabAt(pos);
2192 if (clicked_tab_ == -1)
2195 GuiWorkArea * wa = workArea(clicked_tab_);
2196 LASSERT(wa, return);
2200 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2201 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2203 // we want to show the 'close' option only if this is not a child buffer.
2204 Buffer const & buf = wa->bufferView().buffer();
2206 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2207 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2208 popup.exec(tabBar()->mapToGlobal(pos));
2214 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2216 QWidget * w = widget(fromIndex);
2217 QIcon icon = tabIcon(fromIndex);
2218 QString text = tabText(fromIndex);
2220 setCurrentIndex(fromIndex);
2221 removeTab(fromIndex);
2222 insertTab(toIndex, w, icon, text);
2223 setCurrentIndex(toIndex);
2227 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2228 : QWidget(parent), wa_(wa)
2230 LASSERT(wa, return);
2231 Ui::WorkAreaUi::setupUi(this);
2232 layout()->addWidget(wa);
2233 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2234 this, SLOT(updateDisplay()));
2235 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2236 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2237 setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2242 void GuiWorkAreaContainer::updateDisplay()
2244 Buffer const & buf = wa_->bufferView().buffer();
2245 notificationFrame->setHidden(!buf.notifiesExternalModification());
2246 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2247 .arg(toqstr(buf.fileName().displayName()));
2248 externalModificationLabel->setText(label);
2252 void GuiWorkAreaContainer::dispatch(FuncRequest f) const
2254 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2255 wa_->bufferView().buffer().absFileName()));
2260 void GuiWorkAreaContainer::reload() const
2262 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2266 void GuiWorkAreaContainer::ignore() const
2268 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2272 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2274 // prevent TabWorkArea from opening a new buffer on double click
2279 } // namespace frontend
2282 #include "moc_GuiWorkArea.cpp"