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 /* 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 l = x_ - rect_.left();
147 int const r = rect_.right() - x_;
148 int const bot = rect_.bottom();
150 // draw vertical line
151 painter.fillRect(x, y, caret_width_, rect_.height(), color_);
153 // draw RTL/LTR indication
154 painter.setPen(color_);
157 painter.drawLine(x, bot, x - l, bot);
159 painter.drawLine(x, bot, x + caret_width_ + r, bot);
162 // draw completion triangle
164 int m = y + rect_.height() / 2;
165 int d = TabIndicatorWidth - 1;
167 painter.drawLine(x - 1, m - d, x - 1 - d, m);
168 painter.drawLine(x - 1, m + d, x - 1 - d, m);
170 painter.drawLine(x + caret_width_, m - d, x + caret_width_ + d, m);
171 painter.drawLine(x + caret_width_, m + d, x + caret_width_ + d, m);
176 void update(int x, int y, int h, bool l_shape,
177 bool rtl, bool completable)
179 color_ = guiApp->colorCache().get(Color_cursor);
182 completable_ = completable;
185 // extension to left and right
189 // RTL/LTR indication
197 // completion triangle
200 l = max(l, TabIndicatorWidth);
202 r = max(r, TabIndicatorWidth);
205 //FIXME: LyXRC::cursor_width should be caret_width
206 caret_width_ = lyxrc.cursor_width
208 : 1 + int((lyxrc.currentZoom + 50) / 200.0);
210 // compute overall rectangle
211 rect_ = QRect(x - l, y, caret_width_ + r + l, h);
214 QRect const & rect() { return rect_; }
217 /// caret is in RTL or LTR text
219 /// indication for RTL or LTR
221 /// triangle to show that a completion is available
225 /// rectangle, possibly with l_shape and completion triangle
227 /// x position (were the vertical line is drawn)
229 /// the width of the vertical blinking bar
234 // This is a 'heartbeat' generating synthetic mouse move events when the
235 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
236 SyntheticMouseEvent::SyntheticMouseEvent()
237 : timeout(200), restart_timeout(true)
241 GuiWorkArea::Private::Private(GuiWorkArea * parent)
242 : p(parent), buffer_view_(0), lyx_view_(0),
243 caret_(0), caret_visible_(false),
244 need_resize_(false), preedit_lines_(1),
245 last_pixel_ratio_(1.0),
246 completer_(new GuiCompleter(p, p)), dialog_mode_(false), shell_escape_(false),
247 read_only_(false), clean_(true), externally_modified_(false)
249 int const time = QApplication::cursorFlashTime() / 2;
251 caret_timeout_.setInterval(time);
252 caret_timeout_.start();
254 // let's initialize this just to be safe
255 caret_timeout_.setInterval(500);
260 GuiWorkArea::Private::~Private()
262 // If something is wrong with the buffer, we can ignore it safely
264 buffer_view_->buffer().workAreaManager().remove(p);
268 // Completer has a QObject parent and is thus automatically destroyed.
270 // delete completer_;
274 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
275 : d(new Private(this))
277 new CompressorProxy(this); // not a leak
281 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
282 : d(new Private(this))
284 new CompressorProxy(this); // not a leak
286 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
292 double GuiWorkArea::pixelRatio() const
294 #if QT_VERSION >= 0x050000
295 return qt_scale_factor * devicePixelRatio();
302 void GuiWorkArea::init()
305 connect(&d->caret_timeout_, SIGNAL(timeout()),
306 this, SLOT(toggleCaret()));
308 // This connection is closed at the same time as this is destroyed.
309 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
310 generateSyntheticMouseEvent();
314 // With Qt4.5 a mouse event will happen before the first paint event
315 // so make sure that the buffer view has an up to date metrics.
316 d->buffer_view_->resize(viewport()->width(), viewport()->height());
317 d->caret_ = new frontend::CaretWidget();
319 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
320 setAcceptDrops(true);
321 setMouseTracking(true);
322 setMinimumSize(100, 70);
323 setFrameStyle(QFrame::NoFrame);
326 d->updateCursorShape();
328 // we paint our own background
329 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
331 setFocusPolicy(Qt::StrongFocus);
333 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
334 << " viewport height: " << viewport()->height());
336 // Enables input methods for asian languages.
337 // Must be set when creating custom text editing widgets.
338 setAttribute(Qt::WA_InputMethodEnabled, true);
342 GuiWorkArea::~GuiWorkArea()
348 void GuiWorkArea::Private::updateCursorShape()
350 bool const clickable = buffer_view_ && buffer_view_->clickableInset();
351 p->viewport()->setCursor(clickable ? Qt::PointingHandCursor
356 void GuiWorkArea::setGuiView(GuiView & gv)
362 void GuiWorkArea::setBuffer(Buffer & buffer)
364 delete d->buffer_view_;
365 d->buffer_view_ = new BufferView(buffer);
366 buffer.workAreaManager().add(this);
368 // HACK: Prevents an additional redraw when the scrollbar pops up
369 // which regularily happens on documents with more than one page.
370 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
371 // Since we have no geometry information yet, we assume that
372 // a document needs a scrollbar if there is more then four
373 // paragraph in the outermost text.
374 if (buffer.text().paragraphs().size() > 4)
375 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
376 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
377 Q_EMIT bufferViewChanged();
381 void GuiWorkArea::fixVerticalScrollBar()
384 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
388 void GuiWorkArea::close()
390 d->lyx_view_->removeWorkArea(this);
394 void GuiWorkArea::setFullScreen(bool full_screen)
396 d->buffer_view_->setFullScreen(full_screen);
397 setFrameStyle(QFrame::NoFrame);
399 setFrameStyle(QFrame::NoFrame);
400 if (lyxrc.full_screen_scrollbar)
401 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
403 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
407 BufferView & GuiWorkArea::bufferView()
409 return *d->buffer_view_;
413 BufferView const & GuiWorkArea::bufferView() const
415 return *d->buffer_view_;
419 void GuiWorkArea::stopBlinkingCaret()
421 d->caret_timeout_.stop();
426 void GuiWorkArea::startBlinkingCaret()
428 // do not show the cursor if the view is busy
434 d->buffer_view_->caretPosAndHeight(p, h);
435 // Don't start blinking if the cursor isn't on screen.
436 if (!d->buffer_view_->cursorInView(p, h))
441 //we're not supposed to cache this value.
442 int const time = QApplication::cursorFlashTime() / 2;
445 d->caret_timeout_.setInterval(time);
446 d->caret_timeout_.start();
450 void GuiWorkArea::toggleCaret()
452 if (d->caret_visible_)
459 void GuiWorkArea::scheduleRedraw(bool update_metrics)
462 // No need to redraw in this case.
465 // No need to do anything if this is the current view. The BufferView
466 // metrics are already up to date.
467 if (update_metrics || d->lyx_view_ != guiApp->currentView()
468 || d->lyx_view_->currentWorkArea() != this) {
469 // FIXME: it would be nice to optimize for the off-screen case.
470 d->buffer_view_->cursor().fixIfBroken();
471 d->buffer_view_->updateMetrics();
472 d->buffer_view_->cursor().fixIfBroken();
475 // update caret position, because otherwise it has to wait until
476 // the blinking interval is over
477 d->updateCaretGeometry();
479 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
480 viewport()->update();
482 /// FIXME: is this still true now that paintEvent does the actual painting?
483 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
484 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
485 d->updateScrollbar();
486 d->lyx_view_->updateStatusBar();
488 if (lyxerr.debugging(Debug::WORKAREA))
489 d->buffer_view_->coordCache().dump();
493 d->updateCursorShape();
497 // Keep in sync with GuiWorkArea::processKeySym below
498 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
500 return guiApp->queryKeySym(key, mod);
504 // Keep in sync with GuiWorkArea::queryKeySym above
505 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
507 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
508 && lyxrc.full_screen_menubar) {
509 // FIXME HACK: we should not have to do this here. See related comment
510 // in GuiView::event() (QEvent::ShortcutOverride)
511 d->lyx_view_->menuBar()->hide();
514 // In order to avoid bad surprise in the middle of an operation,
515 // we better stop the blinking caret...
516 // the caret gets restarted in GuiView::restartCaret()
518 guiApp->processKeySym(key, mod);
522 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
525 if (cmd.action() == LFUN_FILE_OPEN) {
527 lyx_view_->dispatch(cmd, dr);
531 bool const notJustMovingTheMouse =
532 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
534 // In order to avoid bad surprise in the middle of an operation, we better stop
535 // the blinking caret.
536 if (notJustMovingTheMouse)
537 p->stopBlinkingCaret();
539 buffer_view_->mouseEventDispatch(cmd);
541 // Skip these when selecting
542 // FIXME: let GuiView take care of those.
543 if (cmd.action() != LFUN_MOUSE_MOTION) {
544 completer_->updateVisibility(false, false);
545 lyx_view_->updateDialogs();
546 lyx_view_->updateStatusBar();
549 // GUI tweaks except with mouse motion with no button pressed.
550 if (notJustMovingTheMouse) {
551 // Slight hack: this is only called currently when we
552 // clicked somewhere, so we force through the display
553 // of the new status here.
554 // FIXME: let GuiView take care of those.
555 lyx_view_->clearMessage();
557 // Show the caret immediately after any operation
558 p->startBlinkingCaret();
565 void GuiWorkArea::Private::resizeBufferView()
567 // WARNING: Please don't put any code that will trigger a repaint here!
568 // We are already inside a paint event.
569 p->stopBlinkingCaret();
570 // Warn our container (GuiView).
575 buffer_view_->caretPosAndHeight(point, h);
576 bool const caret_in_view = buffer_view_->cursorInView(point, h);
577 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
579 buffer_view_->scrollToCursor();
580 updateCaretGeometry();
582 // Update scrollbars which might have changed due different
583 // BufferView dimension. This is especially important when the
584 // BufferView goes from zero-size to the real-size for the first time,
585 // as the scrollbar paramters are then set for the first time.
588 need_resize_ = false;
590 // Eventually, restart the caret after the resize event.
591 // We might be resizing even if the focus is on another widget so we only
592 // restart the caret if we have the focus.
594 QTimer::singleShot(50, p, SLOT(startBlinkingCaret()));
598 void GuiWorkArea::Private::updateCaretGeometry()
602 buffer_view_->caretPosAndHeight(point, h);
603 if (!buffer_view_->cursorInView(point, h))
607 bool l_shape = false;
608 Font const & realfont = buffer_view_->cursor().real_current_font;
609 BufferParams const & bp = buffer_view_->buffer().params();
610 bool const samelang = realfont.language() == bp.language;
611 bool const isrtl = realfont.isVisibleRightToLeft();
613 if (!samelang || isrtl != bp.language->rightToLeft())
616 // The ERT language hack needs fixing up
617 if (realfont.language() == latex_language)
620 // show caret on screen
621 Cursor & cur = buffer_view_->cursor();
622 bool completable = cur.inset().showCompletionCursor()
623 && completer_->completionAvailable()
624 && !completer_->popupVisible()
625 && !completer_->inlineVisible();
626 caret_visible_ = true;
628 caret_->update(point.x_, point.y_, h, l_shape, isrtl, completable);
632 void GuiWorkArea::Private::showCaret()
637 updateCaretGeometry();
638 p->viewport()->update();
642 void GuiWorkArea::Private::hideCaret()
647 caret_visible_ = false;
648 //if (!qApp->focusWidget())
649 p->viewport()->update();
653 void GuiWorkArea::Private::updateScrollbar()
655 // Prevent setRange() and setSliderPosition from causing recursive calls via
656 // the signal valueChanged. (#10311)
657 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
658 p, SLOT(scrollTo(int)));
659 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
660 p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
661 p->verticalScrollBar()->setPageStep(scroll_.page_step);
662 p->verticalScrollBar()->setSingleStep(scroll_.single_step);
663 p->verticalScrollBar()->setSliderPosition(0);
664 // Connect to the vertical scroll bar
665 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
666 p, SLOT(scrollTo(int)));
670 void GuiWorkArea::scrollTo(int value)
673 d->buffer_view_->scrollDocView(value, true);
675 if (lyxrc.cursor_follows_scrollbar) {
676 d->buffer_view_->setCursorFromScrollbar();
677 // FIXME: let GuiView take care of those.
678 d->lyx_view_->updateLayoutList();
680 // Show the caret immediately after any operation.
681 startBlinkingCaret();
684 QApplication::syncX();
689 bool GuiWorkArea::event(QEvent * e)
692 case QEvent::ToolTip: {
693 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
694 if (lyxrc.use_tooltip) {
695 QPoint pos = helpEvent->pos();
696 if (pos.x() < viewport()->width()) {
697 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
698 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
701 QToolTip::hideText();
703 // Don't forget to accept the event!
708 case QEvent::ShortcutOverride:
709 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
711 keyPressEvent(static_cast<QKeyEvent *>(e));
712 return e->isAccepted();
714 case QEvent::KeyPress: {
715 // We catch this event in order to catch the Tab or Shift+Tab key press
716 // which are otherwise reserved to focus switching between controls
718 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
719 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
720 || (ke->key() == Qt::Key_Backtab && (
721 ke->modifiers() == Qt::ShiftModifier
722 || ke->modifiers() == Qt::NoModifier))) {
726 return QAbstractScrollArea::event(e);
730 return QAbstractScrollArea::event(e);
736 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
739 if (e->reason() == QContextMenuEvent::Mouse)
740 // the menu name is set on mouse press
741 name = d->context_menu_name_;
743 QPoint pos = e->pos();
744 Cursor const & cur = d->buffer_view_->cursor();
745 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
746 // Do not access the context menu of math right in front of before
747 // the cursor. This does not work when the cursor is in text.
748 Inset * inset = cur.paragraph().getInset(cur.pos());
749 if (inset && inset->asInsetMath())
751 else if (cur.pos() > 0) {
752 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
757 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
764 // always show mnemonics when the keyboard is used to show the context menu
765 // FIXME: This should be fixed in Qt itself
766 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
767 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
772 // Position the menu to the right.
773 // FIXME: menu position should be different for RTL text.
774 menu->exec(e->globalPos());
779 void GuiWorkArea::focusInEvent(QFocusEvent * e)
781 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
782 if (d->lyx_view_->currentWorkArea() != this) {
783 d->lyx_view_->setCurrentWorkArea(this);
784 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
787 startBlinkingCaret();
788 QAbstractScrollArea::focusInEvent(e);
792 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
794 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
796 QAbstractScrollArea::focusOutEvent(e);
800 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
802 if (d->dc_event_.active && d->dc_event_ == *e) {
803 d->dc_event_.active = false;
804 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
805 q_button_state(e->button()), q_key_state(e->modifiers()));
811 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
812 inputContext()->reset();
815 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
816 q_button_state(e->button()), q_key_state(e->modifiers()));
819 // Save the context menu on mouse press, because also the mouse
820 // cursor is set on mouse press. Afterwards, we can either release
821 // the mousebutton somewhere else, or the cursor might have moved
822 // due to the DEPM. We need to do this after the mouse has been
823 // set in dispatch(), because the selection state might change.
824 if (e->button() == Qt::RightButton)
825 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
831 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
833 if (d->synthetic_mouse_event_.timeout.running())
834 d->synthetic_mouse_event_.timeout.stop();
836 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
837 q_button_state(e->button()), q_key_state(e->modifiers()));
843 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
845 // we kill the triple click if we move
846 doubleClickTimeout();
847 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
848 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
852 // If we're above or below the work area...
853 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
854 && e->buttons() == mouse_button::button1) {
855 // Make sure only a synthetic event can cause a page scroll,
856 // so they come at a steady rate:
858 // _Force_ a scroll up:
859 cmd.set_y(e->y() - 21);
861 cmd.set_y(e->y() + 21);
862 // Store the event, to be handled when the timeout expires.
863 d->synthetic_mouse_event_.cmd = cmd;
865 if (d->synthetic_mouse_event_.timeout.running()) {
866 // Discard the event. Note that it _may_ be handled
867 // when the timeout expires if
868 // synthetic_mouse_event_.cmd has not been overwritten.
869 // Ie, when the timeout expires, we handle the
870 // most recent event but discard all others that
871 // occurred after the one used to start the timeout
872 // in the first place.
876 d->synthetic_mouse_event_.restart_timeout = true;
877 d->synthetic_mouse_event_.timeout.start();
878 // Fall through to handle this event...
880 } else if (d->synthetic_mouse_event_.timeout.running()) {
881 // Store the event, to be possibly handled when the timeout
883 // Once the timeout has expired, normal control is returned
884 // to mouseMoveEvent (restart_timeout = false).
885 // This results in a much smoother 'feel' when moving the
886 // mouse back into the work area.
887 d->synthetic_mouse_event_.cmd = cmd;
888 d->synthetic_mouse_event_.restart_timeout = false;
895 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
897 // Wheel rotation by one notch results in a delta() of 120 (see
898 // documentation of QWheelEvent)
899 // But first we have to ignore horizontal scroll events.
900 #if QT_VERSION < 0x050000
901 if (ev->orientation() == Qt::Horizontal) {
905 double const delta = ev->delta() / 120.0;
907 QPoint const aDelta = ev->angleDelta();
908 // skip horizontal wheel event
909 if (abs(aDelta.x()) > abs(aDelta.y())) {
913 double const delta = aDelta.y() / 120.0;
917 switch (lyxrc.scroll_wheel_zoom) {
918 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
919 zoom = ev->modifiers() & Qt::ControlModifier;
920 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
922 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
923 zoom = ev->modifiers() & Qt::ShiftModifier;
924 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
926 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
927 zoom = ev->modifiers() & Qt::AltModifier;
928 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
930 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
934 docstring arg = convert<docstring>(int(5 * delta));
935 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
939 // Take into account the desktop wide settings.
940 int const lines = qApp->wheelScrollLines();
941 int const page_step = verticalScrollBar()->pageStep();
942 // Test if the wheel mouse is set to one screen at a time.
943 // This is according to
944 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
946 min(lines * verticalScrollBar()->singleStep(), page_step);
948 // Take into account the rotation and the user preferences.
949 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
950 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
951 << " delta = " << delta << " scroll_value = " << scroll_value
952 << " page_step = " << page_step);
954 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
960 void GuiWorkArea::generateSyntheticMouseEvent()
962 int const e_y = d->synthetic_mouse_event_.cmd.y();
963 int const wh = d->buffer_view_->workHeight();
964 bool const up = e_y < 0;
965 bool const down = e_y > wh;
967 // Set things off to generate the _next_ 'pseudo' event.
969 if (d->synthetic_mouse_event_.restart_timeout) {
970 // This is some magic formulae to determine the speed
971 // of scrolling related to the position of the mouse.
974 int dist = up ? -e_y : e_y - wh;
975 time = max(min(200, 250000 / (dist * dist)), 1) ;
978 step = 80000 / (time * time);
982 d->synthetic_mouse_event_.timeout.setTimeout(time);
983 d->synthetic_mouse_event_.timeout.start();
986 // Can we scroll further ?
987 int const value = verticalScrollBar()->value();
988 if (value == verticalScrollBar()->maximum()
989 || value == verticalScrollBar()->minimum()) {
990 d->synthetic_mouse_event_.timeout.stop();
995 if (step <= 2 * wh) {
996 d->buffer_view_->scroll(up ? -step : step);
997 d->buffer_view_->updateMetrics();
999 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
1002 // In which paragraph do we have to set the cursor ?
1003 Cursor & cur = d->buffer_view_->cursor();
1004 // FIXME: we don't know how to handle math.
1005 Text * text = cur.text();
1008 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
1010 // Quit gracefully if there are no metrics, since otherwise next
1011 // line would crash (bug #10324).
1012 // This situation seems related to a (not yet understood) timing problem.
1016 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
1017 ParagraphMetrics const & pm = *pp.second;
1018 pit_type const pit = pp.first;
1020 if (pm.rows().empty())
1023 // Find the row at which we set the cursor.
1024 RowList::const_iterator rit = pm.rows().begin();
1025 RowList::const_iterator rlast = pm.rows().end();
1026 int yy = pm.position() - pm.ascent();
1027 for (--rlast; rit != rlast; ++rit) {
1028 int h = rit->height();
1029 if ((up && yy + h > 0)
1030 || (!up && yy + h > wh - defaultRowHeight()))
1035 // Find the position of the cursor
1037 int x = d->synthetic_mouse_event_.cmd.x();
1038 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1043 cur.boundary(bound);
1045 d->buffer_view_->buffer().changed(false);
1050 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
1051 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
1053 qRegisterMetaType<KeySymbol>("KeySymbol");
1054 qRegisterMetaType<KeyModifier>("KeyModifier");
1055 connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
1056 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
1057 Qt::QueuedConnection);
1058 connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
1059 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1063 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1067 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1068 bool result = flag_;
1074 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1076 if (emitCheck(isAutoRepeat))
1077 Q_EMIT signal(sym, mod);
1079 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1083 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1085 // this is also called for ShortcutOverride events. In this case, one must
1086 // not act but simply accept the event explicitly.
1087 bool const act = (ev->type() != QEvent::ShortcutOverride);
1089 // Do not process here some keys if dialog_mode_ is set
1090 bool const for_dialog_mode = d->dialog_mode_
1091 && (ev->modifiers() == Qt::NoModifier
1092 || ev->modifiers() == Qt::ShiftModifier)
1093 && (ev->key() == Qt::Key_Escape
1094 || ev->key() == Qt::Key_Enter
1095 || ev->key() == Qt::Key_Return);
1096 // also do not use autoRepeat to input shortcuts
1097 bool const autoRepeat = ev->isAutoRepeat();
1099 if (for_dialog_mode || (!act && autoRepeat)) {
1104 // intercept some keys if completion popup is visible
1105 if (d->completer_->popupVisible()) {
1106 switch (ev->key()) {
1108 case Qt::Key_Return:
1110 d->completer_->activate();
1116 KeyModifier const m = q_key_state(ev->modifiers());
1118 if (act && lyxerr.debugging(Debug::KEY)) {
1120 if (m & ShiftModifier)
1122 if (m & ControlModifier)
1124 if (m & AltModifier)
1126 if (m & MetaModifier)
1128 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1129 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1130 << " keyState: " << str);
1134 setKeySymbol(&sym, ev);
1137 Q_EMIT compressKeySym(sym, m, autoRepeat);
1140 // here, !autoRepeat, as determined at the beginning
1141 ev->setAccepted(queryKeySym(sym, m));
1148 void GuiWorkArea::doubleClickTimeout()
1150 d->dc_event_.active = false;
1154 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1156 d->dc_event_ = DoubleClick(ev);
1157 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1158 SLOT(doubleClickTimeout()));
1159 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1160 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1166 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1168 QAbstractScrollArea::resizeEvent(ev);
1169 d->need_resize_ = true;
1174 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1176 if (preedit_string_.empty())
1179 // FIXME: shall we use real_current_font here? (see #10478)
1180 FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1181 FontMetrics const & fm = theFontMetrics(font);
1182 int const height = fm.maxHeight();
1183 int cur_x = caret_->rect().left();
1184 int cur_y = caret_->rect().bottom();
1186 // get attributes of input method cursor.
1187 // cursor_pos : cursor position in preedit string.
1188 size_t cursor_pos = 0;
1189 bool cursor_is_visible = false;
1190 for (auto const & attr : preedit_attr_) {
1191 if (attr.type == QInputMethodEvent::Cursor) {
1192 cursor_pos = attr.start;
1193 cursor_is_visible = attr.length != 0;
1198 size_t const preedit_length = preedit_string_.length();
1200 // get position of selection in input method.
1201 // FIXME: isn't there a way to do this simplier?
1202 // rStart : cursor position in selected string in IM.
1204 // rLength : selected string length in IM.
1206 if (cursor_pos < preedit_length) {
1207 for (auto const & attr : preedit_attr_) {
1208 if (attr.type == QInputMethodEvent::TextFormat) {
1209 if (attr.start <= int(cursor_pos)
1210 && int(cursor_pos) < attr.start + attr.length) {
1211 rStart = attr.start;
1212 rLength = attr.length;
1213 if (!cursor_is_visible)
1214 cursor_pos += rLength;
1221 rStart = cursor_pos;
1225 int const right_margin = buffer_view_->rightMargin();
1226 Painter::preedit_style ps;
1227 // Most often there would be only one line:
1229 for (size_t pos = 0; pos != preedit_length; ++pos) {
1230 char_type const typed_char = preedit_string_[pos];
1231 // reset preedit string style
1232 ps = Painter::preedit_default;
1234 // if we reached the right extremity of the screen, go to next line.
1235 if (cur_x + fm.width(typed_char) > p->viewport()->width() - right_margin) {
1236 cur_x = right_margin;
1237 cur_y += height + 1;
1240 // preedit strings are displayed with dashed underline
1241 // and partial strings are displayed white on black indicating
1242 // that we are in selecting mode in the input method.
1243 // FIXME: rLength == preedit_length is not a changing condition
1244 // FIXME: should be put out of the loop.
1246 && pos < rStart + rLength
1247 && !(cursor_pos < rLength && rLength == preedit_length))
1248 ps = Painter::preedit_selecting;
1250 if (pos == cursor_pos
1251 && (cursor_pos < rLength && rLength == preedit_length))
1252 ps = Painter::preedit_cursor;
1254 // draw one character and update cur_x.
1255 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1260 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1262 // Do not trigger the painting machinery if we are not ready (see
1263 // bug #10989). The second test triggers when in the middle of a
1264 // dispatch operation.
1265 if (view().busy() || d->buffer_view_->buffer().undo().activeUndoGroup()) {
1266 // Since macOS has turned the screen black at this point, our
1267 // backing store has to be copied to screen (this is a no-op
1268 // except on macOS).
1269 d->updateScreen(ev->rect());
1270 // Ignore this paint event, but request a new one for later.
1271 viewport()->update(ev->rect());
1276 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1277 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1279 if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_) {
1281 d->resizeBufferView();
1284 d->last_pixel_ratio_ = pixelRatio();
1286 GuiPainter pain(d->screenDevice(), pixelRatio());
1288 d->buffer_view_->draw(pain, d->caret_visible_);
1290 // The preedit text, if needed
1291 d->paintPreeditText(pain);
1294 if (d->caret_visible_)
1295 d->caret_->draw(pain, d->buffer_view_->horizScrollOffset());
1297 d->updateScreen(ev->rect());
1303 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1305 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1306 << " commitString: " << e->commitString());
1308 // insert the processed text in the document (handles undo)
1309 if (!e->commitString().isEmpty()) {
1310 FuncRequest cmd(LFUN_SELF_INSERT,
1311 qstring_to_ucs4(e->commitString()),
1312 FuncRequest::KEYBOARD);
1314 // FIXME: this is supposed to remove traces from preedit
1315 // string. Can we avoid calling it explicitely?
1316 d->buffer_view_->updateMetrics();
1319 // Hide the caret during the test transformation.
1320 if (e->preeditString().isEmpty())
1321 startBlinkingCaret();
1323 stopBlinkingCaret();
1325 if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1331 // The preedit text and its attributes will be used in paintPreeditText
1332 d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1333 d->preedit_attr_ = e->attributes();
1336 // redraw area of preedit string.
1337 int height = d->caret_->rect().height();
1338 int cur_y = d->caret_->rect().bottom();
1339 viewport()->update(0, cur_y - height, viewport()->width(),
1340 (height + 1) * d->preedit_lines_);
1342 if (d->preedit_string_.empty()) {
1343 d->preedit_lines_ = 1;
1348 // Don't forget to accept the event!
1353 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1355 QRect cur_r(0, 0, 0, 0);
1357 // this is the CJK-specific composition window position and
1358 // the context menu position when the menu key is pressed.
1359 case Qt::ImMicroFocus:
1360 cur_r = d->caret_->rect();
1361 if (d->preedit_lines_ != 1)
1363 cur_r.moveBottom(cur_r.bottom()
1364 + cur_r.height() * (d->preedit_lines_ - 1));
1365 // return lower right of caret in LyX.
1368 return QWidget::inputMethodQuery(query);
1373 void GuiWorkArea::updateWindowTitle()
1375 Buffer const & buf = bufferView().buffer();
1376 if (buf.fileName() != d->file_name_
1377 || buf.params().shell_escape != d->shell_escape_
1378 || buf.hasReadonlyFlag() != d->read_only_
1379 || buf.lyxvc().vcstatus() != d->vc_status_
1380 || buf.isClean() != d->clean_
1381 || buf.notifiesExternalModification() != d->externally_modified_) {
1382 d->file_name_ = buf.fileName();
1383 d->shell_escape_ = buf.params().shell_escape;
1384 d->read_only_ = buf.hasReadonlyFlag();
1385 d->vc_status_ = buf.lyxvc().vcstatus();
1386 d->clean_ = buf.isClean();
1387 d->externally_modified_ = buf.notifiesExternalModification();
1388 Q_EMIT titleChanged(this);
1393 bool GuiWorkArea::isFullScreen() const
1395 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1399 bool GuiWorkArea::inDialogMode() const
1401 return d->dialog_mode_;
1405 void GuiWorkArea::setDialogMode(bool mode)
1407 d->dialog_mode_ = mode;
1411 GuiCompleter & GuiWorkArea::completer()
1413 return *d->completer_;
1416 GuiView const & GuiWorkArea::view() const
1418 return *d->lyx_view_;
1422 GuiView & GuiWorkArea::view()
1424 return *d->lyx_view_;
1427 ////////////////////////////////////////////////////////////////////
1431 ////////////////////////////////////////////////////////////////////
1434 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1436 support::TempFile tempfile("embedded.internal");
1437 tempfile.setAutoRemove(false);
1438 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1439 buffer_->setUnnamed(true);
1440 buffer_->setFullyLoaded(true);
1441 setBuffer(*buffer_);
1442 setDialogMode(true);
1446 EmbeddedWorkArea::~EmbeddedWorkArea()
1448 // No need to destroy buffer and bufferview here, because it is done
1449 // in theBufferList() destruction loop at application exit
1453 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1456 GuiWorkArea::closeEvent(ev);
1460 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1463 GuiWorkArea::hideEvent(ev);
1467 QSize EmbeddedWorkArea::sizeHint () const
1470 // GuiWorkArea sets the size to the screen's viewport
1471 // by returning a value this gets overridden
1472 // EmbeddedWorkArea is now sized to fit in the layout
1473 // of the parent, and has a minimum size set in GuiWorkArea
1474 // which is what we return here
1475 return QSize(100, 70);
1479 void EmbeddedWorkArea::disable()
1481 stopBlinkingCaret();
1482 if (view().currentWorkArea() != this)
1484 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1485 // tolerates it and shows the background logo), what happens if
1486 // an EmbeddedWorkArea is closed after closing all document WAs
1487 view().setCurrentWorkArea(view().currentMainWorkArea());
1490 ////////////////////////////////////////////////////////////////////
1494 ////////////////////////////////////////////////////////////////////
1497 class NoTabFrameMacStyle : public QProxyStyle {
1500 QRect subElementRect(SubElement element, const QStyleOption * option,
1501 const QWidget * widget = 0) const
1503 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1504 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1506 // The Qt Mac style puts the contents into a 3 pixel wide box
1507 // which looks very ugly and not like other Mac applications.
1508 // Hence we remove this here, and moreover the 16 pixel round
1509 // frame above if the tab bar is hidden.
1510 if (element == QStyle::SE_TabWidgetTabContents) {
1511 rect.adjust(- rect.left(), 0, rect.left(), 0);
1520 NoTabFrameMacStyle noTabFrameMacStyle;
1524 TabWorkArea::TabWorkArea(QWidget * parent)
1525 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1528 setStyle(&noTabFrameMacStyle);
1531 QPalette pal = palette();
1532 pal.setColor(QPalette::Active, QPalette::Button,
1533 pal.color(QPalette::Active, QPalette::Window));
1534 pal.setColor(QPalette::Disabled, QPalette::Button,
1535 pal.color(QPalette::Disabled, QPalette::Window));
1536 pal.setColor(QPalette::Inactive, QPalette::Button,
1537 pal.color(QPalette::Inactive, QPalette::Window));
1539 QObject::connect(this, SIGNAL(currentChanged(int)),
1540 this, SLOT(on_currentTabChanged(int)));
1542 closeBufferButton = new QToolButton(this);
1543 closeBufferButton->setPalette(pal);
1544 // FIXME: rename the icon to closebuffer.png
1545 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1546 closeBufferButton->setText("Close File");
1547 closeBufferButton->setAutoRaise(true);
1548 closeBufferButton->setCursor(Qt::ArrowCursor);
1549 closeBufferButton->setToolTip(qt_("Close File"));
1550 closeBufferButton->setEnabled(true);
1551 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1552 this, SLOT(closeCurrentBuffer()));
1553 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1555 // set TabBar behaviour
1556 QTabBar * tb = tabBar();
1557 tb->setTabsClosable(!lyxrc.single_close_tab_button);
1558 tb->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
1559 tb->setElideMode(Qt::ElideNone);
1560 // allow dragging tabs
1561 tb->setMovable(true);
1562 // make us responsible for the context menu of the tabbar
1563 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1564 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1565 this, SLOT(showContextMenu(const QPoint &)));
1566 connect(tb, SIGNAL(tabCloseRequested(int)),
1567 this, SLOT(closeTab(int)));
1569 setUsesScrollButtons(true);
1573 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1575 if (me->button() == Qt::MidButton)
1576 midpressed_tab_ = tabBar()->tabAt(me->pos());
1578 QTabWidget::mousePressEvent(me);
1582 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1584 if (me->button() == Qt::MidButton) {
1585 int const midreleased_tab = tabBar()->tabAt(me->pos());
1586 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1587 closeTab(midreleased_tab);
1589 QTabWidget::mouseReleaseEvent(me);
1593 void TabWorkArea::paintEvent(QPaintEvent * event)
1595 if (tabBar()->isVisible()) {
1596 QTabWidget::paintEvent(event);
1598 // Prevent the selected tab to influence the
1599 // painting of the frame of the tab widget.
1600 // This is needed for gtk style in Qt.
1601 QStylePainter p(this);
1602 #if QT_VERSION < 0x050000
1603 QStyleOptionTabWidgetFrameV2 opt;
1605 QStyleOptionTabWidgetFrame opt;
1607 initStyleOption(&opt);
1608 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1610 opt.selectedTabRect = QRect();
1611 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1616 bool TabWorkArea::posIsTab(QPoint position)
1618 // tabAt returns -1 if tab does not covers position
1619 return tabBar()->tabAt(position) > -1;
1623 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1625 if (event->button() != Qt::LeftButton)
1628 // this code chunk is unnecessary because it seems the event only makes
1629 // it this far if it is not on a tab. I'm not sure why this is (maybe
1630 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1631 // this is true in all cases and if it will be true in the future so I
1632 // leave this code for now. (skostysh, 2016-07-21)
1634 // return early if double click on existing tabs
1635 if (posIsTab(event->pos()))
1638 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1642 void TabWorkArea::setFullScreen(bool full_screen)
1644 for (int i = 0; i != count(); ++i) {
1645 if (GuiWorkArea * wa = workArea(i))
1646 wa->setFullScreen(full_screen);
1649 if (lyxrc.full_screen_tabbar)
1650 showBar(!full_screen && count() > 1);
1652 showBar(count() > 1);
1656 void TabWorkArea::showBar(bool show)
1658 tabBar()->setEnabled(show);
1659 tabBar()->setVisible(show);
1660 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1661 setTabsClosable(!lyxrc.single_close_tab_button);
1665 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1667 QWidget * w = QTabWidget::widget(index);
1670 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1676 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1678 return widget(currentIndex());
1682 GuiWorkArea * TabWorkArea::workArea(int index) const
1684 GuiWorkAreaContainer * w = widget(index);
1687 return w->workArea();
1691 GuiWorkArea * TabWorkArea::currentWorkArea() const
1693 return workArea(currentIndex());
1697 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1699 // FIXME: this method doesn't work if we have more than one work area
1700 // showing the same buffer.
1701 for (int i = 0; i != count(); ++i) {
1702 GuiWorkArea * wa = workArea(i);
1703 LASSERT(wa, return 0);
1704 if (&wa->bufferView().buffer() == &buffer)
1711 void TabWorkArea::closeAll()
1714 QWidget * wac = widget(0);
1715 LASSERT(wac, return);
1722 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1724 for (int index = 0; index < count(); ++index)
1725 if (workArea(index) == w)
1731 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1733 LASSERT(work_area, return false);
1734 int index = indexOfWorkArea(work_area);
1738 if (index == currentIndex())
1739 // Make sure the work area is up to date.
1740 on_currentTabChanged(index);
1742 // Switch to the work area.
1743 setCurrentIndex(index);
1744 work_area->setFocus();
1750 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1752 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1753 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1754 wa->setUpdatesEnabled(false);
1755 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1756 // when hiding it again below).
1757 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1758 showBar(count() > 0);
1759 addTab(wac, wa->windowTitle());
1760 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1761 this, SLOT(updateTabTexts()));
1762 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1763 setFullScreen(true);
1765 // Hide tabbar if there's only one tab.
1766 showBar(count() > 1);
1774 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1776 LASSERT(work_area, return false);
1777 int index = indexOfWorkArea(work_area);
1781 work_area->setUpdatesEnabled(false);
1782 QWidget * wac = widget(index);
1787 // make sure the next work area is enabled.
1788 currentWidget()->setUpdatesEnabled(true);
1789 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1790 setFullScreen(true);
1792 // Show tabbar only if there's more than one tab.
1793 showBar(count() > 1);
1795 lastWorkAreaRemoved();
1803 void TabWorkArea::on_currentTabChanged(int i)
1805 // returns e.g. on application destruction
1808 GuiWorkArea * wa = workArea(i);
1809 LASSERT(wa, return);
1810 wa->setUpdatesEnabled(true);
1811 wa->scheduleRedraw(true);
1814 currentWorkAreaChanged(wa);
1816 LYXERR(Debug::GUI, "currentTabChanged " << i
1817 << " File: " << wa->bufferView().buffer().absFileName());
1821 void TabWorkArea::closeCurrentBuffer()
1824 if (clicked_tab_ == -1)
1825 wa = currentWorkArea();
1827 wa = workArea(clicked_tab_);
1828 LASSERT(wa, return);
1830 wa->view().closeWorkArea(wa);
1834 void TabWorkArea::hideCurrentTab()
1837 if (clicked_tab_ == -1)
1838 wa = currentWorkArea();
1840 wa = workArea(clicked_tab_);
1841 LASSERT(wa, return);
1843 wa->view().hideWorkArea(wa);
1847 void TabWorkArea::closeTab(int index)
1849 on_currentTabChanged(index);
1852 wa = currentWorkArea();
1854 wa = workArea(index);
1855 LASSERT(wa, return);
1857 wa->view().closeWorkArea(wa);
1864 /// make vector happy
1865 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1867 DisplayPath(int tab, FileName const & filename)
1870 filename_ = (filename.extension() == "lyx") ?
1871 toqstr(filename.onlyFileNameWithoutExt())
1872 : toqstr(filename.onlyFileName());
1873 postfix_ = toqstr(filename.absoluteFilePath()).
1874 split("/", QString::SkipEmptyParts);
1875 postfix_.pop_back();
1876 abs_ = toqstr(filename.absoluteFilePath());
1877 dottedPrefix_ = false;
1880 /// Absolute path for debugging.
1885 /// Add the first segment from the postfix or three dots to the prefix.
1886 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1887 /// when really needed.
1888 void shiftPathSegment(bool dotted)
1890 if (postfix_.count() <= 0)
1894 if (dottedPrefix_ && !prefix_.isEmpty())
1895 prefix_ += ellipsisSlash_;
1896 prefix_ += postfix_.front() + "/";
1898 dottedPrefix_ = dotted && !prefix_.isEmpty();
1899 postfix_.pop_front();
1902 QString displayString() const
1904 if (prefix_.isEmpty())
1907 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1908 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1911 QString forecastPathString() const
1913 if (postfix_.count() == 0)
1914 return displayString();
1917 + (dottedPrefix_ ? ellipsisSlash_ : "")
1918 + postfix_.front() + "/";
1921 bool final() const { return postfix_.empty(); }
1923 int tab() const { return tab_; }
1927 static QString const ellipsisSlash_;
1931 QStringList postfix_;
1943 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1947 bool operator<(DisplayPath const & a, DisplayPath const & b)
1949 return a.displayString() < b.displayString();
1953 bool operator==(DisplayPath const & a, DisplayPath const & b)
1955 return a.displayString() == b.displayString();
1959 void TabWorkArea::updateTabTexts()
1964 std::list<DisplayPath> paths;
1965 typedef std::list<DisplayPath>::iterator It;
1967 // collect full names first: path into postfix, empty prefix and
1968 // filename without extension
1969 for (size_t i = 0; i < n; ++i) {
1970 GuiWorkArea * i_wa = workArea(i);
1971 FileName const fn = i_wa->bufferView().buffer().fileName();
1972 paths.push_back(DisplayPath(i, fn));
1975 // go through path segments and see if it helps to make the path more unique
1976 bool somethingChanged = true;
1977 bool allFinal = false;
1978 while (somethingChanged && !allFinal) {
1979 // adding path segments changes order
1982 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1983 somethingChanged = false;
1986 // find segments which are not unique (i.e. non-atomic)
1987 It it = paths.begin();
1989 QString segString = it->displayString();
1990 for (; it != paths.end(); ++it) {
1991 // look to the next item
1996 allFinal = allFinal && it->final();
1998 LYXERR(Debug::GUI, "it = " << it->abs()
1999 << " => " << it->displayString());
2001 // still the same segment?
2003 if ((next != paths.end()
2004 && (nextString = next->displayString()) == segString))
2006 LYXERR(Debug::GUI, "segment ended");
2008 // only a trivial one with one element?
2009 if (it == segStart) {
2010 // start new segment
2012 segString = nextString;
2016 // We found a non-atomic segment
2017 // We know that segStart <= it < next <= paths.end().
2018 // The assertion below tells coverity about it.
2019 LATTEST(segStart != paths.end());
2020 QString dspString = segStart->forecastPathString();
2021 LYXERR(Debug::GUI, "first forecast found for "
2022 << segStart->abs() << " => " << dspString);
2025 // Shift path segments and hope for the best
2026 // that it makes the path more unique.
2027 somethingChanged = true;
2028 bool moreUnique = false;
2029 for (; sit != next; ++sit) {
2030 if (sit->forecastPathString() != dspString) {
2031 LYXERR(Debug::GUI, "different forecast found for "
2032 << sit->abs() << " => " << sit->forecastPathString());
2036 LYXERR(Debug::GUI, "same forecast found for "
2037 << sit->abs() << " => " << dspString);
2040 // if the path segment helped, add it. Otherwise add dots
2041 bool dots = !moreUnique;
2042 LYXERR(Debug::GUI, "using dots = " << dots);
2043 for (sit = segStart; sit != next; ++sit) {
2044 sit->shiftPathSegment(dots);
2045 LYXERR(Debug::GUI, "shifting "
2046 << sit->abs() << " => " << sit->displayString());
2049 // start new segment
2051 segString = nextString;
2055 // set new tab titles
2056 for (It it = paths.begin(); it != paths.end(); ++it) {
2057 int const tab_index = it->tab();
2058 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2059 QString tab_text = it->displayString().replace("&", "&&");
2060 if (!buf.fileName().empty() && !buf.isClean())
2062 QString tab_tooltip = it->abs();
2063 if (buf.hasReadonlyFlag()) {
2064 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2065 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2067 setTabIcon(tab_index, QIcon());
2068 if (buf.notifiesExternalModification()) {
2069 QString const warn = qt_("%1 (modified externally)");
2070 tab_tooltip = warn.arg(tab_tooltip);
2071 tab_text += QChar(0x26a0);
2073 setTabText(tab_index, tab_text);
2074 setTabToolTip(tab_index, tab_tooltip);
2079 void TabWorkArea::showContextMenu(const QPoint & pos)
2082 clicked_tab_ = tabBar()->tabAt(pos);
2083 if (clicked_tab_ == -1)
2088 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2089 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2090 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2091 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2092 popup.exec(tabBar()->mapToGlobal(pos));
2098 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2100 QWidget * w = widget(fromIndex);
2101 QIcon icon = tabIcon(fromIndex);
2102 QString text = tabText(fromIndex);
2104 setCurrentIndex(fromIndex);
2105 removeTab(fromIndex);
2106 insertTab(toIndex, w, icon, text);
2107 setCurrentIndex(toIndex);
2111 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2112 : QWidget(parent), wa_(wa)
2114 LASSERT(wa, return);
2115 Ui::WorkAreaUi::setupUi(this);
2116 layout()->addWidget(wa);
2117 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2118 this, SLOT(updateDisplay()));
2119 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2120 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2121 setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2126 void GuiWorkAreaContainer::updateDisplay()
2128 Buffer const & buf = wa_->bufferView().buffer();
2129 notificationFrame->setHidden(!buf.notifiesExternalModification());
2130 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2131 .arg(toqstr(buf.fileName().displayName()));
2132 externalModificationLabel->setText(label);
2136 void GuiWorkAreaContainer::dispatch(FuncRequest f) const
2138 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2139 wa_->bufferView().buffer().absFileName()));
2144 void GuiWorkAreaContainer::reload() const
2146 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2150 void GuiWorkAreaContainer::ignore() const
2152 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2156 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2158 // prevent TabWorkArea from opening a new buffer on double click
2163 } // namespace frontend
2166 #include "moc_GuiWorkArea.cpp"