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"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "CoordCache.h"
28 #include "FuncRequest.h"
29 #include "GuiApplication.h"
30 #include "GuiCompleter.h"
31 #include "GuiKeySymbol.h"
32 #include "GuiPainter.h"
34 #include "KeySymbol.h"
39 #include "qt_helpers.h"
41 #include "TextMetrics.h"
44 #include "graphics/GraphicsImage.h"
45 #include "graphics/GraphicsLoader.h"
47 #include "support/convert.h"
48 #include "support/debug.h"
49 #include "support/gettext.h"
50 #include "support/FileName.h"
51 #include "support/lassert.h"
52 #include "support/TempFile.h"
54 #include "frontends/Application.h"
55 #include "frontends/FontMetrics.h"
56 #include "frontends/WorkAreaManager.h"
58 #include <QContextMenuEvent>
59 #if (QT_VERSION < 0x050000)
60 #include <QInputContext>
65 #include <QProxyStyle>
67 #include <QMainWindow>
72 #include <QPixmapCache>
74 #include <QStyleOption>
75 #include <QStylePainter>
77 #include <QToolButton>
81 #include "support/bind.h"
86 int const TabIndicatorWidth = 3;
92 using namespace lyx::support;
97 /// return the LyX mouse button state from Qt's
98 static mouse_button::state q_button_state(Qt::MouseButton button)
100 mouse_button::state b = mouse_button::none;
103 b = mouse_button::button1;
106 b = mouse_button::button2;
108 case Qt::RightButton:
109 b = mouse_button::button3;
118 /// return the LyX mouse button state from Qt's
119 mouse_button::state q_motion_state(Qt::MouseButtons state)
121 mouse_button::state b = mouse_button::none;
122 if (state & Qt::LeftButton)
123 b |= mouse_button::button1;
124 if (state & Qt::MidButton)
125 b |= mouse_button::button2;
126 if (state & Qt::RightButton)
127 b |= mouse_button::button3;
136 CursorWidget() : rtl_(false), l_shape_(false), completable_(false),
137 show_(false), x_(0), cursor_width_(0)
142 void draw(QPainter & painter)
144 if (!show_ || !rect_.isValid())
148 int l = x_ - rect_.left();
149 int r = rect_.right() - x_;
150 int bot = rect_.bottom();
152 // draw vertical line
153 painter.fillRect(x_, y, cursor_width_, rect_.height(), color_);
155 // draw RTL/LTR indication
156 painter.setPen(color_);
159 painter.drawLine(x_, bot, x_ - l, bot);
161 painter.drawLine(x_, bot, x_ + cursor_width_ + r, bot);
164 // draw completion triangle
166 int m = y + rect_.height() / 2;
167 int d = TabIndicatorWidth - 1;
169 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
170 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
172 painter.drawLine(x_ + cursor_width_, m - d, x_ + cursor_width_ + d, m);
173 painter.drawLine(x_ + cursor_width_, m + d, x_ + cursor_width_ + d, m);
178 void update(int x, int y, int h, bool l_shape,
179 bool rtl, bool completable)
181 color_ = guiApp->colorCache().get(Color_cursor);
184 completable_ = completable;
187 // extension to left and right
191 // RTL/LTR indication
199 // completion triangle
202 l = max(l, TabIndicatorWidth);
204 r = max(r, TabIndicatorWidth);
207 // compute overall rectangle
208 rect_ = QRect(x - l, y, cursor_width_ + r + l, h);
211 void show(bool set_show = true) { show_ = set_show; }
212 void hide() { show_ = false; }
213 int cursorWidth() const { return cursor_width_; }
214 void recomputeWidth() {
215 cursor_width_ = lyxrc.cursor_width
217 : 1 + int((lyxrc.zoom + 50) / 200.0);
220 QRect const & rect() { return rect_; }
223 /// cursor is in RTL or LTR text
225 /// indication for RTL or LTR
227 /// triangle to show that a completion is available
233 /// rectangle, possibly with l_shape and completion triangle
235 /// x position (were the vertical line is drawn)
242 // This is a 'heartbeat' generating synthetic mouse move events when the
243 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
244 SyntheticMouseEvent::SyntheticMouseEvent()
245 : timeout(200), restart_timeout(true)
249 GuiWorkArea::Private::Private(GuiWorkArea * parent)
250 : p(parent), screen_(0), buffer_view_(0), read_only_(false), lyx_view_(0),
251 cursor_visible_(false), cursor_(0),
252 need_resize_(false), schedule_redraw_(false), preedit_lines_(1),
254 completer_(new GuiCompleter(p, p)), dialog_mode_(false)
259 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
260 : d(new Private(this))
265 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
266 : d(new Private(this))
269 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
275 double GuiWorkArea::pixelRatio() const
277 #if QT_VERSION >= 0x050000
278 return devicePixelRatio();
285 void GuiWorkArea::init()
288 connect(&d->cursor_timeout_, SIGNAL(timeout()),
289 this, SLOT(toggleCursor()));
291 int const time = QApplication::cursorFlashTime() / 2;
293 d->cursor_timeout_.setInterval(time);
294 d->cursor_timeout_.start();
296 // let's initialize this just to be safe
297 d->cursor_timeout_.setInterval(500);
301 // With Qt4.5 a mouse event will happen before the first paint event
302 // so make sure that the buffer view has an up to date metrics.
303 d->buffer_view_->resize(viewport()->width(), viewport()->height());
304 d->cursor_ = new frontend::CursorWidget();
307 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
308 setAcceptDrops(true);
309 setMouseTracking(true);
310 setMinimumSize(100, 70);
311 setFrameStyle(QFrame::NoFrame);
314 viewport()->setAutoFillBackground(false);
315 // We don't need double-buffering nor SystemBackground on
316 // the viewport because we have our own backing pixmap.
317 viewport()->setAttribute(Qt::WA_NoSystemBackground);
319 setFocusPolicy(Qt::StrongFocus);
321 d->setCursorShape(Qt::IBeamCursor);
323 d->synthetic_mouse_event_.timeout.timeout.connect(
324 bind(&GuiWorkArea::generateSyntheticMouseEvent,
327 // Initialize the vertical Scroll Bar
328 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
329 this, SLOT(scrollTo(int)));
331 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
332 << " viewport height: " << viewport()->height());
334 // Enables input methods for asian languages.
335 // Must be set when creating custom text editing widgets.
336 setAttribute(Qt::WA_InputMethodEnabled, true);
338 d->dialog_mode_ = false;
342 GuiWorkArea::~GuiWorkArea()
344 d->buffer_view_->buffer().workAreaManager().remove(this);
346 delete d->buffer_view_;
348 // Completer has a QObject parent and is thus automatically destroyed.
350 // delete completer_;
355 Qt::CursorShape GuiWorkArea::cursorShape() const
357 return viewport()->cursor().shape();
361 void GuiWorkArea::Private::setCursorShape(Qt::CursorShape shape)
363 p->viewport()->setCursor(shape);
367 void GuiWorkArea::Private::updateCursorShape()
369 setCursorShape(buffer_view_->clickableInset()
370 ? Qt::PointingHandCursor : Qt::IBeamCursor);
374 void GuiWorkArea::setGuiView(GuiView & gv)
380 void GuiWorkArea::setBuffer(Buffer & buffer)
382 delete d->buffer_view_;
383 d->buffer_view_ = new BufferView(buffer);
384 buffer.workAreaManager().add(this);
386 // HACK: Prevents an additional redraw when the scrollbar pops up
387 // which regularily happens on documents with more than one page.
388 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
389 // Since we have no geometry information yet, we assume that
390 // a document needs a scrollbar if there is more then four
391 // paragraph in the outermost text.
392 if (buffer.text().paragraphs().size() > 4)
393 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
394 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
398 void GuiWorkArea::fixVerticalScrollBar()
401 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
405 void GuiWorkArea::close()
407 d->lyx_view_->removeWorkArea(this);
411 void GuiWorkArea::setFullScreen(bool full_screen)
413 d->buffer_view_->setFullScreen(full_screen);
414 setFrameStyle(QFrame::NoFrame);
416 setFrameStyle(QFrame::NoFrame);
417 if (lyxrc.full_screen_scrollbar)
418 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
420 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
424 BufferView & GuiWorkArea::bufferView()
426 return *d->buffer_view_;
430 BufferView const & GuiWorkArea::bufferView() const
432 return *d->buffer_view_;
436 void GuiWorkArea::stopBlinkingCursor()
438 d->cursor_timeout_.stop();
443 void GuiWorkArea::startBlinkingCursor()
445 // do not show the cursor if the view is busy
451 d->buffer_view_->cursorPosAndHeight(p, h);
452 // Don't start blinking if the cursor isn't on screen.
453 if (!d->buffer_view_->cursorInView(p, h))
458 //we're not supposed to cache this value.
459 int const time = QApplication::cursorFlashTime() / 2;
462 d->cursor_timeout_.setInterval(time);
463 d->cursor_timeout_.start();
467 void GuiWorkArea::redraw(bool update_metrics)
470 // No need to redraw in this case.
473 // No need to do anything if this is the current view. The BufferView
474 // metrics are already up to date.
475 if (update_metrics || d->lyx_view_ != guiApp->currentView()
476 || d->lyx_view_->currentWorkArea() != this) {
477 // FIXME: it would be nice to optimize for the off-screen case.
478 d->buffer_view_->cursor().fixIfBroken();
479 d->buffer_view_->updateMetrics();
480 d->buffer_view_->cursor().fixIfBroken();
483 // update cursor position, because otherwise it has to wait until
484 // the blinking interval is over
485 if (d->cursor_visible_) {
490 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
492 update(0, 0, viewport()->width(), viewport()->height());
494 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
495 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
496 d->updateScrollbar();
497 d->lyx_view_->updateStatusBar();
499 if (lyxerr.debugging(Debug::WORKAREA))
500 d->buffer_view_->coordCache().dump();
504 d->updateCursorShape();
508 // Keep in sync with GuiWorkArea::processKeySym below
509 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
511 return guiApp->queryKeySym(key, mod);
515 // Keep in sync with GuiWorkArea::queryKeySym above
516 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
518 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
519 && lyxrc.full_screen_menubar) {
520 // FIXME HACK: we should not have to do this here. See related comment
521 // in GuiView::event() (QEvent::ShortcutOverride)
522 d->lyx_view_->menuBar()->hide();
525 // In order to avoid bad surprise in the middle of an operation,
526 // we better stop the blinking cursor...
527 // the cursor gets restarted in GuiView::restartCursor()
528 stopBlinkingCursor();
529 guiApp->processKeySym(key, mod);
533 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
536 if (cmd.action() == LFUN_FILE_OPEN) {
538 lyx_view_->dispatch(cmd, dr);
542 bool const notJustMovingTheMouse =
543 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
545 // In order to avoid bad surprise in the middle of an operation, we better stop
546 // the blinking cursor.
547 if (notJustMovingTheMouse)
548 p->stopBlinkingCursor();
550 buffer_view_->mouseEventDispatch(cmd);
552 // Skip these when selecting
553 // FIXME: let GuiView take care of those.
554 if (cmd.action() != LFUN_MOUSE_MOTION) {
555 completer_->updateVisibility(false, false);
556 lyx_view_->updateDialogs();
557 lyx_view_->updateStatusBar();
560 // GUI tweaks except with mouse motion with no button pressed.
561 if (notJustMovingTheMouse) {
562 // Slight hack: this is only called currently when we
563 // clicked somewhere, so we force through the display
564 // of the new status here.
565 // FIXME: let GuiView take care of those.
566 lyx_view_->clearMessage();
568 // Show the cursor immediately after any operation
569 p->startBlinkingCursor();
576 void GuiWorkArea::Private::resizeBufferView()
578 // WARNING: Please don't put any code that will trigger a repaint here!
579 // We are already inside a paint event.
580 p->stopBlinkingCursor();
581 // Warn our container (GuiView).
586 buffer_view_->cursorPosAndHeight(point, h);
587 bool const cursor_in_view = buffer_view_->cursorInView(point, h);
588 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
590 buffer_view_->scrollToCursor();
593 // Update scrollbars which might have changed due different
594 // BufferView dimension. This is especially important when the
595 // BufferView goes from zero-size to the real-size for the first time,
596 // as the scrollbar paramters are then set for the first time.
599 need_resize_ = false;
601 // Eventually, restart the cursor after the resize event.
602 // We might be resizing even if the focus is on another widget so we only
603 // restart the cursor if we have the focus.
605 QTimer::singleShot(50, p, SLOT(startBlinkingCursor()));
609 void GuiWorkArea::Private::showCursor()
616 buffer_view_->cursorPosAndHeight(p, h);
617 if (!buffer_view_->cursorInView(p, h))
621 bool l_shape = false;
622 Font const & realfont = buffer_view_->cursor().real_current_font;
623 BufferParams const & bp = buffer_view_->buffer().params();
624 bool const samelang = realfont.language() == bp.language;
625 bool const isrtl = realfont.isVisibleRightToLeft();
627 if (!samelang || isrtl != bp.language->rightToLeft())
630 // The ERT language hack needs fixing up
631 if (realfont.language() == latex_language)
634 // show cursor on screen
635 Cursor & cur = buffer_view_->cursor();
636 bool completable = cur.inset().showCompletionCursor()
637 && completer_->completionAvailable()
638 && !completer_->popupVisible()
639 && !completer_->inlineVisible();
640 cursor_visible_ = true;
641 cursor_->recomputeWidth();
643 //int cur_x = buffer_view_->getPos(cur).x_;
644 // We may have decided to slide the cursor row so that cursor
646 p.x_ -= buffer_view_->horizScrollOffset();
648 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
652 void GuiWorkArea::Private::hideCursor()
654 if (!cursor_visible_)
657 cursor_visible_ = false;
662 void GuiWorkArea::toggleCursor()
664 if (d->cursor_visible_)
671 void GuiWorkArea::Private::updateScrollbar()
673 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
674 // Block signals to prevent setRange() and setSliderPosition from causing
675 // recursive calls via the signal valueChanged. (#10311)
676 QSignalBlocker blocker(p->verticalScrollBar());
677 p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
678 p->verticalScrollBar()->setPageStep(scroll_.page_step);
679 p->verticalScrollBar()->setSingleStep(scroll_.single_step);
680 p->verticalScrollBar()->setSliderPosition(0);
684 void GuiWorkArea::scrollTo(int value)
686 stopBlinkingCursor();
687 d->buffer_view_->scrollDocView(value, true);
689 if (lyxrc.cursor_follows_scrollbar) {
690 d->buffer_view_->setCursorFromScrollbar();
691 // FIXME: let GuiView take care of those.
692 d->lyx_view_->updateLayoutList();
694 // Show the cursor immediately after any operation.
695 startBlinkingCursor();
698 QApplication::syncX();
703 bool GuiWorkArea::event(QEvent * e)
706 case QEvent::ToolTip: {
707 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
708 if (lyxrc.use_tooltip) {
709 QPoint pos = helpEvent->pos();
710 if (pos.x() < viewport()->width()) {
711 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
712 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
715 QToolTip::hideText();
717 // Don't forget to accept the event!
722 case QEvent::ShortcutOverride:
723 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
725 keyPressEvent(static_cast<QKeyEvent *>(e));
726 return e->isAccepted();
728 case QEvent::KeyPress: {
729 // We catch this event in order to catch the Tab or Shift+Tab key press
730 // which are otherwise reserved to focus switching between controls
732 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
733 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
734 || (ke->key() == Qt::Key_Backtab && (
735 ke->modifiers() == Qt::ShiftModifier
736 || ke->modifiers() == Qt::NoModifier))) {
740 return QAbstractScrollArea::event(e);
744 return QAbstractScrollArea::event(e);
750 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
753 if (e->reason() == QContextMenuEvent::Mouse)
754 // the menu name is set on mouse press
755 name = d->context_menu_name_;
757 QPoint pos = e->pos();
758 Cursor const & cur = d->buffer_view_->cursor();
759 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
760 // Do not access the context menu of math right in front of before
761 // the cursor. This does not work when the cursor is in text.
762 Inset * inset = cur.paragraph().getInset(cur.pos());
763 if (inset && inset->asInsetMath())
765 else if (cur.pos() > 0) {
766 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
771 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
775 QAbstractScrollArea::contextMenuEvent(e);
778 // always show mnemonics when the keyboard is used to show the context menu
779 // FIXME: This should be fixed in Qt itself
780 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
781 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
783 QAbstractScrollArea::contextMenuEvent(e);
786 // Position the menu to the right.
787 // FIXME: menu position should be different for RTL text.
788 menu->exec(e->globalPos());
793 void GuiWorkArea::focusInEvent(QFocusEvent * e)
795 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
796 if (d->lyx_view_->currentWorkArea() != this) {
797 d->lyx_view_->setCurrentWorkArea(this);
798 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
801 startBlinkingCursor();
802 QAbstractScrollArea::focusInEvent(e);
806 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
808 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
809 stopBlinkingCursor();
810 QAbstractScrollArea::focusOutEvent(e);
814 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
816 if (d->dc_event_.active && d->dc_event_ == *e) {
817 d->dc_event_.active = false;
818 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
819 q_button_state(e->button()), q_key_state(e->modifiers()));
825 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
826 inputContext()->reset();
829 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
830 q_button_state(e->button()), q_key_state(e->modifiers()));
833 // Save the context menu on mouse press, because also the mouse
834 // cursor is set on mouse press. Afterwards, we can either release
835 // the mousebutton somewhere else, or the cursor might have moved
836 // due to the DEPM. We need to do this after the mouse has been
837 // set in dispatch(), because the selection state might change.
838 if (e->button() == Qt::RightButton)
839 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
845 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
847 if (d->synthetic_mouse_event_.timeout.running())
848 d->synthetic_mouse_event_.timeout.stop();
850 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
851 q_button_state(e->button()), q_key_state(e->modifiers()));
857 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
859 // we kill the triple click if we move
860 doubleClickTimeout();
861 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
862 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
866 // If we're above or below the work area...
867 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
868 && e->buttons() == mouse_button::button1) {
869 // Make sure only a synthetic event can cause a page scroll,
870 // so they come at a steady rate:
872 // _Force_ a scroll up:
873 cmd.set_y(e->y() - 21);
875 cmd.set_y(e->y() + 21);
876 // Store the event, to be handled when the timeout expires.
877 d->synthetic_mouse_event_.cmd = cmd;
879 if (d->synthetic_mouse_event_.timeout.running()) {
880 // Discard the event. Note that it _may_ be handled
881 // when the timeout expires if
882 // synthetic_mouse_event_.cmd has not been overwritten.
883 // Ie, when the timeout expires, we handle the
884 // most recent event but discard all others that
885 // occurred after the one used to start the timeout
886 // in the first place.
890 d->synthetic_mouse_event_.restart_timeout = true;
891 d->synthetic_mouse_event_.timeout.start();
892 // Fall through to handle this event...
894 } else if (d->synthetic_mouse_event_.timeout.running()) {
895 // Store the event, to be possibly handled when the timeout
897 // Once the timeout has expired, normal control is returned
898 // to mouseMoveEvent (restart_timeout = false).
899 // This results in a much smoother 'feel' when moving the
900 // mouse back into the work area.
901 d->synthetic_mouse_event_.cmd = cmd;
902 d->synthetic_mouse_event_.restart_timeout = false;
909 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
911 // Wheel rotation by one notch results in a delta() of 120 (see
912 // documentation of QWheelEvent)
913 double const delta = ev->delta() / 120.0;
915 switch (lyxrc.scroll_wheel_zoom) {
916 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
917 zoom = ev->modifiers() & Qt::ControlModifier;
918 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
920 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
921 zoom = ev->modifiers() & Qt::ShiftModifier;
922 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
924 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
925 zoom = ev->modifiers() & Qt::AltModifier;
926 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
928 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
932 docstring arg = convert<docstring>(int(5 * delta));
933 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
937 // Take into account the desktop wide settings.
938 int const lines = qApp->wheelScrollLines();
939 int const page_step = verticalScrollBar()->pageStep();
940 // Test if the wheel mouse is set to one screen at a time.
941 // This is according to
942 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
944 min(lines * verticalScrollBar()->singleStep(), page_step);
946 // Take into account the rotation and the user preferences.
947 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
948 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
949 << " delta = " << delta << " scroll_value = " << scroll_value
950 << " page_step = " << page_step);
952 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
958 void GuiWorkArea::generateSyntheticMouseEvent()
960 int const e_y = d->synthetic_mouse_event_.cmd.y();
961 int const wh = d->buffer_view_->workHeight();
962 bool const up = e_y < 0;
963 bool const down = e_y > wh;
965 // Set things off to generate the _next_ 'pseudo' event.
967 if (d->synthetic_mouse_event_.restart_timeout) {
968 // This is some magic formulae to determine the speed
969 // of scrolling related to the position of the mouse.
972 int dist = up ? -e_y : e_y - wh;
973 time = max(min(200, 250000 / (dist * dist)), 1) ;
976 step = 80000 / (time * time);
980 d->synthetic_mouse_event_.timeout.setTimeout(time);
981 d->synthetic_mouse_event_.timeout.start();
984 // Can we scroll further ?
985 int const value = verticalScrollBar()->value();
986 if (value == verticalScrollBar()->maximum()
987 || value == verticalScrollBar()->minimum()) {
988 d->synthetic_mouse_event_.timeout.stop();
993 if (step <= 2 * wh) {
994 d->buffer_view_->scroll(up ? -step : step);
995 d->buffer_view_->updateMetrics();
997 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
1000 // In which paragraph do we have to set the cursor ?
1001 Cursor & cur = d->buffer_view_->cursor();
1002 // FIXME: we don't know howto handle math.
1003 Text * text = cur.text();
1006 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
1008 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
1009 ParagraphMetrics const & pm = *pp.second;
1010 pit_type const pit = pp.first;
1012 if (pm.rows().empty())
1015 // Find the row at which we set the cursor.
1016 RowList::const_iterator rit = pm.rows().begin();
1017 RowList::const_iterator rlast = pm.rows().end();
1018 int yy = pm.position() - pm.ascent();
1019 for (--rlast; rit != rlast; ++rit) {
1020 int h = rit->height();
1021 if ((up && yy + h > 0)
1022 || (!up && yy + h > wh - defaultRowHeight()))
1027 // Find the position of the cursor
1029 int x = d->synthetic_mouse_event_.cmd.x();
1030 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1035 cur.boundary(bound);
1037 d->buffer_view_->buffer().changed(false);
1042 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1044 // this is also called for ShortcutOverride events. In this case, one must
1045 // not act but simply accept the event explicitly.
1046 bool const act = (ev->type() != QEvent::ShortcutOverride);
1048 // Do not process here some keys if dialog_mode_ is set
1050 && (ev->modifiers() == Qt::NoModifier
1051 || ev->modifiers() == Qt::ShiftModifier)
1052 && (ev->key() == Qt::Key_Escape
1053 || ev->key() == Qt::Key_Enter
1054 || ev->key() == Qt::Key_Return)
1060 // intercept some keys if completion popup is visible
1061 if (d->completer_->popupVisible()) {
1062 switch (ev->key()) {
1064 case Qt::Key_Return:
1066 d->completer_->activate();
1072 // do nothing if there are other events
1073 // (the auto repeated events come too fast)
1074 // it looks like this is only needed on X11
1075 #if defined(Q_WS_X11) || defined(QPA_XCB)
1076 // FIXME: this is a weird way to implement event compression. Also, this is
1077 // broken with IBus.
1078 if (act && qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1079 switch (ev->key()) {
1080 case Qt::Key_PageDown:
1081 case Qt::Key_PageUp:
1086 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1093 KeyModifier const m = q_key_state(ev->modifiers());
1096 if (m & ShiftModifier)
1098 if (m & ControlModifier)
1100 if (m & AltModifier)
1102 if (m & MetaModifier)
1106 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1107 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1108 << " keyState: " << str);
1111 setKeySymbol(&sym, ev);
1114 processKeySym(sym, m);
1117 ev->setAccepted(queryKeySym(sym, m));
1124 void GuiWorkArea::doubleClickTimeout()
1126 d->dc_event_.active = false;
1130 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1132 d->dc_event_ = DoubleClick(ev);
1133 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1134 SLOT(doubleClickTimeout()));
1135 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1136 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1142 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1144 QAbstractScrollArea::resizeEvent(ev);
1145 d->need_resize_ = true;
1150 void GuiWorkArea::Private::update(int x, int y, int w, int h)
1152 p->viewport()->update(x, y, w, h);
1156 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1158 QRectF const rc = ev->rect();
1159 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1160 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1162 if (d->needResize()) {
1164 d->resizeBufferView();
1165 if (d->cursor_visible_) {
1171 QPainter pain(viewport());
1172 double const pr = pixelRatio();
1173 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr, rc.width() * pr, rc.height() * pr);
1175 if (lyxrc.use_qimage) {
1176 QImage const & image = static_cast<QImage const &>(*d->screen_);
1177 pain.drawImage(rc, image, rcs);
1179 QPixmap const & pixmap = static_cast<QPixmap const &>(*d->screen_);
1180 pain.drawPixmap(rc, pixmap, rcs);
1182 d->cursor_->draw(pain);
1187 void GuiWorkArea::Private::updateScreen()
1189 GuiPainter pain(screen_, p->pixelRatio());
1190 buffer_view_->draw(pain);
1194 void GuiWorkArea::Private::showCursor(int x, int y, int h,
1195 bool l_shape, bool rtl, bool completable)
1197 if (schedule_redraw_) {
1198 // This happens when a graphic conversion is finished. As we don't know
1199 // the size of the new graphics, it's better the update everything.
1200 // We can't use redraw() here because this would trigger a infinite
1201 // recursive loop with showCursor().
1202 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
1205 p->viewport()->update(QRect(0, 0, p->viewport()->width(), p->viewport()->height()));
1206 schedule_redraw_ = false;
1207 // Show the cursor immediately after the update.
1213 cursor_->update(x, y, h, l_shape, rtl, completable);
1215 p->viewport()->update(cursor_->rect());
1219 void GuiWorkArea::Private::removeCursor()
1222 //if (!qApp->focusWidget())
1223 p->viewport()->update(cursor_->rect());
1227 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1229 QString const & commit_string = e->commitString();
1230 docstring const & preedit_string
1231 = qstring_to_ucs4(e->preeditString());
1233 if (!commit_string.isEmpty()) {
1235 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1236 << " commitString: " << e->commitString());
1240 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1241 for (int i = 0; i != commit_string.size(); ++i) {
1242 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1247 // Hide the cursor during the kana-kanji transformation.
1248 if (preedit_string.empty())
1249 startBlinkingCursor();
1251 stopBlinkingCursor();
1253 // last_width : for checking if last preedit string was/wasn't empty.
1254 // FIXME THREAD && FIXME
1255 // We could have more than one work area, right?
1256 static bool last_width = false;
1257 if (!last_width && preedit_string.empty()) {
1258 // if last_width is last length of preedit string.
1263 GuiPainter pain(d->screen_, pixelRatio());
1264 d->buffer_view_->updateMetrics();
1265 d->buffer_view_->draw(pain);
1266 FontInfo font = d->buffer_view_->cursor().getFont().fontInfo();
1267 FontMetrics const & fm = theFontMetrics(font);
1268 int height = fm.maxHeight();
1269 int cur_x = d->cursor_->rect().left();
1270 int cur_y = d->cursor_->rect().bottom();
1272 // redraw area of preedit string.
1273 update(0, cur_y - height, viewport()->width(),
1274 (height + 1) * d->preedit_lines_);
1276 if (preedit_string.empty()) {
1278 d->preedit_lines_ = 1;
1284 // att : stores an IM attribute.
1285 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1287 // get attributes of input method cursor.
1288 // cursor_pos : cursor position in preedit string.
1289 size_t cursor_pos = 0;
1290 bool cursor_is_visible = false;
1291 for (int i = 0; i != att.size(); ++i) {
1292 if (att.at(i).type == QInputMethodEvent::Cursor) {
1293 cursor_pos = att.at(i).start;
1294 cursor_is_visible = att.at(i).length != 0;
1299 size_t preedit_length = preedit_string.length();
1301 // get position of selection in input method.
1302 // FIXME: isn't there a way to do this simplier?
1303 // rStart : cursor position in selected string in IM.
1305 // rLength : selected string length in IM.
1307 if (cursor_pos < preedit_length) {
1308 for (int i = 0; i != att.size(); ++i) {
1309 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1310 if (att.at(i).start <= int(cursor_pos)
1311 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1312 rStart = att.at(i).start;
1313 rLength = att.at(i).length;
1314 if (!cursor_is_visible)
1315 cursor_pos += rLength;
1322 rStart = cursor_pos;
1326 int const right_margin = d->buffer_view_->rightMargin();
1327 Painter::preedit_style ps;
1328 // Most often there would be only one line:
1329 d->preedit_lines_ = 1;
1330 for (size_t pos = 0; pos != preedit_length; ++pos) {
1331 char_type const typed_char = preedit_string[pos];
1332 // reset preedit string style
1333 ps = Painter::preedit_default;
1335 // if we reached the right extremity of the screen, go to next line.
1336 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1337 cur_x = right_margin;
1338 cur_y += height + 1;
1339 ++d->preedit_lines_;
1341 // preedit strings are displayed with dashed underline
1342 // and partial strings are displayed white on black indicating
1343 // that we are in selecting mode in the input method.
1344 // FIXME: rLength == preedit_length is not a changing condition
1345 // FIXME: should be put out of the loop.
1347 && pos < rStart + rLength
1348 && !(cursor_pos < rLength && rLength == preedit_length))
1349 ps = Painter::preedit_selecting;
1351 if (pos == cursor_pos
1352 && (cursor_pos < rLength && rLength == preedit_length))
1353 ps = Painter::preedit_cursor;
1355 // draw one character and update cur_x.
1356 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1359 // update the preedit string screen area.
1360 update(0, cur_y - d->preedit_lines_*height, viewport()->width(),
1361 (height + 1) * d->preedit_lines_);
1363 // Don't forget to accept the event!
1368 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1370 QRect cur_r(0, 0, 0, 0);
1372 // this is the CJK-specific composition window position and
1373 // the context menu position when the menu key is pressed.
1374 case Qt::ImMicroFocus:
1375 cur_r = d->cursor_->rect();
1376 if (d->preedit_lines_ != 1)
1378 cur_r.moveBottom(cur_r.bottom()
1379 + cur_r.height() * (d->preedit_lines_ - 1));
1380 // return lower right of cursor in LyX.
1383 return QWidget::inputMethodQuery(query);
1388 void GuiWorkArea::updateWindowTitle()
1390 d->lyx_view_->updateWindowTitle(this);
1395 bool GuiWorkArea::isFullScreen() const
1397 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1401 void GuiWorkArea::scheduleRedraw()
1403 d->schedule_redraw_ = true;
1407 bool GuiWorkArea::inDialogMode() const
1409 return d->dialog_mode_;
1413 void GuiWorkArea::setDialogMode(bool mode)
1415 d->dialog_mode_ = mode;
1419 GuiCompleter & GuiWorkArea::completer()
1421 return *d->completer_;
1424 GuiView const & GuiWorkArea::view() const
1426 return *d->lyx_view_;
1430 GuiView & GuiWorkArea::view()
1432 return *d->lyx_view_;
1435 ////////////////////////////////////////////////////////////////////
1439 ////////////////////////////////////////////////////////////////////
1442 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1444 support::TempFile tempfile("embedded.internal");
1445 tempfile.setAutoRemove(false);
1446 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1447 buffer_->setUnnamed(true);
1448 buffer_->setFullyLoaded(true);
1449 setBuffer(*buffer_);
1450 setDialogMode(true);
1454 EmbeddedWorkArea::~EmbeddedWorkArea()
1456 // No need to destroy buffer and bufferview here, because it is done
1457 // in theBufferList() destruction loop at application exit
1461 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1464 GuiWorkArea::closeEvent(ev);
1468 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1471 GuiWorkArea::hideEvent(ev);
1475 QSize EmbeddedWorkArea::sizeHint () const
1478 // GuiWorkArea sets the size to the screen's viewport
1479 // by returning a value this gets overridden
1480 // EmbeddedWorkArea is now sized to fit in the layout
1481 // of the parent, and has a minimum size set in GuiWorkArea
1482 // which is what we return here
1483 return QSize(100, 70);
1487 void EmbeddedWorkArea::disable()
1489 stopBlinkingCursor();
1490 if (view().currentWorkArea() != this)
1492 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1493 // tolerates it and shows the background logo), what happens if
1494 // an EmbeddedWorkArea is closed after closing all document WAs
1495 view().setCurrentWorkArea(view().currentMainWorkArea());
1498 ////////////////////////////////////////////////////////////////////
1502 ////////////////////////////////////////////////////////////////////
1505 class NoTabFrameMacStyle : public QProxyStyle {
1508 QRect subElementRect(SubElement element, const QStyleOption * option,
1509 const QWidget * widget = 0) const
1511 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1512 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1514 // The Qt Mac style puts the contents into a 3 pixel wide box
1515 // which looks very ugly and not like other Mac applications.
1516 // Hence we remove this here, and moreover the 16 pixel round
1517 // frame above if the tab bar is hidden.
1518 if (element == QStyle::SE_TabWidgetTabContents) {
1519 rect.adjust(- rect.left(), 0, rect.left(), 0);
1528 NoTabFrameMacStyle noTabFrameMacStyle;
1532 TabWorkArea::TabWorkArea(QWidget * parent)
1533 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1536 setStyle(&noTabFrameMacStyle);
1539 QPalette pal = palette();
1540 pal.setColor(QPalette::Active, QPalette::Button,
1541 pal.color(QPalette::Active, QPalette::Window));
1542 pal.setColor(QPalette::Disabled, QPalette::Button,
1543 pal.color(QPalette::Disabled, QPalette::Window));
1544 pal.setColor(QPalette::Inactive, QPalette::Button,
1545 pal.color(QPalette::Inactive, QPalette::Window));
1547 QObject::connect(this, SIGNAL(currentChanged(int)),
1548 this, SLOT(on_currentTabChanged(int)));
1550 closeBufferButton = new QToolButton(this);
1551 closeBufferButton->setPalette(pal);
1552 // FIXME: rename the icon to closebuffer.png
1553 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1554 closeBufferButton->setText("Close File");
1555 closeBufferButton->setAutoRaise(true);
1556 closeBufferButton->setCursor(Qt::ArrowCursor);
1557 closeBufferButton->setToolTip(qt_("Close File"));
1558 closeBufferButton->setEnabled(true);
1559 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1560 this, SLOT(closeCurrentBuffer()));
1561 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1563 // setup drag'n'drop
1564 QTabBar* tb = new DragTabBar;
1565 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1566 this, SLOT(moveTab(int, int)));
1567 tb->setElideMode(Qt::ElideNone);
1570 // make us responsible for the context menu of the tabbar
1571 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1572 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1573 this, SLOT(showContextMenu(const QPoint &)));
1574 connect(tb, SIGNAL(tabCloseRequested(int)),
1575 this, SLOT(closeTab(int)));
1577 setUsesScrollButtons(true);
1581 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1583 if (me->button() == Qt::MidButton)
1584 midpressed_tab_ = tabBar()->tabAt(me->pos());
1586 QTabWidget::mousePressEvent(me);
1590 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1592 if (me->button() == Qt::MidButton) {
1593 int const midreleased_tab = tabBar()->tabAt(me->pos());
1594 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1595 closeTab(midreleased_tab);
1597 QTabWidget::mouseReleaseEvent(me);
1601 void TabWorkArea::paintEvent(QPaintEvent * event)
1603 if (tabBar()->isVisible()) {
1604 QTabWidget::paintEvent(event);
1606 // Prevent the selected tab to influence the
1607 // painting of the frame of the tab widget.
1608 // This is needed for gtk style in Qt.
1609 QStylePainter p(this);
1610 #if QT_VERSION < 0x050000
1611 QStyleOptionTabWidgetFrameV2 opt;
1613 QStyleOptionTabWidgetFrame opt;
1615 initStyleOption(&opt);
1616 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1618 opt.selectedTabRect = QRect();
1619 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1624 bool TabWorkArea::posIsTab(QPoint position)
1626 // tabAt returns -1 if tab does not covers position
1627 return tabBar()->tabAt(position) > -1;
1631 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1633 if (event->button() != Qt::LeftButton)
1636 // this code chunk is unnecessary because it seems the event only makes
1637 // it this far if it is not on a tab. I'm not sure why this is (maybe
1638 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1639 // this is true in all cases and if it will be true in the future so I
1640 // leave this code for now. (skostysh, 2016-07-21)
1642 // return early if double click on existing tabs
1643 if (posIsTab(event->pos()))
1646 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1650 void TabWorkArea::setFullScreen(bool full_screen)
1652 for (int i = 0; i != count(); ++i) {
1653 if (GuiWorkArea * wa = workArea(i))
1654 wa->setFullScreen(full_screen);
1657 if (lyxrc.full_screen_tabbar)
1658 showBar(!full_screen && count() > 1);
1660 showBar(count() > 1);
1664 void TabWorkArea::showBar(bool show)
1666 tabBar()->setEnabled(show);
1667 tabBar()->setVisible(show);
1668 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1669 setTabsClosable(!lyxrc.single_close_tab_button);
1673 GuiWorkArea * TabWorkArea::currentWorkArea()
1678 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1684 GuiWorkArea * TabWorkArea::workArea(int index)
1686 return dynamic_cast<GuiWorkArea *>(widget(index));
1690 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1692 // FIXME: this method doesn't work if we have more than work area
1693 // showing the same buffer.
1694 for (int i = 0; i != count(); ++i) {
1695 GuiWorkArea * wa = workArea(i);
1696 LASSERT(wa, return 0);
1697 if (&wa->bufferView().buffer() == &buffer)
1704 void TabWorkArea::closeAll()
1707 GuiWorkArea * wa = workArea(0);
1708 LASSERT(wa, return);
1715 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1717 LASSERT(work_area, return false);
1718 int index = indexOf(work_area);
1722 if (index == currentIndex())
1723 // Make sure the work area is up to date.
1724 on_currentTabChanged(index);
1726 // Switch to the work area.
1727 setCurrentIndex(index);
1728 work_area->setFocus();
1734 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1736 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1737 wa->setUpdatesEnabled(false);
1738 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1739 // when hiding it again below).
1740 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1741 showBar(count() > 0);
1742 addTab(wa, wa->windowTitle());
1743 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1744 this, SLOT(updateTabTexts()));
1745 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1746 setFullScreen(true);
1748 // Hide tabbar if there's only one tab.
1749 showBar(count() > 1);
1757 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1759 LASSERT(work_area, return false);
1760 int index = indexOf(work_area);
1764 work_area->setUpdatesEnabled(false);
1769 // make sure the next work area is enabled.
1770 currentWidget()->setUpdatesEnabled(true);
1771 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1772 setFullScreen(true);
1774 // Show tabbar only if there's more than one tab.
1775 showBar(count() > 1);
1777 lastWorkAreaRemoved();
1785 void TabWorkArea::on_currentTabChanged(int i)
1787 // returns e.g. on application destruction
1790 GuiWorkArea * wa = workArea(i);
1791 LASSERT(wa, return);
1792 wa->setUpdatesEnabled(true);
1796 currentWorkAreaChanged(wa);
1798 LYXERR(Debug::GUI, "currentTabChanged " << i
1799 << " File: " << wa->bufferView().buffer().absFileName());
1803 void TabWorkArea::closeCurrentBuffer()
1806 if (clicked_tab_ == -1)
1807 wa = currentWorkArea();
1809 wa = workArea(clicked_tab_);
1810 LASSERT(wa, return);
1812 wa->view().closeWorkArea(wa);
1816 void TabWorkArea::hideCurrentTab()
1819 if (clicked_tab_ == -1)
1820 wa = currentWorkArea();
1822 wa = workArea(clicked_tab_);
1823 LASSERT(wa, return);
1825 wa->view().hideWorkArea(wa);
1829 void TabWorkArea::closeTab(int index)
1831 on_currentTabChanged(index);
1834 wa = currentWorkArea();
1836 wa = workArea(index);
1837 LASSERT(wa, return);
1839 wa->view().closeWorkArea(wa);
1846 /// make vector happy
1847 // coverity[UNINIT_CTOR]
1850 DisplayPath(int tab, FileName const & filename)
1853 filename_ = (filename.extension() == "lyx") ?
1854 toqstr(filename.onlyFileNameWithoutExt())
1855 : toqstr(filename.onlyFileName());
1856 postfix_ = toqstr(filename.absoluteFilePath()).
1857 split("/", QString::SkipEmptyParts);
1858 postfix_.pop_back();
1859 abs_ = toqstr(filename.absoluteFilePath());
1860 dottedPrefix_ = false;
1863 /// Absolute path for debugging.
1868 /// Add the first segment from the postfix or three dots to the prefix.
1869 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1870 /// when really needed.
1871 void shiftPathSegment(bool dotted)
1873 if (postfix_.count() <= 0)
1877 if (dottedPrefix_ && !prefix_.isEmpty())
1878 prefix_ += ellipsisSlash_;
1879 prefix_ += postfix_.front() + "/";
1881 dottedPrefix_ = dotted && !prefix_.isEmpty();
1882 postfix_.pop_front();
1885 QString displayString() const
1887 if (prefix_.isEmpty())
1890 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1891 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1894 QString forecastPathString() const
1896 if (postfix_.count() == 0)
1897 return displayString();
1900 + (dottedPrefix_ ? ellipsisSlash_ : "")
1901 + postfix_.front() + "/";
1904 bool final() const { return postfix_.empty(); }
1906 int tab() const { return tab_; }
1910 static QString const ellipsisSlash_;
1914 QStringList postfix_;
1926 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1930 bool operator<(DisplayPath const & a, DisplayPath const & b)
1932 return a.displayString() < b.displayString();
1936 bool operator==(DisplayPath const & a, DisplayPath const & b)
1938 return a.displayString() == b.displayString();
1942 void TabWorkArea::updateTabTexts()
1947 std::list<DisplayPath> paths;
1948 typedef std::list<DisplayPath>::iterator It;
1950 // collect full names first: path into postfix, empty prefix and
1951 // filename without extension
1952 for (size_t i = 0; i < n; ++i) {
1953 GuiWorkArea * i_wa = workArea(i);
1954 FileName const fn = i_wa->bufferView().buffer().fileName();
1955 paths.push_back(DisplayPath(i, fn));
1958 // go through path segments and see if it helps to make the path more unique
1959 bool somethingChanged = true;
1960 bool allFinal = false;
1961 while (somethingChanged && !allFinal) {
1962 // adding path segments changes order
1965 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1966 somethingChanged = false;
1969 // find segments which are not unique (i.e. non-atomic)
1970 It it = paths.begin();
1972 QString segString = it->displayString();
1973 for (; it != paths.end(); ++it) {
1974 // look to the next item
1979 allFinal = allFinal && it->final();
1981 LYXERR(Debug::GUI, "it = " << it->abs()
1982 << " => " << it->displayString());
1984 // still the same segment?
1986 if ((next != paths.end()
1987 && (nextString = next->displayString()) == segString))
1989 LYXERR(Debug::GUI, "segment ended");
1991 // only a trivial one with one element?
1992 if (it == segStart) {
1993 // start new segment
1995 segString = nextString;
1999 // we found a non-atomic segment segStart <= sit <= it < next.
2000 // Shift path segments and hope for the best
2001 // that it makes the path more unique.
2002 somethingChanged = true;
2004 // this is ok for the reason mentioned in the previous comment.
2005 // coverity[INVALIDATE_ITERATOR]
2006 QString dspString = sit->forecastPathString();
2007 LYXERR(Debug::GUI, "first forecast found for "
2008 << sit->abs() << " => " << dspString);
2010 bool moreUnique = false;
2011 for (; sit != next; ++sit) {
2012 if (sit->forecastPathString() != dspString) {
2013 LYXERR(Debug::GUI, "different forecast found for "
2014 << sit->abs() << " => " << sit->forecastPathString());
2018 LYXERR(Debug::GUI, "same forecast found for "
2019 << sit->abs() << " => " << dspString);
2022 // if the path segment helped, add it. Otherwise add dots
2023 bool dots = !moreUnique;
2024 LYXERR(Debug::GUI, "using dots = " << dots);
2025 for (sit = segStart; sit != next; ++sit) {
2026 sit->shiftPathSegment(dots);
2027 LYXERR(Debug::GUI, "shifting "
2028 << sit->abs() << " => " << sit->displayString());
2031 // start new segment
2033 segString = nextString;
2037 // set new tab titles
2038 for (It it = paths.begin(); it != paths.end(); ++it) {
2039 int const tab_index = it->tab();
2040 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2041 QString tab_text = it->displayString().replace("&", "&&");
2042 if (!buf.fileName().empty() && !buf.isClean())
2044 QString tab_tooltip = it->abs();
2045 if (buf.isReadonly()) {
2046 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2047 tab_tooltip = qt_("%1 (read only)").arg(it->abs());
2049 setTabIcon(tab_index, QIcon());
2050 setTabText(tab_index, tab_text);
2051 setTabToolTip(tab_index, tab_tooltip);
2056 void TabWorkArea::showContextMenu(const QPoint & pos)
2059 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
2060 if (clicked_tab_ == -1)
2065 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2066 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2067 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2068 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2069 popup.exec(tabBar()->mapToGlobal(pos));
2075 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2077 QWidget * w = widget(fromIndex);
2078 QIcon icon = tabIcon(fromIndex);
2079 QString text = tabText(fromIndex);
2081 setCurrentIndex(fromIndex);
2082 removeTab(fromIndex);
2083 insertTab(toIndex, w, icon, text);
2084 setCurrentIndex(toIndex);
2088 DragTabBar::DragTabBar(QWidget* parent)
2091 setAcceptDrops(true);
2092 setTabsClosable(!lyxrc.single_close_tab_button);
2096 void DragTabBar::mousePressEvent(QMouseEvent * event)
2098 if (event->button() == Qt::LeftButton)
2099 dragStartPos_ = event->pos();
2100 QTabBar::mousePressEvent(event);
2104 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2106 // If the left button isn't pressed anymore then return
2107 if (!(event->buttons() & Qt::LeftButton))
2110 // If the distance is too small then return
2111 if ((event->pos() - dragStartPos_).manhattanLength()
2112 < QApplication::startDragDistance())
2115 // did we hit something after all?
2116 int tab = tabAt(dragStartPos_);
2120 // simulate button release to remove highlight from button
2121 int i = currentIndex();
2122 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2123 event->button(), event->buttons(), 0);
2124 QTabBar::mouseReleaseEvent(&me);
2128 QDrag * drag = new QDrag(this);
2129 QMimeData * mimeData = new QMimeData;
2130 // a crude way to distinguish tab-reodering drops from other ones
2131 mimeData->setData("action", "tab-reordering") ;
2132 drag->setMimeData(mimeData);
2134 // get tab pixmap as cursor
2135 QRect r = tabRect(tab);
2136 QPixmap pixmap(r.size());
2137 render(&pixmap, - r.topLeft());
2138 drag->setPixmap(pixmap);
2143 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2145 // Only accept if it's an tab-reordering request
2146 QMimeData const * m = event->mimeData();
2147 QStringList formats = m->formats();
2148 if (formats.contains("action")
2149 && m->data("action") == "tab-reordering")
2150 event->acceptProposedAction();
2154 void DragTabBar::dropEvent(QDropEvent * event)
2156 int fromIndex = tabAt(dragStartPos_);
2157 int toIndex = tabAt(event->pos());
2159 // Tell interested objects that
2160 if (fromIndex != toIndex)
2161 tabMoveRequested(fromIndex, toIndex);
2162 event->acceptProposedAction();
2166 } // namespace frontend
2169 #include "moc_GuiWorkArea.cpp"