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), slope_(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;
151 if (slant_ && !rtl_) {
155 path.moveTo(x + ascent_ * slope_, y);
156 path.lineTo(x - (rect_.height() - ascent_) * slope_,
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, double slope)
190 color_ = guiApp->colorCache().get(Color_cursor);
193 completable_ = completable;
199 // extension to left and right
203 // RTL/LTR indication
211 // completion triangle
214 l = max(l, TabIndicatorWidth);
216 r = max(r, TabIndicatorWidth);
219 //FIXME: LyXRC::cursor_width should be caret_width
220 caret_width_ = lyxrc.cursor_width
222 : 1 + int((lyxrc.currentZoom + 50) / 200.0);
224 // compute overall rectangle
225 rect_ = QRect(x - l, y, caret_width_ + r + l, h);
228 QRect const & rect() { return rect_; }
231 /// caret is in RTL or LTR text
233 /// indication for RTL or LTR
235 /// triangle to show that a completion is available
239 /// rectangle, possibly with l_shape and completion triangle
241 /// x position (were the vertical line is drawn)
243 /// the width of the vertical blinking bar
245 /// caret is in slanted text
247 /// the fontmetrics ascent for drawing slanted caret
249 /// the slope for drawing slanted caret
254 // This is a 'heartbeat' generating synthetic mouse move events when the
255 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
256 SyntheticMouseEvent::SyntheticMouseEvent()
257 : timeout(200), restart_timeout(true)
261 GuiWorkArea::Private::Private(GuiWorkArea * parent)
262 : p(parent), buffer_view_(nullptr), lyx_view_(nullptr), caret_(nullptr),
263 caret_visible_(false), need_resize_(false), preedit_lines_(1),
264 last_pixel_ratio_(1.0), completer_(new GuiCompleter(p, p)),
265 dialog_mode_(false), shell_escape_(false), read_only_(false),
266 clean_(true), externally_modified_(false), needs_caret_geometry_update_(true)
268 /* Qt on macOS and Wayland does not respect the
269 * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
270 * store at each update. Therefore, we use our own backing store in
271 * these two cases. */
272 #if QT_VERSION >= 0x050000
273 use_backingstore_ = guiApp->platformName() == "cocoa"
274 || guiApp->platformName().contains("wayland");
277 use_backingstore_ = true;
279 use_backingstore_ = false;
283 int const time = QApplication::cursorFlashTime() / 2;
285 caret_timeout_.setInterval(time);
286 caret_timeout_.start();
288 // let's initialize this just to be safe
289 caret_timeout_.setInterval(500);
294 GuiWorkArea::Private::~Private()
296 // If something is wrong with the buffer, we can ignore it safely
298 buffer_view_->buffer().workAreaManager().remove(p);
302 // Completer has a QObject parent and is thus automatically destroyed.
304 // delete completer_;
308 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
309 : d(new Private(this))
311 new CompressorProxy(this); // not a leak
315 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
316 : d(new Private(this))
318 new CompressorProxy(this); // not a leak
320 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
326 double GuiWorkArea::pixelRatio() const
328 #if QT_VERSION >= 0x050000
329 return qt_scale_factor * devicePixelRatio();
336 void GuiWorkArea::init()
339 connect(&d->caret_timeout_, SIGNAL(timeout()),
340 this, SLOT(toggleCaret()));
342 // This connection is closed at the same time as this is destroyed.
343 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
344 generateSyntheticMouseEvent();
348 // With Qt4.5 a mouse event will happen before the first paint event
349 // so make sure that the buffer view has an up to date metrics.
350 d->buffer_view_->resize(viewport()->width(), viewport()->height());
351 d->caret_ = new frontend::CaretWidget();
353 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
354 setAcceptDrops(true);
355 setMouseTracking(true);
356 setMinimumSize(100, 70);
357 setFrameStyle(QFrame::NoFrame);
360 d->updateCursorShape();
362 // we paint our own background
363 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
365 setFocusPolicy(Qt::StrongFocus);
367 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
368 << " viewport height: " << viewport()->height());
370 // Enables input methods for asian languages.
371 // Must be set when creating custom text editing widgets.
372 setAttribute(Qt::WA_InputMethodEnabled, true);
376 GuiWorkArea::~GuiWorkArea()
382 void GuiWorkArea::Private::updateCursorShape()
384 bool const clickable = buffer_view_ && buffer_view_->clickableInset();
385 p->viewport()->setCursor(clickable ? Qt::PointingHandCursor
390 void GuiWorkArea::setGuiView(GuiView & gv)
396 void GuiWorkArea::setBuffer(Buffer & buffer)
398 delete d->buffer_view_;
399 d->buffer_view_ = new BufferView(buffer);
400 buffer.workAreaManager().add(this);
402 // HACK: Prevents an additional redraw when the scrollbar pops up
403 // which regularly happens on documents with more than one page.
404 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
405 // Since we have no geometry information yet, we assume that
406 // a document needs a scrollbar if there is more then four
407 // paragraph in the outermost text.
408 if (buffer.text().paragraphs().size() > 4)
409 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
410 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
411 Q_EMIT bufferViewChanged();
415 void GuiWorkArea::fixVerticalScrollBar()
418 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
422 void GuiWorkArea::close()
424 d->lyx_view_->removeWorkArea(this);
428 void GuiWorkArea::setFullScreen(bool full_screen)
430 d->buffer_view_->setFullScreen(full_screen);
431 if (full_screen && lyxrc.full_screen_scrollbar)
432 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
434 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
438 BufferView & GuiWorkArea::bufferView()
440 return *d->buffer_view_;
444 BufferView const & GuiWorkArea::bufferView() const
446 return *d->buffer_view_;
450 void GuiWorkArea::stopBlinkingCaret()
452 d->caret_timeout_.stop();
457 void GuiWorkArea::startBlinkingCaret()
459 // do not show the cursor if the view is busy
463 // Don't start blinking if the cursor isn't on screen, unless we
464 // are not ready to know whether the cursor is on screen.
465 if (!d->buffer_view_->buffer().undo().activeUndoGroup()
466 && !d->buffer_view_->caretInView())
471 // Avoid blinking when debugging PAINTING, since it creates too much noise
472 if (!lyxerr.debugging(Debug::PAINTING)) {
473 // we are not supposed to cache this value.
474 int const time = QApplication::cursorFlashTime() / 2;
477 d->caret_timeout_.setInterval(time);
478 d->caret_timeout_.start();
483 void GuiWorkArea::toggleCaret()
485 if (d->caret_visible_)
492 void GuiWorkArea::scheduleRedraw(bool update_metrics)
495 // No need to redraw in this case.
498 // No need to do anything if this is the current view. The BufferView
499 // metrics are already up to date.
500 if (update_metrics || d->lyx_view_ != guiApp->currentView()
501 || d->lyx_view_->currentWorkArea() != this) {
502 // FIXME: it would be nice to optimize for the off-screen case.
503 d->buffer_view_->cursor().fixIfBroken();
504 d->buffer_view_->updateMetrics();
505 d->buffer_view_->cursor().fixIfBroken();
508 // update caret position, because otherwise it has to wait until
509 // the blinking interval is over
512 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
513 viewport()->update();
515 /// FIXME: is this still true now that paintEvent does the actual painting?
516 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
517 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
518 d->updateScrollbar();
519 d->lyx_view_->updateStatusBar();
521 if (lyxerr.debugging(Debug::WORKAREA))
522 d->buffer_view_->coordCache().dump();
526 d->updateCursorShape();
530 // Keep in sync with GuiWorkArea::processKeySym below
531 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
533 return guiApp->queryKeySym(key, mod);
537 // Keep in sync with GuiWorkArea::queryKeySym above
538 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
540 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
541 && lyxrc.full_screen_menubar) {
542 // FIXME HACK: we should not have to do this here. See related comment
543 // in GuiView::event() (QEvent::ShortcutOverride)
544 d->lyx_view_->menuBar()->hide();
547 // In order to avoid bad surprise in the middle of an operation,
548 // we better stop the blinking caret...
549 // the caret gets restarted in GuiView::restartCaret()
551 guiApp->processKeySym(key, mod);
555 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
558 if (cmd.action() == LFUN_FILE_OPEN) {
560 lyx_view_->dispatch(cmd, dr);
564 bool const notJustMovingTheMouse =
565 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
567 // In order to avoid bad surprise in the middle of an operation, we better stop
568 // the blinking caret.
569 if (notJustMovingTheMouse)
570 p->stopBlinkingCaret();
572 buffer_view_->mouseEventDispatch(cmd);
574 // Skip these when selecting
575 // FIXME: let GuiView take care of those.
576 if (cmd.action() != LFUN_MOUSE_MOTION) {
577 completer_->updateVisibility(false, false);
578 lyx_view_->updateDialogs();
579 lyx_view_->updateStatusBar();
582 // GUI tweaks except with mouse motion with no button pressed.
583 if (notJustMovingTheMouse) {
584 // Slight hack: this is only called currently when we
585 // clicked somewhere, so we force through the display
586 // of the new status here.
587 // FIXME: let GuiView take care of those.
588 lyx_view_->clearMessage();
590 // Show the caret immediately after any operation
591 p->startBlinkingCaret();
598 void GuiWorkArea::Private::resizeBufferView()
600 // WARNING: Please don't put any code that will trigger a repaint here!
601 // We are already inside a paint event.
602 p->stopBlinkingCaret();
603 // Warn our container (GuiView).
606 bool const caret_in_view = buffer_view_->caretInView();
607 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
609 buffer_view_->scrollToCursor();
612 // Update scrollbars which might have changed due different
613 // BufferView dimension. This is especially important when the
614 // BufferView goes from zero-size to the real-size for the first time,
615 // as the scrollbar parameters are then set for the first time.
618 need_resize_ = false;
620 // Eventually, restart the caret after the resize event.
621 // We might be resizing even if the focus is on another widget so we only
622 // restart the caret if we have the focus.
624 QTimer::singleShot(50, p, SLOT(startBlinkingCaret()));
628 void GuiWorkArea::Private::resetCaret()
630 // Don't start blinking if the cursor isn't on screen.
631 if (!buffer_view_->caretInView())
634 needs_caret_geometry_update_ = true;
635 caret_visible_ = true;
639 void GuiWorkArea::Private::updateCaretGeometry()
641 // we cannot update geometry if not ready and we do not need to if
642 // caret is not in view.
643 if (buffer_view_->buffer().undo().activeUndoGroup()
644 || !buffer_view_->caretInView())
649 buffer_view_->caretPosAndHeight(point, h);
650 Cursor & cur = buffer_view_->cursor();
653 bool l_shape = false;
654 Font const & realfont = cur.real_current_font;
655 FontMetrics const & fm = theFontMetrics(realfont.fontInfo());
656 BufferParams const & bp = buffer_view_->buffer().params();
657 bool const samelang = realfont.language() == bp.language;
658 bool const isrtl = realfont.isVisibleRightToLeft();
660 if (!samelang || isrtl != bp.language->rightToLeft())
663 // The ERT language hack needs fixing up
664 if (realfont.language() == latex_language)
667 // show caret on screen
668 bool completable = cur.inset().showCompletionCursor()
669 && completer_->completionAvailable()
670 && !completer_->popupVisible()
671 && !completer_->inlineVisible();
673 // use slanted caret for italics in text edit mode
674 // except for selections because the selection rect does not slant
675 int slant = fm.italic() && buffer_view_->cursor().inTexted()
676 && !buffer_view_->cursor().selection();
677 double slope = fm.italicSlope();
679 caret_->update(point.x_, point.y_, h, l_shape, isrtl, completable, slant,
680 fm.maxAscent(), slope);
681 needs_caret_geometry_update_ = false;
685 void GuiWorkArea::Private::showCaret()
691 p->viewport()->update();
695 void GuiWorkArea::Private::hideCaret()
700 caret_visible_ = false;
701 //if (!qApp->focusWidget())
702 p->viewport()->update();
706 void GuiWorkArea::Private::updateScrollbar()
708 // Prevent setRange() and setSliderPosition from causing recursive calls via
709 // the signal valueChanged. (#10311)
710 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
711 p, SLOT(scrollTo(int)));
712 ScrollbarParameters const & scroll = buffer_view_->scrollbarParameters();
713 p->verticalScrollBar()->setRange(scroll.min, scroll.max);
714 p->verticalScrollBar()->setPageStep(scroll.page_step);
715 p->verticalScrollBar()->setSingleStep(scroll.single_step);
716 p->verticalScrollBar()->setSliderPosition(0);
717 // Connect to the vertical scroll bar
718 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
719 p, SLOT(scrollTo(int)));
723 void GuiWorkArea::scrollTo(int value)
726 d->buffer_view_->scrollDocView(value, true);
728 if (lyxrc.cursor_follows_scrollbar) {
729 d->buffer_view_->setCursorFromScrollbar();
730 // FIXME: let GuiView take care of those.
731 d->lyx_view_->updateLayoutList();
733 // Show the caret immediately after any operation.
734 startBlinkingCaret();
737 QApplication::syncX();
742 bool GuiWorkArea::event(QEvent * e)
745 case QEvent::ToolTip: {
746 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
747 if (lyxrc.use_tooltip) {
748 QPoint pos = helpEvent->pos();
749 if (pos.x() < viewport()->width()) {
750 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
751 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
754 QToolTip::hideText();
756 // Don't forget to accept the event!
761 case QEvent::ShortcutOverride:
762 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
764 keyPressEvent(static_cast<QKeyEvent *>(e));
765 return e->isAccepted();
767 case QEvent::KeyPress: {
768 // We catch this event in order to catch the Tab or Shift+Tab key press
769 // which are otherwise reserved to focus switching between controls
771 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
772 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
773 || (ke->key() == Qt::Key_Backtab && (
774 ke->modifiers() == Qt::ShiftModifier
775 || ke->modifiers() == Qt::NoModifier))) {
779 return QAbstractScrollArea::event(e);
783 return QAbstractScrollArea::event(e);
789 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
792 if (e->reason() == QContextMenuEvent::Mouse)
793 // the menu name is set on mouse press
794 name = d->context_menu_name_;
796 QPoint pos = e->pos();
797 Cursor const & cur = d->buffer_view_->cursor();
798 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
799 // Do not access the context menu of math right in front of before
800 // the cursor. This does not work when the cursor is in text.
801 Inset * inset = cur.paragraph().getInset(cur.pos());
802 if (inset && inset->asInsetMath())
804 else if (cur.pos() > 0) {
805 inset = cur.paragraph().getInset(cur.pos() - 1);
810 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
817 // always show mnemonics when the keyboard is used to show the context menu
818 // FIXME: This should be fixed in Qt itself
819 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
820 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
825 // Position the menu to the right.
826 // FIXME: menu position should be different for RTL text.
827 menu->exec(e->globalPos());
832 void GuiWorkArea::focusInEvent(QFocusEvent * e)
834 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
835 if (d->lyx_view_->currentWorkArea() != this) {
836 d->lyx_view_->setCurrentWorkArea(this);
837 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
840 startBlinkingCaret();
841 QAbstractScrollArea::focusInEvent(e);
845 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
847 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
849 QAbstractScrollArea::focusOutEvent(e);
853 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
855 if (d->dc_event_.active && d->dc_event_ == *e) {
856 d->dc_event_.active = false;
857 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
858 q_button_state(e->button()), q_key_state(e->modifiers()));
864 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
865 inputContext()->reset();
868 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
869 q_button_state(e->button()), q_key_state(e->modifiers()));
872 // Save the context menu on mouse press, because also the mouse
873 // cursor is set on mouse press. Afterwards, we can either release
874 // the mousebutton somewhere else, or the cursor might have moved
875 // due to the DEPM. We need to do this after the mouse has been
876 // set in dispatch(), because the selection state might change.
877 if (e->button() == Qt::RightButton)
878 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
884 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
886 if (d->synthetic_mouse_event_.timeout.running())
887 d->synthetic_mouse_event_.timeout.stop();
889 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
890 q_button_state(e->button()), q_key_state(e->modifiers()));
891 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
892 QT_VERSION < QT_VERSION_CHECK(5,15,1))
893 d->synthetic_mouse_event_.cmd = cmd; // QtBug QAbstractScrollArea::mouseMoveEvent
900 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
902 #if (QT_VERSION > QT_VERSION_CHECK(5,10,1) && \
903 QT_VERSION < QT_VERSION_CHECK(5,15,1))
904 // cancel the event if the coordinates didn't change, this is due to QtBug
905 // QAbstractScrollArea::mouseMoveEvent, the event is triggered falsely when quickly
906 // double tapping a touchpad. To test: try to select a word by quickly double tapping
907 // on a touchpad while hovering the cursor over that word in the work area.
908 // This bug does not occur on Qt versions 5.10.1 and below. Only Windows seems to be affected.
909 // ML thread: https://www.mail-archive.com/lyx-devel@lists.lyx.org/msg211699.html
910 // Qt bugtracker: https://bugreports.qt.io/browse/QTBUG-85431
911 // Bug was fixed in Qt 5.15.1
912 if (e->x() == d->synthetic_mouse_event_.cmd.x() && // QtBug QAbstractScrollArea::mouseMoveEvent
913 e->y() == d->synthetic_mouse_event_.cmd.y()) // QtBug QAbstractScrollArea::mouseMoveEvent
914 return; // QtBug QAbstractScrollArea::mouseMoveEvent
917 // we kill the triple click if we move
918 doubleClickTimeout();
919 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
920 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
924 // If we're above or below the work area...
925 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
926 && e->buttons() == mouse_button::button1) {
927 // Make sure only a synthetic event can cause a page scroll,
928 // so they come at a steady rate:
930 // _Force_ a scroll up:
931 cmd.set_y(e->y() - 21);
933 cmd.set_y(e->y() + 21);
934 // Store the event, to be handled when the timeout expires.
935 d->synthetic_mouse_event_.cmd = cmd;
937 if (d->synthetic_mouse_event_.timeout.running()) {
938 // Discard the event. Note that it _may_ be handled
939 // when the timeout expires if
940 // synthetic_mouse_event_.cmd has not been overwritten.
941 // Ie, when the timeout expires, we handle the
942 // most recent event but discard all others that
943 // occurred after the one used to start the timeout
944 // in the first place.
948 d->synthetic_mouse_event_.restart_timeout = true;
949 d->synthetic_mouse_event_.timeout.start();
950 // Fall through to handle this event...
952 } else if (d->synthetic_mouse_event_.timeout.running()) {
953 // Store the event, to be possibly handled when the timeout
955 // Once the timeout has expired, normal control is returned
956 // to mouseMoveEvent (restart_timeout = false).
957 // This results in a much smoother 'feel' when moving the
958 // mouse back into the work area.
959 d->synthetic_mouse_event_.cmd = cmd;
960 d->synthetic_mouse_event_.restart_timeout = false;
967 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
969 // Wheel rotation by one notch results in a delta() of 120 (see
970 // documentation of QWheelEvent)
971 // But first we have to ignore horizontal scroll events.
972 #if QT_VERSION < 0x050000
973 if (ev->orientation() == Qt::Horizontal) {
977 double const delta = ev->delta() / 120.0;
979 QPoint const aDelta = ev->angleDelta();
980 // skip horizontal wheel event
981 if (abs(aDelta.x()) > abs(aDelta.y())) {
985 double const delta = aDelta.y() / 120.0;
989 switch (lyxrc.scroll_wheel_zoom) {
990 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
991 zoom = ev->modifiers() & Qt::ControlModifier;
992 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
994 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
995 zoom = ev->modifiers() & Qt::ShiftModifier;
996 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
998 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
999 zoom = ev->modifiers() & Qt::AltModifier;
1000 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
1002 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
1006 docstring arg = convert<docstring>(int(5 * delta));
1007 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
1011 // Take into account the desktop wide settings.
1012 int const lines = qApp->wheelScrollLines();
1013 int const page_step = verticalScrollBar()->pageStep();
1014 // Test if the wheel mouse is set to one screen at a time.
1015 // This is according to
1016 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
1018 min(lines * verticalScrollBar()->singleStep(), page_step);
1020 // Take into account the rotation and the user preferences.
1021 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
1022 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
1023 << " delta = " << delta << " scroll_value = " << scroll_value
1024 << " page_step = " << page_step);
1026 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
1032 void GuiWorkArea::generateSyntheticMouseEvent()
1034 int const e_y = d->synthetic_mouse_event_.cmd.y();
1035 int const wh = d->buffer_view_->workHeight();
1036 bool const up = e_y < 0;
1037 bool const down = e_y > wh;
1039 // Set things off to generate the _next_ 'pseudo' event.
1041 if (d->synthetic_mouse_event_.restart_timeout) {
1042 // This is some magic formulae to determine the speed
1043 // of scrolling related to the position of the mouse.
1046 int dist = up ? -e_y : e_y - wh;
1047 time = max(min(200, 250000 / (dist * dist)), 1) ;
1050 step = 80000 / (time * time);
1054 d->synthetic_mouse_event_.timeout.setTimeout(time);
1055 d->synthetic_mouse_event_.timeout.start();
1058 // Can we scroll further ?
1059 int const value = verticalScrollBar()->value();
1060 if (value == verticalScrollBar()->maximum()
1061 || value == verticalScrollBar()->minimum()) {
1062 d->synthetic_mouse_event_.timeout.stop();
1067 if (step <= 2 * wh) {
1068 d->buffer_view_->scroll(up ? -step : step);
1069 d->buffer_view_->updateMetrics();
1071 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
1074 // In which paragraph do we have to set the cursor ?
1075 Cursor & cur = d->buffer_view_->cursor();
1076 // FIXME: we don't know how to handle math.
1077 Text * text = cur.text();
1080 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
1082 // Quit gracefully if there are no metrics, since otherwise next
1083 // line would crash (bug #10324).
1084 // This situation seems related to a (not yet understood) timing problem.
1088 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
1089 ParagraphMetrics const & pm = *pp.second;
1090 pit_type const pit = pp.first;
1092 if (pm.rows().empty())
1095 // Find the row at which we set the cursor.
1096 RowList::const_iterator rit = pm.rows().begin();
1097 RowList::const_iterator rlast = pm.rows().end();
1098 int yy = pm.position() - pm.ascent();
1099 for (--rlast; rit != rlast; ++rit) {
1100 int h = rit->height();
1101 if ((up && yy + h > 0)
1102 || (!up && yy + h > wh - defaultRowHeight()))
1107 // Find the position of the cursor
1109 int x = d->synthetic_mouse_event_.cmd.x();
1110 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1115 cur.boundary(bound);
1117 d->buffer_view_->buffer().changed(false);
1122 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
1123 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
1125 qRegisterMetaType<KeySymbol>("KeySymbol");
1126 qRegisterMetaType<KeyModifier>("KeyModifier");
1127 connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
1128 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
1129 Qt::QueuedConnection);
1130 connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
1131 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1135 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1139 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1140 bool result = flag_;
1146 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1148 if (emitCheck(isAutoRepeat))
1149 Q_EMIT signal(sym, mod);
1151 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1155 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1157 // this is also called for ShortcutOverride events. In this case, one must
1158 // not act but simply accept the event explicitly.
1159 bool const act = (ev->type() != QEvent::ShortcutOverride);
1161 // Do not process here some keys if dialog_mode_ is set
1162 bool const for_dialog_mode = d->dialog_mode_
1163 && (ev->modifiers() == Qt::NoModifier
1164 || ev->modifiers() == Qt::ShiftModifier)
1165 && (ev->key() == Qt::Key_Escape
1166 || ev->key() == Qt::Key_Enter
1167 || ev->key() == Qt::Key_Return);
1168 // also do not use autoRepeat to input shortcuts
1169 bool const autoRepeat = ev->isAutoRepeat();
1171 if (for_dialog_mode || (!act && autoRepeat)) {
1176 // intercept some keys if completion popup is visible
1177 if (d->completer_->popupVisible()) {
1178 switch (ev->key()) {
1180 case Qt::Key_Return:
1182 d->completer_->activate();
1188 KeyModifier const m = q_key_state(ev->modifiers());
1190 if (act && lyxerr.debugging(Debug::KEY)) {
1192 if (m & ShiftModifier)
1194 if (m & ControlModifier)
1196 if (m & AltModifier)
1198 if (m & MetaModifier)
1200 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1201 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1202 << " keyState: " << str);
1206 setKeySymbol(&sym, ev);
1209 Q_EMIT compressKeySym(sym, m, autoRepeat);
1212 // here, !autoRepeat, as determined at the beginning
1213 ev->setAccepted(queryKeySym(sym, m));
1220 void GuiWorkArea::doubleClickTimeout()
1222 d->dc_event_.active = false;
1226 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1228 d->dc_event_ = DoubleClick(ev);
1229 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1230 SLOT(doubleClickTimeout()));
1231 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1232 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1238 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1240 QAbstractScrollArea::resizeEvent(ev);
1241 d->need_resize_ = true;
1246 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1248 if (preedit_string_.empty())
1251 // FIXME: shall we use real_current_font here? (see #10478)
1252 FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1253 FontMetrics const & fm = theFontMetrics(font);
1254 int const height = fm.maxHeight();
1255 int cur_x = caret_->rect().left();
1256 int cur_y = caret_->rect().bottom();
1258 // get attributes of input method cursor.
1259 // cursor_pos : cursor position in preedit string.
1260 size_t cursor_pos = 0;
1261 bool cursor_is_visible = false;
1262 for (auto const & attr : preedit_attr_) {
1263 if (attr.type == QInputMethodEvent::Cursor) {
1264 cursor_pos = size_t(attr.start);
1265 cursor_is_visible = attr.length != 0;
1270 size_t const preedit_length = preedit_string_.length();
1272 // get position of selection in input method.
1273 // FIXME: isn't there a simpler way to do this?
1274 // rStart : cursor position in selected string in IM.
1276 // rLength : selected string length in IM.
1278 if (cursor_pos < preedit_length) {
1279 for (auto const & attr : preedit_attr_) {
1280 if (attr.type == QInputMethodEvent::TextFormat) {
1281 if (attr.start <= int(cursor_pos)
1282 && int(cursor_pos) < attr.start + attr.length) {
1283 rStart = size_t(attr.start);
1284 rLength = size_t(attr.length);
1285 if (!cursor_is_visible)
1286 cursor_pos += rLength;
1293 rStart = cursor_pos;
1297 int const right_margin = buffer_view_->rightMargin();
1298 Painter::preedit_style ps;
1299 // Most often there would be only one line:
1301 for (size_t pos = 0; pos != preedit_length; ++pos) {
1302 char_type const typed_char = preedit_string_[pos];
1303 // reset preedit string style
1304 ps = Painter::preedit_default;
1306 // if we reached the right extremity of the screen, go to next line.
1307 if (cur_x + fm.width(typed_char) > p->viewport()->width() - right_margin) {
1308 cur_x = right_margin;
1309 cur_y += height + 1;
1312 // preedit strings are displayed with dashed underline
1313 // and partial strings are displayed white on black indicating
1314 // that we are in selecting mode in the input method.
1315 // FIXME: rLength == preedit_length is not a changing condition
1316 // FIXME: should be put out of the loop.
1318 && pos < rStart + rLength
1319 && !(cursor_pos < rLength && rLength == preedit_length))
1320 ps = Painter::preedit_selecting;
1322 if (pos == cursor_pos
1323 && (cursor_pos < rLength && rLength == preedit_length))
1324 ps = Painter::preedit_cursor;
1326 // draw one character and update cur_x.
1327 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1332 void GuiWorkArea::Private::resetScreen()
1334 if (use_backingstore_) {
1335 int const pr = p->pixelRatio();
1336 screen_ = QImage(static_cast<int>(pr * p->viewport()->width()),
1337 static_cast<int>(pr * p->viewport()->height()),
1338 QImage::Format_ARGB32_Premultiplied);
1339 # if QT_VERSION >= 0x050000
1340 screen_.setDevicePixelRatio(pr);
1346 QPaintDevice * GuiWorkArea::Private::screenDevice()
1348 if (use_backingstore_)
1351 return p->viewport();
1355 void GuiWorkArea::Private::updateScreen(QRectF const & rc)
1357 if (use_backingstore_) {
1358 QPainter qpain(p->viewport());
1359 double const pr = p->pixelRatio();
1360 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr,
1361 rc.width() * pr, rc.height() * pr);
1362 qpain.drawImage(rc, screen_, rcs);
1367 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1369 // Do not trigger the painting machinery if we are not ready (see
1370 // bug #10989). The second test triggers when in the middle of a
1371 // dispatch operation.
1372 if (view().busy() || d->buffer_view_->buffer().undo().activeUndoGroup()) {
1373 // Since macOS has turned the screen black at this point, our
1374 // backing store has to be copied to screen (this is a no-op
1375 // except on macOS).
1376 d->updateScreen(ev->rect());
1377 // Ignore this paint event, but request a new one for later.
1378 viewport()->update(ev->rect());
1383 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1384 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1386 if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_) {
1388 d->resizeBufferView();
1391 d->last_pixel_ratio_ = pixelRatio();
1393 GuiPainter pain(d->screenDevice(), pixelRatio(), d->lyx_view_->develMode());
1395 d->buffer_view_->draw(pain, d->caret_visible_);
1397 // The preedit text, if needed
1398 d->paintPreeditText(pain);
1401 // FIXME: the code would be a little bit simpler if caret geometry
1402 // was updated unconditionally. Some profiling is required to see
1403 // how expensive this is (especially when idle).
1404 if (d->caret_visible_) {
1405 if (d->needs_caret_geometry_update_)
1406 d->updateCaretGeometry();
1407 d->caret_->draw(pain, d->buffer_view_->horizScrollOffset());
1410 d->updateScreen(ev->rect());
1416 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1418 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1419 << " commitString: " << e->commitString());
1421 // insert the processed text in the document (handles undo)
1422 if (!e->commitString().isEmpty()) {
1423 FuncRequest cmd(LFUN_SELF_INSERT,
1424 qstring_to_ucs4(e->commitString()),
1425 FuncRequest::KEYBOARD);
1427 // FIXME: this is supposed to remove traces from preedit
1428 // string. Can we avoid calling it explicitly?
1429 d->buffer_view_->updateMetrics();
1432 // Hide the caret during the test transformation.
1433 if (e->preeditString().isEmpty())
1434 startBlinkingCaret();
1436 stopBlinkingCaret();
1438 if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1444 // The preedit text and its attributes will be used in paintPreeditText
1445 d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1446 d->preedit_attr_ = e->attributes();
1449 // redraw area of preedit string.
1450 int height = d->caret_->rect().height();
1451 int cur_y = d->caret_->rect().bottom();
1452 viewport()->update(0, cur_y - height, viewport()->width(),
1453 (height + 1) * d->preedit_lines_);
1455 if (d->preedit_string_.empty()) {
1456 d->preedit_lines_ = 1;
1461 // Don't forget to accept the event!
1466 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1468 QRect cur_r(0, 0, 0, 0);
1470 // this is the CJK-specific composition window position and
1471 // the context menu position when the menu key is pressed.
1472 case Qt::ImMicroFocus:
1473 cur_r = d->caret_->rect();
1474 if (d->preedit_lines_ != 1)
1476 cur_r.moveBottom(cur_r.bottom()
1477 + cur_r.height() * (d->preedit_lines_ - 1));
1478 // return lower right of caret in LyX.
1481 return QWidget::inputMethodQuery(query);
1486 void GuiWorkArea::updateWindowTitle()
1488 Buffer const & buf = bufferView().buffer();
1489 if (buf.fileName() != d->file_name_
1490 || buf.params().shell_escape != d->shell_escape_
1491 || buf.hasReadonlyFlag() != d->read_only_
1492 || buf.lyxvc().vcstatus() != d->vc_status_
1493 || buf.isClean() != d->clean_
1494 || buf.notifiesExternalModification() != d->externally_modified_) {
1495 d->file_name_ = buf.fileName();
1496 d->shell_escape_ = buf.params().shell_escape;
1497 d->read_only_ = buf.hasReadonlyFlag();
1498 d->vc_status_ = buf.lyxvc().vcstatus();
1499 d->clean_ = buf.isClean();
1500 d->externally_modified_ = buf.notifiesExternalModification();
1501 Q_EMIT titleChanged(this);
1506 bool GuiWorkArea::isFullScreen() const
1508 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1512 bool GuiWorkArea::inDialogMode() const
1514 return d->dialog_mode_;
1518 void GuiWorkArea::setDialogMode(bool mode)
1520 d->dialog_mode_ = mode;
1524 GuiCompleter & GuiWorkArea::completer()
1526 return *d->completer_;
1529 GuiView const & GuiWorkArea::view() const
1531 return *d->lyx_view_;
1535 GuiView & GuiWorkArea::view()
1537 return *d->lyx_view_;
1540 ////////////////////////////////////////////////////////////////////
1544 ////////////////////////////////////////////////////////////////////
1547 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1549 support::TempFile tempfile("embedded.internal");
1550 tempfile.setAutoRemove(false);
1551 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1552 buffer_->setUnnamed(true);
1553 buffer_->setFullyLoaded(true);
1554 setBuffer(*buffer_);
1555 setDialogMode(true);
1559 EmbeddedWorkArea::~EmbeddedWorkArea()
1561 // No need to destroy buffer and bufferview here, because it is done
1562 // in theBufferList() destruction loop at application exit
1566 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1569 GuiWorkArea::closeEvent(ev);
1573 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1576 GuiWorkArea::hideEvent(ev);
1580 QSize EmbeddedWorkArea::sizeHint () const
1583 // GuiWorkArea sets the size to the screen's viewport
1584 // by returning a value this gets overridden
1585 // EmbeddedWorkArea is now sized to fit in the layout
1586 // of the parent, and has a minimum size set in GuiWorkArea
1587 // which is what we return here
1588 return QSize(100, 70);
1592 void EmbeddedWorkArea::disable()
1594 stopBlinkingCaret();
1595 if (view().currentWorkArea() != this)
1597 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1598 // tolerates it and shows the background logo), what happens if
1599 // an EmbeddedWorkArea is closed after closing all document WAs
1600 view().setCurrentWorkArea(view().currentMainWorkArea());
1603 ////////////////////////////////////////////////////////////////////
1607 ////////////////////////////////////////////////////////////////////
1610 class NoTabFrameMacStyle : public QProxyStyle {
1613 QRect subElementRect(SubElement element, const QStyleOption * option,
1614 const QWidget * widget = 0) const
1616 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1617 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1619 // The Qt Mac style puts the contents into a 3 pixel wide box
1620 // which looks very ugly and not like other Mac applications.
1621 // Hence we remove this here, and moreover the 16 pixel round
1622 // frame above if the tab bar is hidden.
1623 if (element == QStyle::SE_TabWidgetTabContents) {
1624 rect.adjust(- rect.left(), 0, rect.left(), 0);
1633 NoTabFrameMacStyle noTabFrameMacStyle;
1637 TabWorkArea::TabWorkArea(QWidget * parent)
1638 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1641 setStyle(&noTabFrameMacStyle);
1644 QPalette pal = palette();
1645 pal.setColor(QPalette::Active, QPalette::Button,
1646 pal.color(QPalette::Active, QPalette::Window));
1647 pal.setColor(QPalette::Disabled, QPalette::Button,
1648 pal.color(QPalette::Disabled, QPalette::Window));
1649 pal.setColor(QPalette::Inactive, QPalette::Button,
1650 pal.color(QPalette::Inactive, QPalette::Window));
1652 QObject::connect(this, SIGNAL(currentChanged(int)),
1653 this, SLOT(on_currentTabChanged(int)));
1655 closeBufferButton = new QToolButton(this);
1656 closeBufferButton->setPalette(pal);
1657 // FIXME: rename the icon to closebuffer.png
1658 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1659 closeBufferButton->setText("Close File");
1660 closeBufferButton->setAutoRaise(true);
1661 closeBufferButton->setCursor(Qt::ArrowCursor);
1662 closeBufferButton->setToolTip(qt_("Close File"));
1663 closeBufferButton->setEnabled(true);
1664 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1665 this, SLOT(closeCurrentBuffer()));
1666 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1668 // set TabBar behaviour
1669 QTabBar * tb = tabBar();
1670 tb->setTabsClosable(!lyxrc.single_close_tab_button);
1671 tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1672 tb->setElideMode(Qt::ElideNone);
1673 // allow dragging tabs
1674 tb->setMovable(true);
1675 // make us responsible for the context menu of the tabbar
1676 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1677 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1678 this, SLOT(showContextMenu(const QPoint &)));
1679 connect(tb, SIGNAL(tabCloseRequested(int)),
1680 this, SLOT(closeTab(int)));
1682 setUsesScrollButtons(true);
1686 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1688 if (me->button() == Qt::MidButton)
1689 midpressed_tab_ = tabBar()->tabAt(me->pos());
1691 QTabWidget::mousePressEvent(me);
1695 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1697 if (me->button() == Qt::MidButton) {
1698 int const midreleased_tab = tabBar()->tabAt(me->pos());
1699 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1700 closeTab(midreleased_tab);
1702 QTabWidget::mouseReleaseEvent(me);
1706 void TabWorkArea::paintEvent(QPaintEvent * event)
1708 if (tabBar()->isVisible()) {
1709 QTabWidget::paintEvent(event);
1711 // Prevent the selected tab to influence the
1712 // painting of the frame of the tab widget.
1713 // This is needed for gtk style in Qt.
1714 QStylePainter p(this);
1715 #if QT_VERSION < 0x050000
1716 QStyleOptionTabWidgetFrameV2 opt;
1718 QStyleOptionTabWidgetFrame opt;
1720 initStyleOption(&opt);
1721 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1723 opt.selectedTabRect = QRect();
1724 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1729 bool TabWorkArea::posIsTab(QPoint position)
1731 // tabAt returns -1 if tab does not covers position
1732 return tabBar()->tabAt(position) > -1;
1736 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1738 if (event->button() != Qt::LeftButton)
1741 // this code chunk is unnecessary because it seems the event only makes
1742 // it this far if it is not on a tab. I'm not sure why this is (maybe
1743 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1744 // this is true in all cases and if it will be true in the future so I
1745 // leave this code for now. (skostysh, 2016-07-21)
1747 // return early if double click on existing tabs
1748 if (posIsTab(event->pos()))
1751 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1755 void TabWorkArea::setFullScreen(bool full_screen)
1757 for (int i = 0; i != count(); ++i) {
1758 if (GuiWorkArea * wa = workArea(i))
1759 wa->setFullScreen(full_screen);
1762 if (lyxrc.full_screen_tabbar)
1763 showBar(!full_screen && count() > 1);
1765 showBar(count() > 1);
1769 void TabWorkArea::showBar(bool show)
1771 tabBar()->setEnabled(show);
1772 tabBar()->setVisible(show);
1773 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1774 setTabsClosable(!lyxrc.single_close_tab_button);
1778 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1780 QWidget * w = QTabWidget::widget(index);
1783 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1789 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1791 return widget(currentIndex());
1795 GuiWorkArea * TabWorkArea::workArea(int index) const
1797 GuiWorkAreaContainer * w = widget(index);
1800 return w->workArea();
1804 GuiWorkArea * TabWorkArea::currentWorkArea() const
1806 return workArea(currentIndex());
1810 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1812 // FIXME: this method doesn't work if we have more than one work area
1813 // showing the same buffer.
1814 for (int i = 0; i != count(); ++i) {
1815 GuiWorkArea * wa = workArea(i);
1816 LASSERT(wa, return nullptr);
1817 if (&wa->bufferView().buffer() == &buffer)
1824 void TabWorkArea::closeAll()
1827 QWidget * wac = widget(0);
1828 LASSERT(wac, return);
1835 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1837 for (int index = 0; index < count(); ++index)
1838 if (workArea(index) == w)
1844 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1846 LASSERT(work_area, return false);
1847 int index = indexOfWorkArea(work_area);
1851 if (index == currentIndex())
1852 // Make sure the work area is up to date.
1853 on_currentTabChanged(index);
1855 // Switch to the work area.
1856 setCurrentIndex(index);
1857 work_area->setFocus();
1863 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1865 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1866 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1867 wa->setUpdatesEnabled(false);
1868 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1869 // when hiding it again below).
1870 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1871 showBar(count() > 0);
1872 addTab(wac, wa->windowTitle());
1873 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1874 this, SLOT(updateTabTexts()));
1875 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1876 setFullScreen(true);
1878 // Hide tabbar if there's only one tab.
1879 showBar(count() > 1);
1887 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1889 LASSERT(work_area, return false);
1890 int index = indexOfWorkArea(work_area);
1894 work_area->setUpdatesEnabled(false);
1895 QWidget * wac = widget(index);
1900 // make sure the next work area is enabled.
1901 currentWidget()->setUpdatesEnabled(true);
1902 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1903 setFullScreen(true);
1905 // Show tabbar only if there's more than one tab.
1906 showBar(count() > 1);
1908 lastWorkAreaRemoved();
1916 void TabWorkArea::on_currentTabChanged(int i)
1918 // returns e.g. on application destruction
1921 GuiWorkArea * wa = workArea(i);
1922 LASSERT(wa, return);
1923 wa->setUpdatesEnabled(true);
1924 wa->scheduleRedraw(true);
1927 currentWorkAreaChanged(wa);
1929 LYXERR(Debug::GUI, "currentTabChanged " << i
1930 << " File: " << wa->bufferView().buffer().absFileName());
1934 void TabWorkArea::closeCurrentBuffer()
1937 if (clicked_tab_ == -1)
1938 wa = currentWorkArea();
1940 wa = workArea(clicked_tab_);
1941 LASSERT(wa, return);
1943 wa->view().closeWorkArea(wa);
1947 void TabWorkArea::hideCurrentTab()
1950 if (clicked_tab_ == -1)
1951 wa = currentWorkArea();
1953 wa = workArea(clicked_tab_);
1954 LASSERT(wa, return);
1956 wa->view().hideWorkArea(wa);
1960 void TabWorkArea::closeTab(int index)
1962 on_currentTabChanged(index);
1965 wa = currentWorkArea();
1967 wa = workArea(index);
1968 LASSERT(wa, return);
1970 wa->view().closeWorkArea(wa);
1977 /// make vector happy
1978 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1980 DisplayPath(int tab, FileName const & filename)
1983 // Recode URL encoded chars via fromPercentEncoding()
1984 string const fn = (filename.extension() == "lyx")
1985 ? filename.onlyFileNameWithoutExt() : filename.onlyFileName();
1986 filename_ = QString::fromUtf8(QByteArray::fromPercentEncoding(fn.c_str()));
1987 postfix_ = toqstr(filename.absoluteFilePath()).
1988 split("/", QString::SkipEmptyParts);
1989 postfix_.pop_back();
1990 abs_ = toqstr(filename.absoluteFilePath());
1991 dottedPrefix_ = false;
1994 /// Absolute path for debugging.
1999 /// Add the first segment from the postfix or three dots to the prefix.
2000 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
2001 /// when really needed.
2002 void shiftPathSegment(bool dotted)
2004 if (postfix_.count() <= 0)
2008 if (dottedPrefix_ && !prefix_.isEmpty())
2009 prefix_ += ellipsisSlash_;
2010 prefix_ += postfix_.front() + "/";
2012 dottedPrefix_ = dotted && !prefix_.isEmpty();
2013 postfix_.pop_front();
2016 QString displayString() const
2018 if (prefix_.isEmpty())
2021 bool dots = dottedPrefix_ || !postfix_.isEmpty();
2022 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
2025 QString forecastPathString() const
2027 if (postfix_.count() == 0)
2028 return displayString();
2031 + (dottedPrefix_ ? ellipsisSlash_ : "")
2032 + postfix_.front() + "/";
2035 bool final() const { return postfix_.empty(); }
2037 int tab() const { return tab_; }
2041 static QString const ellipsisSlash_;
2045 QStringList postfix_;
2057 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
2061 bool operator<(DisplayPath const & a, DisplayPath const & b)
2063 return a.displayString() < b.displayString();
2067 bool operator==(DisplayPath const & a, DisplayPath const & b)
2069 return a.displayString() == b.displayString();
2073 void TabWorkArea::updateTabTexts()
2075 int const n = count();
2078 std::list<DisplayPath> paths;
2079 typedef std::list<DisplayPath>::iterator It;
2081 // collect full names first: path into postfix, empty prefix and
2082 // filename without extension
2083 for (int i = 0; i < n; ++i) {
2084 GuiWorkArea * i_wa = workArea(i);
2085 FileName const fn = i_wa->bufferView().buffer().fileName();
2086 paths.push_back(DisplayPath(i, fn));
2089 // go through path segments and see if it helps to make the path more unique
2090 bool somethingChanged = true;
2091 bool allFinal = false;
2092 while (somethingChanged && !allFinal) {
2093 // adding path segments changes order
2096 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
2097 somethingChanged = false;
2100 // find segments which are not unique (i.e. non-atomic)
2101 It it = paths.begin();
2103 QString segString = it->displayString();
2104 for (; it != paths.end(); ++it) {
2105 // look to the next item
2110 allFinal = allFinal && it->final();
2112 LYXERR(Debug::GUI, "it = " << it->abs()
2113 << " => " << it->displayString());
2115 // still the same segment?
2117 if ((next != paths.end()
2118 && (nextString = next->displayString()) == segString))
2120 LYXERR(Debug::GUI, "segment ended");
2122 // only a trivial one with one element?
2123 if (it == segStart) {
2124 // start new segment
2126 segString = nextString;
2130 // We found a non-atomic segment
2131 // We know that segStart <= it < next <= paths.end().
2132 // The assertion below tells coverity about it.
2133 LATTEST(segStart != paths.end());
2134 QString dspString = segStart->forecastPathString();
2135 LYXERR(Debug::GUI, "first forecast found for "
2136 << segStart->abs() << " => " << dspString);
2139 // Shift path segments and hope for the best
2140 // that it makes the path more unique.
2141 somethingChanged = true;
2142 bool moreUnique = false;
2143 for (; sit != next; ++sit) {
2144 if (sit->forecastPathString() != dspString) {
2145 LYXERR(Debug::GUI, "different forecast found for "
2146 << sit->abs() << " => " << sit->forecastPathString());
2150 LYXERR(Debug::GUI, "same forecast found for "
2151 << sit->abs() << " => " << dspString);
2154 // if the path segment helped, add it. Otherwise add dots
2155 bool dots = !moreUnique;
2156 LYXERR(Debug::GUI, "using dots = " << dots);
2157 for (sit = segStart; sit != next; ++sit) {
2158 sit->shiftPathSegment(dots);
2159 LYXERR(Debug::GUI, "shifting "
2160 << sit->abs() << " => " << sit->displayString());
2163 // start new segment
2165 segString = nextString;
2169 // set new tab titles
2170 for (It it = paths.begin(); it != paths.end(); ++it) {
2171 int const tab_index = it->tab();
2172 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2173 QString tab_text = it->displayString().replace("&", "&&");
2174 if (!buf.fileName().empty() && !buf.isClean())
2176 QString tab_tooltip = it->abs();
2177 if (buf.hasReadonlyFlag()) {
2178 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2179 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2181 setTabIcon(tab_index, QIcon());
2182 if (buf.notifiesExternalModification()) {
2183 QString const warn = qt_("%1 (modified externally)");
2184 tab_tooltip = warn.arg(tab_tooltip);
2185 tab_text += QChar(0x26a0);
2187 setTabText(tab_index, tab_text);
2188 setTabToolTip(tab_index, tab_tooltip);
2193 void TabWorkArea::showContextMenu(const QPoint & pos)
2196 clicked_tab_ = tabBar()->tabAt(pos);
2197 if (clicked_tab_ == -1)
2200 GuiWorkArea * wa = workArea(clicked_tab_);
2201 LASSERT(wa, return);
2205 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2206 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2208 // we want to show the 'close' option only if this is not a child buffer.
2209 Buffer const & buf = wa->bufferView().buffer();
2211 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2212 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2213 popup.exec(tabBar()->mapToGlobal(pos));
2219 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2221 QWidget * w = widget(fromIndex);
2222 QIcon icon = tabIcon(fromIndex);
2223 QString text = tabText(fromIndex);
2225 setCurrentIndex(fromIndex);
2226 removeTab(fromIndex);
2227 insertTab(toIndex, w, icon, text);
2228 setCurrentIndex(toIndex);
2232 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2233 : QWidget(parent), wa_(wa)
2235 LASSERT(wa, return);
2236 Ui::WorkAreaUi::setupUi(this);
2237 layout()->addWidget(wa);
2238 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2239 this, SLOT(updateDisplay()));
2240 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2241 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2242 setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2247 void GuiWorkAreaContainer::updateDisplay()
2249 Buffer const & buf = wa_->bufferView().buffer();
2250 notificationFrame->setHidden(!buf.notifiesExternalModification());
2251 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2252 .arg(toqstr(buf.fileName().displayName()));
2253 externalModificationLabel->setText(label);
2257 void GuiWorkAreaContainer::dispatch(FuncRequest f) const
2259 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2260 wa_->bufferView().buffer().absFileName()));
2265 void GuiWorkAreaContainer::reload() const
2267 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2271 void GuiWorkAreaContainer::ignore() const
2273 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2277 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2279 // prevent TabWorkArea from opening a new buffer on double click
2284 } // namespace frontend
2287 #include "moc_GuiWorkArea.cpp"