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();
308 // With Qt4.5 a mouse event will happen before the first paint event
309 // so make sure that the buffer view has an up to date metrics.
310 d->buffer_view_->resize(viewport()->width(), viewport()->height());
311 d->caret_ = new frontend::CaretWidget();
313 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
314 setAcceptDrops(true);
315 setMouseTracking(true);
316 setMinimumSize(100, 70);
317 setFrameStyle(QFrame::NoFrame);
320 d->updateCursorShape();
322 // we paint our own background
323 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
325 setFocusPolicy(Qt::StrongFocus);
327 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
328 << " viewport height: " << viewport()->height());
330 // Enables input methods for asian languages.
331 // Must be set when creating custom text editing widgets.
332 setAttribute(Qt::WA_InputMethodEnabled, true);
336 GuiWorkArea::~GuiWorkArea()
342 void GuiWorkArea::Private::updateCursorShape()
344 bool const clickable = buffer_view_ && buffer_view_->clickableInset();
345 p->viewport()->setCursor(clickable ? Qt::PointingHandCursor
350 void GuiWorkArea::setGuiView(GuiView & gv)
356 void GuiWorkArea::setBuffer(Buffer & buffer)
358 delete d->buffer_view_;
359 d->buffer_view_ = new BufferView(buffer);
360 buffer.workAreaManager().add(this);
362 // HACK: Prevents an additional redraw when the scrollbar pops up
363 // which regularily happens on documents with more than one page.
364 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
365 // Since we have no geometry information yet, we assume that
366 // a document needs a scrollbar if there is more then four
367 // paragraph in the outermost text.
368 if (buffer.text().paragraphs().size() > 4)
369 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
370 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
371 Q_EMIT bufferViewChanged();
375 void GuiWorkArea::fixVerticalScrollBar()
378 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
382 void GuiWorkArea::close()
384 d->lyx_view_->removeWorkArea(this);
388 void GuiWorkArea::setFullScreen(bool full_screen)
390 d->buffer_view_->setFullScreen(full_screen);
391 setFrameStyle(QFrame::NoFrame);
393 setFrameStyle(QFrame::NoFrame);
394 if (lyxrc.full_screen_scrollbar)
395 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
397 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
401 BufferView & GuiWorkArea::bufferView()
403 return *d->buffer_view_;
407 BufferView const & GuiWorkArea::bufferView() const
409 return *d->buffer_view_;
413 void GuiWorkArea::stopBlinkingCaret()
415 d->caret_timeout_.stop();
420 void GuiWorkArea::startBlinkingCaret()
422 // do not show the cursor if the view is busy
428 d->buffer_view_->caretPosAndHeight(p, h);
429 // Don't start blinking if the cursor isn't on screen.
430 if (!d->buffer_view_->cursorInView(p, h))
435 // Avoid blinking when debugging PAINTING, since it creates too much noise
436 if (!lyxerr.debugging(Debug::PAINTING)) {
437 // we are not supposed to cache this value.
438 int const time = QApplication::cursorFlashTime() / 2;
441 d->caret_timeout_.setInterval(time);
442 d->caret_timeout_.start();
447 void GuiWorkArea::toggleCaret()
449 if (d->caret_visible_)
456 void GuiWorkArea::scheduleRedraw(bool update_metrics)
459 // No need to redraw in this case.
462 // No need to do anything if this is the current view. The BufferView
463 // metrics are already up to date.
464 if (update_metrics || d->lyx_view_ != guiApp->currentView()
465 || d->lyx_view_->currentWorkArea() != this) {
466 // FIXME: it would be nice to optimize for the off-screen case.
467 d->buffer_view_->cursor().fixIfBroken();
468 d->buffer_view_->updateMetrics();
469 d->buffer_view_->cursor().fixIfBroken();
472 // update caret position, because otherwise it has to wait until
473 // the blinking interval is over
474 d->updateCaretGeometry();
476 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
477 viewport()->update();
479 /// FIXME: is this still true now that paintEvent does the actual painting?
480 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
481 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
482 d->updateScrollbar();
483 d->lyx_view_->updateStatusBar();
485 if (lyxerr.debugging(Debug::WORKAREA))
486 d->buffer_view_->coordCache().dump();
490 d->updateCursorShape();
494 // Keep in sync with GuiWorkArea::processKeySym below
495 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
497 return guiApp->queryKeySym(key, mod);
501 // Keep in sync with GuiWorkArea::queryKeySym above
502 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
504 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
505 && lyxrc.full_screen_menubar) {
506 // FIXME HACK: we should not have to do this here. See related comment
507 // in GuiView::event() (QEvent::ShortcutOverride)
508 d->lyx_view_->menuBar()->hide();
511 // In order to avoid bad surprise in the middle of an operation,
512 // we better stop the blinking caret...
513 // the caret gets restarted in GuiView::restartCaret()
515 guiApp->processKeySym(key, mod);
519 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
522 if (cmd.action() == LFUN_FILE_OPEN) {
524 lyx_view_->dispatch(cmd, dr);
528 bool const notJustMovingTheMouse =
529 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
531 // In order to avoid bad surprise in the middle of an operation, we better stop
532 // the blinking caret.
533 if (notJustMovingTheMouse)
534 p->stopBlinkingCaret();
536 buffer_view_->mouseEventDispatch(cmd);
538 // Skip these when selecting
539 // FIXME: let GuiView take care of those.
540 if (cmd.action() != LFUN_MOUSE_MOTION) {
541 completer_->updateVisibility(false, false);
542 lyx_view_->updateDialogs();
543 lyx_view_->updateStatusBar();
546 // GUI tweaks except with mouse motion with no button pressed.
547 if (notJustMovingTheMouse) {
548 // Slight hack: this is only called currently when we
549 // clicked somewhere, so we force through the display
550 // of the new status here.
551 // FIXME: let GuiView take care of those.
552 lyx_view_->clearMessage();
554 // Show the caret immediately after any operation
555 p->startBlinkingCaret();
562 void GuiWorkArea::Private::resizeBufferView()
564 // WARNING: Please don't put any code that will trigger a repaint here!
565 // We are already inside a paint event.
566 p->stopBlinkingCaret();
567 // Warn our container (GuiView).
572 buffer_view_->caretPosAndHeight(point, h);
573 bool const caret_in_view = buffer_view_->cursorInView(point, h);
574 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
576 buffer_view_->scrollToCursor();
577 updateCaretGeometry();
579 // Update scrollbars which might have changed due different
580 // BufferView dimension. This is especially important when the
581 // BufferView goes from zero-size to the real-size for the first time,
582 // as the scrollbar paramters are then set for the first time.
585 need_resize_ = false;
587 // Eventually, restart the caret after the resize event.
588 // We might be resizing even if the focus is on another widget so we only
589 // restart the caret if we have the focus.
591 QTimer::singleShot(50, p, SLOT(startBlinkingCaret()));
595 void GuiWorkArea::Private::updateCaretGeometry()
599 buffer_view_->caretPosAndHeight(point, h);
600 if (!buffer_view_->cursorInView(point, h))
604 bool l_shape = false;
605 Font const & realfont = buffer_view_->cursor().real_current_font;
606 BufferParams const & bp = buffer_view_->buffer().params();
607 bool const samelang = realfont.language() == bp.language;
608 bool const isrtl = realfont.isVisibleRightToLeft();
610 if (!samelang || isrtl != bp.language->rightToLeft())
613 // The ERT language hack needs fixing up
614 if (realfont.language() == latex_language)
617 // show caret on screen
618 Cursor & cur = buffer_view_->cursor();
619 bool completable = cur.inset().showCompletionCursor()
620 && completer_->completionAvailable()
621 && !completer_->popupVisible()
622 && !completer_->inlineVisible();
623 caret_visible_ = true;
625 //int cur_x = buffer_view_->getPos(cur).x_;
626 // We may have decided to slide the cursor row so that caret
628 point.x_ -= buffer_view_->horizScrollOffset();
630 caret_->update(point.x_, point.y_, h, l_shape, isrtl, completable);
634 void GuiWorkArea::Private::showCaret()
639 updateCaretGeometry();
640 p->viewport()->update(caret_->rect());
644 void GuiWorkArea::Private::hideCaret()
649 caret_visible_ = false;
650 //if (!qApp->focusWidget())
651 p->viewport()->update(caret_->rect());
655 void GuiWorkArea::Private::updateScrollbar()
657 // Prevent setRange() and setSliderPosition from causing recursive calls via
658 // the signal valueChanged. (#10311)
659 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
660 p, SLOT(scrollTo(int)));
661 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
662 p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
663 p->verticalScrollBar()->setPageStep(scroll_.page_step);
664 p->verticalScrollBar()->setSingleStep(scroll_.single_step);
665 p->verticalScrollBar()->setSliderPosition(0);
666 // Connect to the vertical scroll bar
667 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
668 p, SLOT(scrollTo(int)));
672 void GuiWorkArea::scrollTo(int value)
675 d->buffer_view_->scrollDocView(value, true);
677 if (lyxrc.cursor_follows_scrollbar) {
678 d->buffer_view_->setCursorFromScrollbar();
679 // FIXME: let GuiView take care of those.
680 d->lyx_view_->updateLayoutList();
682 // Show the caret immediately after any operation.
683 startBlinkingCaret();
686 QApplication::syncX();
691 bool GuiWorkArea::event(QEvent * e)
694 case QEvent::ToolTip: {
695 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
696 if (lyxrc.use_tooltip) {
697 QPoint pos = helpEvent->pos();
698 if (pos.x() < viewport()->width()) {
699 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
700 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
703 QToolTip::hideText();
705 // Don't forget to accept the event!
710 case QEvent::ShortcutOverride:
711 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
713 keyPressEvent(static_cast<QKeyEvent *>(e));
714 return e->isAccepted();
716 case QEvent::KeyPress: {
717 // We catch this event in order to catch the Tab or Shift+Tab key press
718 // which are otherwise reserved to focus switching between controls
720 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
721 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
722 || (ke->key() == Qt::Key_Backtab && (
723 ke->modifiers() == Qt::ShiftModifier
724 || ke->modifiers() == Qt::NoModifier))) {
728 return QAbstractScrollArea::event(e);
732 return QAbstractScrollArea::event(e);
738 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
741 if (e->reason() == QContextMenuEvent::Mouse)
742 // the menu name is set on mouse press
743 name = d->context_menu_name_;
745 QPoint pos = e->pos();
746 Cursor const & cur = d->buffer_view_->cursor();
747 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
748 // Do not access the context menu of math right in front of before
749 // the cursor. This does not work when the cursor is in text.
750 Inset * inset = cur.paragraph().getInset(cur.pos());
751 if (inset && inset->asInsetMath())
753 else if (cur.pos() > 0) {
754 inset = cur.paragraph().getInset(cur.pos() - 1);
759 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
766 // always show mnemonics when the keyboard is used to show the context menu
767 // FIXME: This should be fixed in Qt itself
768 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
769 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
774 // Position the menu to the right.
775 // FIXME: menu position should be different for RTL text.
776 menu->exec(e->globalPos());
781 void GuiWorkArea::focusInEvent(QFocusEvent * e)
783 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
784 if (d->lyx_view_->currentWorkArea() != this) {
785 d->lyx_view_->setCurrentWorkArea(this);
786 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
789 startBlinkingCaret();
790 QAbstractScrollArea::focusInEvent(e);
794 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
796 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
798 QAbstractScrollArea::focusOutEvent(e);
802 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
804 if (d->dc_event_.active && d->dc_event_ == *e) {
805 d->dc_event_.active = false;
806 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
807 q_button_state(e->button()), q_key_state(e->modifiers()));
813 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
814 inputContext()->reset();
817 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
818 q_button_state(e->button()), q_key_state(e->modifiers()));
821 // Save the context menu on mouse press, because also the mouse
822 // cursor is set on mouse press. Afterwards, we can either release
823 // the mousebutton somewhere else, or the cursor might have moved
824 // due to the DEPM. We need to do this after the mouse has been
825 // set in dispatch(), because the selection state might change.
826 if (e->button() == Qt::RightButton)
827 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
833 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
835 if (d->synthetic_mouse_event_.timeout.running())
836 d->synthetic_mouse_event_.timeout.stop();
838 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
839 q_button_state(e->button()), q_key_state(e->modifiers()));
845 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
847 // we kill the triple click if we move
848 doubleClickTimeout();
849 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
850 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
854 // If we're above or below the work area...
855 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
856 && e->buttons() == mouse_button::button1) {
857 // Make sure only a synthetic event can cause a page scroll,
858 // so they come at a steady rate:
860 // _Force_ a scroll up:
861 cmd.set_y(e->y() - 21);
863 cmd.set_y(e->y() + 21);
864 // Store the event, to be handled when the timeout expires.
865 d->synthetic_mouse_event_.cmd = cmd;
867 if (d->synthetic_mouse_event_.timeout.running()) {
868 // Discard the event. Note that it _may_ be handled
869 // when the timeout expires if
870 // synthetic_mouse_event_.cmd has not been overwritten.
871 // Ie, when the timeout expires, we handle the
872 // most recent event but discard all others that
873 // occurred after the one used to start the timeout
874 // in the first place.
878 d->synthetic_mouse_event_.restart_timeout = true;
879 d->synthetic_mouse_event_.timeout.start();
880 // Fall through to handle this event...
882 } else if (d->synthetic_mouse_event_.timeout.running()) {
883 // Store the event, to be possibly handled when the timeout
885 // Once the timeout has expired, normal control is returned
886 // to mouseMoveEvent (restart_timeout = false).
887 // This results in a much smoother 'feel' when moving the
888 // mouse back into the work area.
889 d->synthetic_mouse_event_.cmd = cmd;
890 d->synthetic_mouse_event_.restart_timeout = false;
897 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
899 // Wheel rotation by one notch results in a delta() of 120 (see
900 // documentation of QWheelEvent)
901 double const delta = ev->delta() / 120.0;
903 switch (lyxrc.scroll_wheel_zoom) {
904 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
905 zoom = ev->modifiers() & Qt::ControlModifier;
906 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
908 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
909 zoom = ev->modifiers() & Qt::ShiftModifier;
910 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
912 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
913 zoom = ev->modifiers() & Qt::AltModifier;
914 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
916 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
920 docstring arg = convert<docstring>(int(5 * delta));
921 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
925 // Take into account the desktop wide settings.
926 int const lines = qApp->wheelScrollLines();
927 int const page_step = verticalScrollBar()->pageStep();
928 // Test if the wheel mouse is set to one screen at a time.
929 // This is according to
930 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
932 min(lines * verticalScrollBar()->singleStep(), page_step);
934 // Take into account the rotation and the user preferences.
935 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
936 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
937 << " delta = " << delta << " scroll_value = " << scroll_value
938 << " page_step = " << page_step);
940 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
946 void GuiWorkArea::generateSyntheticMouseEvent()
948 int const e_y = d->synthetic_mouse_event_.cmd.y();
949 int const wh = d->buffer_view_->workHeight();
950 bool const up = e_y < 0;
951 bool const down = e_y > wh;
953 // Set things off to generate the _next_ 'pseudo' event.
955 if (d->synthetic_mouse_event_.restart_timeout) {
956 // This is some magic formulae to determine the speed
957 // of scrolling related to the position of the mouse.
960 int dist = up ? -e_y : e_y - wh;
961 time = max(min(200, 250000 / (dist * dist)), 1) ;
964 step = 80000 / (time * time);
968 d->synthetic_mouse_event_.timeout.setTimeout(time);
969 d->synthetic_mouse_event_.timeout.start();
972 // Can we scroll further ?
973 int const value = verticalScrollBar()->value();
974 if (value == verticalScrollBar()->maximum()
975 || value == verticalScrollBar()->minimum()) {
976 d->synthetic_mouse_event_.timeout.stop();
981 if (step <= 2 * wh) {
982 d->buffer_view_->scroll(up ? -step : step);
983 d->buffer_view_->updateMetrics();
985 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
988 // In which paragraph do we have to set the cursor ?
989 Cursor & cur = d->buffer_view_->cursor();
990 // FIXME: we don't know how to handle math.
991 Text * text = cur.text();
994 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
996 // Quit gracefully if there are no metrics, since otherwise next
997 // line would crash (bug #10324).
998 // This situation seems related to a (not yet understood) timing problem.
1002 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
1003 ParagraphMetrics const & pm = *pp.second;
1004 pit_type const pit = pp.first;
1006 if (pm.rows().empty())
1009 // Find the row at which we set the cursor.
1010 RowList::const_iterator rit = pm.rows().begin();
1011 RowList::const_iterator rlast = pm.rows().end();
1012 int yy = pm.position() - pm.ascent();
1013 for (--rlast; rit != rlast; ++rit) {
1014 int h = rit->height();
1015 if ((up && yy + h > 0)
1016 || (!up && yy + h > wh - defaultRowHeight()))
1021 // Find the position of the cursor
1023 int x = d->synthetic_mouse_event_.cmd.x();
1024 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1029 cur.boundary(bound);
1031 d->buffer_view_->buffer().changed(false);
1036 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1038 // this is also called for ShortcutOverride events. In this case, one must
1039 // not act but simply accept the event explicitly.
1040 bool const act = (ev->type() != QEvent::ShortcutOverride);
1042 // Do not process here some keys if dialog_mode_ is set
1044 && (ev->modifiers() == Qt::NoModifier
1045 || ev->modifiers() == Qt::ShiftModifier)
1046 && (ev->key() == Qt::Key_Escape
1047 || ev->key() == Qt::Key_Enter
1048 || ev->key() == Qt::Key_Return)
1054 // intercept some keys if completion popup is visible
1055 if (d->completer_->popupVisible()) {
1056 switch (ev->key()) {
1058 case Qt::Key_Return:
1060 d->completer_->activate();
1066 // do nothing if there are other events
1067 // (the auto repeated events come too fast)
1068 // it looks like this is only needed on X11
1069 #if defined(Q_WS_X11) || defined(QPA_XCB)
1070 // FIXME: this is a weird way to implement event compression. Also, this is
1071 // broken with IBus.
1072 if (act && qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1073 switch (ev->key()) {
1074 case Qt::Key_PageDown:
1075 case Qt::Key_PageUp:
1080 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1087 KeyModifier const m = q_key_state(ev->modifiers());
1090 if (m & ShiftModifier)
1092 if (m & ControlModifier)
1094 if (m & AltModifier)
1096 if (m & MetaModifier)
1100 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1101 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1102 << " keyState: " << str);
1105 setKeySymbol(&sym, ev);
1108 processKeySym(sym, m);
1111 ev->setAccepted(queryKeySym(sym, m));
1118 void GuiWorkArea::doubleClickTimeout()
1120 d->dc_event_.active = false;
1124 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1126 d->dc_event_ = DoubleClick(ev);
1127 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1128 SLOT(doubleClickTimeout()));
1129 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1130 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1136 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1138 QAbstractScrollArea::resizeEvent(ev);
1139 d->need_resize_ = true;
1144 void GuiWorkArea::Private::paintPreeditText(GuiPainter & pain)
1146 if (preedit_string_.empty())
1149 // FIXME: shall we use real_current_font here? (see #10478)
1150 FontInfo const font = buffer_view_->cursor().getFont().fontInfo();
1151 FontMetrics const & fm = theFontMetrics(font);
1152 int const height = fm.maxHeight();
1153 int cur_x = caret_->rect().left();
1154 int cur_y = caret_->rect().bottom();
1156 // get attributes of input method cursor.
1157 // cursor_pos : cursor position in preedit string.
1158 size_t cursor_pos = 0;
1159 bool cursor_is_visible = false;
1160 for (auto const & attr : preedit_attr_) {
1161 if (attr.type == QInputMethodEvent::Cursor) {
1162 cursor_pos = attr.start;
1163 cursor_is_visible = attr.length != 0;
1168 size_t const preedit_length = preedit_string_.length();
1170 // get position of selection in input method.
1171 // FIXME: isn't there a way to do this simplier?
1172 // rStart : cursor position in selected string in IM.
1174 // rLength : selected string length in IM.
1176 if (cursor_pos < preedit_length) {
1177 for (auto const & attr : preedit_attr_) {
1178 if (attr.type == QInputMethodEvent::TextFormat) {
1179 if (attr.start <= int(cursor_pos)
1180 && int(cursor_pos) < attr.start + attr.length) {
1181 rStart = attr.start;
1182 rLength = attr.length;
1183 if (!cursor_is_visible)
1184 cursor_pos += rLength;
1191 rStart = cursor_pos;
1195 int const right_margin = buffer_view_->rightMargin();
1196 Painter::preedit_style ps;
1197 // Most often there would be only one line:
1199 for (size_t pos = 0; pos != preedit_length; ++pos) {
1200 char_type const typed_char = preedit_string_[pos];
1201 // reset preedit string style
1202 ps = Painter::preedit_default;
1204 // if we reached the right extremity of the screen, go to next line.
1205 if (cur_x + fm.width(typed_char) > p->viewport()->width() - right_margin) {
1206 cur_x = right_margin;
1207 cur_y += height + 1;
1210 // preedit strings are displayed with dashed underline
1211 // and partial strings are displayed white on black indicating
1212 // that we are in selecting mode in the input method.
1213 // FIXME: rLength == preedit_length is not a changing condition
1214 // FIXME: should be put out of the loop.
1216 && pos < rStart + rLength
1217 && !(cursor_pos < rLength && rLength == preedit_length))
1218 ps = Painter::preedit_selecting;
1220 if (pos == cursor_pos
1221 && (cursor_pos < rLength && rLength == preedit_length))
1222 ps = Painter::preedit_cursor;
1224 // draw one character and update cur_x.
1225 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1230 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1232 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1233 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1235 if (d->need_resize_ || pixelRatio() != d->last_pixel_ratio_) {
1237 d->resizeBufferView();
1240 d->last_pixel_ratio_ = pixelRatio();
1242 GuiPainter pain(d->screenDevice(), pixelRatio());
1244 d->buffer_view_->draw(pain, d->caret_visible_);
1246 // The preedit text, if needed
1247 d->paintPreeditText(pain);
1250 if (d->caret_visible_)
1251 d->caret_->draw(pain);
1253 d->updateScreen(ev->rect());
1259 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1261 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1262 << " commitString: " << e->commitString());
1264 // insert the processed text in the document (handles undo)
1265 if (!e->commitString().isEmpty()) {
1266 d->buffer_view_->cursor().beginUndoGroup();
1267 d->buffer_view_->cursor().insert(qstring_to_ucs4(e->commitString()));
1268 d->buffer_view_->updateMetrics();
1269 d->buffer_view_->cursor().endUndoGroup();
1270 viewport()->update();
1273 // Hide the caret during the test transformation.
1274 if (e->preeditString().isEmpty())
1275 startBlinkingCaret();
1277 stopBlinkingCaret();
1279 if (d->preedit_string_.empty() && e->preeditString().isEmpty()) {
1285 // The preedit text and its attributes will be used in paintPreeditText
1286 d->preedit_string_ = qstring_to_ucs4(e->preeditString());
1287 d->preedit_attr_ = e->attributes();
1290 // redraw area of preedit string.
1291 int height = d->caret_->rect().height();
1292 int cur_y = d->caret_->rect().bottom();
1293 viewport()->update(0, cur_y - height, viewport()->width(),
1294 (height + 1) * d->preedit_lines_);
1296 if (d->preedit_string_.empty()) {
1297 d->preedit_lines_ = 1;
1302 // Don't forget to accept the event!
1307 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1309 QRect cur_r(0, 0, 0, 0);
1311 // this is the CJK-specific composition window position and
1312 // the context menu position when the menu key is pressed.
1313 case Qt::ImMicroFocus:
1314 cur_r = d->caret_->rect();
1315 if (d->preedit_lines_ != 1)
1317 cur_r.moveBottom(cur_r.bottom()
1318 + cur_r.height() * (d->preedit_lines_ - 1));
1319 // return lower right of caret in LyX.
1322 return QWidget::inputMethodQuery(query);
1327 void GuiWorkArea::updateWindowTitle()
1329 Buffer const & buf = bufferView().buffer();
1330 if (buf.fileName() != d->file_name_
1331 || buf.params().shell_escape != d->shell_escape_
1332 || buf.hasReadonlyFlag() != d->read_only_
1333 || buf.lyxvc().vcstatus() != d->vc_status_
1334 || buf.isClean() != d->clean_
1335 || buf.notifiesExternalModification() != d->externally_modified_) {
1336 d->file_name_ = buf.fileName();
1337 d->shell_escape_ = buf.params().shell_escape;
1338 d->read_only_ = buf.hasReadonlyFlag();
1339 d->vc_status_ = buf.lyxvc().vcstatus();
1340 d->clean_ = buf.isClean();
1341 d->externally_modified_ = buf.notifiesExternalModification();
1342 Q_EMIT titleChanged(this);
1347 bool GuiWorkArea::isFullScreen() const
1349 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1353 bool GuiWorkArea::inDialogMode() const
1355 return d->dialog_mode_;
1359 void GuiWorkArea::setDialogMode(bool mode)
1361 d->dialog_mode_ = mode;
1365 GuiCompleter & GuiWorkArea::completer()
1367 return *d->completer_;
1370 GuiView const & GuiWorkArea::view() const
1372 return *d->lyx_view_;
1376 GuiView & GuiWorkArea::view()
1378 return *d->lyx_view_;
1381 ////////////////////////////////////////////////////////////////////
1385 ////////////////////////////////////////////////////////////////////
1388 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1390 support::TempFile tempfile("embedded.internal");
1391 tempfile.setAutoRemove(false);
1392 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1393 buffer_->setUnnamed(true);
1394 buffer_->setFullyLoaded(true);
1395 setBuffer(*buffer_);
1396 setDialogMode(true);
1400 EmbeddedWorkArea::~EmbeddedWorkArea()
1402 // No need to destroy buffer and bufferview here, because it is done
1403 // in theBufferList() destruction loop at application exit
1407 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1410 GuiWorkArea::closeEvent(ev);
1414 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1417 GuiWorkArea::hideEvent(ev);
1421 QSize EmbeddedWorkArea::sizeHint () const
1424 // GuiWorkArea sets the size to the screen's viewport
1425 // by returning a value this gets overridden
1426 // EmbeddedWorkArea is now sized to fit in the layout
1427 // of the parent, and has a minimum size set in GuiWorkArea
1428 // which is what we return here
1429 return QSize(100, 70);
1433 void EmbeddedWorkArea::disable()
1435 stopBlinkingCaret();
1436 if (view().currentWorkArea() != this)
1438 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1439 // tolerates it and shows the background logo), what happens if
1440 // an EmbeddedWorkArea is closed after closing all document WAs
1441 view().setCurrentWorkArea(view().currentMainWorkArea());
1444 ////////////////////////////////////////////////////////////////////
1448 ////////////////////////////////////////////////////////////////////
1451 class NoTabFrameMacStyle : public QProxyStyle {
1454 QRect subElementRect(SubElement element, const QStyleOption * option,
1455 const QWidget * widget = 0) const
1457 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1458 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1460 // The Qt Mac style puts the contents into a 3 pixel wide box
1461 // which looks very ugly and not like other Mac applications.
1462 // Hence we remove this here, and moreover the 16 pixel round
1463 // frame above if the tab bar is hidden.
1464 if (element == QStyle::SE_TabWidgetTabContents) {
1465 rect.adjust(- rect.left(), 0, rect.left(), 0);
1474 NoTabFrameMacStyle noTabFrameMacStyle;
1478 TabWorkArea::TabWorkArea(QWidget * parent)
1479 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1482 setStyle(&noTabFrameMacStyle);
1485 QPalette pal = palette();
1486 pal.setColor(QPalette::Active, QPalette::Button,
1487 pal.color(QPalette::Active, QPalette::Window));
1488 pal.setColor(QPalette::Disabled, QPalette::Button,
1489 pal.color(QPalette::Disabled, QPalette::Window));
1490 pal.setColor(QPalette::Inactive, QPalette::Button,
1491 pal.color(QPalette::Inactive, QPalette::Window));
1493 QObject::connect(this, SIGNAL(currentChanged(int)),
1494 this, SLOT(on_currentTabChanged(int)));
1496 closeBufferButton = new QToolButton(this);
1497 closeBufferButton->setPalette(pal);
1498 // FIXME: rename the icon to closebuffer.png
1499 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1500 closeBufferButton->setText("Close File");
1501 closeBufferButton->setAutoRaise(true);
1502 closeBufferButton->setCursor(Qt::ArrowCursor);
1503 closeBufferButton->setToolTip(qt_("Close File"));
1504 closeBufferButton->setEnabled(true);
1505 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1506 this, SLOT(closeCurrentBuffer()));
1507 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1509 // setup drag'n'drop
1510 QTabBar* tb = new DragTabBar;
1511 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1512 this, SLOT(moveTab(int, int)));
1513 tb->setElideMode(Qt::ElideNone);
1516 // make us responsible for the context menu of the tabbar
1517 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1518 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1519 this, SLOT(showContextMenu(const QPoint &)));
1520 connect(tb, SIGNAL(tabCloseRequested(int)),
1521 this, SLOT(closeTab(int)));
1523 setUsesScrollButtons(true);
1527 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1529 if (me->button() == Qt::MidButton)
1530 midpressed_tab_ = tabBar()->tabAt(me->pos());
1532 QTabWidget::mousePressEvent(me);
1536 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1538 if (me->button() == Qt::MidButton) {
1539 int const midreleased_tab = tabBar()->tabAt(me->pos());
1540 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1541 closeTab(midreleased_tab);
1543 QTabWidget::mouseReleaseEvent(me);
1547 void TabWorkArea::paintEvent(QPaintEvent * event)
1549 if (tabBar()->isVisible()) {
1550 QTabWidget::paintEvent(event);
1552 // Prevent the selected tab to influence the
1553 // painting of the frame of the tab widget.
1554 // This is needed for gtk style in Qt.
1555 QStylePainter p(this);
1556 #if QT_VERSION < 0x050000
1557 QStyleOptionTabWidgetFrameV2 opt;
1559 QStyleOptionTabWidgetFrame opt;
1561 initStyleOption(&opt);
1562 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1564 opt.selectedTabRect = QRect();
1565 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1570 bool TabWorkArea::posIsTab(QPoint position)
1572 // tabAt returns -1 if tab does not covers position
1573 return tabBar()->tabAt(position) > -1;
1577 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1579 if (event->button() != Qt::LeftButton)
1582 // this code chunk is unnecessary because it seems the event only makes
1583 // it this far if it is not on a tab. I'm not sure why this is (maybe
1584 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1585 // this is true in all cases and if it will be true in the future so I
1586 // leave this code for now. (skostysh, 2016-07-21)
1588 // return early if double click on existing tabs
1589 if (posIsTab(event->pos()))
1592 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1596 void TabWorkArea::setFullScreen(bool full_screen)
1598 for (int i = 0; i != count(); ++i) {
1599 if (GuiWorkArea * wa = workArea(i))
1600 wa->setFullScreen(full_screen);
1603 if (lyxrc.full_screen_tabbar)
1604 showBar(!full_screen && count() > 1);
1606 showBar(count() > 1);
1610 void TabWorkArea::showBar(bool show)
1612 tabBar()->setEnabled(show);
1613 tabBar()->setVisible(show);
1614 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1615 setTabsClosable(!lyxrc.single_close_tab_button);
1619 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1621 QWidget * w = QTabWidget::widget(index);
1624 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1630 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1632 return widget(currentIndex());
1636 GuiWorkArea * TabWorkArea::workArea(int index) const
1638 GuiWorkAreaContainer * w = widget(index);
1641 return w->workArea();
1645 GuiWorkArea * TabWorkArea::currentWorkArea() const
1647 return workArea(currentIndex());
1651 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1653 // FIXME: this method doesn't work if we have more than one work area
1654 // showing the same buffer.
1655 for (int i = 0; i != count(); ++i) {
1656 GuiWorkArea * wa = workArea(i);
1657 LASSERT(wa, return 0);
1658 if (&wa->bufferView().buffer() == &buffer)
1665 void TabWorkArea::closeAll()
1668 QWidget * wac = widget(0);
1669 LASSERT(wac, return);
1676 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1678 for (int index = 0; index < count(); ++index)
1679 if (workArea(index) == w)
1685 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1687 LASSERT(work_area, return false);
1688 int index = indexOfWorkArea(work_area);
1692 if (index == currentIndex())
1693 // Make sure the work area is up to date.
1694 on_currentTabChanged(index);
1696 // Switch to the work area.
1697 setCurrentIndex(index);
1698 work_area->setFocus();
1704 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1706 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1707 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1708 wa->setUpdatesEnabled(false);
1709 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1710 // when hiding it again below).
1711 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1712 showBar(count() > 0);
1713 addTab(wac, wa->windowTitle());
1714 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1715 this, SLOT(updateTabTexts()));
1716 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1717 setFullScreen(true);
1719 // Hide tabbar if there's only one tab.
1720 showBar(count() > 1);
1728 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1730 LASSERT(work_area, return false);
1731 int index = indexOfWorkArea(work_area);
1735 work_area->setUpdatesEnabled(false);
1736 QWidget * wac = widget(index);
1741 // make sure the next work area is enabled.
1742 currentWidget()->setUpdatesEnabled(true);
1743 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1744 setFullScreen(true);
1746 // Show tabbar only if there's more than one tab.
1747 showBar(count() > 1);
1749 lastWorkAreaRemoved();
1757 void TabWorkArea::on_currentTabChanged(int i)
1759 // returns e.g. on application destruction
1762 GuiWorkArea * wa = workArea(i);
1763 LASSERT(wa, return);
1764 wa->setUpdatesEnabled(true);
1765 wa->scheduleRedraw(true);
1768 currentWorkAreaChanged(wa);
1770 LYXERR(Debug::GUI, "currentTabChanged " << i
1771 << " File: " << wa->bufferView().buffer().absFileName());
1775 void TabWorkArea::closeCurrentBuffer()
1778 if (clicked_tab_ == -1)
1779 wa = currentWorkArea();
1781 wa = workArea(clicked_tab_);
1782 LASSERT(wa, return);
1784 wa->view().closeWorkArea(wa);
1788 void TabWorkArea::hideCurrentTab()
1791 if (clicked_tab_ == -1)
1792 wa = currentWorkArea();
1794 wa = workArea(clicked_tab_);
1795 LASSERT(wa, return);
1797 wa->view().hideWorkArea(wa);
1801 void TabWorkArea::closeTab(int index)
1803 on_currentTabChanged(index);
1806 wa = currentWorkArea();
1808 wa = workArea(index);
1809 LASSERT(wa, return);
1811 wa->view().closeWorkArea(wa);
1818 /// make vector happy
1819 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1821 DisplayPath(int tab, FileName const & filename)
1824 filename_ = (filename.extension() == "lyx") ?
1825 toqstr(filename.onlyFileNameWithoutExt())
1826 : toqstr(filename.onlyFileName());
1827 postfix_ = toqstr(filename.absoluteFilePath()).
1828 split("/", QString::SkipEmptyParts);
1829 postfix_.pop_back();
1830 abs_ = toqstr(filename.absoluteFilePath());
1831 dottedPrefix_ = false;
1834 /// Absolute path for debugging.
1839 /// Add the first segment from the postfix or three dots to the prefix.
1840 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1841 /// when really needed.
1842 void shiftPathSegment(bool dotted)
1844 if (postfix_.count() <= 0)
1848 if (dottedPrefix_ && !prefix_.isEmpty())
1849 prefix_ += ellipsisSlash_;
1850 prefix_ += postfix_.front() + "/";
1852 dottedPrefix_ = dotted && !prefix_.isEmpty();
1853 postfix_.pop_front();
1856 QString displayString() const
1858 if (prefix_.isEmpty())
1861 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1862 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1865 QString forecastPathString() const
1867 if (postfix_.count() == 0)
1868 return displayString();
1871 + (dottedPrefix_ ? ellipsisSlash_ : "")
1872 + postfix_.front() + "/";
1875 bool final() const { return postfix_.empty(); }
1877 int tab() const { return tab_; }
1881 static QString const ellipsisSlash_;
1885 QStringList postfix_;
1897 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1901 bool operator<(DisplayPath const & a, DisplayPath const & b)
1903 return a.displayString() < b.displayString();
1907 bool operator==(DisplayPath const & a, DisplayPath const & b)
1909 return a.displayString() == b.displayString();
1913 void TabWorkArea::updateTabTexts()
1918 std::list<DisplayPath> paths;
1919 typedef std::list<DisplayPath>::iterator It;
1921 // collect full names first: path into postfix, empty prefix and
1922 // filename without extension
1923 for (size_t i = 0; i < n; ++i) {
1924 GuiWorkArea * i_wa = workArea(i);
1925 FileName const fn = i_wa->bufferView().buffer().fileName();
1926 paths.push_back(DisplayPath(i, fn));
1929 // go through path segments and see if it helps to make the path more unique
1930 bool somethingChanged = true;
1931 bool allFinal = false;
1932 while (somethingChanged && !allFinal) {
1933 // adding path segments changes order
1936 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1937 somethingChanged = false;
1940 // find segments which are not unique (i.e. non-atomic)
1941 It it = paths.begin();
1943 QString segString = it->displayString();
1944 for (; it != paths.end(); ++it) {
1945 // look to the next item
1950 allFinal = allFinal && it->final();
1952 LYXERR(Debug::GUI, "it = " << it->abs()
1953 << " => " << it->displayString());
1955 // still the same segment?
1957 if ((next != paths.end()
1958 && (nextString = next->displayString()) == segString))
1960 LYXERR(Debug::GUI, "segment ended");
1962 // only a trivial one with one element?
1963 if (it == segStart) {
1964 // start new segment
1966 segString = nextString;
1970 // We found a non-atomic segment
1971 // We know that segStart <= it < next <= paths.end().
1972 // The assertion below tells coverity about it.
1973 LATTEST(segStart != paths.end());
1974 QString dspString = segStart->forecastPathString();
1975 LYXERR(Debug::GUI, "first forecast found for "
1976 << segStart->abs() << " => " << dspString);
1979 // Shift path segments and hope for the best
1980 // that it makes the path more unique.
1981 somethingChanged = true;
1982 bool moreUnique = false;
1983 for (; sit != next; ++sit) {
1984 if (sit->forecastPathString() != dspString) {
1985 LYXERR(Debug::GUI, "different forecast found for "
1986 << sit->abs() << " => " << sit->forecastPathString());
1990 LYXERR(Debug::GUI, "same forecast found for "
1991 << sit->abs() << " => " << dspString);
1994 // if the path segment helped, add it. Otherwise add dots
1995 bool dots = !moreUnique;
1996 LYXERR(Debug::GUI, "using dots = " << dots);
1997 for (sit = segStart; sit != next; ++sit) {
1998 sit->shiftPathSegment(dots);
1999 LYXERR(Debug::GUI, "shifting "
2000 << sit->abs() << " => " << sit->displayString());
2003 // start new segment
2005 segString = nextString;
2009 // set new tab titles
2010 for (It it = paths.begin(); it != paths.end(); ++it) {
2011 int const tab_index = it->tab();
2012 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2013 QString tab_text = it->displayString().replace("&", "&&");
2014 if (!buf.fileName().empty() && !buf.isClean())
2016 QString tab_tooltip = it->abs();
2017 if (buf.hasReadonlyFlag()) {
2018 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2019 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2021 setTabIcon(tab_index, QIcon());
2022 if (buf.notifiesExternalModification()) {
2023 QString const warn = qt_("%1 (modified externally)");
2024 tab_tooltip = warn.arg(tab_tooltip);
2025 tab_text += QChar(0x26a0);
2027 setTabText(tab_index, tab_text);
2028 setTabToolTip(tab_index, tab_tooltip);
2033 void TabWorkArea::showContextMenu(const QPoint & pos)
2036 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
2037 if (clicked_tab_ == -1)
2042 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2043 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2044 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2045 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2046 popup.exec(tabBar()->mapToGlobal(pos));
2052 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2054 QWidget * w = widget(fromIndex);
2055 QIcon icon = tabIcon(fromIndex);
2056 QString text = tabText(fromIndex);
2058 setCurrentIndex(fromIndex);
2059 removeTab(fromIndex);
2060 insertTab(toIndex, w, icon, text);
2061 setCurrentIndex(toIndex);
2065 DragTabBar::DragTabBar(QWidget* parent)
2068 setAcceptDrops(true);
2069 setTabsClosable(!lyxrc.single_close_tab_button);
2073 void DragTabBar::mousePressEvent(QMouseEvent * event)
2075 if (event->button() == Qt::LeftButton)
2076 dragStartPos_ = event->pos();
2077 QTabBar::mousePressEvent(event);
2081 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2083 // If the left button isn't pressed anymore then return
2084 if (!(event->buttons() & Qt::LeftButton))
2087 // If the distance is too small then return
2088 if ((event->pos() - dragStartPos_).manhattanLength()
2089 < QApplication::startDragDistance())
2092 // did we hit something after all?
2093 int tab = tabAt(dragStartPos_);
2097 // simulate button release to remove highlight from button
2098 int i = currentIndex();
2099 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2100 event->button(), event->buttons(), 0);
2101 QTabBar::mouseReleaseEvent(&me);
2105 QDrag * drag = new QDrag(this);
2106 QMimeData * mimeData = new QMimeData;
2107 // a crude way to distinguish tab-reodering drops from other ones
2108 mimeData->setData("action", "tab-reordering") ;
2109 drag->setMimeData(mimeData);
2111 // get tab pixmap as cursor
2112 QRect r = tabRect(tab);
2113 QPixmap pixmap(r.size());
2114 render(&pixmap, - r.topLeft());
2115 drag->setPixmap(pixmap);
2120 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2122 // Only accept if it's an tab-reordering request
2123 QMimeData const * m = event->mimeData();
2124 QStringList formats = m->formats();
2125 if (formats.contains("action")
2126 && m->data("action") == "tab-reordering")
2127 event->acceptProposedAction();
2131 void DragTabBar::dropEvent(QDropEvent * event)
2133 int fromIndex = tabAt(dragStartPos_);
2134 int toIndex = tabAt(event->pos());
2136 // Tell interested objects that
2137 if (fromIndex != toIndex)
2138 tabMoveRequested(fromIndex, toIndex);
2139 event->acceptProposedAction();
2143 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2144 : QWidget(parent), wa_(wa)
2146 LASSERT(wa, return);
2147 Ui::WorkAreaUi::setupUi(this);
2148 layout()->addWidget(wa);
2149 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2150 this, SLOT(updateDisplay()));
2151 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2152 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2153 setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2158 void GuiWorkAreaContainer::updateDisplay()
2160 Buffer const & buf = wa_->bufferView().buffer();
2161 notificationFrame->setHidden(!buf.notifiesExternalModification());
2162 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2163 .arg(toqstr(buf.fileName().displayName()));
2164 externalModificationLabel->setText(label);
2168 void GuiWorkAreaContainer::dispatch(FuncRequest f) const
2170 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2171 wa_->bufferView().buffer().absFileName()));
2176 void GuiWorkAreaContainer::reload() const
2178 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2182 void GuiWorkAreaContainer::ignore() const
2184 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2188 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2190 // prevent TabWorkArea from opening a new buffer on double click
2195 } // namespace frontend
2198 #include "moc_GuiWorkArea.cpp"