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, bot);
155 painter.drawLine(x_, bot, x_ + caret_width_ + r, 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))
276 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
277 : d(new Private(this))
280 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
286 double GuiWorkArea::pixelRatio() const
288 #if QT_VERSION >= 0x050000
289 return qt_scale_factor * devicePixelRatio();
296 void GuiWorkArea::init()
299 connect(&d->caret_timeout_, SIGNAL(timeout()),
300 this, SLOT(toggleCaret()));
302 // This connection is closed at the same time as this is destroyed.
303 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
304 generateSyntheticMouseEvent();
307 // With Qt4.5 a mouse event will happen before the first paint event
308 // so make sure that the buffer view has an up to date metrics.
309 d->buffer_view_->resize(viewport()->width(), viewport()->height());
310 d->caret_ = new frontend::CaretWidget();
312 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
313 setAcceptDrops(true);
314 setMouseTracking(true);
315 setMinimumSize(100, 70);
316 setFrameStyle(QFrame::NoFrame);
319 d->updateCursorShape();
321 // we paint our own background
322 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
324 setFocusPolicy(Qt::StrongFocus);
326 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
327 << " viewport height: " << viewport()->height());
329 // Enables input methods for asian languages.
330 // Must be set when creating custom text editing widgets.
331 setAttribute(Qt::WA_InputMethodEnabled, true);
335 GuiWorkArea::~GuiWorkArea()
341 void GuiWorkArea::Private::updateCursorShape()
343 bool const clickable = buffer_view_ && buffer_view_->clickableInset();
344 p->viewport()->setCursor(clickable ? Qt::PointingHandCursor
349 void GuiWorkArea::setGuiView(GuiView & gv)
355 void GuiWorkArea::setBuffer(Buffer & buffer)
357 delete d->buffer_view_;
358 d->buffer_view_ = new BufferView(buffer);
359 buffer.workAreaManager().add(this);
361 // HACK: Prevents an additional redraw when the scrollbar pops up
362 // which regularily happens on documents with more than one page.
363 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
364 // Since we have no geometry information yet, we assume that
365 // a document needs a scrollbar if there is more then four
366 // paragraph in the outermost text.
367 if (buffer.text().paragraphs().size() > 4)
368 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
369 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
370 Q_EMIT bufferViewChanged();
374 void GuiWorkArea::fixVerticalScrollBar()
377 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
381 void GuiWorkArea::close()
383 d->lyx_view_->removeWorkArea(this);
387 void GuiWorkArea::setFullScreen(bool full_screen)
389 d->buffer_view_->setFullScreen(full_screen);
390 setFrameStyle(QFrame::NoFrame);
392 setFrameStyle(QFrame::NoFrame);
393 if (lyxrc.full_screen_scrollbar)
394 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
396 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
400 BufferView & GuiWorkArea::bufferView()
402 return *d->buffer_view_;
406 BufferView const & GuiWorkArea::bufferView() const
408 return *d->buffer_view_;
412 void GuiWorkArea::stopBlinkingCaret()
414 d->caret_timeout_.stop();
419 void GuiWorkArea::startBlinkingCaret()
421 // do not show the cursor if the view is busy
427 d->buffer_view_->caretPosAndHeight(p, h);
428 // Don't start blinking if the cursor isn't on screen.
429 if (!d->buffer_view_->cursorInView(p, h))
434 // Avoid blinking when debugging PAINTING, since it creates too much noise
435 if (!lyxerr.debugging(Debug::PAINTING)) {
436 // we are not supposed to cache this value.
437 int const time = QApplication::cursorFlashTime() / 2;
440 d->caret_timeout_.setInterval(time);
441 d->caret_timeout_.start();
446 void GuiWorkArea::toggleCaret()
448 if (d->caret_visible_)
455 void GuiWorkArea::scheduleRedraw(bool update_metrics)
458 // No need to redraw in this case.
461 // No need to do anything if this is the current view. The BufferView
462 // metrics are already up to date.
463 if (update_metrics || d->lyx_view_ != guiApp->currentView()
464 || d->lyx_view_->currentWorkArea() != this) {
465 // FIXME: it would be nice to optimize for the off-screen case.
466 d->buffer_view_->cursor().fixIfBroken();
467 d->buffer_view_->updateMetrics();
468 d->buffer_view_->cursor().fixIfBroken();
471 // update caret position, because otherwise it has to wait until
472 // the blinking interval is over
473 d->updateCaretGeometry();
475 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
476 viewport()->update();
478 /// FIXME: is this still true now that paintEvent does the actual painting?
479 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
480 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
481 d->updateScrollbar();
482 d->lyx_view_->updateStatusBar();
484 if (lyxerr.debugging(Debug::WORKAREA))
485 d->buffer_view_->coordCache().dump();
489 d->updateCursorShape();
493 // Keep in sync with GuiWorkArea::processKeySym below
494 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
496 return guiApp->queryKeySym(key, mod);
500 // Keep in sync with GuiWorkArea::queryKeySym above
501 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
503 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
504 && lyxrc.full_screen_menubar) {
505 // FIXME HACK: we should not have to do this here. See related comment
506 // in GuiView::event() (QEvent::ShortcutOverride)
507 d->lyx_view_->menuBar()->hide();
510 // In order to avoid bad surprise in the middle of an operation,
511 // we better stop the blinking caret...
512 // the caret gets restarted in GuiView::restartCaret()
514 guiApp->processKeySym(key, mod);
518 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
521 if (cmd.action() == LFUN_FILE_OPEN) {
523 lyx_view_->dispatch(cmd, dr);
527 bool const notJustMovingTheMouse =
528 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
530 // In order to avoid bad surprise in the middle of an operation, we better stop
531 // the blinking caret.
532 if (notJustMovingTheMouse)
533 p->stopBlinkingCaret();
535 buffer_view_->mouseEventDispatch(cmd);
537 // Skip these when selecting
538 // FIXME: let GuiView take care of those.
539 if (cmd.action() != LFUN_MOUSE_MOTION) {
540 completer_->updateVisibility(false, false);
541 lyx_view_->updateDialogs();
542 lyx_view_->updateStatusBar();
545 // GUI tweaks except with mouse motion with no button pressed.
546 if (notJustMovingTheMouse) {
547 // Slight hack: this is only called currently when we
548 // clicked somewhere, so we force through the display
549 // of the new status here.
550 // FIXME: let GuiView take care of those.
551 lyx_view_->clearMessage();
553 // Show the caret immediately after any operation
554 p->startBlinkingCaret();
561 void GuiWorkArea::Private::resizeBufferView()
563 // WARNING: Please don't put any code that will trigger a repaint here!
564 // We are already inside a paint event.
565 p->stopBlinkingCaret();
566 // Warn our container (GuiView).
571 buffer_view_->caretPosAndHeight(point, h);
572 bool const caret_in_view = buffer_view_->cursorInView(point, h);
573 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
575 buffer_view_->scrollToCursor();
576 updateCaretGeometry();
578 // Update scrollbars which might have changed due different
579 // BufferView dimension. This is especially important when the
580 // BufferView goes from zero-size to the real-size for the first time,
581 // as the scrollbar paramters are then set for the first time.
584 need_resize_ = false;
586 // Eventually, restart the caret after the resize event.
587 // We might be resizing even if the focus is on another widget so we only
588 // restart the caret if we have the focus.
590 QTimer::singleShot(50, p, SLOT(startBlinkingCaret()));
594 void GuiWorkArea::Private::updateCaretGeometry()
598 buffer_view_->caretPosAndHeight(point, h);
599 if (!buffer_view_->cursorInView(point, h))
603 bool l_shape = false;
604 Font const & realfont = buffer_view_->cursor().real_current_font;
605 BufferParams const & bp = buffer_view_->buffer().params();
606 bool const samelang = realfont.language() == bp.language;
607 bool const isrtl = realfont.isVisibleRightToLeft();
609 if (!samelang || isrtl != bp.language->rightToLeft())
612 // The ERT language hack needs fixing up
613 if (realfont.language() == latex_language)
616 // show caret on screen
617 Cursor & cur = buffer_view_->cursor();
618 bool completable = cur.inset().showCompletionCursor()
619 && completer_->completionAvailable()
620 && !completer_->popupVisible()
621 && !completer_->inlineVisible();
622 caret_visible_ = true;
624 //int cur_x = buffer_view_->getPos(cur).x_;
625 // We may have decided to slide the cursor row so that caret
627 point.x_ -= buffer_view_->horizScrollOffset();
629 caret_->update(point.x_, point.y_, h, l_shape, isrtl, completable);
633 void GuiWorkArea::Private::showCaret()
638 updateCaretGeometry();
639 p->viewport()->update(caret_->rect());
643 void GuiWorkArea::Private::hideCaret()
648 caret_visible_ = false;
649 //if (!qApp->focusWidget())
650 p->viewport()->update(caret_->rect());
654 void GuiWorkArea::Private::updateScrollbar()
656 // Prevent setRange() and setSliderPosition from causing recursive calls via
657 // the signal valueChanged. (#10311)
658 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
659 p, SLOT(scrollTo(int)));
660 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
661 p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
662 p->verticalScrollBar()->setPageStep(scroll_.page_step);
663 p->verticalScrollBar()->setSingleStep(scroll_.single_step);
664 p->verticalScrollBar()->setSliderPosition(0);
665 // Connect to the vertical scroll bar
666 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
667 p, SLOT(scrollTo(int)));
671 void GuiWorkArea::scrollTo(int value)
674 d->buffer_view_->scrollDocView(value, true);
676 if (lyxrc.cursor_follows_scrollbar) {
677 d->buffer_view_->setCursorFromScrollbar();
678 // FIXME: let GuiView take care of those.
679 d->lyx_view_->updateLayoutList();
681 // Show the caret immediately after any operation.
682 startBlinkingCaret();
685 QApplication::syncX();
690 bool GuiWorkArea::event(QEvent * e)
693 case QEvent::ToolTip: {
694 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
695 if (lyxrc.use_tooltip) {
696 QPoint pos = helpEvent->pos();
697 if (pos.x() < viewport()->width()) {
698 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
699 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
702 QToolTip::hideText();
704 // Don't forget to accept the event!
709 case QEvent::ShortcutOverride:
710 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
712 keyPressEvent(static_cast<QKeyEvent *>(e));
713 return e->isAccepted();
715 case QEvent::KeyPress: {
716 // We catch this event in order to catch the Tab or Shift+Tab key press
717 // which are otherwise reserved to focus switching between controls
719 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
720 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
721 || (ke->key() == Qt::Key_Backtab && (
722 ke->modifiers() == Qt::ShiftModifier
723 || ke->modifiers() == Qt::NoModifier))) {
727 return QAbstractScrollArea::event(e);
731 return QAbstractScrollArea::event(e);
737 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
740 if (e->reason() == QContextMenuEvent::Mouse)
741 // the menu name is set on mouse press
742 name = d->context_menu_name_;
744 QPoint pos = e->pos();
745 Cursor const & cur = d->buffer_view_->cursor();
746 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
747 // Do not access the context menu of math right in front of before
748 // the cursor. This does not work when the cursor is in text.
749 Inset * inset = cur.paragraph().getInset(cur.pos());
750 if (inset && inset->asInsetMath())
752 else if (cur.pos() > 0) {
753 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
758 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
765 // always show mnemonics when the keyboard is used to show the context menu
766 // FIXME: This should be fixed in Qt itself
767 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
768 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
773 // Position the menu to the right.
774 // FIXME: menu position should be different for RTL text.
775 menu->exec(e->globalPos());
780 void GuiWorkArea::focusInEvent(QFocusEvent * e)
782 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
783 if (d->lyx_view_->currentWorkArea() != this) {
784 d->lyx_view_->setCurrentWorkArea(this);
785 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
788 startBlinkingCaret();
789 QAbstractScrollArea::focusInEvent(e);
793 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
795 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
797 QAbstractScrollArea::focusOutEvent(e);
801 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
803 if (d->dc_event_.active && d->dc_event_ == *e) {
804 d->dc_event_.active = false;
805 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
806 q_button_state(e->button()), q_key_state(e->modifiers()));
812 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
813 inputContext()->reset();
816 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
817 q_button_state(e->button()), q_key_state(e->modifiers()));
820 // Save the context menu on mouse press, because also the mouse
821 // cursor is set on mouse press. Afterwards, we can either release
822 // the mousebutton somewhere else, or the cursor might have moved
823 // due to the DEPM. We need to do this after the mouse has been
824 // set in dispatch(), because the selection state might change.
825 if (e->button() == Qt::RightButton)
826 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
832 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
834 if (d->synthetic_mouse_event_.timeout.running())
835 d->synthetic_mouse_event_.timeout.stop();
837 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
838 q_button_state(e->button()), q_key_state(e->modifiers()));
844 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
846 // we kill the triple click if we move
847 doubleClickTimeout();
848 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
849 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
853 // If we're above or below the work area...
854 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
855 && e->buttons() == mouse_button::button1) {
856 // Make sure only a synthetic event can cause a page scroll,
857 // so they come at a steady rate:
859 // _Force_ a scroll up:
860 cmd.set_y(e->y() - 21);
862 cmd.set_y(e->y() + 21);
863 // Store the event, to be handled when the timeout expires.
864 d->synthetic_mouse_event_.cmd = cmd;
866 if (d->synthetic_mouse_event_.timeout.running()) {
867 // Discard the event. Note that it _may_ be handled
868 // when the timeout expires if
869 // synthetic_mouse_event_.cmd has not been overwritten.
870 // Ie, when the timeout expires, we handle the
871 // most recent event but discard all others that
872 // occurred after the one used to start the timeout
873 // in the first place.
877 d->synthetic_mouse_event_.restart_timeout = true;
878 d->synthetic_mouse_event_.timeout.start();
879 // Fall through to handle this event...
881 } else if (d->synthetic_mouse_event_.timeout.running()) {
882 // Store the event, to be possibly handled when the timeout
884 // Once the timeout has expired, normal control is returned
885 // to mouseMoveEvent (restart_timeout = false).
886 // This results in a much smoother 'feel' when moving the
887 // mouse back into the work area.
888 d->synthetic_mouse_event_.cmd = cmd;
889 d->synthetic_mouse_event_.restart_timeout = false;
896 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
898 // Wheel rotation by one notch results in a delta() of 120 (see
899 // documentation of QWheelEvent)
900 double const delta = ev->delta() / 120.0;
902 switch (lyxrc.scroll_wheel_zoom) {
903 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
904 zoom = ev->modifiers() & Qt::ControlModifier;
905 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
907 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
908 zoom = ev->modifiers() & Qt::ShiftModifier;
909 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
911 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
912 zoom = ev->modifiers() & Qt::AltModifier;
913 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
915 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
919 docstring arg = convert<docstring>(int(5 * delta));
920 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
924 // Take into account the desktop wide settings.
925 int const lines = qApp->wheelScrollLines();
926 int const page_step = verticalScrollBar()->pageStep();
927 // Test if the wheel mouse is set to one screen at a time.
928 // This is according to
929 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
931 min(lines * verticalScrollBar()->singleStep(), page_step);
933 // Take into account the rotation and the user preferences.
934 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
935 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
936 << " delta = " << delta << " scroll_value = " << scroll_value
937 << " page_step = " << page_step);
939 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
945 void GuiWorkArea::generateSyntheticMouseEvent()
947 int const e_y = d->synthetic_mouse_event_.cmd.y();
948 int const wh = d->buffer_view_->workHeight();
949 bool const up = e_y < 0;
950 bool const down = e_y > wh;
952 // Set things off to generate the _next_ 'pseudo' event.
954 if (d->synthetic_mouse_event_.restart_timeout) {
955 // This is some magic formulae to determine the speed
956 // of scrolling related to the position of the mouse.
959 int dist = up ? -e_y : e_y - wh;
960 time = max(min(200, 250000 / (dist * dist)), 1) ;
963 step = 80000 / (time * time);
967 d->synthetic_mouse_event_.timeout.setTimeout(time);
968 d->synthetic_mouse_event_.timeout.start();
971 // Can we scroll further ?
972 int const value = verticalScrollBar()->value();
973 if (value == verticalScrollBar()->maximum()
974 || value == verticalScrollBar()->minimum()) {
975 d->synthetic_mouse_event_.timeout.stop();
980 if (step <= 2 * wh) {
981 d->buffer_view_->scroll(up ? -step : step);
982 d->buffer_view_->updateMetrics();
984 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
987 // In which paragraph do we have to set the cursor ?
988 Cursor & cur = d->buffer_view_->cursor();
989 // FIXME: we don't know how to handle math.
990 Text * text = cur.text();
993 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
995 // Quit gracefully if there are no metrics, since otherwise next
996 // line would crash (bug #10324).
997 // This situation seems related to a (not yet understood) timing problem.
1001 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
1002 ParagraphMetrics const & pm = *pp.second;
1003 pit_type const pit = pp.first;
1005 if (pm.rows().empty())
1008 // Find the row at which we set the cursor.
1009 RowList::const_iterator rit = pm.rows().begin();
1010 RowList::const_iterator rlast = pm.rows().end();
1011 int yy = pm.position() - pm.ascent();
1012 for (--rlast; rit != rlast; ++rit) {
1013 int h = rit->height();
1014 if ((up && yy + h > 0)
1015 || (!up && yy + h > wh - defaultRowHeight()))
1020 // Find the position of the cursor
1022 int x = d->synthetic_mouse_event_.cmd.x();
1023 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1028 cur.boundary(bound);
1030 d->buffer_view_->buffer().changed(false);
1035 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1037 // this is also called for ShortcutOverride events. In this case, one must
1038 // not act but simply accept the event explicitly.
1039 bool const act = (ev->type() != QEvent::ShortcutOverride);
1041 // Do not process here some keys if dialog_mode_ is set
1043 && (ev->modifiers() == Qt::NoModifier
1044 || ev->modifiers() == Qt::ShiftModifier)
1045 && (ev->key() == Qt::Key_Escape
1046 || ev->key() == Qt::Key_Enter
1047 || ev->key() == Qt::Key_Return)
1053 // intercept some keys if completion popup is visible
1054 if (d->completer_->popupVisible()) {
1055 switch (ev->key()) {
1057 case Qt::Key_Return:
1059 d->completer_->activate();
1065 // do nothing if there are other events
1066 // (the auto repeated events come too fast)
1067 // it looks like this is only needed on X11
1068 #if defined(Q_WS_X11) || defined(QPA_XCB)
1069 // FIXME: this is a weird way to implement event compression. Also, this is
1070 // broken with IBus.
1071 if (act && qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1072 switch (ev->key()) {
1073 case Qt::Key_PageDown:
1074 case Qt::Key_PageUp:
1079 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1086 KeyModifier const m = q_key_state(ev->modifiers());
1089 if (m & ShiftModifier)
1091 if (m & ControlModifier)
1093 if (m & AltModifier)
1095 if (m & MetaModifier)
1099 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1100 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1101 << " keyState: " << str);
1104 setKeySymbol(&sym, ev);
1107 processKeySym(sym, m);
1110 ev->setAccepted(queryKeySym(sym, m));
1117 void GuiWorkArea::doubleClickTimeout()
1119 d->dc_event_.active = false;
1123 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1125 d->dc_event_ = DoubleClick(ev);
1126 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1127 SLOT(doubleClickTimeout()));
1128 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1129 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1135 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1137 QAbstractScrollArea::resizeEvent(ev);
1138 d->need_resize_ = true;
1143 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1145 if (preedit_string_.empty())
1148 // FIXME: shall we use real_current_font here? (see #10478)
1149 FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1150 FontMetrics const & fm = theFontMetrics(font);
1151 int const height = fm.maxHeight();
1152 int cur_x = caret_->rect().left();
1153 int cur_y = caret_->rect().bottom();
1155 // get attributes of input method cursor.
1156 // cursor_pos : cursor position in preedit string.
1157 size_t cursor_pos = 0;
1158 bool cursor_is_visible = false;
1159 for (auto const & attr : preedit_attr_) {
1160 if (attr.type == QInputMethodEvent::Cursor) {
1161 cursor_pos = attr.start;
1162 cursor_is_visible = attr.length != 0;
1167 size_t const preedit_length = preedit_string_.length();
1169 // get position of selection in input method.
1170 // FIXME: isn't there a way to do this simplier?
1171 // rStart : cursor position in selected string in IM.
1173 // rLength : selected string length in IM.
1175 if (cursor_pos < preedit_length) {
1176 for (auto const & attr : preedit_attr_) {
1177 if (attr.type == QInputMethodEvent::TextFormat) {
1178 if (attr.start <= int(cursor_pos)
1179 && int(cursor_pos) < attr.start + attr.length) {
1180 rStart = attr.start;
1181 rLength = attr.length;
1182 if (!cursor_is_visible)
1183 cursor_pos += rLength;
1190 rStart = cursor_pos;
1194 int const right_margin = buffer_view_->rightMargin();
1195 Painter::preedit_style ps;
1196 // Most often there would be only one line:
1198 for (size_t pos = 0; pos != preedit_length; ++pos) {
1199 char_type const typed_char = preedit_string_[pos];
1200 // reset preedit string style
1201 ps = Painter::preedit_default;
1203 // if we reached the right extremity of the screen, go to next line.
1204 if (cur_x + fm.width(typed_char) > p->viewport()->width() - right_margin) {
1205 cur_x = right_margin;
1206 cur_y += height + 1;
1209 // preedit strings are displayed with dashed underline
1210 // and partial strings are displayed white on black indicating
1211 // that we are in selecting mode in the input method.
1212 // FIXME: rLength == preedit_length is not a changing condition
1213 // FIXME: should be put out of the loop.
1215 && pos < rStart + rLength
1216 && !(cursor_pos < rLength && rLength == preedit_length))
1217 ps = Painter::preedit_selecting;
1219 if (pos == cursor_pos
1220 && (cursor_pos < rLength && rLength == preedit_length))
1221 ps = Painter::preedit_cursor;
1223 // draw one character and update cur_x.
1224 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1229 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1231 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1232 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1234 if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_)
1235 d->resizeBufferView();
1237 d->last_pixel_ratio_ = pixelRatio();
1239 GuiPainter pain(viewport(), pixelRatio());
1240 d->buffer_view_->draw(pain, d->caret_visible_);
1242 // The preedit text, if needed
1243 d->paintPreeditText(pain);
1246 if (d->caret_visible_)
1247 d->caret_->draw(pain);
1252 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1254 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1255 << " commitString: " << e->commitString());
1257 // insert the processed text in the document (handles undo)
1258 if (!e->commitString().isEmpty()) {
1259 d->buffer_view_->cursor().beginUndoGroup();
1260 d->buffer_view_->cursor().insert(qstring_to_ucs4(e->commitString()));
1261 d->buffer_view_->updateMetrics();
1262 d->buffer_view_->cursor().endUndoGroup();
1263 viewport()->update();
1266 // Hide the caret during the test transformation.
1267 if (e->preeditString().isEmpty())
1268 startBlinkingCaret();
1270 stopBlinkingCaret();
1272 if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1278 // The preedit text and its attributes will be used in paintPreeditText
1279 d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1280 d->preedit_attr_ = e->attributes();
1283 // redraw area of preedit string.
1284 int height = d->caret_->rect().height();
1285 int cur_y = d->caret_->rect().bottom();
1286 viewport()->update(0, cur_y - height, viewport()->width(),
1287 (height + 1) * d->preedit_lines_);
1289 if (d->preedit_string_.empty()) {
1290 d->preedit_lines_ = 1;
1295 // Don't forget to accept the event!
1300 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1302 QRect cur_r(0, 0, 0, 0);
1304 // this is the CJK-specific composition window position and
1305 // the context menu position when the menu key is pressed.
1306 case Qt::ImMicroFocus:
1307 cur_r = d->caret_->rect();
1308 if (d->preedit_lines_ != 1)
1310 cur_r.moveBottom(cur_r.bottom()
1311 + cur_r.height() * (d->preedit_lines_ - 1));
1312 // return lower right of caret in LyX.
1315 return QWidget::inputMethodQuery(query);
1320 void GuiWorkArea::updateWindowTitle()
1322 Buffer const & buf = bufferView().buffer();
1323 if (buf.fileName() != d->file_name_
1324 || buf.params().shell_escape != d->shell_escape_
1325 || buf.hasReadonlyFlag() != d->read_only_
1326 || buf.lyxvc().vcstatus() != d->vc_status_
1327 || buf.isClean() != d->clean_
1328 || buf.notifiesExternalModification() != d->externally_modified_) {
1329 d->file_name_ = buf.fileName();
1330 d->shell_escape_ = buf.params().shell_escape;
1331 d->read_only_ = buf.hasReadonlyFlag();
1332 d->vc_status_ = buf.lyxvc().vcstatus();
1333 d->clean_ = buf.isClean();
1334 d->externally_modified_ = buf.notifiesExternalModification();
1335 Q_EMIT titleChanged(this);
1340 bool GuiWorkArea::isFullScreen() const
1342 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1346 bool GuiWorkArea::inDialogMode() const
1348 return d->dialog_mode_;
1352 void GuiWorkArea::setDialogMode(bool mode)
1354 d->dialog_mode_ = mode;
1358 GuiCompleter & GuiWorkArea::completer()
1360 return *d->completer_;
1363 GuiView const & GuiWorkArea::view() const
1365 return *d->lyx_view_;
1369 GuiView & GuiWorkArea::view()
1371 return *d->lyx_view_;
1374 ////////////////////////////////////////////////////////////////////
1378 ////////////////////////////////////////////////////////////////////
1381 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1383 support::TempFile tempfile("embedded.internal");
1384 tempfile.setAutoRemove(false);
1385 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1386 buffer_->setUnnamed(true);
1387 buffer_->setFullyLoaded(true);
1388 setBuffer(*buffer_);
1389 setDialogMode(true);
1393 EmbeddedWorkArea::~EmbeddedWorkArea()
1395 // No need to destroy buffer and bufferview here, because it is done
1396 // in theBufferList() destruction loop at application exit
1400 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1403 GuiWorkArea::closeEvent(ev);
1407 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1410 GuiWorkArea::hideEvent(ev);
1414 QSize EmbeddedWorkArea::sizeHint () const
1417 // GuiWorkArea sets the size to the screen's viewport
1418 // by returning a value this gets overridden
1419 // EmbeddedWorkArea is now sized to fit in the layout
1420 // of the parent, and has a minimum size set in GuiWorkArea
1421 // which is what we return here
1422 return QSize(100, 70);
1426 void EmbeddedWorkArea::disable()
1428 stopBlinkingCaret();
1429 if (view().currentWorkArea() != this)
1431 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1432 // tolerates it and shows the background logo), what happens if
1433 // an EmbeddedWorkArea is closed after closing all document WAs
1434 view().setCurrentWorkArea(view().currentMainWorkArea());
1437 ////////////////////////////////////////////////////////////////////
1441 ////////////////////////////////////////////////////////////////////
1444 class NoTabFrameMacStyle : public QProxyStyle {
1447 QRect subElementRect(SubElement element, const QStyleOption * option,
1448 const QWidget * widget = 0) const
1450 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1451 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1453 // The Qt Mac style puts the contents into a 3 pixel wide box
1454 // which looks very ugly and not like other Mac applications.
1455 // Hence we remove this here, and moreover the 16 pixel round
1456 // frame above if the tab bar is hidden.
1457 if (element == QStyle::SE_TabWidgetTabContents) {
1458 rect.adjust(- rect.left(), 0, rect.left(), 0);
1467 NoTabFrameMacStyle noTabFrameMacStyle;
1471 TabWorkArea::TabWorkArea(QWidget * parent)
1472 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1475 setStyle(&noTabFrameMacStyle);
1478 QPalette pal = palette();
1479 pal.setColor(QPalette::Active, QPalette::Button,
1480 pal.color(QPalette::Active, QPalette::Window));
1481 pal.setColor(QPalette::Disabled, QPalette::Button,
1482 pal.color(QPalette::Disabled, QPalette::Window));
1483 pal.setColor(QPalette::Inactive, QPalette::Button,
1484 pal.color(QPalette::Inactive, QPalette::Window));
1486 QObject::connect(this, SIGNAL(currentChanged(int)),
1487 this, SLOT(on_currentTabChanged(int)));
1489 closeBufferButton = new QToolButton(this);
1490 closeBufferButton->setPalette(pal);
1491 // FIXME: rename the icon to closebuffer.png
1492 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1493 closeBufferButton->setText("Close File");
1494 closeBufferButton->setAutoRaise(true);
1495 closeBufferButton->setCursor(Qt::ArrowCursor);
1496 closeBufferButton->setToolTip(qt_("Close File"));
1497 closeBufferButton->setEnabled(true);
1498 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1499 this, SLOT(closeCurrentBuffer()));
1500 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1502 // setup drag'n'drop
1503 QTabBar* tb = new DragTabBar;
1504 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1505 this, SLOT(moveTab(int, int)));
1506 tb->setElideMode(Qt::ElideNone);
1509 // make us responsible for the context menu of the tabbar
1510 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1511 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1512 this, SLOT(showContextMenu(const QPoint &)));
1513 connect(tb, SIGNAL(tabCloseRequested(int)),
1514 this, SLOT(closeTab(int)));
1516 setUsesScrollButtons(true);
1520 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1522 if (me->button() == Qt::MidButton)
1523 midpressed_tab_ = tabBar()->tabAt(me->pos());
1525 QTabWidget::mousePressEvent(me);
1529 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1531 if (me->button() == Qt::MidButton) {
1532 int const midreleased_tab = tabBar()->tabAt(me->pos());
1533 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1534 closeTab(midreleased_tab);
1536 QTabWidget::mouseReleaseEvent(me);
1540 void TabWorkArea::paintEvent(QPaintEvent * event)
1542 if (tabBar()->isVisible()) {
1543 QTabWidget::paintEvent(event);
1545 // Prevent the selected tab to influence the
1546 // painting of the frame of the tab widget.
1547 // This is needed for gtk style in Qt.
1548 QStylePainter p(this);
1549 #if QT_VERSION < 0x050000
1550 QStyleOptionTabWidgetFrameV2 opt;
1552 QStyleOptionTabWidgetFrame opt;
1554 initStyleOption(&opt);
1555 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1557 opt.selectedTabRect = QRect();
1558 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1563 bool TabWorkArea::posIsTab(QPoint position)
1565 // tabAt returns -1 if tab does not covers position
1566 return tabBar()->tabAt(position) > -1;
1570 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1572 if (event->button() != Qt::LeftButton)
1575 // this code chunk is unnecessary because it seems the event only makes
1576 // it this far if it is not on a tab. I'm not sure why this is (maybe
1577 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1578 // this is true in all cases and if it will be true in the future so I
1579 // leave this code for now. (skostysh, 2016-07-21)
1581 // return early if double click on existing tabs
1582 if (posIsTab(event->pos()))
1585 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1589 void TabWorkArea::setFullScreen(bool full_screen)
1591 for (int i = 0; i != count(); ++i) {
1592 if (GuiWorkArea * wa = workArea(i))
1593 wa->setFullScreen(full_screen);
1596 if (lyxrc.full_screen_tabbar)
1597 showBar(!full_screen && count() > 1);
1599 showBar(count() > 1);
1603 void TabWorkArea::showBar(bool show)
1605 tabBar()->setEnabled(show);
1606 tabBar()->setVisible(show);
1607 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1608 setTabsClosable(!lyxrc.single_close_tab_button);
1612 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1614 QWidget * w = QTabWidget::widget(index);
1617 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1623 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1625 return widget(currentIndex());
1629 GuiWorkArea * TabWorkArea::workArea(int index) const
1631 GuiWorkAreaContainer * w = widget(index);
1634 return w->workArea();
1638 GuiWorkArea * TabWorkArea::currentWorkArea() const
1640 return workArea(currentIndex());
1644 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1646 // FIXME: this method doesn't work if we have more than one work area
1647 // showing the same buffer.
1648 for (int i = 0; i != count(); ++i) {
1649 GuiWorkArea * wa = workArea(i);
1650 LASSERT(wa, return 0);
1651 if (&wa->bufferView().buffer() == &buffer)
1658 void TabWorkArea::closeAll()
1661 QWidget * wac = widget(0);
1662 LASSERT(wac, return);
1669 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1671 for (int index = 0; index < count(); ++index)
1672 if (workArea(index) == w)
1678 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1680 LASSERT(work_area, return false);
1681 int index = indexOfWorkArea(work_area);
1685 if (index == currentIndex())
1686 // Make sure the work area is up to date.
1687 on_currentTabChanged(index);
1689 // Switch to the work area.
1690 setCurrentIndex(index);
1691 work_area->setFocus();
1697 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1699 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1700 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1701 wa->setUpdatesEnabled(false);
1702 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1703 // when hiding it again below).
1704 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1705 showBar(count() > 0);
1706 addTab(wac, wa->windowTitle());
1707 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1708 this, SLOT(updateTabTexts()));
1709 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1710 setFullScreen(true);
1712 // Hide tabbar if there's only one tab.
1713 showBar(count() > 1);
1721 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1723 LASSERT(work_area, return false);
1724 int index = indexOfWorkArea(work_area);
1728 work_area->setUpdatesEnabled(false);
1729 QWidget * wac = widget(index);
1734 // make sure the next work area is enabled.
1735 currentWidget()->setUpdatesEnabled(true);
1736 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1737 setFullScreen(true);
1739 // Show tabbar only if there's more than one tab.
1740 showBar(count() > 1);
1742 lastWorkAreaRemoved();
1750 void TabWorkArea::on_currentTabChanged(int i)
1752 // returns e.g. on application destruction
1755 GuiWorkArea * wa = workArea(i);
1756 LASSERT(wa, return);
1757 wa->setUpdatesEnabled(true);
1758 wa->scheduleRedraw(true);
1761 currentWorkAreaChanged(wa);
1763 LYXERR(Debug::GUI, "currentTabChanged " << i
1764 << " File: " << wa->bufferView().buffer().absFileName());
1768 void TabWorkArea::closeCurrentBuffer()
1771 if (clicked_tab_ == -1)
1772 wa = currentWorkArea();
1774 wa = workArea(clicked_tab_);
1775 LASSERT(wa, return);
1777 wa->view().closeWorkArea(wa);
1781 void TabWorkArea::hideCurrentTab()
1784 if (clicked_tab_ == -1)
1785 wa = currentWorkArea();
1787 wa = workArea(clicked_tab_);
1788 LASSERT(wa, return);
1790 wa->view().hideWorkArea(wa);
1794 void TabWorkArea::closeTab(int index)
1796 on_currentTabChanged(index);
1799 wa = currentWorkArea();
1801 wa = workArea(index);
1802 LASSERT(wa, return);
1804 wa->view().closeWorkArea(wa);
1811 /// make vector happy
1812 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1814 DisplayPath(int tab, FileName const & filename)
1817 filename_ = (filename.extension() == "lyx") ?
1818 toqstr(filename.onlyFileNameWithoutExt())
1819 : toqstr(filename.onlyFileName());
1820 postfix_ = toqstr(filename.absoluteFilePath()).
1821 split("/", QString::SkipEmptyParts);
1822 postfix_.pop_back();
1823 abs_ = toqstr(filename.absoluteFilePath());
1824 dottedPrefix_ = false;
1827 /// Absolute path for debugging.
1832 /// Add the first segment from the postfix or three dots to the prefix.
1833 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1834 /// when really needed.
1835 void shiftPathSegment(bool dotted)
1837 if (postfix_.count() <= 0)
1841 if (dottedPrefix_ && !prefix_.isEmpty())
1842 prefix_ += ellipsisSlash_;
1843 prefix_ += postfix_.front() + "/";
1845 dottedPrefix_ = dotted && !prefix_.isEmpty();
1846 postfix_.pop_front();
1849 QString displayString() const
1851 if (prefix_.isEmpty())
1854 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1855 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1858 QString forecastPathString() const
1860 if (postfix_.count() == 0)
1861 return displayString();
1864 + (dottedPrefix_ ? ellipsisSlash_ : "")
1865 + postfix_.front() + "/";
1868 bool final() const { return postfix_.empty(); }
1870 int tab() const { return tab_; }
1874 static QString const ellipsisSlash_;
1878 QStringList postfix_;
1890 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1894 bool operator<(DisplayPath const & a, DisplayPath const & b)
1896 return a.displayString() < b.displayString();
1900 bool operator==(DisplayPath const & a, DisplayPath const & b)
1902 return a.displayString() == b.displayString();
1906 void TabWorkArea::updateTabTexts()
1911 std::list<DisplayPath> paths;
1912 typedef std::list<DisplayPath>::iterator It;
1914 // collect full names first: path into postfix, empty prefix and
1915 // filename without extension
1916 for (size_t i = 0; i < n; ++i) {
1917 GuiWorkArea * i_wa = workArea(i);
1918 FileName const fn = i_wa->bufferView().buffer().fileName();
1919 paths.push_back(DisplayPath(i, fn));
1922 // go through path segments and see if it helps to make the path more unique
1923 bool somethingChanged = true;
1924 bool allFinal = false;
1925 while (somethingChanged && !allFinal) {
1926 // adding path segments changes order
1929 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1930 somethingChanged = false;
1933 // find segments which are not unique (i.e. non-atomic)
1934 It it = paths.begin();
1936 QString segString = it->displayString();
1937 for (; it != paths.end(); ++it) {
1938 // look to the next item
1943 allFinal = allFinal && it->final();
1945 LYXERR(Debug::GUI, "it = " << it->abs()
1946 << " => " << it->displayString());
1948 // still the same segment?
1950 if ((next != paths.end()
1951 && (nextString = next->displayString()) == segString))
1953 LYXERR(Debug::GUI, "segment ended");
1955 // only a trivial one with one element?
1956 if (it == segStart) {
1957 // start new segment
1959 segString = nextString;
1963 // We found a non-atomic segment
1964 // We know that segStart <= it < next <= paths.end().
1965 // The assertion below tells coverity about it.
1966 LATTEST(segStart != paths.end());
1967 QString dspString = segStart->forecastPathString();
1968 LYXERR(Debug::GUI, "first forecast found for "
1969 << segStart->abs() << " => " << dspString);
1972 // Shift path segments and hope for the best
1973 // that it makes the path more unique.
1974 somethingChanged = true;
1975 bool moreUnique = false;
1976 for (; sit != next; ++sit) {
1977 if (sit->forecastPathString() != dspString) {
1978 LYXERR(Debug::GUI, "different forecast found for "
1979 << sit->abs() << " => " << sit->forecastPathString());
1983 LYXERR(Debug::GUI, "same forecast found for "
1984 << sit->abs() << " => " << dspString);
1987 // if the path segment helped, add it. Otherwise add dots
1988 bool dots = !moreUnique;
1989 LYXERR(Debug::GUI, "using dots = " << dots);
1990 for (sit = segStart; sit != next; ++sit) {
1991 sit->shiftPathSegment(dots);
1992 LYXERR(Debug::GUI, "shifting "
1993 << sit->abs() << " => " << sit->displayString());
1996 // start new segment
1998 segString = nextString;
2002 // set new tab titles
2003 for (It it = paths.begin(); it != paths.end(); ++it) {
2004 int const tab_index = it->tab();
2005 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2006 QString tab_text = it->displayString().replace("&", "&&");
2007 if (!buf.fileName().empty() && !buf.isClean())
2009 QString tab_tooltip = it->abs();
2010 if (buf.hasReadonlyFlag()) {
2011 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2012 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2014 setTabIcon(tab_index, QIcon());
2015 if (buf.notifiesExternalModification()) {
2016 QString const warn = qt_("%1 (modified externally)");
2017 tab_tooltip = warn.arg(tab_tooltip);
2018 tab_text += QChar(0x26a0);
2020 setTabText(tab_index, tab_text);
2021 setTabToolTip(tab_index, tab_tooltip);
2026 void TabWorkArea::showContextMenu(const QPoint & pos)
2029 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
2030 if (clicked_tab_ == -1)
2035 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2036 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2037 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2038 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2039 popup.exec(tabBar()->mapToGlobal(pos));
2045 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2047 QWidget * w = widget(fromIndex);
2048 QIcon icon = tabIcon(fromIndex);
2049 QString text = tabText(fromIndex);
2051 setCurrentIndex(fromIndex);
2052 removeTab(fromIndex);
2053 insertTab(toIndex, w, icon, text);
2054 setCurrentIndex(toIndex);
2058 DragTabBar::DragTabBar(QWidget* parent)
2061 setAcceptDrops(true);
2062 setTabsClosable(!lyxrc.single_close_tab_button);
2066 void DragTabBar::mousePressEvent(QMouseEvent * event)
2068 if (event->button() == Qt::LeftButton)
2069 dragStartPos_ = event->pos();
2070 QTabBar::mousePressEvent(event);
2074 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2076 // If the left button isn't pressed anymore then return
2077 if (!(event->buttons() & Qt::LeftButton))
2080 // If the distance is too small then return
2081 if ((event->pos() - dragStartPos_).manhattanLength()
2082 < QApplication::startDragDistance())
2085 // did we hit something after all?
2086 int tab = tabAt(dragStartPos_);
2090 // simulate button release to remove highlight from button
2091 int i = currentIndex();
2092 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2093 event->button(), event->buttons(), 0);
2094 QTabBar::mouseReleaseEvent(&me);
2098 QDrag * drag = new QDrag(this);
2099 QMimeData * mimeData = new QMimeData;
2100 // a crude way to distinguish tab-reodering drops from other ones
2101 mimeData->setData("action", "tab-reordering") ;
2102 drag->setMimeData(mimeData);
2104 // get tab pixmap as cursor
2105 QRect r = tabRect(tab);
2106 QPixmap pixmap(r.size());
2107 render(&pixmap, - r.topLeft());
2108 drag->setPixmap(pixmap);
2113 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2115 // Only accept if it's an tab-reordering request
2116 QMimeData const * m = event->mimeData();
2117 QStringList formats = m->formats();
2118 if (formats.contains("action")
2119 && m->data("action") == "tab-reordering")
2120 event->acceptProposedAction();
2124 void DragTabBar::dropEvent(QDropEvent * event)
2126 int fromIndex = tabAt(dragStartPos_);
2127 int toIndex = tabAt(event->pos());
2129 // Tell interested objects that
2130 if (fromIndex != toIndex)
2131 tabMoveRequested(fromIndex, toIndex);
2132 event->acceptProposedAction();
2136 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2137 : QWidget(parent), wa_(wa)
2139 LASSERT(wa, return);
2140 Ui::WorkAreaUi::setupUi(this);
2141 layout()->addWidget(wa);
2142 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2143 this, SLOT(updateDisplay()));
2144 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2145 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2146 setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2151 void GuiWorkAreaContainer::updateDisplay()
2153 Buffer const & buf = wa_->bufferView().buffer();
2154 notificationFrame->setHidden(!buf.notifiesExternalModification());
2155 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2156 .arg(toqstr(buf.fileName().displayName()));
2157 externalModificationLabel->setText(label);
2161 void GuiWorkAreaContainer::dispatch(FuncRequest f) const
2163 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2164 wa_->bufferView().buffer().absFileName()));
2169 void GuiWorkAreaContainer::reload() const
2171 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2175 void GuiWorkAreaContainer::ignore() const
2177 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2181 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2183 // prevent TabWorkArea from opening a new buffer on double click
2188 } // namespace frontend
2191 #include "moc_GuiWorkArea.cpp"