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)
136 void draw(QPainter & painter)
138 if (!rect_.isValid())
142 int l = x_ - rect_.left();
143 int r = rect_.right() - x_;
144 int bot = rect_.bottom();
146 // draw vertical line
147 painter.fillRect(x_, y, caret_width_, rect_.height(), color_);
149 // draw RTL/LTR indication
150 painter.setPen(color_);
153 painter.drawLine(x_, bot, x_ - l + 1, bot);
155 painter.drawLine(x_, bot, x_ + caret_width_ + r - 1, bot);
158 // draw completion triangle
160 int m = y + rect_.height() / 2;
161 int d = TabIndicatorWidth - 1;
163 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
164 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
166 painter.drawLine(x_ + caret_width_, m - d, x_ + caret_width_ + d, m);
167 painter.drawLine(x_ + caret_width_, m + d, x_ + caret_width_ + d, m);
172 void update(int x, int y, int h, bool l_shape,
173 bool rtl, bool completable)
175 color_ = guiApp->colorCache().get(Color_cursor);
178 completable_ = completable;
181 // extension to left and right
185 // RTL/LTR indication
193 // completion triangle
196 l = max(l, TabIndicatorWidth);
198 r = max(r, TabIndicatorWidth);
201 //FIXME: LyXRC::cursor_width should be caret_width
202 caret_width_ = lyxrc.cursor_width
204 : 1 + int((lyxrc.currentZoom + 50) / 200.0);
206 // compute overall rectangle
207 rect_ = QRect(x - l, y, caret_width_ + r + l, h);
210 QRect const & rect() { return rect_; }
213 /// caret is in RTL or LTR text
215 /// indication for RTL or LTR
217 /// triangle to show that a completion is available
221 /// rectangle, possibly with l_shape and completion triangle
223 /// x position (were the vertical line is drawn)
225 /// the width of the vertical blinking bar
230 // This is a 'heartbeat' generating synthetic mouse move events when the
231 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
232 SyntheticMouseEvent::SyntheticMouseEvent()
233 : timeout(200), restart_timeout(true)
237 GuiWorkArea::Private::Private(GuiWorkArea * parent)
238 : p(parent), buffer_view_(0), lyx_view_(0),
239 caret_(0), caret_visible_(false),
240 need_resize_(false), preedit_lines_(1),
241 last_pixel_ratio_(1.0),
242 completer_(new GuiCompleter(p, p)), dialog_mode_(false), shell_escape_(false),
243 read_only_(false), clean_(true), externally_modified_(false)
245 int const time = QApplication::cursorFlashTime() / 2;
247 caret_timeout_.setInterval(time);
248 caret_timeout_.start();
250 // let's initialize this just to be safe
251 caret_timeout_.setInterval(500);
256 GuiWorkArea::Private::~Private()
258 // If something is wrong with the buffer, we can ignore it safely
260 buffer_view_->buffer().workAreaManager().remove(p);
264 // Completer has a QObject parent and is thus automatically destroyed.
266 // delete completer_;
270 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
271 : d(new Private(this))
273 new CompressorProxy(this); // not a leak
277 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
278 : d(new Private(this))
280 new CompressorProxy(this); // not a leak
282 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
288 double GuiWorkArea::pixelRatio() const
290 #if QT_VERSION >= 0x050000
291 return qt_scale_factor * devicePixelRatio();
298 void GuiWorkArea::init()
301 connect(&d->caret_timeout_, SIGNAL(timeout()),
302 this, SLOT(toggleCaret()));
304 // This connection is closed at the same time as this is destroyed.
305 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
306 generateSyntheticMouseEvent();
310 // With Qt4.5 a mouse event will happen before the first paint event
311 // so make sure that the buffer view has an up to date metrics.
312 d->buffer_view_->resize(viewport()->width(), viewport()->height());
313 d->caret_ = new frontend::CaretWidget();
315 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
316 setAcceptDrops(true);
317 setMouseTracking(true);
318 setMinimumSize(100, 70);
319 setFrameStyle(QFrame::NoFrame);
322 d->updateCursorShape();
324 // we paint our own background
325 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
327 setFocusPolicy(Qt::StrongFocus);
329 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
330 << " viewport height: " << viewport()->height());
332 // Enables input methods for asian languages.
333 // Must be set when creating custom text editing widgets.
334 setAttribute(Qt::WA_InputMethodEnabled, true);
338 GuiWorkArea::~GuiWorkArea()
344 void GuiWorkArea::Private::updateCursorShape()
346 bool const clickable = buffer_view_ && buffer_view_->clickableInset();
347 p->viewport()->setCursor(clickable ? Qt::PointingHandCursor
352 void GuiWorkArea::setGuiView(GuiView & gv)
358 void GuiWorkArea::setBuffer(Buffer & buffer)
360 delete d->buffer_view_;
361 d->buffer_view_ = new BufferView(buffer);
362 buffer.workAreaManager().add(this);
364 // HACK: Prevents an additional redraw when the scrollbar pops up
365 // which regularily happens on documents with more than one page.
366 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
367 // Since we have no geometry information yet, we assume that
368 // a document needs a scrollbar if there is more then four
369 // paragraph in the outermost text.
370 if (buffer.text().paragraphs().size() > 4)
371 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
372 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
373 Q_EMIT bufferViewChanged();
377 void GuiWorkArea::fixVerticalScrollBar()
380 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
384 void GuiWorkArea::close()
386 d->lyx_view_->removeWorkArea(this);
390 void GuiWorkArea::setFullScreen(bool full_screen)
392 d->buffer_view_->setFullScreen(full_screen);
393 setFrameStyle(QFrame::NoFrame);
395 setFrameStyle(QFrame::NoFrame);
396 if (lyxrc.full_screen_scrollbar)
397 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
399 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
403 BufferView & GuiWorkArea::bufferView()
405 return *d->buffer_view_;
409 BufferView const & GuiWorkArea::bufferView() const
411 return *d->buffer_view_;
415 void GuiWorkArea::stopBlinkingCaret()
417 d->caret_timeout_.stop();
422 void GuiWorkArea::startBlinkingCaret()
424 // do not show the cursor if the view is busy
430 d->buffer_view_->caretPosAndHeight(p, h);
431 // Don't start blinking if the cursor isn't on screen.
432 if (!d->buffer_view_->cursorInView(p, h))
437 // Avoid blinking when debugging PAINTING, since it creates too much noise
438 if (!lyxerr.debugging(Debug::PAINTING)) {
439 // we are not supposed to cache this value.
440 int const time = QApplication::cursorFlashTime() / 2;
443 d->caret_timeout_.setInterval(time);
444 d->caret_timeout_.start();
449 void GuiWorkArea::toggleCaret()
451 if (d->caret_visible_)
458 void GuiWorkArea::scheduleRedraw(bool update_metrics)
461 // No need to redraw in this case.
464 // No need to do anything if this is the current view. The BufferView
465 // metrics are already up to date.
466 if (update_metrics || d->lyx_view_ != guiApp->currentView()
467 || d->lyx_view_->currentWorkArea() != this) {
468 // FIXME: it would be nice to optimize for the off-screen case.
469 d->buffer_view_->cursor().fixIfBroken();
470 d->buffer_view_->updateMetrics();
471 d->buffer_view_->cursor().fixIfBroken();
474 // update caret position, because otherwise it has to wait until
475 // the blinking interval is over
476 d->updateCaretGeometry();
478 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
479 viewport()->update();
481 /// FIXME: is this still true now that paintEvent does the actual painting?
482 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
483 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
484 d->updateScrollbar();
485 d->lyx_view_->updateStatusBar();
487 if (lyxerr.debugging(Debug::WORKAREA))
488 d->buffer_view_->coordCache().dump();
492 d->updateCursorShape();
496 // Keep in sync with GuiWorkArea::processKeySym below
497 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
499 return guiApp->queryKeySym(key, mod);
503 // Keep in sync with GuiWorkArea::queryKeySym above
504 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
506 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
507 && lyxrc.full_screen_menubar) {
508 // FIXME HACK: we should not have to do this here. See related comment
509 // in GuiView::event() (QEvent::ShortcutOverride)
510 d->lyx_view_->menuBar()->hide();
513 // In order to avoid bad surprise in the middle of an operation,
514 // we better stop the blinking caret...
515 // the caret gets restarted in GuiView::restartCaret()
517 guiApp->processKeySym(key, mod);
521 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
524 if (cmd.action() == LFUN_FILE_OPEN) {
526 lyx_view_->dispatch(cmd, dr);
530 bool const notJustMovingTheMouse =
531 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
533 // In order to avoid bad surprise in the middle of an operation, we better stop
534 // the blinking caret.
535 if (notJustMovingTheMouse)
536 p->stopBlinkingCaret();
538 buffer_view_->mouseEventDispatch(cmd);
540 // Skip these when selecting
541 // FIXME: let GuiView take care of those.
542 if (cmd.action() != LFUN_MOUSE_MOTION) {
543 completer_->updateVisibility(false, false);
544 lyx_view_->updateDialogs();
545 lyx_view_->updateStatusBar();
548 // GUI tweaks except with mouse motion with no button pressed.
549 if (notJustMovingTheMouse) {
550 // Slight hack: this is only called currently when we
551 // clicked somewhere, so we force through the display
552 // of the new status here.
553 // FIXME: let GuiView take care of those.
554 lyx_view_->clearMessage();
556 // Show the caret immediately after any operation
557 p->startBlinkingCaret();
564 void GuiWorkArea::Private::resizeBufferView()
566 // WARNING: Please don't put any code that will trigger a repaint here!
567 // We are already inside a paint event.
568 p->stopBlinkingCaret();
569 // Warn our container (GuiView).
574 buffer_view_->caretPosAndHeight(point, h);
575 bool const caret_in_view = buffer_view_->cursorInView(point, h);
576 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
578 buffer_view_->scrollToCursor();
579 updateCaretGeometry();
581 // Update scrollbars which might have changed due different
582 // BufferView dimension. This is especially important when the
583 // BufferView goes from zero-size to the real-size for the first time,
584 // as the scrollbar paramters are then set for the first time.
587 need_resize_ = false;
589 // Eventually, restart the caret after the resize event.
590 // We might be resizing even if the focus is on another widget so we only
591 // restart the caret if we have the focus.
593 QTimer::singleShot(50, p, SLOT(startBlinkingCaret()));
597 void GuiWorkArea::Private::updateCaretGeometry()
601 buffer_view_->caretPosAndHeight(point, h);
602 if (!buffer_view_->cursorInView(point, h))
606 bool l_shape = false;
607 Font const & realfont = buffer_view_->cursor().real_current_font;
608 BufferParams const & bp = buffer_view_->buffer().params();
609 bool const samelang = realfont.language() == bp.language;
610 bool const isrtl = realfont.isVisibleRightToLeft();
612 if (!samelang || isrtl != bp.language->rightToLeft())
615 // The ERT language hack needs fixing up
616 if (realfont.language() == latex_language)
619 // show caret on screen
620 Cursor & cur = buffer_view_->cursor();
621 bool completable = cur.inset().showCompletionCursor()
622 && completer_->completionAvailable()
623 && !completer_->popupVisible()
624 && !completer_->inlineVisible();
625 caret_visible_ = true;
627 //int cur_x = buffer_view_->getPos(cur).x_;
628 // We may have decided to slide the cursor row so that caret
630 point.x_ -= buffer_view_->horizScrollOffset();
632 caret_->update(point.x_, point.y_, h, l_shape, isrtl, completable);
636 void GuiWorkArea::Private::showCaret()
641 updateCaretGeometry();
642 p->viewport()->update(caret_->rect());
646 void GuiWorkArea::Private::hideCaret()
651 caret_visible_ = false;
652 //if (!qApp->focusWidget())
653 p->viewport()->update(caret_->rect());
657 void GuiWorkArea::Private::updateScrollbar()
659 // Prevent setRange() and setSliderPosition from causing recursive calls via
660 // the signal valueChanged. (#10311)
661 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
662 p, SLOT(scrollTo(int)));
663 ScrollbarParameters const & scroll = buffer_view_->scrollbarParameters();
664 p->verticalScrollBar()->setRange(scroll.min, scroll.max);
665 p->verticalScrollBar()->setPageStep(scroll.page_step);
666 p->verticalScrollBar()->setSingleStep(scroll.single_step);
667 p->verticalScrollBar()->setSliderPosition(0);
668 // Connect to the vertical scroll bar
669 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
670 p, SLOT(scrollTo(int)));
674 void GuiWorkArea::scrollTo(int value)
677 d->buffer_view_->scrollDocView(value, true);
679 if (lyxrc.cursor_follows_scrollbar) {
680 d->buffer_view_->setCursorFromScrollbar();
681 // FIXME: let GuiView take care of those.
682 d->lyx_view_->updateLayoutList();
684 // Show the caret immediately after any operation.
685 startBlinkingCaret();
688 QApplication::syncX();
693 bool GuiWorkArea::event(QEvent * e)
696 case QEvent::ToolTip: {
697 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
698 if (lyxrc.use_tooltip) {
699 QPoint pos = helpEvent->pos();
700 if (pos.x() < viewport()->width()) {
701 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
702 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
705 QToolTip::hideText();
707 // Don't forget to accept the event!
712 case QEvent::ShortcutOverride:
713 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
715 keyPressEvent(static_cast<QKeyEvent *>(e));
716 return e->isAccepted();
718 case QEvent::KeyPress: {
719 // We catch this event in order to catch the Tab or Shift+Tab key press
720 // which are otherwise reserved to focus switching between controls
722 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
723 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
724 || (ke->key() == Qt::Key_Backtab && (
725 ke->modifiers() == Qt::ShiftModifier
726 || ke->modifiers() == Qt::NoModifier))) {
730 return QAbstractScrollArea::event(e);
734 return QAbstractScrollArea::event(e);
740 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
743 if (e->reason() == QContextMenuEvent::Mouse)
744 // the menu name is set on mouse press
745 name = d->context_menu_name_;
747 QPoint pos = e->pos();
748 Cursor const & cur = d->buffer_view_->cursor();
749 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
750 // Do not access the context menu of math right in front of before
751 // the cursor. This does not work when the cursor is in text.
752 Inset * inset = cur.paragraph().getInset(cur.pos());
753 if (inset && inset->asInsetMath())
755 else if (cur.pos() > 0) {
756 inset = cur.paragraph().getInset(cur.pos() - 1);
761 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
768 // always show mnemonics when the keyboard is used to show the context menu
769 // FIXME: This should be fixed in Qt itself
770 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
771 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
776 // Position the menu to the right.
777 // FIXME: menu position should be different for RTL text.
778 menu->exec(e->globalPos());
783 void GuiWorkArea::focusInEvent(QFocusEvent * e)
785 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
786 if (d->lyx_view_->currentWorkArea() != this) {
787 d->lyx_view_->setCurrentWorkArea(this);
788 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
791 startBlinkingCaret();
792 QAbstractScrollArea::focusInEvent(e);
796 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
798 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
800 QAbstractScrollArea::focusOutEvent(e);
804 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
806 if (d->dc_event_.active && d->dc_event_ == *e) {
807 d->dc_event_.active = false;
808 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
809 q_button_state(e->button()), q_key_state(e->modifiers()));
815 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
816 inputContext()->reset();
819 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
820 q_button_state(e->button()), q_key_state(e->modifiers()));
823 // Save the context menu on mouse press, because also the mouse
824 // cursor is set on mouse press. Afterwards, we can either release
825 // the mousebutton somewhere else, or the cursor might have moved
826 // due to the DEPM. We need to do this after the mouse has been
827 // set in dispatch(), because the selection state might change.
828 if (e->button() == Qt::RightButton)
829 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
835 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
837 if (d->synthetic_mouse_event_.timeout.running())
838 d->synthetic_mouse_event_.timeout.stop();
840 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
841 q_button_state(e->button()), q_key_state(e->modifiers()));
847 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
849 // we kill the triple click if we move
850 doubleClickTimeout();
851 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
852 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
856 // If we're above or below the work area...
857 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
858 && e->buttons() == mouse_button::button1) {
859 // Make sure only a synthetic event can cause a page scroll,
860 // so they come at a steady rate:
862 // _Force_ a scroll up:
863 cmd.set_y(e->y() - 21);
865 cmd.set_y(e->y() + 21);
866 // Store the event, to be handled when the timeout expires.
867 d->synthetic_mouse_event_.cmd = cmd;
869 if (d->synthetic_mouse_event_.timeout.running()) {
870 // Discard the event. Note that it _may_ be handled
871 // when the timeout expires if
872 // synthetic_mouse_event_.cmd has not been overwritten.
873 // Ie, when the timeout expires, we handle the
874 // most recent event but discard all others that
875 // occurred after the one used to start the timeout
876 // in the first place.
880 d->synthetic_mouse_event_.restart_timeout = true;
881 d->synthetic_mouse_event_.timeout.start();
882 // Fall through to handle this event...
884 } else if (d->synthetic_mouse_event_.timeout.running()) {
885 // Store the event, to be possibly handled when the timeout
887 // Once the timeout has expired, normal control is returned
888 // to mouseMoveEvent (restart_timeout = false).
889 // This results in a much smoother 'feel' when moving the
890 // mouse back into the work area.
891 d->synthetic_mouse_event_.cmd = cmd;
892 d->synthetic_mouse_event_.restart_timeout = false;
899 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
901 // Wheel rotation by one notch results in a delta() of 120 (see
902 // documentation of QWheelEvent)
903 // But first we have to ignore horizontal scroll events.
904 #if QT_VERSION < 0x050000
905 if (ev->orientation() == Qt::Horizontal) {
909 double const delta = ev->delta() / 120.0;
911 QPoint const aDelta = ev->angleDelta();
912 // skip horizontal wheel event
913 if (abs(aDelta.x()) > abs(aDelta.y())) {
917 double const delta = aDelta.y() / 120.0;
921 switch (lyxrc.scroll_wheel_zoom) {
922 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
923 zoom = ev->modifiers() & Qt::ControlModifier;
924 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
926 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
927 zoom = ev->modifiers() & Qt::ShiftModifier;
928 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
930 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
931 zoom = ev->modifiers() & Qt::AltModifier;
932 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
934 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
938 docstring arg = convert<docstring>(int(5 * delta));
939 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
943 // Take into account the desktop wide settings.
944 int const lines = qApp->wheelScrollLines();
945 int const page_step = verticalScrollBar()->pageStep();
946 // Test if the wheel mouse is set to one screen at a time.
947 // This is according to
948 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
950 min(lines * verticalScrollBar()->singleStep(), page_step);
952 // Take into account the rotation and the user preferences.
953 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
954 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
955 << " delta = " << delta << " scroll_value = " << scroll_value
956 << " page_step = " << page_step);
958 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
964 void GuiWorkArea::generateSyntheticMouseEvent()
966 int const e_y = d->synthetic_mouse_event_.cmd.y();
967 int const wh = d->buffer_view_->workHeight();
968 bool const up = e_y < 0;
969 bool const down = e_y > wh;
971 // Set things off to generate the _next_ 'pseudo' event.
973 if (d->synthetic_mouse_event_.restart_timeout) {
974 // This is some magic formulae to determine the speed
975 // of scrolling related to the position of the mouse.
978 int dist = up ? -e_y : e_y - wh;
979 time = max(min(200, 250000 / (dist * dist)), 1) ;
982 step = 80000 / (time * time);
986 d->synthetic_mouse_event_.timeout.setTimeout(time);
987 d->synthetic_mouse_event_.timeout.start();
990 // Can we scroll further ?
991 int const value = verticalScrollBar()->value();
992 if (value == verticalScrollBar()->maximum()
993 || value == verticalScrollBar()->minimum()) {
994 d->synthetic_mouse_event_.timeout.stop();
999 if (step <= 2 * wh) {
1000 d->buffer_view_->scroll(up ? -step : step);
1001 d->buffer_view_->updateMetrics();
1003 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
1006 // In which paragraph do we have to set the cursor ?
1007 Cursor & cur = d->buffer_view_->cursor();
1008 // FIXME: we don't know how to handle math.
1009 Text * text = cur.text();
1012 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
1014 // Quit gracefully if there are no metrics, since otherwise next
1015 // line would crash (bug #10324).
1016 // This situation seems related to a (not yet understood) timing problem.
1020 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
1021 ParagraphMetrics const & pm = *pp.second;
1022 pit_type const pit = pp.first;
1024 if (pm.rows().empty())
1027 // Find the row at which we set the cursor.
1028 RowList::const_iterator rit = pm.rows().begin();
1029 RowList::const_iterator rlast = pm.rows().end();
1030 int yy = pm.position() - pm.ascent();
1031 for (--rlast; rit != rlast; ++rit) {
1032 int h = rit->height();
1033 if ((up && yy + h > 0)
1034 || (!up && yy + h > wh - defaultRowHeight()))
1039 // Find the position of the cursor
1041 int x = d->synthetic_mouse_event_.cmd.x();
1042 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1047 cur.boundary(bound);
1049 d->buffer_view_->buffer().changed(false);
1054 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
1055 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
1057 qRegisterMetaType<KeySymbol>("KeySymbol");
1058 qRegisterMetaType<KeyModifier>("KeyModifier");
1059 connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
1060 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
1061 Qt::QueuedConnection);
1062 connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
1063 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1067 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1071 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1072 bool result = flag_;
1078 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1080 if (emitCheck(isAutoRepeat))
1081 Q_EMIT signal(sym, mod);
1083 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1087 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1089 // this is also called for ShortcutOverride events. In this case, one must
1090 // not act but simply accept the event explicitly.
1091 bool const act = (ev->type() != QEvent::ShortcutOverride);
1093 // Do not process here some keys if dialog_mode_ is set
1094 bool const for_dialog_mode = d->dialog_mode_
1095 && (ev->modifiers() == Qt::NoModifier
1096 || ev->modifiers() == Qt::ShiftModifier)
1097 && (ev->key() == Qt::Key_Escape
1098 || ev->key() == Qt::Key_Enter
1099 || ev->key() == Qt::Key_Return);
1100 // also do not use autoRepeat to input shortcuts
1101 bool const autoRepeat = ev->isAutoRepeat();
1103 if (for_dialog_mode || (!act && autoRepeat)) {
1108 // intercept some keys if completion popup is visible
1109 if (d->completer_->popupVisible()) {
1110 switch (ev->key()) {
1112 case Qt::Key_Return:
1114 d->completer_->activate();
1120 KeyModifier const m = q_key_state(ev->modifiers());
1122 if (act && lyxerr.debugging(Debug::KEY)) {
1124 if (m & ShiftModifier)
1126 if (m & ControlModifier)
1128 if (m & AltModifier)
1130 if (m & MetaModifier)
1132 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1133 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1134 << " keyState: " << str);
1138 setKeySymbol(&sym, ev);
1141 Q_EMIT compressKeySym(sym, m, autoRepeat);
1144 // here, !autoRepeat, as determined at the beginning
1145 ev->setAccepted(queryKeySym(sym, m));
1152 void GuiWorkArea::doubleClickTimeout()
1154 d->dc_event_.active = false;
1158 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1160 d->dc_event_ = DoubleClick(ev);
1161 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1162 SLOT(doubleClickTimeout()));
1163 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1164 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1170 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1172 QAbstractScrollArea::resizeEvent(ev);
1173 d->need_resize_ = true;
1178 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1180 if (preedit_string_.empty())
1183 // FIXME: shall we use real_current_font here? (see #10478)
1184 FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1185 FontMetrics const & fm = theFontMetrics(font);
1186 int const height = fm.maxHeight();
1187 int cur_x = caret_->rect().left();
1188 int cur_y = caret_->rect().bottom();
1190 // get attributes of input method cursor.
1191 // cursor_pos : cursor position in preedit string.
1192 size_t cursor_pos = 0;
1193 bool cursor_is_visible = false;
1194 for (auto const & attr : preedit_attr_) {
1195 if (attr.type == QInputMethodEvent::Cursor) {
1196 cursor_pos = attr.start;
1197 cursor_is_visible = attr.length != 0;
1202 size_t const preedit_length = preedit_string_.length();
1204 // get position of selection in input method.
1205 // FIXME: isn't there a way to do this simplier?
1206 // rStart : cursor position in selected string in IM.
1208 // rLength : selected string length in IM.
1210 if (cursor_pos < preedit_length) {
1211 for (auto const & attr : preedit_attr_) {
1212 if (attr.type == QInputMethodEvent::TextFormat) {
1213 if (attr.start <= int(cursor_pos)
1214 && int(cursor_pos) < attr.start + attr.length) {
1215 rStart = attr.start;
1216 rLength = attr.length;
1217 if (!cursor_is_visible)
1218 cursor_pos += rLength;
1225 rStart = cursor_pos;
1229 int const right_margin = buffer_view_->rightMargin();
1230 Painter::preedit_style ps;
1231 // Most often there would be only one line:
1233 for (size_t pos = 0; pos != preedit_length; ++pos) {
1234 char_type const typed_char = preedit_string_[pos];
1235 // reset preedit string style
1236 ps = Painter::preedit_default;
1238 // if we reached the right extremity of the screen, go to next line.
1239 if (cur_x + fm.width(typed_char) > p->viewport()->width() - right_margin) {
1240 cur_x = right_margin;
1241 cur_y += height + 1;
1244 // preedit strings are displayed with dashed underline
1245 // and partial strings are displayed white on black indicating
1246 // that we are in selecting mode in the input method.
1247 // FIXME: rLength == preedit_length is not a changing condition
1248 // FIXME: should be put out of the loop.
1250 && pos < rStart + rLength
1251 && !(cursor_pos < rLength && rLength == preedit_length))
1252 ps = Painter::preedit_selecting;
1254 if (pos == cursor_pos
1255 && (cursor_pos < rLength && rLength == preedit_length))
1256 ps = Painter::preedit_cursor;
1258 // draw one character and update cur_x.
1259 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1264 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1266 // Do not trigger the painting machinery if we are not ready (see
1267 // bug #10989). The second test triggers when in the middle of a
1268 // dispatch operation.
1269 if (view().busy() || d->buffer_view_->buffer().undo().activeUndoGroup()) {
1270 // Since macOS has turned the screen black at this point, our
1271 // backing store has to be copied to screen (this is a no-op
1272 // except on macOS).
1273 d->updateScreen(ev->rect());
1274 // Ignore this paint event, but request a new one for later.
1275 viewport()->update(ev->rect());
1280 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1281 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1283 if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_) {
1285 d->resizeBufferView();
1288 d->last_pixel_ratio_ = pixelRatio();
1290 GuiPainter pain(d->screenDevice(), pixelRatio());
1292 d->buffer_view_->draw(pain, d->caret_visible_);
1294 // The preedit text, if needed
1295 d->paintPreeditText(pain);
1298 if (d->caret_visible_)
1299 d->caret_->draw(pain);
1301 d->updateScreen(ev->rect());
1307 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1309 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1310 << " commitString: " << e->commitString());
1312 // insert the processed text in the document (handles undo)
1313 if (!e->commitString().isEmpty()) {
1314 FuncRequest cmd(LFUN_SELF_INSERT,
1315 qstring_to_ucs4(e->commitString()),
1316 FuncRequest::KEYBOARD);
1318 // FIXME: this is supposed to remove traces from preedit
1319 // string. Can we avoid calling it explicitely?
1320 d->buffer_view_->updateMetrics();
1323 // Hide the caret during the test transformation.
1324 if (e->preeditString().isEmpty())
1325 startBlinkingCaret();
1327 stopBlinkingCaret();
1329 if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1335 // The preedit text and its attributes will be used in paintPreeditText
1336 d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1337 d->preedit_attr_ = e->attributes();
1340 // redraw area of preedit string.
1341 int height = d->caret_->rect().height();
1342 int cur_y = d->caret_->rect().bottom();
1343 viewport()->update(0, cur_y - height, viewport()->width(),
1344 (height + 1) * d->preedit_lines_);
1346 if (d->preedit_string_.empty()) {
1347 d->preedit_lines_ = 1;
1352 // Don't forget to accept the event!
1357 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1359 QRect cur_r(0, 0, 0, 0);
1361 // this is the CJK-specific composition window position and
1362 // the context menu position when the menu key is pressed.
1363 case Qt::ImMicroFocus:
1364 cur_r = d->caret_->rect();
1365 if (d->preedit_lines_ != 1)
1367 cur_r.moveBottom(cur_r.bottom()
1368 + cur_r.height() * (d->preedit_lines_ - 1));
1369 // return lower right of caret in LyX.
1372 return QWidget::inputMethodQuery(query);
1377 void GuiWorkArea::updateWindowTitle()
1379 Buffer const & buf = bufferView().buffer();
1380 if (buf.fileName() != d->file_name_
1381 || buf.params().shell_escape != d->shell_escape_
1382 || buf.hasReadonlyFlag() != d->read_only_
1383 || buf.lyxvc().vcstatus() != d->vc_status_
1384 || buf.isClean() != d->clean_
1385 || buf.notifiesExternalModification() != d->externally_modified_) {
1386 d->file_name_ = buf.fileName();
1387 d->shell_escape_ = buf.params().shell_escape;
1388 d->read_only_ = buf.hasReadonlyFlag();
1389 d->vc_status_ = buf.lyxvc().vcstatus();
1390 d->clean_ = buf.isClean();
1391 d->externally_modified_ = buf.notifiesExternalModification();
1392 Q_EMIT titleChanged(this);
1397 bool GuiWorkArea::isFullScreen() const
1399 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1403 bool GuiWorkArea::inDialogMode() const
1405 return d->dialog_mode_;
1409 void GuiWorkArea::setDialogMode(bool mode)
1411 d->dialog_mode_ = mode;
1415 GuiCompleter & GuiWorkArea::completer()
1417 return *d->completer_;
1420 GuiView const & GuiWorkArea::view() const
1422 return *d->lyx_view_;
1426 GuiView & GuiWorkArea::view()
1428 return *d->lyx_view_;
1431 ////////////////////////////////////////////////////////////////////
1435 ////////////////////////////////////////////////////////////////////
1438 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1440 support::TempFile tempfile("embedded.internal");
1441 tempfile.setAutoRemove(false);
1442 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1443 buffer_->setUnnamed(true);
1444 buffer_->setFullyLoaded(true);
1445 setBuffer(*buffer_);
1446 setDialogMode(true);
1450 EmbeddedWorkArea::~EmbeddedWorkArea()
1452 // No need to destroy buffer and bufferview here, because it is done
1453 // in theBufferList() destruction loop at application exit
1457 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1460 GuiWorkArea::closeEvent(ev);
1464 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1467 GuiWorkArea::hideEvent(ev);
1471 QSize EmbeddedWorkArea::sizeHint () const
1474 // GuiWorkArea sets the size to the screen's viewport
1475 // by returning a value this gets overridden
1476 // EmbeddedWorkArea is now sized to fit in the layout
1477 // of the parent, and has a minimum size set in GuiWorkArea
1478 // which is what we return here
1479 return QSize(100, 70);
1483 void EmbeddedWorkArea::disable()
1485 stopBlinkingCaret();
1486 if (view().currentWorkArea() != this)
1488 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1489 // tolerates it and shows the background logo), what happens if
1490 // an EmbeddedWorkArea is closed after closing all document WAs
1491 view().setCurrentWorkArea(view().currentMainWorkArea());
1494 ////////////////////////////////////////////////////////////////////
1498 ////////////////////////////////////////////////////////////////////
1501 class NoTabFrameMacStyle : public QProxyStyle {
1504 QRect subElementRect(SubElement element, const QStyleOption * option,
1505 const QWidget * widget = 0) const
1507 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1508 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1510 // The Qt Mac style puts the contents into a 3 pixel wide box
1511 // which looks very ugly and not like other Mac applications.
1512 // Hence we remove this here, and moreover the 16 pixel round
1513 // frame above if the tab bar is hidden.
1514 if (element == QStyle::SE_TabWidgetTabContents) {
1515 rect.adjust(- rect.left(), 0, rect.left(), 0);
1524 NoTabFrameMacStyle noTabFrameMacStyle;
1528 TabWorkArea::TabWorkArea(QWidget * parent)
1529 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1532 setStyle(&noTabFrameMacStyle);
1535 QPalette pal = palette();
1536 pal.setColor(QPalette::Active, QPalette::Button,
1537 pal.color(QPalette::Active, QPalette::Window));
1538 pal.setColor(QPalette::Disabled, QPalette::Button,
1539 pal.color(QPalette::Disabled, QPalette::Window));
1540 pal.setColor(QPalette::Inactive, QPalette::Button,
1541 pal.color(QPalette::Inactive, QPalette::Window));
1543 QObject::connect(this, SIGNAL(currentChanged(int)),
1544 this, SLOT(on_currentTabChanged(int)));
1546 closeBufferButton = new QToolButton(this);
1547 closeBufferButton->setPalette(pal);
1548 // FIXME: rename the icon to closebuffer.png
1549 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1550 closeBufferButton->setText("Close File");
1551 closeBufferButton->setAutoRaise(true);
1552 closeBufferButton->setCursor(Qt::ArrowCursor);
1553 closeBufferButton->setToolTip(qt_("Close File"));
1554 closeBufferButton->setEnabled(true);
1555 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1556 this, SLOT(closeCurrentBuffer()));
1557 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1559 // set TabBar behaviour
1560 QTabBar * tb = tabBar();
1561 tb->setTabsClosable(!lyxrc.single_close_tab_button);
1562 tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1563 tb->setElideMode(Qt::ElideNone);
1564 // allow dragging tabs
1565 tb->setMovable(true);
1566 // make us responsible for the context menu of the tabbar
1567 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1568 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1569 this, SLOT(showContextMenu(const QPoint &)));
1570 connect(tb, SIGNAL(tabCloseRequested(int)),
1571 this, SLOT(closeTab(int)));
1573 setUsesScrollButtons(true);
1577 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1579 if (me->button() == Qt::MidButton)
1580 midpressed_tab_ = tabBar()->tabAt(me->pos());
1582 QTabWidget::mousePressEvent(me);
1586 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1588 if (me->button() == Qt::MidButton) {
1589 int const midreleased_tab = tabBar()->tabAt(me->pos());
1590 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1591 closeTab(midreleased_tab);
1593 QTabWidget::mouseReleaseEvent(me);
1597 void TabWorkArea::paintEvent(QPaintEvent * event)
1599 if (tabBar()->isVisible()) {
1600 QTabWidget::paintEvent(event);
1602 // Prevent the selected tab to influence the
1603 // painting of the frame of the tab widget.
1604 // This is needed for gtk style in Qt.
1605 QStylePainter p(this);
1606 #if QT_VERSION < 0x050000
1607 QStyleOptionTabWidgetFrameV2 opt;
1609 QStyleOptionTabWidgetFrame opt;
1611 initStyleOption(&opt);
1612 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1614 opt.selectedTabRect = QRect();
1615 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1620 bool TabWorkArea::posIsTab(QPoint position)
1622 // tabAt returns -1 if tab does not covers position
1623 return tabBar()->tabAt(position) > -1;
1627 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1629 if (event->button() != Qt::LeftButton)
1632 // this code chunk is unnecessary because it seems the event only makes
1633 // it this far if it is not on a tab. I'm not sure why this is (maybe
1634 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1635 // this is true in all cases and if it will be true in the future so I
1636 // leave this code for now. (skostysh, 2016-07-21)
1638 // return early if double click on existing tabs
1639 if (posIsTab(event->pos()))
1642 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1646 void TabWorkArea::setFullScreen(bool full_screen)
1648 for (int i = 0; i != count(); ++i) {
1649 if (GuiWorkArea * wa = workArea(i))
1650 wa->setFullScreen(full_screen);
1653 if (lyxrc.full_screen_tabbar)
1654 showBar(!full_screen && count() > 1);
1656 showBar(count() > 1);
1660 void TabWorkArea::showBar(bool show)
1662 tabBar()->setEnabled(show);
1663 tabBar()->setVisible(show);
1664 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1665 setTabsClosable(!lyxrc.single_close_tab_button);
1669 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1671 QWidget * w = QTabWidget::widget(index);
1674 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1680 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1682 return widget(currentIndex());
1686 GuiWorkArea * TabWorkArea::workArea(int index) const
1688 GuiWorkAreaContainer * w = widget(index);
1691 return w->workArea();
1695 GuiWorkArea * TabWorkArea::currentWorkArea() const
1697 return workArea(currentIndex());
1701 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1703 // FIXME: this method doesn't work if we have more than one work area
1704 // showing the same buffer.
1705 for (int i = 0; i != count(); ++i) {
1706 GuiWorkArea * wa = workArea(i);
1707 LASSERT(wa, return 0);
1708 if (&wa->bufferView().buffer() == &buffer)
1715 void TabWorkArea::closeAll()
1718 QWidget * wac = widget(0);
1719 LASSERT(wac, return);
1726 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1728 for (int index = 0; index < count(); ++index)
1729 if (workArea(index) == w)
1735 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1737 LASSERT(work_area, return false);
1738 int index = indexOfWorkArea(work_area);
1742 if (index == currentIndex())
1743 // Make sure the work area is up to date.
1744 on_currentTabChanged(index);
1746 // Switch to the work area.
1747 setCurrentIndex(index);
1748 work_area->setFocus();
1754 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1756 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1757 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1758 wa->setUpdatesEnabled(false);
1759 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1760 // when hiding it again below).
1761 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1762 showBar(count() > 0);
1763 addTab(wac, wa->windowTitle());
1764 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1765 this, SLOT(updateTabTexts()));
1766 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1767 setFullScreen(true);
1769 // Hide tabbar if there's only one tab.
1770 showBar(count() > 1);
1778 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1780 LASSERT(work_area, return false);
1781 int index = indexOfWorkArea(work_area);
1785 work_area->setUpdatesEnabled(false);
1786 QWidget * wac = widget(index);
1791 // make sure the next work area is enabled.
1792 currentWidget()->setUpdatesEnabled(true);
1793 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1794 setFullScreen(true);
1796 // Show tabbar only if there's more than one tab.
1797 showBar(count() > 1);
1799 lastWorkAreaRemoved();
1807 void TabWorkArea::on_currentTabChanged(int i)
1809 // returns e.g. on application destruction
1812 GuiWorkArea * wa = workArea(i);
1813 LASSERT(wa, return);
1814 wa->setUpdatesEnabled(true);
1815 wa->scheduleRedraw(true);
1818 currentWorkAreaChanged(wa);
1820 LYXERR(Debug::GUI, "currentTabChanged " << i
1821 << " File: " << wa->bufferView().buffer().absFileName());
1825 void TabWorkArea::closeCurrentBuffer()
1828 if (clicked_tab_ == -1)
1829 wa = currentWorkArea();
1831 wa = workArea(clicked_tab_);
1832 LASSERT(wa, return);
1834 wa->view().closeWorkArea(wa);
1838 void TabWorkArea::hideCurrentTab()
1841 if (clicked_tab_ == -1)
1842 wa = currentWorkArea();
1844 wa = workArea(clicked_tab_);
1845 LASSERT(wa, return);
1847 wa->view().hideWorkArea(wa);
1851 void TabWorkArea::closeTab(int index)
1853 on_currentTabChanged(index);
1856 wa = currentWorkArea();
1858 wa = workArea(index);
1859 LASSERT(wa, return);
1861 wa->view().closeWorkArea(wa);
1868 /// make vector happy
1869 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1871 DisplayPath(int tab, FileName const & filename)
1874 filename_ = (filename.extension() == "lyx") ?
1875 toqstr(filename.onlyFileNameWithoutExt())
1876 : toqstr(filename.onlyFileName());
1877 postfix_ = toqstr(filename.absoluteFilePath()).
1878 split("/", QString::SkipEmptyParts);
1879 postfix_.pop_back();
1880 abs_ = toqstr(filename.absoluteFilePath());
1881 dottedPrefix_ = false;
1884 /// Absolute path for debugging.
1889 /// Add the first segment from the postfix or three dots to the prefix.
1890 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1891 /// when really needed.
1892 void shiftPathSegment(bool dotted)
1894 if (postfix_.count() <= 0)
1898 if (dottedPrefix_ && !prefix_.isEmpty())
1899 prefix_ += ellipsisSlash_;
1900 prefix_ += postfix_.front() + "/";
1902 dottedPrefix_ = dotted && !prefix_.isEmpty();
1903 postfix_.pop_front();
1906 QString displayString() const
1908 if (prefix_.isEmpty())
1911 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1912 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1915 QString forecastPathString() const
1917 if (postfix_.count() == 0)
1918 return displayString();
1921 + (dottedPrefix_ ? ellipsisSlash_ : "")
1922 + postfix_.front() + "/";
1925 bool final() const { return postfix_.empty(); }
1927 int tab() const { return tab_; }
1931 static QString const ellipsisSlash_;
1935 QStringList postfix_;
1947 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1951 bool operator<(DisplayPath const & a, DisplayPath const & b)
1953 return a.displayString() < b.displayString();
1957 bool operator==(DisplayPath const & a, DisplayPath const & b)
1959 return a.displayString() == b.displayString();
1963 void TabWorkArea::updateTabTexts()
1968 std::list<DisplayPath> paths;
1969 typedef std::list<DisplayPath>::iterator It;
1971 // collect full names first: path into postfix, empty prefix and
1972 // filename without extension
1973 for (size_t i = 0; i < n; ++i) {
1974 GuiWorkArea * i_wa = workArea(i);
1975 FileName const fn = i_wa->bufferView().buffer().fileName();
1976 paths.push_back(DisplayPath(i, fn));
1979 // go through path segments and see if it helps to make the path more unique
1980 bool somethingChanged = true;
1981 bool allFinal = false;
1982 while (somethingChanged && !allFinal) {
1983 // adding path segments changes order
1986 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1987 somethingChanged = false;
1990 // find segments which are not unique (i.e. non-atomic)
1991 It it = paths.begin();
1993 QString segString = it->displayString();
1994 for (; it != paths.end(); ++it) {
1995 // look to the next item
2000 allFinal = allFinal && it->final();
2002 LYXERR(Debug::GUI, "it = " << it->abs()
2003 << " => " << it->displayString());
2005 // still the same segment?
2007 if ((next != paths.end()
2008 && (nextString = next->displayString()) == segString))
2010 LYXERR(Debug::GUI, "segment ended");
2012 // only a trivial one with one element?
2013 if (it == segStart) {
2014 // start new segment
2016 segString = nextString;
2020 // We found a non-atomic segment
2021 // We know that segStart <= it < next <= paths.end().
2022 // The assertion below tells coverity about it.
2023 LATTEST(segStart != paths.end());
2024 QString dspString = segStart->forecastPathString();
2025 LYXERR(Debug::GUI, "first forecast found for "
2026 << segStart->abs() << " => " << dspString);
2029 // Shift path segments and hope for the best
2030 // that it makes the path more unique.
2031 somethingChanged = true;
2032 bool moreUnique = false;
2033 for (; sit != next; ++sit) {
2034 if (sit->forecastPathString() != dspString) {
2035 LYXERR(Debug::GUI, "different forecast found for "
2036 << sit->abs() << " => " << sit->forecastPathString());
2040 LYXERR(Debug::GUI, "same forecast found for "
2041 << sit->abs() << " => " << dspString);
2044 // if the path segment helped, add it. Otherwise add dots
2045 bool dots = !moreUnique;
2046 LYXERR(Debug::GUI, "using dots = " << dots);
2047 for (sit = segStart; sit != next; ++sit) {
2048 sit->shiftPathSegment(dots);
2049 LYXERR(Debug::GUI, "shifting "
2050 << sit->abs() << " => " << sit->displayString());
2053 // start new segment
2055 segString = nextString;
2059 // set new tab titles
2060 for (It it = paths.begin(); it != paths.end(); ++it) {
2061 int const tab_index = it->tab();
2062 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2063 QString tab_text = it->displayString().replace("&", "&&");
2064 if (!buf.fileName().empty() && !buf.isClean())
2066 QString tab_tooltip = it->abs();
2067 if (buf.hasReadonlyFlag()) {
2068 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2069 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2071 setTabIcon(tab_index, QIcon());
2072 if (buf.notifiesExternalModification()) {
2073 QString const warn = qt_("%1 (modified externally)");
2074 tab_tooltip = warn.arg(tab_tooltip);
2075 tab_text += QChar(0x26a0);
2077 setTabText(tab_index, tab_text);
2078 setTabToolTip(tab_index, tab_tooltip);
2083 void TabWorkArea::showContextMenu(const QPoint & pos)
2086 clicked_tab_ = tabBar()->tabAt(pos);
2087 if (clicked_tab_ == -1)
2092 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2093 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2094 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2095 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2096 popup.exec(tabBar()->mapToGlobal(pos));
2102 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2104 QWidget * w = widget(fromIndex);
2105 QIcon icon = tabIcon(fromIndex);
2106 QString text = tabText(fromIndex);
2108 setCurrentIndex(fromIndex);
2109 removeTab(fromIndex);
2110 insertTab(toIndex, w, icon, text);
2111 setCurrentIndex(toIndex);
2115 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2116 : QWidget(parent), wa_(wa)
2118 LASSERT(wa, return);
2119 Ui::WorkAreaUi::setupUi(this);
2120 layout()->addWidget(wa);
2121 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2122 this, SLOT(updateDisplay()));
2123 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2124 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2125 setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2130 void GuiWorkAreaContainer::updateDisplay()
2132 Buffer const & buf = wa_->bufferView().buffer();
2133 notificationFrame->setHidden(!buf.notifiesExternalModification());
2134 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2135 .arg(toqstr(buf.fileName().displayName()));
2136 externalModificationLabel->setText(label);
2140 void GuiWorkAreaContainer::dispatch(FuncRequest f) const
2142 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2143 wa_->bufferView().buffer().absFileName()));
2148 void GuiWorkAreaContainer::reload() const
2150 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2154 void GuiWorkAreaContainer::ignore() const
2156 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2160 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2162 // prevent TabWorkArea from opening a new buffer on double click
2167 } // namespace frontend
2170 #include "moc_GuiWorkArea.cpp"