2 * \file GuiWorkArea.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Abdelrazak Younes
9 * Full author contact details are available in file CREDITS.
14 #include "GuiWorkArea.h"
15 #include "GuiWorkArea_Private.h"
17 #include "ColorCache.h"
18 #include "FontLoader.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "CoordCache.h"
28 #include "FuncRequest.h"
29 #include "GuiApplication.h"
30 #include "GuiCompleter.h"
31 #include "GuiKeySymbol.h"
32 #include "GuiPainter.h"
34 #include "KeySymbol.h"
39 #include "qt_helpers.h"
41 #include "TextMetrics.h"
44 #include "graphics/GraphicsImage.h"
45 #include "graphics/GraphicsLoader.h"
47 #include "support/convert.h"
48 #include "support/debug.h"
49 #include "support/gettext.h"
50 #include "support/FileName.h"
51 #include "support/lassert.h"
52 #include "support/TempFile.h"
54 #include "frontends/Application.h"
55 #include "frontends/FontMetrics.h"
56 #include "frontends/WorkAreaManager.h"
58 #include <QContextMenuEvent>
59 #if (QT_VERSION < 0x050000)
60 #include <QInputContext>
65 #include <QProxyStyle>
67 #include <QMainWindow>
72 #include <QPixmapCache>
74 #include <QStyleOption>
75 #include <QStylePainter>
77 #include <QToolButton>
81 #include "support/bind.h"
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;
139 void draw(QPainter & painter)
141 if (!show_ || !rect_.isValid())
145 int l = x_ - rect_.left();
146 int r = rect_.right() - x_;
147 int bot = rect_.bottom();
149 // draw vertical line
150 painter.fillRect(x_, y, cursor_width_, rect_.height(), color_);
152 // draw RTL/LTR indication
153 painter.setPen(color_);
156 painter.drawLine(x_, bot, x_ - l, bot);
158 painter.drawLine(x_, bot, x_ + cursor_width_ + r, bot);
161 // draw completion triangle
163 int m = y + rect_.height() / 2;
164 int d = TabIndicatorWidth - 1;
166 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
167 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
169 painter.drawLine(x_ + cursor_width_, m - d, x_ + cursor_width_ + d, m);
170 painter.drawLine(x_ + cursor_width_, m + d, x_ + cursor_width_ + d, m);
175 void update(int x, int y, int h, bool l_shape,
176 bool rtl, bool completable)
178 color_ = guiApp->colorCache().get(Color_cursor);
181 completable_ = completable;
184 // extension to left and right
188 // RTL/LTR indication
196 // completion triangle
199 l = max(l, TabIndicatorWidth);
201 r = max(r, TabIndicatorWidth);
204 // compute overall rectangle
205 rect_ = QRect(x - l, y, cursor_width_ + r + l, h);
208 void show(bool set_show = true) { show_ = set_show; }
209 void hide() { show_ = false; }
210 int cursorWidth() const { return cursor_width_; }
211 void recomputeWidth() {
212 cursor_width_ = lyxrc.cursor_width
214 : 1 + int((lyxrc.zoom + 50) / 200.0);
217 QRect const & rect() { return rect_; }
220 /// cursor is in RTL or LTR text
222 /// indication for RTL or LTR
224 /// triangle to show that a completion is available
230 /// rectangle, possibly with l_shape and completion triangle
232 /// x position (were the vertical line is drawn)
239 // This is a 'heartbeat' generating synthetic mouse move events when the
240 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
241 SyntheticMouseEvent::SyntheticMouseEvent()
242 : timeout(200), restart_timeout(true)
246 GuiWorkArea::Private::Private(GuiWorkArea * parent)
247 : p(parent), screen_(0), buffer_view_(0), lyx_view_(0), cursor_visible_(false),
248 need_resize_(false), schedule_redraw_(false), preedit_lines_(1),
250 completer_(new GuiCompleter(p, p))
255 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
256 : d(new Private(this))
261 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
262 : d(new Private(this))
270 double GuiWorkArea::pixelRatio() const
272 #if QT_VERSION > 0x050000
273 return devicePixelRatio();
280 void GuiWorkArea::init()
283 connect(&d->cursor_timeout_, SIGNAL(timeout()),
284 this, SLOT(toggleCursor()));
286 int const time = QApplication::cursorFlashTime() / 2;
288 d->cursor_timeout_.setInterval(time);
289 d->cursor_timeout_.start();
291 // let's initialize this just to be safe
292 d->cursor_timeout_.setInterval(500);
296 // With Qt4.5 a mouse event will happen before the first paint event
297 // so make sure that the buffer view has an up to date metrics.
298 d->buffer_view_->resize(viewport()->width(), viewport()->height());
299 d->cursor_ = new frontend::CursorWidget();
302 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
303 setAcceptDrops(true);
304 setMouseTracking(true);
305 setMinimumSize(100, 70);
306 setFrameStyle(QFrame::NoFrame);
309 viewport()->setAutoFillBackground(false);
310 // We don't need double-buffering nor SystemBackground on
311 // the viewport because we have our own backing pixmap.
312 viewport()->setAttribute(Qt::WA_NoSystemBackground);
314 setFocusPolicy(Qt::StrongFocus);
316 d->setCursorShape(Qt::IBeamCursor);
318 d->synthetic_mouse_event_.timeout.timeout.connect(
319 bind(&GuiWorkArea::generateSyntheticMouseEvent,
322 // Initialize the vertical Scroll Bar
323 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
324 this, SLOT(scrollTo(int)));
326 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
327 << " viewport height: " << viewport()->height());
329 // Enables input methods for asian languages.
330 // Must be set when creating custom text editing widgets.
331 setAttribute(Qt::WA_InputMethodEnabled, true);
333 d->dialog_mode_ = false;
337 GuiWorkArea::~GuiWorkArea()
339 d->buffer_view_->buffer().workAreaManager().remove(this);
341 delete d->buffer_view_;
343 // Completer has a QObject parent and is thus automatically destroyed.
345 // delete completer_;
350 Qt::CursorShape GuiWorkArea::cursorShape() const
352 return viewport()->cursor().shape();
356 void GuiWorkArea::Private::setCursorShape(Qt::CursorShape shape)
358 p->viewport()->setCursor(shape);
362 void GuiWorkArea::Private::updateCursorShape()
364 setCursorShape(buffer_view_->clickableInset()
365 ? Qt::PointingHandCursor : Qt::IBeamCursor);
369 void GuiWorkArea::setGuiView(GuiView & gv)
375 void GuiWorkArea::setBuffer(Buffer & buffer)
377 delete d->buffer_view_;
378 d->buffer_view_ = new BufferView(buffer);
379 buffer.workAreaManager().add(this);
381 // HACK: Prevents an additional redraw when the scrollbar pops up
382 // which regularily happens on documents with more than one page.
383 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
384 // Since we have no geometry information yet, we assume that
385 // a document needs a scrollbar if there is more then four
386 // paragraph in the outermost text.
387 if (buffer.text().paragraphs().size() > 4)
388 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
389 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
393 void GuiWorkArea::fixVerticalScrollBar()
396 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
400 void GuiWorkArea::close()
402 d->lyx_view_->removeWorkArea(this);
406 void GuiWorkArea::setFullScreen(bool full_screen)
408 d->buffer_view_->setFullScreen(full_screen);
409 setFrameStyle(QFrame::NoFrame);
411 setFrameStyle(QFrame::NoFrame);
412 if (lyxrc.full_screen_scrollbar)
413 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
415 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
419 BufferView & GuiWorkArea::bufferView()
421 return *d->buffer_view_;
425 BufferView const & GuiWorkArea::bufferView() const
427 return *d->buffer_view_;
431 void GuiWorkArea::stopBlinkingCursor()
433 d->cursor_timeout_.stop();
438 void GuiWorkArea::startBlinkingCursor()
440 // do not show the cursor if the view is busy
446 d->buffer_view_->cursorPosAndHeight(p, h);
447 // Don't start blinking if the cursor isn't on screen.
448 if (!d->buffer_view_->cursorInView(p, h))
453 //we're not supposed to cache this value.
454 int const time = QApplication::cursorFlashTime() / 2;
457 d->cursor_timeout_.setInterval(time);
458 d->cursor_timeout_.start();
462 void GuiWorkArea::redraw(bool update_metrics)
465 // No need to redraw in this case.
468 // No need to do anything if this is the current view. The BufferView
469 // metrics are already up to date.
470 if (update_metrics || d->lyx_view_ != guiApp->currentView()
471 || d->lyx_view_->currentWorkArea() != this) {
472 // FIXME: it would be nice to optimize for the off-screen case.
473 d->buffer_view_->cursor().fixIfBroken();
474 d->buffer_view_->updateMetrics();
475 d->buffer_view_->cursor().fixIfBroken();
478 // update cursor position, because otherwise it has to wait until
479 // the blinking interval is over
480 if (d->cursor_visible_) {
485 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
487 update(0, 0, viewport()->width(), viewport()->height());
489 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
490 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
491 d->updateScrollbar();
492 d->lyx_view_->updateStatusBar();
494 if (lyxerr.debugging(Debug::WORKAREA))
495 d->buffer_view_->coordCache().dump();
499 d->updateCursorShape();
503 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
505 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
506 && lyxrc.full_screen_menubar) {
507 // FIXME HACK: we should not have to do this here. See related comment
508 // in GuiView::event() (QEvent::ShortcutOverride)
509 d->lyx_view_->menuBar()->hide();
512 // In order to avoid bad surprise in the middle of an operation,
513 // we better stop the blinking cursor...
514 // the cursor gets restarted in GuiView::restartCursor()
515 stopBlinkingCursor();
516 guiApp->processKeySym(key, mod);
520 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd0, KeyModifier mod)
523 if (cmd0.action() == LFUN_FILE_OPEN) {
525 lyx_view_->dispatch(cmd0, dr);
531 if (cmd0.action() == LFUN_MOUSE_PRESS) {
532 if (mod == ShiftModifier)
533 cmd = FuncRequest(cmd0, "region-select");
534 else if (mod == ControlModifier)
535 cmd = FuncRequest(cmd0, "paragraph-select");
542 bool const notJustMovingTheMouse =
543 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
545 // In order to avoid bad surprise in the middle of an operation, we better stop
546 // the blinking cursor.
547 if (notJustMovingTheMouse)
548 p->stopBlinkingCursor();
550 buffer_view_->mouseEventDispatch(cmd);
552 // Skip these when selecting
553 // FIXME: let GuiView take care of those.
554 if (cmd.action() != LFUN_MOUSE_MOTION) {
555 completer_->updateVisibility(false, false);
556 lyx_view_->updateDialogs();
557 lyx_view_->updateStatusBar();
560 // GUI tweaks except with mouse motion with no button pressed.
561 if (notJustMovingTheMouse) {
562 // Slight hack: this is only called currently when we
563 // clicked somewhere, so we force through the display
564 // of the new status here.
565 // FIXME: let GuiView take care of those.
566 lyx_view_->clearMessage();
568 // Show the cursor immediately after any operation
569 p->startBlinkingCursor();
576 void GuiWorkArea::Private::resizeBufferView()
578 // WARNING: Please don't put any code that will trigger a repaint here!
579 // We are already inside a paint event.
580 p->stopBlinkingCursor();
581 // Warn our container (GuiView).
586 buffer_view_->cursorPosAndHeight(point, h);
587 bool const cursor_in_view = buffer_view_->cursorInView(point, h);
588 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
590 buffer_view_->scrollToCursor();
593 // Update scrollbars which might have changed due different
594 // BufferView dimension. This is especially important when the
595 // BufferView goes from zero-size to the real-size for the first time,
596 // as the scrollbar paramters are then set for the first time.
599 need_resize_ = false;
601 // Eventually, restart the cursor after the resize event.
602 // We might be resizing even if the focus is on another widget so we only
603 // restart the cursor if we have the focus.
605 QTimer::singleShot(50, p, SLOT(startBlinkingCursor()));
609 void GuiWorkArea::Private::showCursor()
616 buffer_view_->cursorPosAndHeight(p, h);
617 if (!buffer_view_->cursorInView(p, h))
621 bool l_shape = false;
622 Font const & realfont = buffer_view_->cursor().real_current_font;
623 BufferParams const & bp = buffer_view_->buffer().params();
624 bool const samelang = realfont.language() == bp.language;
625 bool const isrtl = realfont.isVisibleRightToLeft();
627 if (!samelang || isrtl != bp.language->rightToLeft())
630 // The ERT language hack needs fixing up
631 if (realfont.language() == latex_language)
634 // show cursor on screen
635 Cursor & cur = buffer_view_->cursor();
636 bool completable = cur.inset().showCompletionCursor()
637 && completer_->completionAvailable()
638 && !completer_->popupVisible()
639 && !completer_->inlineVisible();
640 cursor_visible_ = true;
641 cursor_->recomputeWidth();
642 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
646 void GuiWorkArea::Private::hideCursor()
648 if (!cursor_visible_)
651 cursor_visible_ = false;
656 void GuiWorkArea::toggleCursor()
658 if (d->cursor_visible_)
665 void GuiWorkArea::Private::updateScrollbar()
667 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
668 // WARNING: don't touch at the scrollbar value like this:
669 // verticalScrollBar()->setValue(scroll_.position);
670 // because this would cause a recursive signal/slot calling with
671 // GuiWorkArea::scrollTo
672 p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
673 p->verticalScrollBar()->setPageStep(scroll_.page_step);
674 p->verticalScrollBar()->setSingleStep(scroll_.single_step);
675 p->verticalScrollBar()->setSliderPosition(scroll_.position);
679 void GuiWorkArea::scrollTo(int value)
681 stopBlinkingCursor();
682 d->buffer_view_->scrollDocView(value, true);
684 if (lyxrc.cursor_follows_scrollbar) {
685 d->buffer_view_->setCursorFromScrollbar();
686 // FIXME: let GuiView take care of those.
687 d->lyx_view_->updateLayoutList();
689 // Show the cursor immediately after any operation.
690 startBlinkingCursor();
692 QApplication::syncX();
697 bool GuiWorkArea::event(QEvent * e)
700 case QEvent::ToolTip: {
701 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
702 if (lyxrc.use_tooltip) {
703 QPoint pos = helpEvent->pos();
704 if (pos.x() < viewport()->width()) {
705 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
706 QToolTip::showText(helpEvent->globalPos(), s);
709 QToolTip::hideText();
711 // Don't forget to accept the event!
716 case QEvent::ShortcutOverride: {
717 // We catch this event in order to catch the Tab or Shift+Tab key press
718 // which are otherwise reserved to focus switching between controls
720 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
721 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
722 || (ke->key() == Qt::Key_Backtab && (
723 ke->modifiers() == Qt::ShiftModifier
724 || ke->modifiers() == Qt::NoModifier))) {
728 return QAbstractScrollArea::event(e);
732 return QAbstractScrollArea::event(e);
738 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
741 if (e->reason() == QContextMenuEvent::Mouse)
742 // the menu name is set on mouse press
743 name = d->context_menu_name_;
745 QPoint pos = e->pos();
746 Cursor const & cur = d->buffer_view_->cursor();
747 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
748 // Do not access the context menu of math right in front of before
749 // the cursor. This does not work when the cursor is in text.
750 Inset * inset = cur.paragraph().getInset(cur.pos());
751 if (inset && inset->asInsetMath())
753 else if (cur.pos() > 0) {
754 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
759 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
763 QAbstractScrollArea::contextMenuEvent(e);
766 // always show mnemonics when the keyboard is used to show the context menu
767 // FIXME: This should be fixed in Qt itself
768 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
769 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
771 QAbstractScrollArea::contextMenuEvent(e);
774 // Position the menu to the right.
775 // FIXME: menu position should be different for RTL text.
776 menu->exec(e->globalPos());
781 void GuiWorkArea::focusInEvent(QFocusEvent * e)
783 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
784 if (d->lyx_view_->currentWorkArea() != this) {
785 d->lyx_view_->setCurrentWorkArea(this);
786 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
789 startBlinkingCursor();
790 QAbstractScrollArea::focusInEvent(e);
794 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
796 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
797 stopBlinkingCursor();
798 QAbstractScrollArea::focusOutEvent(e);
802 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
804 if (d->dc_event_.active && d->dc_event_ == *e) {
805 d->dc_event_.active = false;
806 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
807 q_button_state(e->button()));
813 #if (QT_VERSION < 0x050000)
814 inputContext()->reset();
817 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
818 q_button_state(e->button()));
819 d->dispatch(cmd, q_key_state(e->modifiers()));
821 // Save the context menu on mouse press, because also the mouse
822 // cursor is set on mouse press. Afterwards, we can either release
823 // the mousebutton somewhere else, or the cursor might have moved
824 // due to the DEPM. We need to do this after the mouse has been
825 // set in dispatch(), because the selection state might change.
826 if (e->button() == Qt::RightButton)
827 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
833 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
835 if (d->synthetic_mouse_event_.timeout.running())
836 d->synthetic_mouse_event_.timeout.stop();
838 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
839 q_button_state(e->button()));
845 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
847 // we kill the triple click if we move
848 doubleClickTimeout();
849 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
850 q_motion_state(e->buttons()));
854 // If we're above or below the work area...
855 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
856 && e->buttons() == mouse_button::button1) {
857 // Make sure only a synthetic event can cause a page scroll,
858 // so they come at a steady rate:
860 // _Force_ a scroll up:
861 cmd.set_y(e->y() - 21);
863 cmd.set_y(e->y() + 21);
864 // Store the event, to be handled when the timeout expires.
865 d->synthetic_mouse_event_.cmd = cmd;
867 if (d->synthetic_mouse_event_.timeout.running()) {
868 // Discard the event. Note that it _may_ be handled
869 // when the timeout expires if
870 // synthetic_mouse_event_.cmd has not been overwritten.
871 // Ie, when the timeout expires, we handle the
872 // most recent event but discard all others that
873 // occurred after the one used to start the timeout
874 // in the first place.
878 d->synthetic_mouse_event_.restart_timeout = true;
879 d->synthetic_mouse_event_.timeout.start();
880 // Fall through to handle this event...
882 } else if (d->synthetic_mouse_event_.timeout.running()) {
883 // Store the event, to be possibly handled when the timeout
885 // Once the timeout has expired, normal control is returned
886 // to mouseMoveEvent (restart_timeout = false).
887 // This results in a much smoother 'feel' when moving the
888 // mouse back into the work area.
889 d->synthetic_mouse_event_.cmd = cmd;
890 d->synthetic_mouse_event_.restart_timeout = false;
897 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
899 // Wheel rotation by one notch results in a delta() of 120 (see
900 // documentation of QWheelEvent)
901 double const delta = ev->delta() / 120.0;
903 switch (lyxrc.scroll_wheel_zoom) {
904 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
905 zoom = ev->modifiers() & Qt::ControlModifier;
906 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
908 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
909 zoom = ev->modifiers() & Qt::ShiftModifier;
910 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
912 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
913 zoom = ev->modifiers() & Qt::AltModifier;
914 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
916 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
920 docstring arg = convert<docstring>(int(5 * delta));
921 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
925 // Take into account the desktop wide settings.
926 int const lines = qApp->wheelScrollLines();
927 int const page_step = verticalScrollBar()->pageStep();
928 // Test if the wheel mouse is set to one screen at a time.
929 int scroll_value = lines > page_step
930 ? page_step : lines * verticalScrollBar()->singleStep();
932 // Take into account the rotation and the user preferences.
933 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
934 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
935 << " delta = " << delta << " scroll_value = " << scroll_value
936 << " page_step = " << page_step);
938 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
944 void GuiWorkArea::generateSyntheticMouseEvent()
946 int const e_y = d->synthetic_mouse_event_.cmd.y();
947 int const wh = d->buffer_view_->workHeight();
948 bool const up = e_y < 0;
949 bool const down = e_y > wh;
951 // Set things off to generate the _next_ 'pseudo' event.
953 if (d->synthetic_mouse_event_.restart_timeout) {
954 // This is some magic formulae to determine the speed
955 // of scrolling related to the position of the mouse.
958 int dist = up ? -e_y : e_y - wh;
959 time = max(min(200, 250000 / (dist * dist)), 1) ;
962 step = 80000 / (time * time);
966 d->synthetic_mouse_event_.timeout.setTimeout(time);
967 d->synthetic_mouse_event_.timeout.start();
970 // Can we scroll further ?
971 int const value = verticalScrollBar()->value();
972 if (value == verticalScrollBar()->maximum()
973 || value == verticalScrollBar()->minimum()) {
974 d->synthetic_mouse_event_.timeout.stop();
979 if (step <= 2 * wh) {
980 d->buffer_view_->scroll(up ? -step : step);
981 d->buffer_view_->updateMetrics();
983 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
986 // In which paragraph do we have to set the cursor ?
987 Cursor & cur = d->buffer_view_->cursor();
988 // FIXME: we don't know howto handle math.
989 Text * text = cur.text();
992 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
994 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
995 ParagraphMetrics const & pm = *pp.second;
996 pit_type const pit = pp.first;
998 if (pm.rows().empty())
1001 // Find the row at which we set the cursor.
1002 RowList::const_iterator rit = pm.rows().begin();
1003 RowList::const_iterator rlast = pm.rows().end();
1004 int yy = pm.position() - pm.ascent();
1005 for (--rlast; rit != rlast; ++rit) {
1006 int h = rit->height();
1007 if ((up && yy + h > 0)
1008 || (!up && yy + h > wh - defaultRowHeight()))
1013 // Find the position of the cursor
1015 int x = d->synthetic_mouse_event_.cmd.x();
1016 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1021 cur.boundary(bound);
1023 d->buffer_view_->buffer().changed(false);
1028 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1030 // Do not process here some keys if dialog_mode_ is set
1032 && (ev->modifiers() == Qt::NoModifier
1033 || ev->modifiers() == Qt::ShiftModifier)
1034 && (ev->key() == Qt::Key_Escape
1035 || ev->key() == Qt::Key_Enter
1036 || ev->key() == Qt::Key_Return)
1042 // intercept some keys if completion popup is visible
1043 if (d->completer_->popupVisible()) {
1044 switch (ev->key()) {
1046 case Qt::Key_Return:
1047 d->completer_->activate();
1053 // do nothing if there are other events
1054 // (the auto repeated events come too fast)
1055 // it looks like this is only needed on X11
1057 if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1058 switch (ev->key()) {
1059 case Qt::Key_PageDown:
1060 case Qt::Key_PageUp:
1065 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1072 KeyModifier m = q_key_state(ev->modifiers());
1075 if (m & ShiftModifier)
1077 if (m & ControlModifier)
1079 if (m & AltModifier)
1081 if (m & MetaModifier)
1084 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1085 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1086 << " keyState: " << str);
1089 setKeySymbol(&sym, ev);
1091 processKeySym(sym, q_key_state(ev->modifiers()));
1099 void GuiWorkArea::doubleClickTimeout()
1101 d->dc_event_.active = false;
1105 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1107 d->dc_event_ = DoubleClick(ev);
1108 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1109 SLOT(doubleClickTimeout()));
1110 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1112 q_button_state(ev->button()));
1118 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1120 QAbstractScrollArea::resizeEvent(ev);
1121 d->need_resize_ = true;
1126 void GuiWorkArea::Private::update(int x, int y, int w, int h)
1128 p->viewport()->update(x, y, w, h);
1132 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1134 QRectF const rc = ev->rect();
1135 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1136 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1138 if (d->needResize()) {
1140 d->resizeBufferView();
1141 if (d->cursor_visible_) {
1147 QPainter pain(viewport());
1148 double const pr = pixelRatio();
1149 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr, rc.width() * pr, rc.height() * pr);
1151 if (lyxrc.use_qimage) {
1152 QImage const & image = static_cast<QImage const &>(*d->screen_);
1153 pain.drawImage(rc, image, rcs);
1155 QPixmap const & pixmap = static_cast<QPixmap const &>(*d->screen_);
1156 pain.drawPixmap(rc, pixmap, rcs);
1158 d->cursor_->draw(pain);
1163 void GuiWorkArea::Private::updateScreen()
1165 GuiPainter pain(screen_, p->pixelRatio());
1166 buffer_view_->draw(pain);
1170 void GuiWorkArea::Private::showCursor(int x, int y, int h,
1171 bool l_shape, bool rtl, bool completable)
1173 if (schedule_redraw_) {
1174 // This happens when a graphic conversion is finished. As we don't know
1175 // the size of the new graphics, it's better the update everything.
1176 // We can't use redraw() here because this would trigger a infinite
1177 // recursive loop with showCursor().
1178 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
1181 p->viewport()->update(QRect(0, 0, p->viewport()->width(), p->viewport()->height()));
1182 schedule_redraw_ = false;
1183 // Show the cursor immediately after the update.
1189 cursor_->update(x, y, h, l_shape, rtl, completable);
1191 p->viewport()->update(cursor_->rect());
1195 void GuiWorkArea::Private::removeCursor()
1198 //if (!qApp->focusWidget())
1199 p->viewport()->update(cursor_->rect());
1203 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1205 QString const & commit_string = e->commitString();
1206 docstring const & preedit_string
1207 = qstring_to_ucs4(e->preeditString());
1209 if (!commit_string.isEmpty()) {
1211 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1212 << " commitString: " << e->commitString());
1216 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1217 for (int i = 0; i != commit_string.size(); ++i) {
1218 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1223 // Hide the cursor during the kana-kanji transformation.
1224 if (preedit_string.empty())
1225 startBlinkingCursor();
1227 stopBlinkingCursor();
1229 // last_width : for checking if last preedit string was/wasn't empty.
1231 // We could have more than one work area, right?
1232 static bool last_width = false;
1233 if (!last_width && preedit_string.empty()) {
1234 // if last_width is last length of preedit string.
1239 GuiPainter pain(d->screen_, pixelRatio());
1240 d->buffer_view_->updateMetrics();
1241 d->buffer_view_->draw(pain);
1242 FontInfo font = d->buffer_view_->cursor().getFont().fontInfo();
1243 FontMetrics const & fm = theFontMetrics(font);
1244 int height = fm.maxHeight();
1245 int cur_x = d->cursor_->rect().left();
1246 int cur_y = d->cursor_->rect().bottom();
1248 // redraw area of preedit string.
1249 update(0, cur_y - height, viewport()->width(),
1250 (height + 1) * d->preedit_lines_);
1252 if (preedit_string.empty()) {
1254 d->preedit_lines_ = 1;
1260 // att : stores an IM attribute.
1261 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1263 // get attributes of input method cursor.
1264 // cursor_pos : cursor position in preedit string.
1265 size_t cursor_pos = 0;
1266 bool cursor_is_visible = false;
1267 for (int i = 0; i != att.size(); ++i) {
1268 if (att.at(i).type == QInputMethodEvent::Cursor) {
1269 cursor_pos = att.at(i).start;
1270 cursor_is_visible = att.at(i).length != 0;
1275 size_t preedit_length = preedit_string.length();
1277 // get position of selection in input method.
1278 // FIXME: isn't there a way to do this simplier?
1279 // rStart : cursor position in selected string in IM.
1281 // rLength : selected string length in IM.
1283 if (cursor_pos < preedit_length) {
1284 for (int i = 0; i != att.size(); ++i) {
1285 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1286 if (att.at(i).start <= int(cursor_pos)
1287 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1288 rStart = att.at(i).start;
1289 rLength = att.at(i).length;
1290 if (!cursor_is_visible)
1291 cursor_pos += rLength;
1298 rStart = cursor_pos;
1302 int const right_margin = d->buffer_view_->rightMargin();
1303 Painter::preedit_style ps;
1304 // Most often there would be only one line:
1305 d->preedit_lines_ = 1;
1306 for (size_t pos = 0; pos != preedit_length; ++pos) {
1307 char_type const typed_char = preedit_string[pos];
1308 // reset preedit string style
1309 ps = Painter::preedit_default;
1311 // if we reached the right extremity of the screen, go to next line.
1312 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1313 cur_x = right_margin;
1314 cur_y += height + 1;
1315 ++d->preedit_lines_;
1317 // preedit strings are displayed with dashed underline
1318 // and partial strings are displayed white on black indicating
1319 // that we are in selecting mode in the input method.
1320 // FIXME: rLength == preedit_length is not a changing condition
1321 // FIXME: should be put out of the loop.
1323 && pos < rStart + rLength
1324 && !(cursor_pos < rLength && rLength == preedit_length))
1325 ps = Painter::preedit_selecting;
1327 if (pos == cursor_pos
1328 && (cursor_pos < rLength && rLength == preedit_length))
1329 ps = Painter::preedit_cursor;
1331 // draw one character and update cur_x.
1332 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1335 // update the preedit string screen area.
1336 update(0, cur_y - d->preedit_lines_*height, viewport()->width(),
1337 (height + 1) * d->preedit_lines_);
1339 // Don't forget to accept the event!
1344 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1346 QRect cur_r(0, 0, 0, 0);
1348 // this is the CJK-specific composition window position and
1349 // the context menu position when the menu key is pressed.
1350 case Qt::ImMicroFocus:
1351 cur_r = d->cursor_->rect();
1352 if (d->preedit_lines_ != 1)
1354 cur_r.moveBottom(cur_r.bottom()
1355 + cur_r.height() * (d->preedit_lines_ - 1));
1356 // return lower right of cursor in LyX.
1359 return QWidget::inputMethodQuery(query);
1364 void GuiWorkArea::updateWindowTitle()
1366 docstring maximize_title;
1367 docstring minimize_title;
1369 Buffer const & buf = d->buffer_view_->buffer();
1370 FileName const file_name = buf.fileName();
1371 if (!file_name.empty()) {
1372 maximize_title = file_name.displayName(130);
1373 minimize_title = from_utf8(file_name.onlyFileName());
1374 if (buf.lyxvc().inUse()) {
1375 if (buf.lyxvc().locking())
1376 maximize_title += _(" (version control, locking)");
1378 maximize_title += _(" (version control)");
1380 if (!buf.isClean()) {
1381 maximize_title += _(" (changed)");
1382 minimize_title += char_type('*');
1384 if (buf.isReadonly())
1385 maximize_title += _(" (read only)");
1388 QString const new_title = toqstr(maximize_title);
1389 if (new_title != windowTitle()) {
1390 QWidget::setWindowTitle(new_title);
1391 QWidget::setWindowIconText(toqstr(minimize_title));
1397 bool GuiWorkArea::isFullScreen() const
1399 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1403 void GuiWorkArea::scheduleRedraw()
1405 d->schedule_redraw_ = true;
1409 bool GuiWorkArea::inDialogMode() const
1411 return d->dialog_mode_;
1415 void GuiWorkArea::setDialogMode(bool mode)
1417 d->dialog_mode_ = mode;
1421 GuiCompleter & GuiWorkArea::completer()
1423 return *d->completer_;
1426 GuiView const & GuiWorkArea::view() const
1428 return *d->lyx_view_;
1432 GuiView & GuiWorkArea::view()
1434 return *d->lyx_view_;
1437 ////////////////////////////////////////////////////////////////////
1441 ////////////////////////////////////////////////////////////////////
1444 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1446 support::TempFile tempfile("embedded.internal");
1447 tempfile.setAutoRemove(false);
1448 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1449 buffer_->setUnnamed(true);
1450 buffer_->setFullyLoaded(true);
1451 setBuffer(*buffer_);
1452 setDialogMode(true);
1456 EmbeddedWorkArea::~EmbeddedWorkArea()
1458 // No need to destroy buffer and bufferview here, because it is done
1459 // in theBufferList() destruction loop at application exit
1463 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1466 GuiWorkArea::closeEvent(ev);
1470 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1473 GuiWorkArea::hideEvent(ev);
1477 QSize EmbeddedWorkArea::sizeHint () const
1480 // GuiWorkArea sets the size to the screen's viewport
1481 // by returning a value this gets overridden
1482 // EmbeddedWorkArea is now sized to fit in the layout
1483 // of the parent, and has a minimum size set in GuiWorkArea
1484 // which is what we return here
1485 return QSize(100, 70);
1489 void EmbeddedWorkArea::disable()
1491 stopBlinkingCursor();
1492 if (view().currentWorkArea() != this)
1494 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1495 // tolerates it and shows the background logo), what happens if
1496 // an EmbeddedWorkArea is closed after closing all document WAs
1497 view().setCurrentWorkArea(view().currentMainWorkArea());
1500 ////////////////////////////////////////////////////////////////////
1504 ////////////////////////////////////////////////////////////////////
1507 class NoTabFrameMacStyle : public QProxyStyle {
1510 QRect subElementRect(SubElement element, const QStyleOption * option,
1511 const QWidget * widget = 0) const
1513 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1514 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1516 // The Qt Mac style puts the contents into a 3 pixel wide box
1517 // which looks very ugly and not like other Mac applications.
1518 // Hence we remove this here, and moreover the 16 pixel round
1519 // frame above if the tab bar is hidden.
1520 if (element == QStyle::SE_TabWidgetTabContents) {
1521 rect.adjust(- rect.left(), 0, rect.left(), 0);
1530 NoTabFrameMacStyle noTabFrameMacStyle;
1534 TabWorkArea::TabWorkArea(QWidget * parent)
1535 : QTabWidget(parent), clicked_tab_(-1)
1538 setStyle(&noTabFrameMacStyle);
1541 QPalette pal = palette();
1542 pal.setColor(QPalette::Active, QPalette::Button,
1543 pal.color(QPalette::Active, QPalette::Window));
1544 pal.setColor(QPalette::Disabled, QPalette::Button,
1545 pal.color(QPalette::Disabled, QPalette::Window));
1546 pal.setColor(QPalette::Inactive, QPalette::Button,
1547 pal.color(QPalette::Inactive, QPalette::Window));
1549 QObject::connect(this, SIGNAL(currentChanged(int)),
1550 this, SLOT(on_currentTabChanged(int)));
1552 closeBufferButton = new QToolButton(this);
1553 closeBufferButton->setPalette(pal);
1554 // FIXME: rename the icon to closebuffer.png
1555 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1556 closeBufferButton->setText("Close File");
1557 closeBufferButton->setAutoRaise(true);
1558 closeBufferButton->setCursor(Qt::ArrowCursor);
1559 closeBufferButton->setToolTip(qt_("Close File"));
1560 closeBufferButton->setEnabled(true);
1561 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1562 this, SLOT(closeCurrentBuffer()));
1563 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1565 // setup drag'n'drop
1566 QTabBar* tb = new DragTabBar;
1567 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1568 this, SLOT(moveTab(int, int)));
1569 tb->setElideMode(Qt::ElideNone);
1572 // make us responsible for the context menu of the tabbar
1573 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1574 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1575 this, SLOT(showContextMenu(const QPoint &)));
1576 connect(tb, SIGNAL(tabCloseRequested(int)),
1577 this, SLOT(closeTab(int)));
1579 setUsesScrollButtons(true);
1583 void TabWorkArea::paintEvent(QPaintEvent * event)
1585 if (tabBar()->isVisible()) {
1586 QTabWidget::paintEvent(event);
1588 // Prevent the selected tab to influence the
1589 // painting of the frame of the tab widget.
1590 // This is needed for gtk style in Qt.
1591 QStylePainter p(this);
1592 #if QT_VERSION < 0x050000
1593 QStyleOptionTabWidgetFrameV2 opt;
1595 QStyleOptionTabWidgetFrame opt;
1597 initStyleOption(&opt);
1598 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1600 opt.selectedTabRect = QRect();
1601 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1606 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1608 if (event->button() != Qt::LeftButton)
1611 // return early if double click on existing tabs
1612 for (int i = 0; i < count(); ++i)
1613 if (tabBar()->tabRect(i).contains(event->pos()))
1616 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1620 void TabWorkArea::setFullScreen(bool full_screen)
1622 for (int i = 0; i != count(); ++i) {
1623 if (GuiWorkArea * wa = workArea(i))
1624 wa->setFullScreen(full_screen);
1627 if (lyxrc.full_screen_tabbar)
1628 showBar(!full_screen && count() > 1);
1630 showBar(count() > 1);
1634 void TabWorkArea::showBar(bool show)
1636 tabBar()->setEnabled(show);
1637 tabBar()->setVisible(show);
1638 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1639 setTabsClosable(!lyxrc.single_close_tab_button);
1643 GuiWorkArea * TabWorkArea::currentWorkArea()
1648 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1654 GuiWorkArea * TabWorkArea::workArea(int index)
1656 return dynamic_cast<GuiWorkArea *>(widget(index));
1660 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1662 // FIXME: this method doesn't work if we have more than work area
1663 // showing the same buffer.
1664 for (int i = 0; i != count(); ++i) {
1665 GuiWorkArea * wa = workArea(i);
1666 LASSERT(wa, return 0);
1667 if (&wa->bufferView().buffer() == &buffer)
1674 void TabWorkArea::closeAll()
1677 GuiWorkArea * wa = workArea(0);
1678 LASSERT(wa, return);
1685 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1687 LASSERT(work_area, return false);
1688 int index = indexOf(work_area);
1692 if (index == currentIndex())
1693 // Make sure the work area is up to date.
1694 on_currentTabChanged(index);
1696 // Switch to the work area.
1697 setCurrentIndex(index);
1698 work_area->setFocus();
1704 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1706 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1707 wa->setUpdatesEnabled(false);
1708 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1709 // when hiding it again below).
1710 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1711 showBar(count() > 0);
1712 addTab(wa, wa->windowTitle());
1713 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1714 this, SLOT(updateTabTexts()));
1715 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1716 setFullScreen(true);
1718 // Hide tabbar if there's only one tab.
1719 showBar(count() > 1);
1727 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1729 LASSERT(work_area, return false);
1730 int index = indexOf(work_area);
1734 work_area->setUpdatesEnabled(false);
1739 // make sure the next work area is enabled.
1740 currentWidget()->setUpdatesEnabled(true);
1741 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1742 setFullScreen(true);
1744 // Show tabbar only if there's more than one tab.
1745 showBar(count() > 1);
1747 lastWorkAreaRemoved();
1755 void TabWorkArea::on_currentTabChanged(int i)
1757 // returns e.g. on application destruction
1760 GuiWorkArea * wa = workArea(i);
1761 LASSERT(wa, return);
1762 wa->setUpdatesEnabled(true);
1766 currentWorkAreaChanged(wa);
1768 LYXERR(Debug::GUI, "currentTabChanged " << i
1769 << " File: " << wa->bufferView().buffer().absFileName());
1773 void TabWorkArea::closeCurrentBuffer()
1776 if (clicked_tab_ == -1)
1777 wa = currentWorkArea();
1779 wa = workArea(clicked_tab_);
1780 LASSERT(wa, return);
1782 wa->view().closeWorkArea(wa);
1786 void TabWorkArea::hideCurrentTab()
1789 if (clicked_tab_ == -1)
1790 wa = currentWorkArea();
1792 wa = workArea(clicked_tab_);
1793 LASSERT(wa, return);
1795 wa->view().hideWorkArea(wa);
1799 void TabWorkArea::closeTab(int index)
1801 on_currentTabChanged(index);
1804 wa = currentWorkArea();
1806 wa = workArea(index);
1807 LASSERT(wa, return);
1809 wa->view().closeWorkArea(wa);
1816 /// make vector happy
1819 DisplayPath(int tab, FileName const & filename)
1822 filename_ = (filename.extension() == "lyx") ?
1823 toqstr(filename.onlyFileNameWithoutExt())
1824 : toqstr(filename.onlyFileName());
1825 postfix_ = toqstr(filename.absoluteFilePath()).
1826 split("/", QString::SkipEmptyParts);
1827 postfix_.pop_back();
1828 abs_ = toqstr(filename.absoluteFilePath());
1829 dottedPrefix_ = false;
1832 /// Absolute path for debugging.
1837 /// Add the first segment from the postfix or three dots to the prefix.
1838 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1839 /// when really needed.
1840 void shiftPathSegment(bool dotted)
1842 if (postfix_.count() <= 0)
1846 if (dottedPrefix_ && !prefix_.isEmpty())
1848 prefix_ += postfix_.front() + "/";
1850 dottedPrefix_ = dotted && !prefix_.isEmpty();
1851 postfix_.pop_front();
1854 QString displayString() const
1856 if (prefix_.isEmpty())
1859 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1860 return prefix_ + (dots ? ".../" : "") + filename_;
1863 QString forecastPathString() const
1865 if (postfix_.count() == 0)
1866 return displayString();
1869 + (dottedPrefix_ ? ".../" : "")
1870 + postfix_.front() + "/";
1873 bool final() const { return postfix_.empty(); }
1875 int tab() const { return tab_; }
1881 QStringList postfix_;
1894 bool operator<(DisplayPath const & a, DisplayPath const & b)
1896 return a.displayString() < b.displayString();
1900 bool operator==(DisplayPath const & a, DisplayPath const & b)
1902 return a.displayString() == b.displayString();
1906 void TabWorkArea::updateTabTexts()
1911 std::list<DisplayPath> paths;
1912 typedef std::list<DisplayPath>::iterator It;
1914 // collect full names first: path into postfix, empty prefix and
1915 // filename without extension
1916 for (size_t i = 0; i < n; ++i) {
1917 GuiWorkArea * i_wa = workArea(i);
1918 FileName const fn = i_wa->bufferView().buffer().fileName();
1919 paths.push_back(DisplayPath(i, fn));
1922 // go through path segments and see if it helps to make the path more unique
1923 bool somethingChanged = true;
1924 bool allFinal = false;
1925 while (somethingChanged && !allFinal) {
1926 // adding path segments changes order
1929 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1930 somethingChanged = false;
1933 // find segments which are not unique (i.e. non-atomic)
1934 It it = paths.begin();
1936 QString segString = it->displayString();
1937 for (; it != paths.end(); ++it) {
1938 // look to the next item
1943 allFinal = allFinal && it->final();
1945 LYXERR(Debug::GUI, "it = " << it->abs()
1946 << " => " << it->displayString());
1948 // still the same segment?
1950 if ((next != paths.end()
1951 && (nextString = next->displayString()) == segString))
1953 LYXERR(Debug::GUI, "segment ended");
1955 // only a trivial one with one element?
1956 if (it == segStart) {
1957 // start new segment
1959 segString = nextString;
1963 // we found a non-atomic segment segStart <= sit <= it < next.
1964 // Shift path segments and hope for the best
1965 // that it makes the path more unique.
1966 somethingChanged = true;
1968 QString dspString = sit->forecastPathString();
1969 LYXERR(Debug::GUI, "first forecast found for "
1970 << sit->abs() << " => " << dspString);
1972 bool moreUnique = false;
1973 for (; sit != next; ++sit) {
1974 if (sit->forecastPathString() != dspString) {
1975 LYXERR(Debug::GUI, "different forecast found for "
1976 << sit->abs() << " => " << sit->forecastPathString());
1980 LYXERR(Debug::GUI, "same forecast found for "
1981 << sit->abs() << " => " << dspString);
1984 // if the path segment helped, add it. Otherwise add dots
1985 bool dots = !moreUnique;
1986 LYXERR(Debug::GUI, "using dots = " << dots);
1987 for (sit = segStart; sit != next; ++sit) {
1988 sit->shiftPathSegment(dots);
1989 LYXERR(Debug::GUI, "shifting "
1990 << sit->abs() << " => " << sit->displayString());
1993 // start new segment
1995 segString = nextString;
1999 // set new tab titles
2000 for (It it = paths.begin(); it != paths.end(); ++it) {
2001 int const tab_index = it->tab();
2002 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2003 QString tab_text = it->displayString().replace("&", "&&");
2004 if (!buf.fileName().empty() && !buf.isClean())
2006 setTabText(tab_index, tab_text);
2007 setTabToolTip(tab_index, it->abs());
2012 void TabWorkArea::showContextMenu(const QPoint & pos)
2015 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
2016 if (clicked_tab_ == -1)
2021 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
2022 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2023 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
2024 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2025 popup.exec(tabBar()->mapToGlobal(pos));
2031 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2033 QWidget * w = widget(fromIndex);
2034 QIcon icon = tabIcon(fromIndex);
2035 QString text = tabText(fromIndex);
2037 setCurrentIndex(fromIndex);
2038 removeTab(fromIndex);
2039 insertTab(toIndex, w, icon, text);
2040 setCurrentIndex(toIndex);
2044 DragTabBar::DragTabBar(QWidget* parent)
2047 setAcceptDrops(true);
2048 setTabsClosable(!lyxrc.single_close_tab_button);
2052 void DragTabBar::mousePressEvent(QMouseEvent * event)
2054 if (event->button() == Qt::LeftButton)
2055 dragStartPos_ = event->pos();
2056 QTabBar::mousePressEvent(event);
2060 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2062 // If the left button isn't pressed anymore then return
2063 if (!(event->buttons() & Qt::LeftButton))
2066 // If the distance is too small then return
2067 if ((event->pos() - dragStartPos_).manhattanLength()
2068 < QApplication::startDragDistance())
2071 // did we hit something after all?
2072 int tab = tabAt(dragStartPos_);
2076 // simulate button release to remove highlight from button
2077 int i = currentIndex();
2078 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2079 event->button(), event->buttons(), 0);
2080 QTabBar::mouseReleaseEvent(&me);
2084 QDrag * drag = new QDrag(this);
2085 QMimeData * mimeData = new QMimeData;
2086 // a crude way to distinguish tab-reodering drops from other ones
2087 mimeData->setData("action", "tab-reordering") ;
2088 drag->setMimeData(mimeData);
2090 // get tab pixmap as cursor
2091 QRect r = tabRect(tab);
2092 QPixmap pixmap(r.size());
2093 render(&pixmap, - r.topLeft());
2094 drag->setPixmap(pixmap);
2099 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2101 // Only accept if it's an tab-reordering request
2102 QMimeData const * m = event->mimeData();
2103 QStringList formats = m->formats();
2104 if (formats.contains("action")
2105 && m->data("action") == "tab-reordering")
2106 event->acceptProposedAction();
2110 void DragTabBar::dropEvent(QDropEvent * event)
2112 int fromIndex = tabAt(dragStartPos_);
2113 int toIndex = tabAt(event->pos());
2115 // Tell interested objects that
2116 if (fromIndex != toIndex)
2117 tabMoveRequested(fromIndex, toIndex);
2118 event->acceptProposedAction();
2122 } // namespace frontend
2125 #include "moc_GuiWorkArea.cpp"