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/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>
71 #include <QPixmapCache>
73 #include <QStyleOption>
74 #include <QStylePainter>
76 #include <QToolButton>
80 #include "support/bind.h"
85 int const TabIndicatorWidth = 3;
91 using namespace lyx::support;
96 /// return the LyX mouse button state from Qt's
97 static mouse_button::state q_button_state(Qt::MouseButton button)
99 mouse_button::state b = mouse_button::none;
102 b = mouse_button::button1;
105 b = mouse_button::button2;
107 case Qt::RightButton:
108 b = mouse_button::button3;
117 /// return the LyX mouse button state from Qt's
118 mouse_button::state q_motion_state(Qt::MouseButtons state)
120 mouse_button::state b = mouse_button::none;
121 if (state & Qt::LeftButton)
122 b |= mouse_button::button1;
123 if (state & Qt::MidButton)
124 b |= mouse_button::button2;
125 if (state & Qt::RightButton)
126 b |= mouse_button::button3;
135 CursorWidget() : rtl_(false), l_shape_(false), completable_(false),
136 show_(false), x_(0), cursor_width_(0)
141 void draw(QPainter & painter)
143 if (!show_ || !rect_.isValid())
147 int l = x_ - rect_.left();
148 int r = rect_.right() - x_;
149 int bot = rect_.bottom();
151 // draw vertical line
152 painter.fillRect(x_, y, cursor_width_, rect_.height(), color_);
154 // draw RTL/LTR indication
155 painter.setPen(color_);
158 painter.drawLine(x_, bot, x_ - l, bot);
160 painter.drawLine(x_, bot, x_ + cursor_width_ + r, bot);
163 // draw completion triangle
165 int m = y + rect_.height() / 2;
166 int d = TabIndicatorWidth - 1;
168 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
169 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
171 painter.drawLine(x_ + cursor_width_, m - d, x_ + cursor_width_ + d, m);
172 painter.drawLine(x_ + cursor_width_, m + d, x_ + cursor_width_ + d, m);
177 void update(int x, int y, int h, bool l_shape,
178 bool rtl, bool completable)
180 color_ = guiApp->colorCache().get(Color_cursor);
183 completable_ = completable;
186 // extension to left and right
190 // RTL/LTR indication
198 // completion triangle
201 l = max(l, TabIndicatorWidth);
203 r = max(r, TabIndicatorWidth);
206 // compute overall rectangle
207 rect_ = QRect(x - l, y, cursor_width_ + r + l, h);
210 void show(bool set_show = true) { show_ = set_show; }
211 void hide() { show_ = false; }
212 int cursorWidth() const { return cursor_width_; }
213 void recomputeWidth() {
214 cursor_width_ = lyxrc.cursor_width
216 : 1 + int((lyxrc.currentZoom + 50) / 200.0);
219 QRect const & rect() { return rect_; }
222 /// cursor is in RTL or LTR text
224 /// indication for RTL or LTR
226 /// triangle to show that a completion is available
232 /// rectangle, possibly with l_shape and completion triangle
234 /// x position (were the vertical line is drawn)
241 // This is a 'heartbeat' generating synthetic mouse move events when the
242 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
243 SyntheticMouseEvent::SyntheticMouseEvent()
244 : timeout(200), restart_timeout(true)
248 GuiWorkArea::Private::Private(GuiWorkArea * parent)
249 : p(parent), screen_(0), buffer_view_(0), lyx_view_(0),
250 cursor_visible_(false), cursor_(0),
251 need_resize_(false), schedule_redraw_(false), preedit_lines_(1),
253 completer_(new GuiCompleter(p, p)), dialog_mode_(false), shell_escape_(false),
254 read_only_(false), clean_(true), externally_modified_(false)
259 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
260 : d(new Private(this))
262 new CompressorProxy(this); // not a leak
266 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
267 : d(new Private(this))
269 new CompressorProxy(this); // not a leak
271 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
277 double GuiWorkArea::pixelRatio() const
279 #if QT_VERSION >= 0x050000
280 return qt_scale_factor * devicePixelRatio();
287 void GuiWorkArea::init()
290 connect(&d->cursor_timeout_, SIGNAL(timeout()),
291 this, SLOT(toggleCursor()));
293 int const time = QApplication::cursorFlashTime() / 2;
295 d->cursor_timeout_.setInterval(time);
296 d->cursor_timeout_.start();
298 // let's initialize this just to be safe
299 d->cursor_timeout_.setInterval(500);
303 // With Qt4.5 a mouse event will happen before the first paint event
304 // so make sure that the buffer view has an up to date metrics.
305 d->buffer_view_->resize(viewport()->width(), viewport()->height());
306 d->cursor_ = new frontend::CursorWidget();
309 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
310 setAcceptDrops(true);
311 setMouseTracking(true);
312 setMinimumSize(100, 70);
313 setFrameStyle(QFrame::NoFrame);
316 viewport()->setAutoFillBackground(false);
317 // We don't need double-buffering nor SystemBackground on
318 // the viewport because we have our own backing pixmap.
319 viewport()->setAttribute(Qt::WA_NoSystemBackground);
321 setFocusPolicy(Qt::StrongFocus);
323 d->setCursorShape(Qt::IBeamCursor);
325 // This connection is closed at the same time as this is destroyed.
326 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
327 generateSyntheticMouseEvent();
330 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
331 << " viewport height: " << viewport()->height());
333 // Enables input methods for asian languages.
334 // Must be set when creating custom text editing widgets.
335 setAttribute(Qt::WA_InputMethodEnabled, true);
337 d->dialog_mode_ = false;
341 GuiWorkArea::~GuiWorkArea()
343 // If something is wrong with the buffer, we can ignore it safely
345 d->buffer_view_->buffer().workAreaManager().remove(this);
348 delete d->buffer_view_;
350 // Completer has a QObject parent and is thus automatically destroyed.
352 // delete completer_;
357 Qt::CursorShape GuiWorkArea::cursorShape() const
359 return viewport()->cursor().shape();
363 void GuiWorkArea::Private::setCursorShape(Qt::CursorShape shape)
365 p->viewport()->setCursor(shape);
369 void GuiWorkArea::Private::updateCursorShape()
371 setCursorShape(buffer_view_->clickableInset()
372 ? Qt::PointingHandCursor : Qt::IBeamCursor);
376 void GuiWorkArea::setGuiView(GuiView & gv)
382 void GuiWorkArea::setBuffer(Buffer & buffer)
384 delete d->buffer_view_;
385 d->buffer_view_ = new BufferView(buffer);
386 buffer.workAreaManager().add(this);
388 // HACK: Prevents an additional redraw when the scrollbar pops up
389 // which regularily happens on documents with more than one page.
390 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
391 // Since we have no geometry information yet, we assume that
392 // a document needs a scrollbar if there is more then four
393 // paragraph in the outermost text.
394 if (buffer.text().paragraphs().size() > 4)
395 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
396 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
397 Q_EMIT bufferViewChanged();
401 void GuiWorkArea::fixVerticalScrollBar()
404 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
408 void GuiWorkArea::close()
410 d->lyx_view_->removeWorkArea(this);
414 void GuiWorkArea::setFullScreen(bool full_screen)
416 d->buffer_view_->setFullScreen(full_screen);
417 setFrameStyle(QFrame::NoFrame);
419 setFrameStyle(QFrame::NoFrame);
420 if (lyxrc.full_screen_scrollbar)
421 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
423 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
427 BufferView & GuiWorkArea::bufferView()
429 return *d->buffer_view_;
433 BufferView const & GuiWorkArea::bufferView() const
435 return *d->buffer_view_;
439 void GuiWorkArea::stopBlinkingCursor()
441 d->cursor_timeout_.stop();
446 void GuiWorkArea::startBlinkingCursor()
448 // do not show the cursor if the view is busy
454 d->buffer_view_->cursorPosAndHeight(p, h);
455 // Don't start blinking if the cursor isn't on screen.
456 if (!d->buffer_view_->cursorInView(p, h))
461 //we're not supposed to cache this value.
462 int const time = QApplication::cursorFlashTime() / 2;
465 d->cursor_timeout_.setInterval(time);
466 d->cursor_timeout_.start();
470 void GuiWorkArea::redraw(bool update_metrics)
473 // No need to redraw in this case.
476 // No need to do anything if this is the current view. The BufferView
477 // metrics are already up to date.
478 if (update_metrics || d->lyx_view_ != guiApp->currentView()
479 || d->lyx_view_->currentWorkArea() != this) {
480 // FIXME: it would be nice to optimize for the off-screen case.
481 d->buffer_view_->cursor().fixIfBroken();
482 d->buffer_view_->updateMetrics();
483 d->buffer_view_->cursor().fixIfBroken();
486 // update cursor position, because otherwise it has to wait until
487 // the blinking interval is over
488 if (d->cursor_visible_) {
493 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
495 update(0, 0, viewport()->width(), viewport()->height());
497 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
498 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
499 d->updateScrollbar();
500 d->lyx_view_->updateStatusBar();
502 if (lyxerr.debugging(Debug::WORKAREA))
503 d->buffer_view_->coordCache().dump();
507 d->updateCursorShape();
511 // Keep in sync with GuiWorkArea::processKeySym below
512 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
514 return guiApp->queryKeySym(key, mod);
518 // Keep in sync with GuiWorkArea::queryKeySym above
519 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
521 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
522 && lyxrc.full_screen_menubar) {
523 // FIXME HACK: we should not have to do this here. See related comment
524 // in GuiView::event() (QEvent::ShortcutOverride)
525 d->lyx_view_->menuBar()->hide();
528 // In order to avoid bad surprise in the middle of an operation,
529 // we better stop the blinking cursor...
530 // the cursor gets restarted in GuiView::restartCursor()
531 stopBlinkingCursor();
532 guiApp->processKeySym(key, mod);
536 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
539 if (cmd.action() == LFUN_FILE_OPEN) {
541 lyx_view_->dispatch(cmd, dr);
545 bool const notJustMovingTheMouse =
546 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
548 // In order to avoid bad surprise in the middle of an operation, we better stop
549 // the blinking cursor.
550 if (notJustMovingTheMouse)
551 p->stopBlinkingCursor();
553 buffer_view_->mouseEventDispatch(cmd);
555 // Skip these when selecting
556 // FIXME: let GuiView take care of those.
557 if (cmd.action() != LFUN_MOUSE_MOTION) {
558 completer_->updateVisibility(false, false);
559 lyx_view_->updateDialogs();
560 lyx_view_->updateStatusBar();
563 // GUI tweaks except with mouse motion with no button pressed.
564 if (notJustMovingTheMouse) {
565 // Slight hack: this is only called currently when we
566 // clicked somewhere, so we force through the display
567 // of the new status here.
568 // FIXME: let GuiView take care of those.
569 lyx_view_->clearMessage();
571 // Show the cursor immediately after any operation
572 p->startBlinkingCursor();
579 void GuiWorkArea::Private::resizeBufferView()
581 // WARNING: Please don't put any code that will trigger a repaint here!
582 // We are already inside a paint event.
583 p->stopBlinkingCursor();
584 // Warn our container (GuiView).
589 buffer_view_->cursorPosAndHeight(point, h);
590 bool const cursor_in_view = buffer_view_->cursorInView(point, h);
591 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
593 buffer_view_->scrollToCursor();
596 // Update scrollbars which might have changed due different
597 // BufferView dimension. This is especially important when the
598 // BufferView goes from zero-size to the real-size for the first time,
599 // as the scrollbar paramters are then set for the first time.
602 need_resize_ = false;
604 // Eventually, restart the cursor after the resize event.
605 // We might be resizing even if the focus is on another widget so we only
606 // restart the cursor if we have the focus.
608 QTimer::singleShot(50, p, SLOT(startBlinkingCursor()));
612 void GuiWorkArea::Private::showCursor()
619 buffer_view_->cursorPosAndHeight(p, h);
620 if (!buffer_view_->cursorInView(p, h))
624 bool l_shape = false;
625 Font const & realfont = buffer_view_->cursor().real_current_font;
626 BufferParams const & bp = buffer_view_->buffer().params();
627 bool const samelang = realfont.language() == bp.language;
628 bool const isrtl = realfont.isVisibleRightToLeft();
630 if (!samelang || isrtl != bp.language->rightToLeft())
633 // The ERT language hack needs fixing up
634 if (realfont.language() == latex_language)
637 // show cursor on screen
638 Cursor & cur = buffer_view_->cursor();
639 bool completable = cur.inset().showCompletionCursor()
640 && completer_->completionAvailable()
641 && !completer_->popupVisible()
642 && !completer_->inlineVisible();
643 cursor_visible_ = true;
644 cursor_->recomputeWidth();
646 //int cur_x = buffer_view_->getPos(cur).x_;
647 // We may have decided to slide the cursor row so that cursor
649 p.x_ -= buffer_view_->horizScrollOffset();
651 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
655 void GuiWorkArea::Private::hideCursor()
657 if (!cursor_visible_)
660 cursor_visible_ = false;
665 void GuiWorkArea::toggleCursor()
667 if (d->cursor_visible_)
674 void GuiWorkArea::Private::updateScrollbar()
676 // Prevent setRange() and setSliderPosition from causing recursive calls via
677 // the signal valueChanged. (#10311)
678 QObject::disconnect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
679 p, SLOT(scrollTo(int)));
680 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
681 p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
682 p->verticalScrollBar()->setPageStep(scroll_.page_step);
683 p->verticalScrollBar()->setSingleStep(scroll_.single_step);
684 p->verticalScrollBar()->setSliderPosition(0);
685 // Connect to the vertical scroll bar
686 QObject::connect(p->verticalScrollBar(), SIGNAL(valueChanged(int)),
687 p, SLOT(scrollTo(int)));
691 void GuiWorkArea::scrollTo(int value)
693 stopBlinkingCursor();
694 d->buffer_view_->scrollDocView(value, true);
696 if (lyxrc.cursor_follows_scrollbar) {
697 d->buffer_view_->setCursorFromScrollbar();
698 // FIXME: let GuiView take care of those.
699 d->lyx_view_->updateLayoutList();
701 // Show the cursor immediately after any operation.
702 startBlinkingCursor();
705 QApplication::syncX();
710 bool GuiWorkArea::event(QEvent * e)
713 case QEvent::ToolTip: {
714 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
715 if (lyxrc.use_tooltip) {
716 QPoint pos = helpEvent->pos();
717 if (pos.x() < viewport()->width()) {
718 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
719 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
722 QToolTip::hideText();
724 // Don't forget to accept the event!
729 case QEvent::ShortcutOverride:
730 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
732 keyPressEvent(static_cast<QKeyEvent *>(e));
733 return e->isAccepted();
735 case QEvent::KeyPress: {
736 // We catch this event in order to catch the Tab or Shift+Tab key press
737 // which are otherwise reserved to focus switching between controls
739 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
740 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
741 || (ke->key() == Qt::Key_Backtab && (
742 ke->modifiers() == Qt::ShiftModifier
743 || ke->modifiers() == Qt::NoModifier))) {
747 return QAbstractScrollArea::event(e);
751 return QAbstractScrollArea::event(e);
757 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
760 if (e->reason() == QContextMenuEvent::Mouse)
761 // the menu name is set on mouse press
762 name = d->context_menu_name_;
764 QPoint pos = e->pos();
765 Cursor const & cur = d->buffer_view_->cursor();
766 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
767 // Do not access the context menu of math right in front of before
768 // the cursor. This does not work when the cursor is in text.
769 Inset * inset = cur.paragraph().getInset(cur.pos());
770 if (inset && inset->asInsetMath())
772 else if (cur.pos() > 0) {
773 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
778 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
785 // always show mnemonics when the keyboard is used to show the context menu
786 // FIXME: This should be fixed in Qt itself
787 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
788 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
793 // Position the menu to the right.
794 // FIXME: menu position should be different for RTL text.
795 menu->exec(e->globalPos());
800 void GuiWorkArea::focusInEvent(QFocusEvent * e)
802 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
803 if (d->lyx_view_->currentWorkArea() != this) {
804 d->lyx_view_->setCurrentWorkArea(this);
805 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
808 startBlinkingCursor();
809 QAbstractScrollArea::focusInEvent(e);
813 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
815 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
816 stopBlinkingCursor();
817 QAbstractScrollArea::focusOutEvent(e);
821 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
823 if (d->dc_event_.active && d->dc_event_ == *e) {
824 d->dc_event_.active = false;
825 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
826 q_button_state(e->button()), q_key_state(e->modifiers()));
832 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
833 inputContext()->reset();
836 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
837 q_button_state(e->button()), q_key_state(e->modifiers()));
840 // Save the context menu on mouse press, because also the mouse
841 // cursor is set on mouse press. Afterwards, we can either release
842 // the mousebutton somewhere else, or the cursor might have moved
843 // due to the DEPM. We need to do this after the mouse has been
844 // set in dispatch(), because the selection state might change.
845 if (e->button() == Qt::RightButton)
846 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
852 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
854 if (d->synthetic_mouse_event_.timeout.running())
855 d->synthetic_mouse_event_.timeout.stop();
857 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
858 q_button_state(e->button()), q_key_state(e->modifiers()));
864 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
866 // we kill the triple click if we move
867 doubleClickTimeout();
868 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
869 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
873 // If we're above or below the work area...
874 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
875 && e->buttons() == mouse_button::button1) {
876 // Make sure only a synthetic event can cause a page scroll,
877 // so they come at a steady rate:
879 // _Force_ a scroll up:
880 cmd.set_y(e->y() - 21);
882 cmd.set_y(e->y() + 21);
883 // Store the event, to be handled when the timeout expires.
884 d->synthetic_mouse_event_.cmd = cmd;
886 if (d->synthetic_mouse_event_.timeout.running()) {
887 // Discard the event. Note that it _may_ be handled
888 // when the timeout expires if
889 // synthetic_mouse_event_.cmd has not been overwritten.
890 // Ie, when the timeout expires, we handle the
891 // most recent event but discard all others that
892 // occurred after the one used to start the timeout
893 // in the first place.
897 d->synthetic_mouse_event_.restart_timeout = true;
898 d->synthetic_mouse_event_.timeout.start();
899 // Fall through to handle this event...
901 } else if (d->synthetic_mouse_event_.timeout.running()) {
902 // Store the event, to be possibly handled when the timeout
904 // Once the timeout has expired, normal control is returned
905 // to mouseMoveEvent (restart_timeout = false).
906 // This results in a much smoother 'feel' when moving the
907 // mouse back into the work area.
908 d->synthetic_mouse_event_.cmd = cmd;
909 d->synthetic_mouse_event_.restart_timeout = false;
916 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
918 // Wheel rotation by one notch results in a delta() of 120 (see
919 // documentation of QWheelEvent)
920 double const delta = ev->delta() / 120.0;
922 switch (lyxrc.scroll_wheel_zoom) {
923 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
924 zoom = ev->modifiers() & Qt::ControlModifier;
925 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
927 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
928 zoom = ev->modifiers() & Qt::ShiftModifier;
929 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
931 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
932 zoom = ev->modifiers() & Qt::AltModifier;
933 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
935 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
939 docstring arg = convert<docstring>(int(5 * delta));
940 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
944 // Take into account the desktop wide settings.
945 int const lines = qApp->wheelScrollLines();
946 int const page_step = verticalScrollBar()->pageStep();
947 // Test if the wheel mouse is set to one screen at a time.
948 // This is according to
949 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
951 min(lines * verticalScrollBar()->singleStep(), page_step);
953 // Take into account the rotation and the user preferences.
954 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
955 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
956 << " delta = " << delta << " scroll_value = " << scroll_value
957 << " page_step = " << page_step);
959 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
965 void GuiWorkArea::generateSyntheticMouseEvent()
967 int const e_y = d->synthetic_mouse_event_.cmd.y();
968 int const wh = d->buffer_view_->workHeight();
969 bool const up = e_y < 0;
970 bool const down = e_y > wh;
972 // Set things off to generate the _next_ 'pseudo' event.
974 if (d->synthetic_mouse_event_.restart_timeout) {
975 // This is some magic formulae to determine the speed
976 // of scrolling related to the position of the mouse.
979 int dist = up ? -e_y : e_y - wh;
980 time = max(min(200, 250000 / (dist * dist)), 1) ;
983 step = 80000 / (time * time);
987 d->synthetic_mouse_event_.timeout.setTimeout(time);
988 d->synthetic_mouse_event_.timeout.start();
991 // Can we scroll further ?
992 int const value = verticalScrollBar()->value();
993 if (value == verticalScrollBar()->maximum()
994 || value == verticalScrollBar()->minimum()) {
995 d->synthetic_mouse_event_.timeout.stop();
1000 if (step <= 2 * wh) {
1001 d->buffer_view_->scroll(up ? -step : step);
1002 d->buffer_view_->updateMetrics();
1004 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
1007 // In which paragraph do we have to set the cursor ?
1008 Cursor & cur = d->buffer_view_->cursor();
1009 // FIXME: we don't know how to handle math.
1010 Text * text = cur.text();
1013 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
1015 // Quit gracefully if there are no metrics, since otherwise next
1016 // line would crash (bug #10324).
1017 // This situation seems related to a (not yet understood) timing problem.
1021 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
1022 ParagraphMetrics const & pm = *pp.second;
1023 pit_type const pit = pp.first;
1025 if (pm.rows().empty())
1028 // Find the row at which we set the cursor.
1029 RowList::const_iterator rit = pm.rows().begin();
1030 RowList::const_iterator rlast = pm.rows().end();
1031 int yy = pm.position() - pm.ascent();
1032 for (--rlast; rit != rlast; ++rit) {
1033 int h = rit->height();
1034 if ((up && yy + h > 0)
1035 || (!up && yy + h > wh - defaultRowHeight()))
1040 // Find the position of the cursor
1042 int x = d->synthetic_mouse_event_.cmd.x();
1043 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1048 cur.boundary(bound);
1050 d->buffer_view_->buffer().changed(false);
1055 // CompressorProxy adapted from Kuba Ober https://stackoverflow.com/a/21006207
1056 CompressorProxy::CompressorProxy(GuiWorkArea * wa) : QObject(wa), flag_(false)
1058 qRegisterMetaType<KeySymbol>("KeySymbol");
1059 qRegisterMetaType<KeyModifier>("KeyModifier");
1060 connect(wa, SIGNAL(compressKeySym(KeySymbol, KeyModifier, bool)),
1061 this, SLOT(slot(KeySymbol, KeyModifier, bool)),
1062 Qt::QueuedConnection);
1063 connect(this, SIGNAL(signal(KeySymbol, KeyModifier)),
1064 wa, SLOT(processKeySym(KeySymbol, KeyModifier)));
1068 bool CompressorProxy::emitCheck(bool isAutoRepeat)
1072 QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); // recurse
1073 bool result = flag_;
1079 void CompressorProxy::slot(KeySymbol sym, KeyModifier mod, bool isAutoRepeat)
1081 if (emitCheck(isAutoRepeat))
1082 Q_EMIT signal(sym, mod);
1084 LYXERR(Debug::KEY, "system is busy: autoRepeat key event ignored");
1088 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1090 // this is also called for ShortcutOverride events. In this case, one must
1091 // not act but simply accept the event explicitly.
1092 bool const act = (ev->type() != QEvent::ShortcutOverride);
1094 // Do not process here some keys if dialog_mode_ is set
1095 bool const for_dialog_mode = d->dialog_mode_
1096 && (ev->modifiers() == Qt::NoModifier
1097 || ev->modifiers() == Qt::ShiftModifier)
1098 && (ev->key() == Qt::Key_Escape
1099 || ev->key() == Qt::Key_Enter
1100 || ev->key() == Qt::Key_Return);
1101 // also do not use autoRepeat to input shortcuts
1102 bool const autoRepeat = ev->isAutoRepeat();
1104 if (for_dialog_mode || (!act && autoRepeat)) {
1109 // intercept some keys if completion popup is visible
1110 if (d->completer_->popupVisible()) {
1111 switch (ev->key()) {
1113 case Qt::Key_Return:
1115 d->completer_->activate();
1121 KeyModifier const m = q_key_state(ev->modifiers());
1123 if (act && lyxerr.debugging(Debug::KEY)) {
1125 if (m & ShiftModifier)
1127 if (m & ControlModifier)
1129 if (m & AltModifier)
1131 if (m & MetaModifier)
1133 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1134 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1135 << " keyState: " << str);
1139 setKeySymbol(&sym, ev);
1142 Q_EMIT compressKeySym(sym, m, autoRepeat);
1145 // here, !autoRepeat, as determined at the beginning
1146 ev->setAccepted(queryKeySym(sym, m));
1153 void GuiWorkArea::doubleClickTimeout()
1155 d->dc_event_.active = false;
1159 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1161 d->dc_event_ = DoubleClick(ev);
1162 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1163 SLOT(doubleClickTimeout()));
1164 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1165 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1171 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1173 QAbstractScrollArea::resizeEvent(ev);
1174 d->need_resize_ = true;
1179 void GuiWorkArea::Private::update(int x, int y, int w, int h)
1181 p->viewport()->update(x, y, w, h);
1185 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1187 QRectF const rc = ev->rect();
1188 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1189 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1191 if (d->needResize()) {
1193 d->resizeBufferView();
1194 if (d->cursor_visible_) {
1200 QPainter pain(viewport());
1201 double const pr = pixelRatio();
1202 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr, rc.width() * pr, rc.height() * pr);
1204 if (lyxrc.use_qimage) {
1205 QImage const & image = static_cast<QImage const &>(*d->screen_);
1206 pain.drawImage(rc, image, rcs);
1208 QPixmap const & pixmap = static_cast<QPixmap const &>(*d->screen_);
1209 pain.drawPixmap(rc, pixmap, rcs);
1211 d->cursor_->draw(pain);
1216 void GuiWorkArea::Private::updateScreen()
1218 GuiPainter pain(screen_, p->pixelRatio());
1219 buffer_view_->draw(pain);
1223 void GuiWorkArea::Private::showCursor(int x, int y, int h,
1224 bool l_shape, bool rtl, bool completable)
1226 if (schedule_redraw_) {
1227 // This happens when a graphic conversion is finished. As we don't know
1228 // the size of the new graphics, it's better the update everything.
1229 // We can't use redraw() here because this would trigger a infinite
1230 // recursive loop with showCursor().
1231 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
1234 p->viewport()->update(QRect(0, 0, p->viewport()->width(), p->viewport()->height()));
1235 schedule_redraw_ = false;
1236 // Show the cursor immediately after the update.
1242 cursor_->update(x, y, h, l_shape, rtl, completable);
1244 p->viewport()->update(cursor_->rect());
1248 void GuiWorkArea::Private::removeCursor()
1251 //if (!qApp->focusWidget())
1252 p->viewport()->update(cursor_->rect());
1256 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1258 QString const & commit_string = e->commitString();
1259 docstring const & preedit_string
1260 = qstring_to_ucs4(e->preeditString());
1262 if (!commit_string.isEmpty()) {
1264 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1265 << " commitString: " << e->commitString());
1269 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1270 for (int i = 0; i != commit_string.size(); ++i) {
1271 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1276 // Hide the cursor during the kana-kanji transformation.
1277 if (preedit_string.empty())
1278 startBlinkingCursor();
1280 stopBlinkingCursor();
1282 // last_width : for checking if last preedit string was/wasn't empty.
1283 // FIXME THREAD && FIXME
1284 // We could have more than one work area, right?
1285 static bool last_width = false;
1286 if (!last_width && preedit_string.empty()) {
1287 // if last_width is last length of preedit string.
1292 GuiPainter pain(d->screen_, pixelRatio());
1293 d->buffer_view_->updateMetrics();
1294 d->buffer_view_->draw(pain);
1295 // FIXME: shall we use real_current_font here? (see #10478)
1296 FontInfo font = d->buffer_view_->cursor().getFont().fontInfo();
1297 FontMetrics const & fm = theFontMetrics(font);
1298 int height = fm.maxHeight();
1299 int cur_x = d->cursor_->rect().left();
1300 int cur_y = d->cursor_->rect().bottom();
1302 // redraw area of preedit string.
1303 update(0, cur_y - height, viewport()->width(),
1304 (height + 1) * d->preedit_lines_);
1306 if (preedit_string.empty()) {
1308 d->preedit_lines_ = 1;
1314 // att : stores an IM attribute.
1315 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1317 // get attributes of input method cursor.
1318 // cursor_pos : cursor position in preedit string.
1319 size_t cursor_pos = 0;
1320 bool cursor_is_visible = false;
1321 for (int i = 0; i != att.size(); ++i) {
1322 if (att.at(i).type == QInputMethodEvent::Cursor) {
1323 cursor_pos = att.at(i).start;
1324 cursor_is_visible = att.at(i).length != 0;
1329 size_t preedit_length = preedit_string.length();
1331 // get position of selection in input method.
1332 // FIXME: isn't there a way to do this simplier?
1333 // rStart : cursor position in selected string in IM.
1335 // rLength : selected string length in IM.
1337 if (cursor_pos < preedit_length) {
1338 for (int i = 0; i != att.size(); ++i) {
1339 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1340 if (att.at(i).start <= int(cursor_pos)
1341 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1342 rStart = att.at(i).start;
1343 rLength = att.at(i).length;
1344 if (!cursor_is_visible)
1345 cursor_pos += rLength;
1352 rStart = cursor_pos;
1356 int const right_margin = d->buffer_view_->rightMargin();
1357 Painter::preedit_style ps;
1358 // Most often there would be only one line:
1359 d->preedit_lines_ = 1;
1360 for (size_t pos = 0; pos != preedit_length; ++pos) {
1361 char_type const typed_char = preedit_string[pos];
1362 // reset preedit string style
1363 ps = Painter::preedit_default;
1365 // if we reached the right extremity of the screen, go to next line.
1366 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1367 cur_x = right_margin;
1368 cur_y += height + 1;
1369 ++d->preedit_lines_;
1371 // preedit strings are displayed with dashed underline
1372 // and partial strings are displayed white on black indicating
1373 // that we are in selecting mode in the input method.
1374 // FIXME: rLength == preedit_length is not a changing condition
1375 // FIXME: should be put out of the loop.
1377 && pos < rStart + rLength
1378 && !(cursor_pos < rLength && rLength == preedit_length))
1379 ps = Painter::preedit_selecting;
1381 if (pos == cursor_pos
1382 && (cursor_pos < rLength && rLength == preedit_length))
1383 ps = Painter::preedit_cursor;
1385 // draw one character and update cur_x.
1386 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1389 // update the preedit string screen area.
1390 update(0, cur_y - d->preedit_lines_*height, viewport()->width(),
1391 (height + 1) * d->preedit_lines_);
1393 // Don't forget to accept the event!
1398 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1400 QRect cur_r(0, 0, 0, 0);
1402 // this is the CJK-specific composition window position and
1403 // the context menu position when the menu key is pressed.
1404 case Qt::ImMicroFocus:
1405 cur_r = d->cursor_->rect();
1406 if (d->preedit_lines_ != 1)
1408 cur_r.moveBottom(cur_r.bottom()
1409 + cur_r.height() * (d->preedit_lines_ - 1));
1410 // return lower right of cursor in LyX.
1413 return QWidget::inputMethodQuery(query);
1418 void GuiWorkArea::updateWindowTitle()
1420 Buffer const & buf = bufferView().buffer();
1421 if (buf.fileName() != d->file_name_
1422 || buf.params().shell_escape != d->shell_escape_
1423 || buf.hasReadonlyFlag() != d->read_only_
1424 || buf.lyxvc().vcstatus() != d->vc_status_
1425 || buf.isClean() != d->clean_
1426 || buf.notifiesExternalModification() != d->externally_modified_) {
1427 d->file_name_ = buf.fileName();
1428 d->shell_escape_ = buf.params().shell_escape;
1429 d->read_only_ = buf.hasReadonlyFlag();
1430 d->vc_status_ = buf.lyxvc().vcstatus();
1431 d->clean_ = buf.isClean();
1432 d->externally_modified_ = buf.notifiesExternalModification();
1433 Q_EMIT titleChanged(this);
1438 bool GuiWorkArea::isFullScreen() const
1440 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1444 void GuiWorkArea::scheduleRedraw()
1446 d->schedule_redraw_ = true;
1450 bool GuiWorkArea::inDialogMode() const
1452 return d->dialog_mode_;
1456 void GuiWorkArea::setDialogMode(bool mode)
1458 d->dialog_mode_ = mode;
1462 GuiCompleter & GuiWorkArea::completer()
1464 return *d->completer_;
1467 GuiView const & GuiWorkArea::view() const
1469 return *d->lyx_view_;
1473 GuiView & GuiWorkArea::view()
1475 return *d->lyx_view_;
1478 ////////////////////////////////////////////////////////////////////
1482 ////////////////////////////////////////////////////////////////////
1485 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1487 support::TempFile tempfile("embedded.internal");
1488 tempfile.setAutoRemove(false);
1489 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1490 buffer_->setUnnamed(true);
1491 buffer_->setFullyLoaded(true);
1492 setBuffer(*buffer_);
1493 setDialogMode(true);
1497 EmbeddedWorkArea::~EmbeddedWorkArea()
1499 // No need to destroy buffer and bufferview here, because it is done
1500 // in theBufferList() destruction loop at application exit
1504 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1507 GuiWorkArea::closeEvent(ev);
1511 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1514 GuiWorkArea::hideEvent(ev);
1518 QSize EmbeddedWorkArea::sizeHint () const
1521 // GuiWorkArea sets the size to the screen's viewport
1522 // by returning a value this gets overridden
1523 // EmbeddedWorkArea is now sized to fit in the layout
1524 // of the parent, and has a minimum size set in GuiWorkArea
1525 // which is what we return here
1526 return QSize(100, 70);
1530 void EmbeddedWorkArea::disable()
1532 stopBlinkingCursor();
1533 if (view().currentWorkArea() != this)
1535 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1536 // tolerates it and shows the background logo), what happens if
1537 // an EmbeddedWorkArea is closed after closing all document WAs
1538 view().setCurrentWorkArea(view().currentMainWorkArea());
1541 ////////////////////////////////////////////////////////////////////
1545 ////////////////////////////////////////////////////////////////////
1548 class NoTabFrameMacStyle : public QProxyStyle {
1551 QRect subElementRect(SubElement element, const QStyleOption * option,
1552 const QWidget * widget = 0) const
1554 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1555 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1557 // The Qt Mac style puts the contents into a 3 pixel wide box
1558 // which looks very ugly and not like other Mac applications.
1559 // Hence we remove this here, and moreover the 16 pixel round
1560 // frame above if the tab bar is hidden.
1561 if (element == QStyle::SE_TabWidgetTabContents) {
1562 rect.adjust(- rect.left(), 0, rect.left(), 0);
1571 NoTabFrameMacStyle noTabFrameMacStyle;
1575 TabWorkArea::TabWorkArea(QWidget * parent)
1576 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1579 setStyle(&noTabFrameMacStyle);
1582 QPalette pal = palette();
1583 pal.setColor(QPalette::Active, QPalette::Button,
1584 pal.color(QPalette::Active, QPalette::Window));
1585 pal.setColor(QPalette::Disabled, QPalette::Button,
1586 pal.color(QPalette::Disabled, QPalette::Window));
1587 pal.setColor(QPalette::Inactive, QPalette::Button,
1588 pal.color(QPalette::Inactive, QPalette::Window));
1590 QObject::connect(this, SIGNAL(currentChanged(int)),
1591 this, SLOT(on_currentTabChanged(int)));
1593 closeBufferButton = new QToolButton(this);
1594 closeBufferButton->setPalette(pal);
1595 // FIXME: rename the icon to closebuffer.png
1596 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1597 closeBufferButton->setText("Close File");
1598 closeBufferButton->setAutoRaise(true);
1599 closeBufferButton->setCursor(Qt::ArrowCursor);
1600 closeBufferButton->setToolTip(qt_("Close File"));
1601 closeBufferButton->setEnabled(true);
1602 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1603 this, SLOT(closeCurrentBuffer()));
1604 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1606 // setup drag'n'drop
1607 QTabBar* tb = new DragTabBar;
1608 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1609 this, SLOT(moveTab(int, int)));
1610 tb->setElideMode(Qt::ElideNone);
1613 // make us responsible for the context menu of the tabbar
1614 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1615 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1616 this, SLOT(showContextMenu(const QPoint &)));
1617 connect(tb, SIGNAL(tabCloseRequested(int)),
1618 this, SLOT(closeTab(int)));
1620 setUsesScrollButtons(true);
1624 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1626 if (me->button() == Qt::MidButton)
1627 midpressed_tab_ = tabBar()->tabAt(me->pos());
1629 QTabWidget::mousePressEvent(me);
1633 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1635 if (me->button() == Qt::MidButton) {
1636 int const midreleased_tab = tabBar()->tabAt(me->pos());
1637 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1638 closeTab(midreleased_tab);
1640 QTabWidget::mouseReleaseEvent(me);
1644 void TabWorkArea::paintEvent(QPaintEvent * event)
1646 if (tabBar()->isVisible()) {
1647 QTabWidget::paintEvent(event);
1649 // Prevent the selected tab to influence the
1650 // painting of the frame of the tab widget.
1651 // This is needed for gtk style in Qt.
1652 QStylePainter p(this);
1653 #if QT_VERSION < 0x050000
1654 QStyleOptionTabWidgetFrameV2 opt;
1656 QStyleOptionTabWidgetFrame opt;
1658 initStyleOption(&opt);
1659 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1661 opt.selectedTabRect = QRect();
1662 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1667 bool TabWorkArea::posIsTab(QPoint position)
1669 // tabAt returns -1 if tab does not covers position
1670 return tabBar()->tabAt(position) > -1;
1674 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1676 if (event->button() != Qt::LeftButton)
1679 // this code chunk is unnecessary because it seems the event only makes
1680 // it this far if it is not on a tab. I'm not sure why this is (maybe
1681 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1682 // this is true in all cases and if it will be true in the future so I
1683 // leave this code for now. (skostysh, 2016-07-21)
1685 // return early if double click on existing tabs
1686 if (posIsTab(event->pos()))
1689 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1693 void TabWorkArea::setFullScreen(bool full_screen)
1695 for (int i = 0; i != count(); ++i) {
1696 if (GuiWorkArea * wa = workArea(i))
1697 wa->setFullScreen(full_screen);
1700 if (lyxrc.full_screen_tabbar)
1701 showBar(!full_screen && count() > 1);
1703 showBar(count() > 1);
1707 void TabWorkArea::showBar(bool show)
1709 tabBar()->setEnabled(show);
1710 tabBar()->setVisible(show);
1711 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1712 setTabsClosable(!lyxrc.single_close_tab_button);
1716 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1718 QWidget * w = QTabWidget::widget(index);
1721 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1727 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1729 return widget(currentIndex());
1733 GuiWorkArea * TabWorkArea::workArea(int index) const
1735 GuiWorkAreaContainer * w = widget(index);
1738 return w->workArea();
1742 GuiWorkArea * TabWorkArea::currentWorkArea() const
1744 return workArea(currentIndex());
1748 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1750 // FIXME: this method doesn't work if we have more than one work area
1751 // showing the same buffer.
1752 for (int i = 0; i != count(); ++i) {
1753 GuiWorkArea * wa = workArea(i);
1754 LASSERT(wa, return 0);
1755 if (&wa->bufferView().buffer() == &buffer)
1762 void TabWorkArea::closeAll()
1765 QWidget * wac = widget(0);
1766 LASSERT(wac, return);
1773 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1775 for (int index = 0; index < count(); ++index)
1776 if (workArea(index) == w)
1782 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1784 LASSERT(work_area, return false);
1785 int index = indexOfWorkArea(work_area);
1789 if (index == currentIndex())
1790 // Make sure the work area is up to date.
1791 on_currentTabChanged(index);
1793 // Switch to the work area.
1794 setCurrentIndex(index);
1795 work_area->setFocus();
1801 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1803 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1804 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1805 wa->setUpdatesEnabled(false);
1806 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1807 // when hiding it again below).
1808 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1809 showBar(count() > 0);
1810 addTab(wac, wa->windowTitle());
1811 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1812 this, SLOT(updateTabTexts()));
1813 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1814 setFullScreen(true);
1816 // Hide tabbar if there's only one tab.
1817 showBar(count() > 1);
1825 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1827 LASSERT(work_area, return false);
1828 int index = indexOfWorkArea(work_area);
1832 work_area->setUpdatesEnabled(false);
1833 QWidget * wac = widget(index);
1838 // make sure the next work area is enabled.
1839 currentWidget()->setUpdatesEnabled(true);
1840 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1841 setFullScreen(true);
1843 // Show tabbar only if there's more than one tab.
1844 showBar(count() > 1);
1846 lastWorkAreaRemoved();
1854 void TabWorkArea::on_currentTabChanged(int i)
1856 // returns e.g. on application destruction
1859 GuiWorkArea * wa = workArea(i);
1860 LASSERT(wa, return);
1861 wa->setUpdatesEnabled(true);
1865 currentWorkAreaChanged(wa);
1867 LYXERR(Debug::GUI, "currentTabChanged " << i
1868 << " File: " << wa->bufferView().buffer().absFileName());
1872 void TabWorkArea::closeCurrentBuffer()
1875 if (clicked_tab_ == -1)
1876 wa = currentWorkArea();
1878 wa = workArea(clicked_tab_);
1879 LASSERT(wa, return);
1881 wa->view().closeWorkArea(wa);
1885 void TabWorkArea::hideCurrentTab()
1888 if (clicked_tab_ == -1)
1889 wa = currentWorkArea();
1891 wa = workArea(clicked_tab_);
1892 LASSERT(wa, return);
1894 wa->view().hideWorkArea(wa);
1898 void TabWorkArea::closeTab(int index)
1900 on_currentTabChanged(index);
1903 wa = currentWorkArea();
1905 wa = workArea(index);
1906 LASSERT(wa, return);
1908 wa->view().closeWorkArea(wa);
1915 /// make vector happy
1916 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1918 DisplayPath(int tab, FileName const & filename)
1921 filename_ = (filename.extension() == "lyx") ?
1922 toqstr(filename.onlyFileNameWithoutExt())
1923 : toqstr(filename.onlyFileName());
1924 postfix_ = toqstr(filename.absoluteFilePath()).
1925 split("/", QString::SkipEmptyParts);
1926 postfix_.pop_back();
1927 abs_ = toqstr(filename.absoluteFilePath());
1928 dottedPrefix_ = false;
1931 /// Absolute path for debugging.
1936 /// Add the first segment from the postfix or three dots to the prefix.
1937 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1938 /// when really needed.
1939 void shiftPathSegment(bool dotted)
1941 if (postfix_.count() <= 0)
1945 if (dottedPrefix_ && !prefix_.isEmpty())
1946 prefix_ += ellipsisSlash_;
1947 prefix_ += postfix_.front() + "/";
1949 dottedPrefix_ = dotted && !prefix_.isEmpty();
1950 postfix_.pop_front();
1953 QString displayString() const
1955 if (prefix_.isEmpty())
1958 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1959 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1962 QString forecastPathString() const
1964 if (postfix_.count() == 0)
1965 return displayString();
1968 + (dottedPrefix_ ? ellipsisSlash_ : "")
1969 + postfix_.front() + "/";
1972 bool final() const { return postfix_.empty(); }
1974 int tab() const { return tab_; }
1978 static QString const ellipsisSlash_;
1982 QStringList postfix_;
1994 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1998 bool operator<(DisplayPath const & a, DisplayPath const & b)
2000 return a.displayString() < b.displayString();
2004 bool operator==(DisplayPath const & a, DisplayPath const & b)
2006 return a.displayString() == b.displayString();
2010 void TabWorkArea::updateTabTexts()
2015 std::list<DisplayPath> paths;
2016 typedef std::list<DisplayPath>::iterator It;
2018 // collect full names first: path into postfix, empty prefix and
2019 // filename without extension
2020 for (size_t i = 0; i < n; ++i) {
2021 GuiWorkArea * i_wa = workArea(i);
2022 FileName const fn = i_wa->bufferView().buffer().fileName();
2023 paths.push_back(DisplayPath(i, fn));
2026 // go through path segments and see if it helps to make the path more unique
2027 bool somethingChanged = true;
2028 bool allFinal = false;
2029 while (somethingChanged && !allFinal) {
2030 // adding path segments changes order
2033 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
2034 somethingChanged = false;
2037 // find segments which are not unique (i.e. non-atomic)
2038 It it = paths.begin();
2040 QString segString = it->displayString();
2041 for (; it != paths.end(); ++it) {
2042 // look to the next item
2047 allFinal = allFinal && it->final();
2049 LYXERR(Debug::GUI, "it = " << it->abs()
2050 << " => " << it->displayString());
2052 // still the same segment?
2054 if ((next != paths.end()
2055 && (nextString = next->displayString()) == segString))
2057 LYXERR(Debug::GUI, "segment ended");
2059 // only a trivial one with one element?
2060 if (it == segStart) {
2061 // start new segment
2063 segString = nextString;
2067 // We found a non-atomic segment
2068 // We know that segStart <= it < next <= paths.end().
2069 // The assertion below tells coverity about it.
2070 LATTEST(segStart != paths.end());
2071 QString dspString = segStart->forecastPathString();
2072 LYXERR(Debug::GUI, "first forecast found for "
2073 << segStart->abs() << " => " << dspString);
2076 // Shift path segments and hope for the best
2077 // that it makes the path more unique.
2078 somethingChanged = true;
2079 bool moreUnique = false;
2080 for (; sit != next; ++sit) {
2081 if (sit->forecastPathString() != dspString) {
2082 LYXERR(Debug::GUI, "different forecast found for "
2083 << sit->abs() << " => " << sit->forecastPathString());
2087 LYXERR(Debug::GUI, "same forecast found for "
2088 << sit->abs() << " => " << dspString);
2091 // if the path segment helped, add it. Otherwise add dots
2092 bool dots = !moreUnique;
2093 LYXERR(Debug::GUI, "using dots = " << dots);
2094 for (sit = segStart; sit != next; ++sit) {
2095 sit->shiftPathSegment(dots);
2096 LYXERR(Debug::GUI, "shifting "
2097 << sit->abs() << " => " << sit->displayString());
2100 // start new segment
2102 segString = nextString;
2106 // set new tab titles
2107 for (It it = paths.begin(); it != paths.end(); ++it) {
2108 int const tab_index = it->tab();
2109 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2110 QString tab_text = it->displayString().replace("&", "&&");
2111 if (!buf.fileName().empty() && !buf.isClean())
2113 QString tab_tooltip = it->abs();
2114 if (buf.hasReadonlyFlag()) {
2115 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2116 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2118 setTabIcon(tab_index, QIcon());
2119 if (buf.notifiesExternalModification()) {
2120 QString const warn = qt_("%1 (modified externally)");
2121 tab_tooltip = warn.arg(tab_tooltip);
2122 tab_text += QChar(0x26a0);
2124 setTabText(tab_index, tab_text);
2125 setTabToolTip(tab_index, tab_tooltip);
2130 void TabWorkArea::showContextMenu(const QPoint & pos)
2133 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
2134 if (clicked_tab_ == -1)
2139 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2140 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2141 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2142 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2143 popup.exec(tabBar()->mapToGlobal(pos));
2149 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2151 QWidget * w = widget(fromIndex);
2152 QIcon icon = tabIcon(fromIndex);
2153 QString text = tabText(fromIndex);
2155 setCurrentIndex(fromIndex);
2156 removeTab(fromIndex);
2157 insertTab(toIndex, w, icon, text);
2158 setCurrentIndex(toIndex);
2162 DragTabBar::DragTabBar(QWidget* parent)
2165 setAcceptDrops(true);
2166 setTabsClosable(!lyxrc.single_close_tab_button);
2170 void DragTabBar::mousePressEvent(QMouseEvent * event)
2172 if (event->button() == Qt::LeftButton)
2173 dragStartPos_ = event->pos();
2174 QTabBar::mousePressEvent(event);
2178 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2180 // If the left button isn't pressed anymore then return
2181 if (!(event->buttons() & Qt::LeftButton))
2184 // If the distance is too small then return
2185 if ((event->pos() - dragStartPos_).manhattanLength()
2186 < QApplication::startDragDistance())
2189 // did we hit something after all?
2190 int tab = tabAt(dragStartPos_);
2194 // simulate button release to remove highlight from button
2195 int i = currentIndex();
2196 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2197 event->button(), event->buttons(), 0);
2198 QTabBar::mouseReleaseEvent(&me);
2202 QDrag * drag = new QDrag(this);
2203 QMimeData * mimeData = new QMimeData;
2204 // a crude way to distinguish tab-reodering drops from other ones
2205 mimeData->setData("action", "tab-reordering") ;
2206 drag->setMimeData(mimeData);
2208 // get tab pixmap as cursor
2209 QRect r = tabRect(tab);
2210 QPixmap pixmap(r.size());
2211 render(&pixmap, - r.topLeft());
2212 drag->setPixmap(pixmap);
2217 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2219 // Only accept if it's an tab-reordering request
2220 QMimeData const * m = event->mimeData();
2221 QStringList formats = m->formats();
2222 if (formats.contains("action")
2223 && m->data("action") == "tab-reordering")
2224 event->acceptProposedAction();
2228 void DragTabBar::dropEvent(QDropEvent * event)
2230 int fromIndex = tabAt(dragStartPos_);
2231 int toIndex = tabAt(event->pos());
2233 // Tell interested objects that
2234 if (fromIndex != toIndex)
2235 tabMoveRequested(fromIndex, toIndex);
2236 event->acceptProposedAction();
2240 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2241 : QWidget(parent), wa_(wa)
2243 LASSERT(wa, return);
2244 Ui::WorkAreaUi::setupUi(this);
2245 layout()->addWidget(wa);
2246 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2247 this, SLOT(updateDisplay()));
2248 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2249 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2250 setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2255 void GuiWorkAreaContainer::updateDisplay()
2257 Buffer const & buf = wa_->bufferView().buffer();
2258 notificationFrame->setHidden(!buf.notifiesExternalModification());
2259 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2260 .arg(toqstr(buf.fileName().displayName()));
2261 externalModificationLabel->setText(label);
2265 void GuiWorkAreaContainer::dispatch(FuncRequest f) const
2267 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2268 wa_->bufferView().buffer().absFileName()));
2273 void GuiWorkAreaContainer::reload() const
2275 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2279 void GuiWorkAreaContainer::ignore() const
2281 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2285 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2287 // prevent TabWorkArea from opening a new buffer on double click
2292 } // namespace frontend
2295 #include "moc_GuiWorkArea.cpp"