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),
254 read_only_(false), clean_(true), externally_modified_(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 qt_scale_factor * 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 // This connection is closed at the same time as this is destroyed.
324 d->synthetic_mouse_event_.timeout.timeout.connect([this](){
325 generateSyntheticMouseEvent();
328 // Initialize the vertical Scroll Bar
329 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
330 this, SLOT(scrollTo(int)));
332 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
333 << " viewport height: " << viewport()->height());
335 // Enables input methods for asian languages.
336 // Must be set when creating custom text editing widgets.
337 setAttribute(Qt::WA_InputMethodEnabled, true);
339 d->dialog_mode_ = false;
343 GuiWorkArea::~GuiWorkArea()
345 // If something is wrong with the buffer, we can ignore it safely
347 d->buffer_view_->buffer().workAreaManager().remove(this);
350 delete d->buffer_view_;
352 // Completer has a QObject parent and is thus automatically destroyed.
354 // delete completer_;
359 Qt::CursorShape GuiWorkArea::cursorShape() const
361 return viewport()->cursor().shape();
365 void GuiWorkArea::Private::setCursorShape(Qt::CursorShape shape)
367 p->viewport()->setCursor(shape);
371 void GuiWorkArea::Private::updateCursorShape()
373 setCursorShape(buffer_view_->clickableInset()
374 ? Qt::PointingHandCursor : Qt::IBeamCursor);
378 void GuiWorkArea::setGuiView(GuiView & gv)
384 void GuiWorkArea::setBuffer(Buffer & buffer)
386 delete d->buffer_view_;
387 d->buffer_view_ = new BufferView(buffer);
388 buffer.workAreaManager().add(this);
390 // HACK: Prevents an additional redraw when the scrollbar pops up
391 // which regularily happens on documents with more than one page.
392 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
393 // Since we have no geometry information yet, we assume that
394 // a document needs a scrollbar if there is more then four
395 // paragraph in the outermost text.
396 if (buffer.text().paragraphs().size() > 4)
397 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
398 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
399 Q_EMIT bufferViewChanged();
403 void GuiWorkArea::fixVerticalScrollBar()
406 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
410 void GuiWorkArea::close()
412 d->lyx_view_->removeWorkArea(this);
416 void GuiWorkArea::setFullScreen(bool full_screen)
418 d->buffer_view_->setFullScreen(full_screen);
419 setFrameStyle(QFrame::NoFrame);
421 setFrameStyle(QFrame::NoFrame);
422 if (lyxrc.full_screen_scrollbar)
423 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
425 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
429 BufferView & GuiWorkArea::bufferView()
431 return *d->buffer_view_;
435 BufferView const & GuiWorkArea::bufferView() const
437 return *d->buffer_view_;
441 void GuiWorkArea::stopBlinkingCursor()
443 d->cursor_timeout_.stop();
448 void GuiWorkArea::startBlinkingCursor()
450 // do not show the cursor if the view is busy
456 d->buffer_view_->cursorPosAndHeight(p, h);
457 // Don't start blinking if the cursor isn't on screen.
458 if (!d->buffer_view_->cursorInView(p, h))
463 //we're not supposed to cache this value.
464 int const time = QApplication::cursorFlashTime() / 2;
467 d->cursor_timeout_.setInterval(time);
468 d->cursor_timeout_.start();
472 void GuiWorkArea::redraw(bool update_metrics)
475 // No need to redraw in this case.
478 // No need to do anything if this is the current view. The BufferView
479 // metrics are already up to date.
480 if (update_metrics || d->lyx_view_ != guiApp->currentView()
481 || d->lyx_view_->currentWorkArea() != this) {
482 // FIXME: it would be nice to optimize for the off-screen case.
483 d->buffer_view_->cursor().fixIfBroken();
484 d->buffer_view_->updateMetrics();
485 d->buffer_view_->cursor().fixIfBroken();
488 // update cursor position, because otherwise it has to wait until
489 // the blinking interval is over
490 if (d->cursor_visible_) {
495 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
497 update(0, 0, viewport()->width(), viewport()->height());
499 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
500 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
501 d->updateScrollbar();
502 d->lyx_view_->updateStatusBar();
504 if (lyxerr.debugging(Debug::WORKAREA))
505 d->buffer_view_->coordCache().dump();
509 d->updateCursorShape();
513 // Keep in sync with GuiWorkArea::processKeySym below
514 bool GuiWorkArea::queryKeySym(KeySymbol const & key, KeyModifier mod) const
516 return guiApp->queryKeySym(key, mod);
520 // Keep in sync with GuiWorkArea::queryKeySym above
521 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
523 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
524 && lyxrc.full_screen_menubar) {
525 // FIXME HACK: we should not have to do this here. See related comment
526 // in GuiView::event() (QEvent::ShortcutOverride)
527 d->lyx_view_->menuBar()->hide();
530 // In order to avoid bad surprise in the middle of an operation,
531 // we better stop the blinking cursor...
532 // the cursor gets restarted in GuiView::restartCursor()
533 stopBlinkingCursor();
534 guiApp->processKeySym(key, mod);
538 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd)
541 if (cmd.action() == LFUN_FILE_OPEN) {
543 lyx_view_->dispatch(cmd, dr);
547 bool const notJustMovingTheMouse =
548 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
550 // In order to avoid bad surprise in the middle of an operation, we better stop
551 // the blinking cursor.
552 if (notJustMovingTheMouse)
553 p->stopBlinkingCursor();
555 buffer_view_->mouseEventDispatch(cmd);
557 // Skip these when selecting
558 // FIXME: let GuiView take care of those.
559 if (cmd.action() != LFUN_MOUSE_MOTION) {
560 completer_->updateVisibility(false, false);
561 lyx_view_->updateDialogs();
562 lyx_view_->updateStatusBar();
565 // GUI tweaks except with mouse motion with no button pressed.
566 if (notJustMovingTheMouse) {
567 // Slight hack: this is only called currently when we
568 // clicked somewhere, so we force through the display
569 // of the new status here.
570 // FIXME: let GuiView take care of those.
571 lyx_view_->clearMessage();
573 // Show the cursor immediately after any operation
574 p->startBlinkingCursor();
581 void GuiWorkArea::Private::resizeBufferView()
583 // WARNING: Please don't put any code that will trigger a repaint here!
584 // We are already inside a paint event.
585 p->stopBlinkingCursor();
586 // Warn our container (GuiView).
591 buffer_view_->cursorPosAndHeight(point, h);
592 bool const cursor_in_view = buffer_view_->cursorInView(point, h);
593 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
595 buffer_view_->scrollToCursor();
598 // Update scrollbars which might have changed due different
599 // BufferView dimension. This is especially important when the
600 // BufferView goes from zero-size to the real-size for the first time,
601 // as the scrollbar paramters are then set for the first time.
604 need_resize_ = false;
606 // Eventually, restart the cursor after the resize event.
607 // We might be resizing even if the focus is on another widget so we only
608 // restart the cursor if we have the focus.
610 QTimer::singleShot(50, p, SLOT(startBlinkingCursor()));
614 void GuiWorkArea::Private::showCursor()
621 buffer_view_->cursorPosAndHeight(p, h);
622 if (!buffer_view_->cursorInView(p, h))
626 bool l_shape = false;
627 Font const & realfont = buffer_view_->cursor().real_current_font;
628 BufferParams const & bp = buffer_view_->buffer().params();
629 bool const samelang = realfont.language() == bp.language;
630 bool const isrtl = realfont.isVisibleRightToLeft();
632 if (!samelang || isrtl != bp.language->rightToLeft())
635 // The ERT language hack needs fixing up
636 if (realfont.language() == latex_language)
639 // show cursor on screen
640 Cursor & cur = buffer_view_->cursor();
641 bool completable = cur.inset().showCompletionCursor()
642 && completer_->completionAvailable()
643 && !completer_->popupVisible()
644 && !completer_->inlineVisible();
645 cursor_visible_ = true;
646 cursor_->recomputeWidth();
648 //int cur_x = buffer_view_->getPos(cur).x_;
649 // We may have decided to slide the cursor row so that cursor
651 p.x_ -= buffer_view_->horizScrollOffset();
653 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
657 void GuiWorkArea::Private::hideCursor()
659 if (!cursor_visible_)
662 cursor_visible_ = false;
667 void GuiWorkArea::toggleCursor()
669 if (d->cursor_visible_)
676 void GuiWorkArea::Private::updateScrollbar()
678 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
679 // Block signals to prevent setRange() and setSliderPosition from causing
680 // recursive calls via the signal valueChanged. (#10311)
681 QSignalBlocker blocker(p->verticalScrollBar());
682 p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
683 p->verticalScrollBar()->setPageStep(scroll_.page_step);
684 p->verticalScrollBar()->setSingleStep(scroll_.single_step);
685 p->verticalScrollBar()->setSliderPosition(0);
689 void GuiWorkArea::scrollTo(int value)
691 stopBlinkingCursor();
692 d->buffer_view_->scrollDocView(value, true);
694 if (lyxrc.cursor_follows_scrollbar) {
695 d->buffer_view_->setCursorFromScrollbar();
696 // FIXME: let GuiView take care of those.
697 d->lyx_view_->updateLayoutList();
699 // Show the cursor immediately after any operation.
700 startBlinkingCursor();
703 QApplication::syncX();
708 bool GuiWorkArea::event(QEvent * e)
711 case QEvent::ToolTip: {
712 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
713 if (lyxrc.use_tooltip) {
714 QPoint pos = helpEvent->pos();
715 if (pos.x() < viewport()->width()) {
716 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
717 QToolTip::showText(helpEvent->globalPos(), formatToolTip(s,35));
720 QToolTip::hideText();
722 // Don't forget to accept the event!
727 case QEvent::ShortcutOverride:
728 // keyPressEvent is ShortcutOverride-aware and only accepts the event in
730 keyPressEvent(static_cast<QKeyEvent *>(e));
731 return e->isAccepted();
733 case QEvent::KeyPress: {
734 // We catch this event in order to catch the Tab or Shift+Tab key press
735 // which are otherwise reserved to focus switching between controls
737 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
738 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
739 || (ke->key() == Qt::Key_Backtab && (
740 ke->modifiers() == Qt::ShiftModifier
741 || ke->modifiers() == Qt::NoModifier))) {
745 return QAbstractScrollArea::event(e);
749 return QAbstractScrollArea::event(e);
755 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
758 if (e->reason() == QContextMenuEvent::Mouse)
759 // the menu name is set on mouse press
760 name = d->context_menu_name_;
762 QPoint pos = e->pos();
763 Cursor const & cur = d->buffer_view_->cursor();
764 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
765 // Do not access the context menu of math right in front of before
766 // the cursor. This does not work when the cursor is in text.
767 Inset * inset = cur.paragraph().getInset(cur.pos());
768 if (inset && inset->asInsetMath())
770 else if (cur.pos() > 0) {
771 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
776 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
780 QAbstractScrollArea::contextMenuEvent(e);
783 // always show mnemonics when the keyboard is used to show the context menu
784 // FIXME: This should be fixed in Qt itself
785 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
786 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
788 QAbstractScrollArea::contextMenuEvent(e);
791 // Position the menu to the right.
792 // FIXME: menu position should be different for RTL text.
793 menu->exec(e->globalPos());
798 void GuiWorkArea::focusInEvent(QFocusEvent * e)
800 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
801 if (d->lyx_view_->currentWorkArea() != this) {
802 d->lyx_view_->setCurrentWorkArea(this);
803 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
806 startBlinkingCursor();
807 QAbstractScrollArea::focusInEvent(e);
811 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
813 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
814 stopBlinkingCursor();
815 QAbstractScrollArea::focusOutEvent(e);
819 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
821 if (d->dc_event_.active && d->dc_event_ == *e) {
822 d->dc_event_.active = false;
823 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
824 q_button_state(e->button()), q_key_state(e->modifiers()));
830 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
831 inputContext()->reset();
834 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
835 q_button_state(e->button()), q_key_state(e->modifiers()));
838 // Save the context menu on mouse press, because also the mouse
839 // cursor is set on mouse press. Afterwards, we can either release
840 // the mousebutton somewhere else, or the cursor might have moved
841 // due to the DEPM. We need to do this after the mouse has been
842 // set in dispatch(), because the selection state might change.
843 if (e->button() == Qt::RightButton)
844 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
850 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
852 if (d->synthetic_mouse_event_.timeout.running())
853 d->synthetic_mouse_event_.timeout.stop();
855 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
856 q_button_state(e->button()), q_key_state(e->modifiers()));
862 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
864 // we kill the triple click if we move
865 doubleClickTimeout();
866 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
867 q_motion_state(e->buttons()), q_key_state(e->modifiers()));
871 // If we're above or below the work area...
872 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
873 && e->buttons() == mouse_button::button1) {
874 // Make sure only a synthetic event can cause a page scroll,
875 // so they come at a steady rate:
877 // _Force_ a scroll up:
878 cmd.set_y(e->y() - 21);
880 cmd.set_y(e->y() + 21);
881 // Store the event, to be handled when the timeout expires.
882 d->synthetic_mouse_event_.cmd = cmd;
884 if (d->synthetic_mouse_event_.timeout.running()) {
885 // Discard the event. Note that it _may_ be handled
886 // when the timeout expires if
887 // synthetic_mouse_event_.cmd has not been overwritten.
888 // Ie, when the timeout expires, we handle the
889 // most recent event but discard all others that
890 // occurred after the one used to start the timeout
891 // in the first place.
895 d->synthetic_mouse_event_.restart_timeout = true;
896 d->synthetic_mouse_event_.timeout.start();
897 // Fall through to handle this event...
899 } else if (d->synthetic_mouse_event_.timeout.running()) {
900 // Store the event, to be possibly handled when the timeout
902 // Once the timeout has expired, normal control is returned
903 // to mouseMoveEvent (restart_timeout = false).
904 // This results in a much smoother 'feel' when moving the
905 // mouse back into the work area.
906 d->synthetic_mouse_event_.cmd = cmd;
907 d->synthetic_mouse_event_.restart_timeout = false;
914 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
916 // Wheel rotation by one notch results in a delta() of 120 (see
917 // documentation of QWheelEvent)
918 double const delta = ev->delta() / 120.0;
920 switch (lyxrc.scroll_wheel_zoom) {
921 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
922 zoom = ev->modifiers() & Qt::ControlModifier;
923 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
925 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
926 zoom = ev->modifiers() & Qt::ShiftModifier;
927 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
929 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
930 zoom = ev->modifiers() & Qt::AltModifier;
931 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
933 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
937 docstring arg = convert<docstring>(int(5 * delta));
938 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
942 // Take into account the desktop wide settings.
943 int const lines = qApp->wheelScrollLines();
944 int const page_step = verticalScrollBar()->pageStep();
945 // Test if the wheel mouse is set to one screen at a time.
946 // This is according to
947 // https://doc.qt.io/qt-5/qapplication.html#wheelScrollLines-prop
949 min(lines * verticalScrollBar()->singleStep(), page_step);
951 // Take into account the rotation and the user preferences.
952 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
953 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
954 << " delta = " << delta << " scroll_value = " << scroll_value
955 << " page_step = " << page_step);
957 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
963 void GuiWorkArea::generateSyntheticMouseEvent()
965 int const e_y = d->synthetic_mouse_event_.cmd.y();
966 int const wh = d->buffer_view_->workHeight();
967 bool const up = e_y < 0;
968 bool const down = e_y > wh;
970 // Set things off to generate the _next_ 'pseudo' event.
972 if (d->synthetic_mouse_event_.restart_timeout) {
973 // This is some magic formulae to determine the speed
974 // of scrolling related to the position of the mouse.
977 int dist = up ? -e_y : e_y - wh;
978 time = max(min(200, 250000 / (dist * dist)), 1) ;
981 step = 80000 / (time * time);
985 d->synthetic_mouse_event_.timeout.setTimeout(time);
986 d->synthetic_mouse_event_.timeout.start();
989 // Can we scroll further ?
990 int const value = verticalScrollBar()->value();
991 if (value == verticalScrollBar()->maximum()
992 || value == verticalScrollBar()->minimum()) {
993 d->synthetic_mouse_event_.timeout.stop();
998 if (step <= 2 * wh) {
999 d->buffer_view_->scroll(up ? -step : step);
1000 d->buffer_view_->updateMetrics();
1002 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
1005 // In which paragraph do we have to set the cursor ?
1006 Cursor & cur = d->buffer_view_->cursor();
1007 // FIXME: we don't know howto handle math.
1008 Text * text = cur.text();
1011 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
1013 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
1014 ParagraphMetrics const & pm = *pp.second;
1015 pit_type const pit = pp.first;
1017 if (pm.rows().empty())
1020 // Find the row at which we set the cursor.
1021 RowList::const_iterator rit = pm.rows().begin();
1022 RowList::const_iterator rlast = pm.rows().end();
1023 int yy = pm.position() - pm.ascent();
1024 for (--rlast; rit != rlast; ++rit) {
1025 int h = rit->height();
1026 if ((up && yy + h > 0)
1027 || (!up && yy + h > wh - defaultRowHeight()))
1032 // Find the position of the cursor
1034 int x = d->synthetic_mouse_event_.cmd.x();
1035 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1040 cur.boundary(bound);
1042 d->buffer_view_->buffer().changed(false);
1047 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1049 // this is also called for ShortcutOverride events. In this case, one must
1050 // not act but simply accept the event explicitly.
1051 bool const act = (ev->type() != QEvent::ShortcutOverride);
1053 // Do not process here some keys if dialog_mode_ is set
1055 && (ev->modifiers() == Qt::NoModifier
1056 || ev->modifiers() == Qt::ShiftModifier)
1057 && (ev->key() == Qt::Key_Escape
1058 || ev->key() == Qt::Key_Enter
1059 || ev->key() == Qt::Key_Return)
1065 // intercept some keys if completion popup is visible
1066 if (d->completer_->popupVisible()) {
1067 switch (ev->key()) {
1069 case Qt::Key_Return:
1071 d->completer_->activate();
1077 // do nothing if there are other events
1078 // (the auto repeated events come too fast)
1079 // it looks like this is only needed on X11
1080 #if defined(Q_WS_X11) || defined(QPA_XCB)
1081 // FIXME: this is a weird way to implement event compression. Also, this is
1082 // broken with IBus.
1083 if (act && qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1084 switch (ev->key()) {
1085 case Qt::Key_PageDown:
1086 case Qt::Key_PageUp:
1091 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1098 KeyModifier const m = q_key_state(ev->modifiers());
1101 if (m & ShiftModifier)
1103 if (m & ControlModifier)
1105 if (m & AltModifier)
1107 if (m & MetaModifier)
1111 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1112 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1113 << " keyState: " << str);
1116 setKeySymbol(&sym, ev);
1119 processKeySym(sym, m);
1122 ev->setAccepted(queryKeySym(sym, m));
1129 void GuiWorkArea::doubleClickTimeout()
1131 d->dc_event_.active = false;
1135 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1137 d->dc_event_ = DoubleClick(ev);
1138 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1139 SLOT(doubleClickTimeout()));
1140 FuncRequest cmd(LFUN_MOUSE_DOUBLE, ev->x(), ev->y(),
1141 q_button_state(ev->button()), q_key_state(ev->modifiers()));
1147 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1149 QAbstractScrollArea::resizeEvent(ev);
1150 d->need_resize_ = true;
1155 void GuiWorkArea::Private::update(int x, int y, int w, int h)
1157 p->viewport()->update(x, y, w, h);
1161 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1163 QRectF const rc = ev->rect();
1164 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1165 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1167 if (d->needResize()) {
1169 d->resizeBufferView();
1170 if (d->cursor_visible_) {
1176 QPainter pain(viewport());
1177 double const pr = pixelRatio();
1178 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr, rc.width() * pr, rc.height() * pr);
1180 if (lyxrc.use_qimage) {
1181 QImage const & image = static_cast<QImage const &>(*d->screen_);
1182 pain.drawImage(rc, image, rcs);
1184 QPixmap const & pixmap = static_cast<QPixmap const &>(*d->screen_);
1185 pain.drawPixmap(rc, pixmap, rcs);
1187 d->cursor_->draw(pain);
1192 void GuiWorkArea::Private::updateScreen()
1194 GuiPainter pain(screen_, p->pixelRatio());
1195 buffer_view_->draw(pain);
1199 void GuiWorkArea::Private::showCursor(int x, int y, int h,
1200 bool l_shape, bool rtl, bool completable)
1202 if (schedule_redraw_) {
1203 // This happens when a graphic conversion is finished. As we don't know
1204 // the size of the new graphics, it's better the update everything.
1205 // We can't use redraw() here because this would trigger a infinite
1206 // recursive loop with showCursor().
1207 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
1210 p->viewport()->update(QRect(0, 0, p->viewport()->width(), p->viewport()->height()));
1211 schedule_redraw_ = false;
1212 // Show the cursor immediately after the update.
1218 cursor_->update(x, y, h, l_shape, rtl, completable);
1220 p->viewport()->update(cursor_->rect());
1224 void GuiWorkArea::Private::removeCursor()
1227 //if (!qApp->focusWidget())
1228 p->viewport()->update(cursor_->rect());
1232 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1234 QString const & commit_string = e->commitString();
1235 docstring const & preedit_string
1236 = qstring_to_ucs4(e->preeditString());
1238 if (!commit_string.isEmpty()) {
1240 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1241 << " commitString: " << e->commitString());
1245 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1246 for (int i = 0; i != commit_string.size(); ++i) {
1247 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1252 // Hide the cursor during the kana-kanji transformation.
1253 if (preedit_string.empty())
1254 startBlinkingCursor();
1256 stopBlinkingCursor();
1258 // last_width : for checking if last preedit string was/wasn't empty.
1259 // FIXME THREAD && FIXME
1260 // We could have more than one work area, right?
1261 static bool last_width = false;
1262 if (!last_width && preedit_string.empty()) {
1263 // if last_width is last length of preedit string.
1268 GuiPainter pain(d->screen_, pixelRatio());
1269 d->buffer_view_->updateMetrics();
1270 d->buffer_view_->draw(pain);
1271 // FIXME: shall we use real_current_font here? (see #10478)
1272 FontInfo font = d->buffer_view_->cursor().getFont().fontInfo();
1273 FontMetrics const & fm = theFontMetrics(font);
1274 int height = fm.maxHeight();
1275 int cur_x = d->cursor_->rect().left();
1276 int cur_y = d->cursor_->rect().bottom();
1278 // redraw area of preedit string.
1279 update(0, cur_y - height, viewport()->width(),
1280 (height + 1) * d->preedit_lines_);
1282 if (preedit_string.empty()) {
1284 d->preedit_lines_ = 1;
1290 // att : stores an IM attribute.
1291 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1293 // get attributes of input method cursor.
1294 // cursor_pos : cursor position in preedit string.
1295 size_t cursor_pos = 0;
1296 bool cursor_is_visible = false;
1297 for (int i = 0; i != att.size(); ++i) {
1298 if (att.at(i).type == QInputMethodEvent::Cursor) {
1299 cursor_pos = att.at(i).start;
1300 cursor_is_visible = att.at(i).length != 0;
1305 size_t preedit_length = preedit_string.length();
1307 // get position of selection in input method.
1308 // FIXME: isn't there a way to do this simplier?
1309 // rStart : cursor position in selected string in IM.
1311 // rLength : selected string length in IM.
1313 if (cursor_pos < preedit_length) {
1314 for (int i = 0; i != att.size(); ++i) {
1315 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1316 if (att.at(i).start <= int(cursor_pos)
1317 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1318 rStart = att.at(i).start;
1319 rLength = att.at(i).length;
1320 if (!cursor_is_visible)
1321 cursor_pos += rLength;
1328 rStart = cursor_pos;
1332 int const right_margin = d->buffer_view_->rightMargin();
1333 Painter::preedit_style ps;
1334 // Most often there would be only one line:
1335 d->preedit_lines_ = 1;
1336 for (size_t pos = 0; pos != preedit_length; ++pos) {
1337 char_type const typed_char = preedit_string[pos];
1338 // reset preedit string style
1339 ps = Painter::preedit_default;
1341 // if we reached the right extremity of the screen, go to next line.
1342 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1343 cur_x = right_margin;
1344 cur_y += height + 1;
1345 ++d->preedit_lines_;
1347 // preedit strings are displayed with dashed underline
1348 // and partial strings are displayed white on black indicating
1349 // that we are in selecting mode in the input method.
1350 // FIXME: rLength == preedit_length is not a changing condition
1351 // FIXME: should be put out of the loop.
1353 && pos < rStart + rLength
1354 && !(cursor_pos < rLength && rLength == preedit_length))
1355 ps = Painter::preedit_selecting;
1357 if (pos == cursor_pos
1358 && (cursor_pos < rLength && rLength == preedit_length))
1359 ps = Painter::preedit_cursor;
1361 // draw one character and update cur_x.
1362 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1365 // update the preedit string screen area.
1366 update(0, cur_y - d->preedit_lines_*height, viewport()->width(),
1367 (height + 1) * d->preedit_lines_);
1369 // Don't forget to accept the event!
1374 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1376 QRect cur_r(0, 0, 0, 0);
1378 // this is the CJK-specific composition window position and
1379 // the context menu position when the menu key is pressed.
1380 case Qt::ImMicroFocus:
1381 cur_r = d->cursor_->rect();
1382 if (d->preedit_lines_ != 1)
1384 cur_r.moveBottom(cur_r.bottom()
1385 + cur_r.height() * (d->preedit_lines_ - 1));
1386 // return lower right of cursor in LyX.
1389 return QWidget::inputMethodQuery(query);
1394 void GuiWorkArea::updateWindowTitle()
1396 Buffer const & buf = bufferView().buffer();
1397 if (buf.fileName() != d->file_name_
1398 || buf.hasReadonlyFlag() != d->read_only_
1399 || buf.lyxvc().vcstatus() != d->vc_status_
1400 || buf.isClean() != d->clean_
1401 || buf.notifiesExternalModification() != d->externally_modified_) {
1402 d->file_name_ = buf.fileName();
1403 d->read_only_ = buf.hasReadonlyFlag();
1404 d->vc_status_ = buf.lyxvc().vcstatus();
1405 d->clean_ = buf.isClean();
1406 d->externally_modified_ = buf.notifiesExternalModification();
1407 Q_EMIT titleChanged(this);
1412 bool GuiWorkArea::isFullScreen() const
1414 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1418 void GuiWorkArea::scheduleRedraw()
1420 d->schedule_redraw_ = true;
1424 bool GuiWorkArea::inDialogMode() const
1426 return d->dialog_mode_;
1430 void GuiWorkArea::setDialogMode(bool mode)
1432 d->dialog_mode_ = mode;
1436 GuiCompleter & GuiWorkArea::completer()
1438 return *d->completer_;
1441 GuiView const & GuiWorkArea::view() const
1443 return *d->lyx_view_;
1447 GuiView & GuiWorkArea::view()
1449 return *d->lyx_view_;
1452 ////////////////////////////////////////////////////////////////////
1456 ////////////////////////////////////////////////////////////////////
1459 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1461 support::TempFile tempfile("embedded.internal");
1462 tempfile.setAutoRemove(false);
1463 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1464 buffer_->setUnnamed(true);
1465 buffer_->setFullyLoaded(true);
1466 setBuffer(*buffer_);
1467 setDialogMode(true);
1471 EmbeddedWorkArea::~EmbeddedWorkArea()
1473 // No need to destroy buffer and bufferview here, because it is done
1474 // in theBufferList() destruction loop at application exit
1478 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1481 GuiWorkArea::closeEvent(ev);
1485 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1488 GuiWorkArea::hideEvent(ev);
1492 QSize EmbeddedWorkArea::sizeHint () const
1495 // GuiWorkArea sets the size to the screen's viewport
1496 // by returning a value this gets overridden
1497 // EmbeddedWorkArea is now sized to fit in the layout
1498 // of the parent, and has a minimum size set in GuiWorkArea
1499 // which is what we return here
1500 return QSize(100, 70);
1504 void EmbeddedWorkArea::disable()
1506 stopBlinkingCursor();
1507 if (view().currentWorkArea() != this)
1509 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1510 // tolerates it and shows the background logo), what happens if
1511 // an EmbeddedWorkArea is closed after closing all document WAs
1512 view().setCurrentWorkArea(view().currentMainWorkArea());
1515 ////////////////////////////////////////////////////////////////////
1519 ////////////////////////////////////////////////////////////////////
1522 class NoTabFrameMacStyle : public QProxyStyle {
1525 QRect subElementRect(SubElement element, const QStyleOption * option,
1526 const QWidget * widget = 0) const
1528 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1529 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1531 // The Qt Mac style puts the contents into a 3 pixel wide box
1532 // which looks very ugly and not like other Mac applications.
1533 // Hence we remove this here, and moreover the 16 pixel round
1534 // frame above if the tab bar is hidden.
1535 if (element == QStyle::SE_TabWidgetTabContents) {
1536 rect.adjust(- rect.left(), 0, rect.left(), 0);
1545 NoTabFrameMacStyle noTabFrameMacStyle;
1549 TabWorkArea::TabWorkArea(QWidget * parent)
1550 : QTabWidget(parent), clicked_tab_(-1), midpressed_tab_(-1)
1553 setStyle(&noTabFrameMacStyle);
1556 QPalette pal = palette();
1557 pal.setColor(QPalette::Active, QPalette::Button,
1558 pal.color(QPalette::Active, QPalette::Window));
1559 pal.setColor(QPalette::Disabled, QPalette::Button,
1560 pal.color(QPalette::Disabled, QPalette::Window));
1561 pal.setColor(QPalette::Inactive, QPalette::Button,
1562 pal.color(QPalette::Inactive, QPalette::Window));
1564 QObject::connect(this, SIGNAL(currentChanged(int)),
1565 this, SLOT(on_currentTabChanged(int)));
1567 closeBufferButton = new QToolButton(this);
1568 closeBufferButton->setPalette(pal);
1569 // FIXME: rename the icon to closebuffer.png
1570 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1571 closeBufferButton->setText("Close File");
1572 closeBufferButton->setAutoRaise(true);
1573 closeBufferButton->setCursor(Qt::ArrowCursor);
1574 closeBufferButton->setToolTip(qt_("Close File"));
1575 closeBufferButton->setEnabled(true);
1576 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1577 this, SLOT(closeCurrentBuffer()));
1578 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1580 // setup drag'n'drop
1581 QTabBar* tb = new DragTabBar;
1582 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1583 this, SLOT(moveTab(int, int)));
1584 tb->setElideMode(Qt::ElideNone);
1587 // make us responsible for the context menu of the tabbar
1588 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1589 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1590 this, SLOT(showContextMenu(const QPoint &)));
1591 connect(tb, SIGNAL(tabCloseRequested(int)),
1592 this, SLOT(closeTab(int)));
1594 setUsesScrollButtons(true);
1598 void TabWorkArea::mousePressEvent(QMouseEvent *me)
1600 if (me->button() == Qt::MidButton)
1601 midpressed_tab_ = tabBar()->tabAt(me->pos());
1603 QTabWidget::mousePressEvent(me);
1607 void TabWorkArea::mouseReleaseEvent(QMouseEvent *me)
1609 if (me->button() == Qt::MidButton) {
1610 int const midreleased_tab = tabBar()->tabAt(me->pos());
1611 if (midpressed_tab_ == midreleased_tab && posIsTab(me->pos()))
1612 closeTab(midreleased_tab);
1614 QTabWidget::mouseReleaseEvent(me);
1618 void TabWorkArea::paintEvent(QPaintEvent * event)
1620 if (tabBar()->isVisible()) {
1621 QTabWidget::paintEvent(event);
1623 // Prevent the selected tab to influence the
1624 // painting of the frame of the tab widget.
1625 // This is needed for gtk style in Qt.
1626 QStylePainter p(this);
1627 #if QT_VERSION < 0x050000
1628 QStyleOptionTabWidgetFrameV2 opt;
1630 QStyleOptionTabWidgetFrame opt;
1632 initStyleOption(&opt);
1633 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1635 opt.selectedTabRect = QRect();
1636 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1641 bool TabWorkArea::posIsTab(QPoint position)
1643 // tabAt returns -1 if tab does not covers position
1644 return tabBar()->tabAt(position) > -1;
1648 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1650 if (event->button() != Qt::LeftButton)
1653 // this code chunk is unnecessary because it seems the event only makes
1654 // it this far if it is not on a tab. I'm not sure why this is (maybe
1655 // it is handled and ended in DragTabBar?), and thus I'm not sure if
1656 // this is true in all cases and if it will be true in the future so I
1657 // leave this code for now. (skostysh, 2016-07-21)
1659 // return early if double click on existing tabs
1660 if (posIsTab(event->pos()))
1663 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1667 void TabWorkArea::setFullScreen(bool full_screen)
1669 for (int i = 0; i != count(); ++i) {
1670 if (GuiWorkArea * wa = workArea(i))
1671 wa->setFullScreen(full_screen);
1674 if (lyxrc.full_screen_tabbar)
1675 showBar(!full_screen && count() > 1);
1677 showBar(count() > 1);
1681 void TabWorkArea::showBar(bool show)
1683 tabBar()->setEnabled(show);
1684 tabBar()->setVisible(show);
1685 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1686 setTabsClosable(!lyxrc.single_close_tab_button);
1690 GuiWorkAreaContainer * TabWorkArea::widget(int index) const
1692 QWidget * w = QTabWidget::widget(index);
1695 GuiWorkAreaContainer * wac = dynamic_cast<GuiWorkAreaContainer *>(w);
1701 GuiWorkAreaContainer * TabWorkArea::currentWidget() const
1703 return widget(currentIndex());
1707 GuiWorkArea * TabWorkArea::workArea(int index) const
1709 GuiWorkAreaContainer * w = widget(index);
1712 return w->workArea();
1716 GuiWorkArea * TabWorkArea::currentWorkArea() const
1718 return workArea(currentIndex());
1722 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer) const
1724 // FIXME: this method doesn't work if we have more than one work area
1725 // showing the same buffer.
1726 for (int i = 0; i != count(); ++i) {
1727 GuiWorkArea * wa = workArea(i);
1728 LASSERT(wa, return 0);
1729 if (&wa->bufferView().buffer() == &buffer)
1736 void TabWorkArea::closeAll()
1739 QWidget * wac = widget(0);
1740 LASSERT(wac, return);
1747 int TabWorkArea::indexOfWorkArea(GuiWorkArea * w) const
1749 for (int index = 0; index < count(); ++index)
1750 if (workArea(index) == w)
1756 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1758 LASSERT(work_area, return false);
1759 int index = indexOfWorkArea(work_area);
1763 if (index == currentIndex())
1764 // Make sure the work area is up to date.
1765 on_currentTabChanged(index);
1767 // Switch to the work area.
1768 setCurrentIndex(index);
1769 work_area->setFocus();
1775 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1777 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1778 GuiWorkAreaContainer * wac = new GuiWorkAreaContainer(wa);
1779 wa->setUpdatesEnabled(false);
1780 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1781 // when hiding it again below).
1782 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1783 showBar(count() > 0);
1784 addTab(wac, wa->windowTitle());
1785 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1786 this, SLOT(updateTabTexts()));
1787 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1788 setFullScreen(true);
1790 // Hide tabbar if there's only one tab.
1791 showBar(count() > 1);
1799 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1801 LASSERT(work_area, return false);
1802 int index = indexOfWorkArea(work_area);
1806 work_area->setUpdatesEnabled(false);
1807 QWidget * wac = widget(index);
1812 // make sure the next work area is enabled.
1813 currentWidget()->setUpdatesEnabled(true);
1814 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1815 setFullScreen(true);
1817 // Show tabbar only if there's more than one tab.
1818 showBar(count() > 1);
1820 lastWorkAreaRemoved();
1828 void TabWorkArea::on_currentTabChanged(int i)
1830 // returns e.g. on application destruction
1833 GuiWorkArea * wa = workArea(i);
1834 LASSERT(wa, return);
1835 wa->setUpdatesEnabled(true);
1839 currentWorkAreaChanged(wa);
1841 LYXERR(Debug::GUI, "currentTabChanged " << i
1842 << " File: " << wa->bufferView().buffer().absFileName());
1846 void TabWorkArea::closeCurrentBuffer()
1849 if (clicked_tab_ == -1)
1850 wa = currentWorkArea();
1852 wa = workArea(clicked_tab_);
1853 LASSERT(wa, return);
1855 wa->view().closeWorkArea(wa);
1859 void TabWorkArea::hideCurrentTab()
1862 if (clicked_tab_ == -1)
1863 wa = currentWorkArea();
1865 wa = workArea(clicked_tab_);
1866 LASSERT(wa, return);
1868 wa->view().hideWorkArea(wa);
1872 void TabWorkArea::closeTab(int index)
1874 on_currentTabChanged(index);
1877 wa = currentWorkArea();
1879 wa = workArea(index);
1880 LASSERT(wa, return);
1882 wa->view().closeWorkArea(wa);
1889 /// make vector happy
1890 DisplayPath() : tab_(-1), dottedPrefix_(false) {}
1892 DisplayPath(int tab, FileName const & filename)
1895 filename_ = (filename.extension() == "lyx") ?
1896 toqstr(filename.onlyFileNameWithoutExt())
1897 : toqstr(filename.onlyFileName());
1898 postfix_ = toqstr(filename.absoluteFilePath()).
1899 split("/", QString::SkipEmptyParts);
1900 postfix_.pop_back();
1901 abs_ = toqstr(filename.absoluteFilePath());
1902 dottedPrefix_ = false;
1905 /// Absolute path for debugging.
1910 /// Add the first segment from the postfix or three dots to the prefix.
1911 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1912 /// when really needed.
1913 void shiftPathSegment(bool dotted)
1915 if (postfix_.count() <= 0)
1919 if (dottedPrefix_ && !prefix_.isEmpty())
1920 prefix_ += ellipsisSlash_;
1921 prefix_ += postfix_.front() + "/";
1923 dottedPrefix_ = dotted && !prefix_.isEmpty();
1924 postfix_.pop_front();
1927 QString displayString() const
1929 if (prefix_.isEmpty())
1932 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1933 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1936 QString forecastPathString() const
1938 if (postfix_.count() == 0)
1939 return displayString();
1942 + (dottedPrefix_ ? ellipsisSlash_ : "")
1943 + postfix_.front() + "/";
1946 bool final() const { return postfix_.empty(); }
1948 int tab() const { return tab_; }
1952 static QString const ellipsisSlash_;
1956 QStringList postfix_;
1968 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1972 bool operator<(DisplayPath const & a, DisplayPath const & b)
1974 return a.displayString() < b.displayString();
1978 bool operator==(DisplayPath const & a, DisplayPath const & b)
1980 return a.displayString() == b.displayString();
1984 void TabWorkArea::updateTabTexts()
1989 std::list<DisplayPath> paths;
1990 typedef std::list<DisplayPath>::iterator It;
1992 // collect full names first: path into postfix, empty prefix and
1993 // filename without extension
1994 for (size_t i = 0; i < n; ++i) {
1995 GuiWorkArea * i_wa = workArea(i);
1996 FileName const fn = i_wa->bufferView().buffer().fileName();
1997 paths.push_back(DisplayPath(i, fn));
2000 // go through path segments and see if it helps to make the path more unique
2001 bool somethingChanged = true;
2002 bool allFinal = false;
2003 while (somethingChanged && !allFinal) {
2004 // adding path segments changes order
2007 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
2008 somethingChanged = false;
2011 // find segments which are not unique (i.e. non-atomic)
2012 It it = paths.begin();
2014 QString segString = it->displayString();
2015 for (; it != paths.end(); ++it) {
2016 // look to the next item
2021 allFinal = allFinal && it->final();
2023 LYXERR(Debug::GUI, "it = " << it->abs()
2024 << " => " << it->displayString());
2026 // still the same segment?
2028 if ((next != paths.end()
2029 && (nextString = next->displayString()) == segString))
2031 LYXERR(Debug::GUI, "segment ended");
2033 // only a trivial one with one element?
2034 if (it == segStart) {
2035 // start new segment
2037 segString = nextString;
2041 // We found a non-atomic segment
2042 // We know that segStart <= it < next <= paths.end().
2043 // The assertion below tells coverity about it.
2044 LATTEST(segStart != paths.end());
2045 QString dspString = segStart->forecastPathString();
2046 LYXERR(Debug::GUI, "first forecast found for "
2047 << segStart->abs() << " => " << dspString);
2050 // Shift path segments and hope for the best
2051 // that it makes the path more unique.
2052 somethingChanged = true;
2053 bool moreUnique = false;
2054 for (; sit != next; ++sit) {
2055 if (sit->forecastPathString() != dspString) {
2056 LYXERR(Debug::GUI, "different forecast found for "
2057 << sit->abs() << " => " << sit->forecastPathString());
2061 LYXERR(Debug::GUI, "same forecast found for "
2062 << sit->abs() << " => " << dspString);
2065 // if the path segment helped, add it. Otherwise add dots
2066 bool dots = !moreUnique;
2067 LYXERR(Debug::GUI, "using dots = " << dots);
2068 for (sit = segStart; sit != next; ++sit) {
2069 sit->shiftPathSegment(dots);
2070 LYXERR(Debug::GUI, "shifting "
2071 << sit->abs() << " => " << sit->displayString());
2074 // start new segment
2076 segString = nextString;
2080 // set new tab titles
2081 for (It it = paths.begin(); it != paths.end(); ++it) {
2082 int const tab_index = it->tab();
2083 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2084 QString tab_text = it->displayString().replace("&", "&&");
2085 if (!buf.fileName().empty() && !buf.isClean())
2087 QString tab_tooltip = it->abs();
2088 if (buf.hasReadonlyFlag()) {
2089 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2090 tab_tooltip = qt_("%1 (read only)").arg(tab_tooltip);
2092 setTabIcon(tab_index, QIcon());
2093 if (buf.notifiesExternalModification()) {
2094 QString const warn = qt_("%1 (modified externally)");
2095 tab_tooltip = warn.arg(tab_tooltip);
2096 tab_text += QChar(0x26a0);
2098 setTabText(tab_index, tab_text);
2099 setTabToolTip(tab_index, tab_tooltip);
2104 void TabWorkArea::showContextMenu(const QPoint & pos)
2107 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
2108 if (clicked_tab_ == -1)
2113 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2114 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2115 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2116 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2117 popup.exec(tabBar()->mapToGlobal(pos));
2123 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2125 QWidget * w = widget(fromIndex);
2126 QIcon icon = tabIcon(fromIndex);
2127 QString text = tabText(fromIndex);
2129 setCurrentIndex(fromIndex);
2130 removeTab(fromIndex);
2131 insertTab(toIndex, w, icon, text);
2132 setCurrentIndex(toIndex);
2136 DragTabBar::DragTabBar(QWidget* parent)
2139 setAcceptDrops(true);
2140 setTabsClosable(!lyxrc.single_close_tab_button);
2144 void DragTabBar::mousePressEvent(QMouseEvent * event)
2146 if (event->button() == Qt::LeftButton)
2147 dragStartPos_ = event->pos();
2148 QTabBar::mousePressEvent(event);
2152 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2154 // If the left button isn't pressed anymore then return
2155 if (!(event->buttons() & Qt::LeftButton))
2158 // If the distance is too small then return
2159 if ((event->pos() - dragStartPos_).manhattanLength()
2160 < QApplication::startDragDistance())
2163 // did we hit something after all?
2164 int tab = tabAt(dragStartPos_);
2168 // simulate button release to remove highlight from button
2169 int i = currentIndex();
2170 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2171 event->button(), event->buttons(), 0);
2172 QTabBar::mouseReleaseEvent(&me);
2176 QDrag * drag = new QDrag(this);
2177 QMimeData * mimeData = new QMimeData;
2178 // a crude way to distinguish tab-reodering drops from other ones
2179 mimeData->setData("action", "tab-reordering") ;
2180 drag->setMimeData(mimeData);
2182 // get tab pixmap as cursor
2183 QRect r = tabRect(tab);
2184 QPixmap pixmap(r.size());
2185 render(&pixmap, - r.topLeft());
2186 drag->setPixmap(pixmap);
2191 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2193 // Only accept if it's an tab-reordering request
2194 QMimeData const * m = event->mimeData();
2195 QStringList formats = m->formats();
2196 if (formats.contains("action")
2197 && m->data("action") == "tab-reordering")
2198 event->acceptProposedAction();
2202 void DragTabBar::dropEvent(QDropEvent * event)
2204 int fromIndex = tabAt(dragStartPos_);
2205 int toIndex = tabAt(event->pos());
2207 // Tell interested objects that
2208 if (fromIndex != toIndex)
2209 tabMoveRequested(fromIndex, toIndex);
2210 event->acceptProposedAction();
2214 GuiWorkAreaContainer::GuiWorkAreaContainer(GuiWorkArea * wa, QWidget * parent)
2215 : QWidget(parent), wa_(wa)
2217 LASSERT(wa, return);
2218 Ui::WorkAreaUi::setupUi(this);
2219 layout()->addWidget(wa);
2220 connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
2221 this, SLOT(updateDisplay()));
2222 connect(reloadPB, SIGNAL(clicked()), this, SLOT(reload()));
2223 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
2224 setMessageColour({notificationFrame}, {reloadPB, ignorePB});
2229 void GuiWorkAreaContainer::updateDisplay()
2231 Buffer const & buf = wa_->bufferView().buffer();
2232 notificationFrame->setHidden(!buf.notifiesExternalModification());
2233 QString const label = qt_("<b>The file %1 changed on disk.</b>")
2234 .arg(toqstr(buf.fileName().displayName()));
2235 externalModificationLabel->setText(label);
2239 void GuiWorkAreaContainer::dispatch(FuncRequest f) const
2241 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
2242 wa_->bufferView().buffer().absFileName()));
2247 void GuiWorkAreaContainer::reload() const
2249 dispatch(FuncRequest(LFUN_BUFFER_RELOAD));
2253 void GuiWorkAreaContainer::ignore() const
2255 dispatch(FuncRequest(LFUN_BUFFER_EXTERNAL_MODIFICATION_CLEAR));
2259 void GuiWorkAreaContainer::mouseDoubleClickEvent(QMouseEvent * event)
2261 // prevent TabWorkArea from opening a new buffer on double click
2266 } // namespace frontend
2269 #include "moc_GuiWorkArea.cpp"