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"
53 #include "frontends/Application.h"
54 #include "frontends/FontMetrics.h"
55 #include "frontends/WorkAreaManager.h"
57 #include <QContextMenuEvent>
58 #include <QInputContext>
63 #include <QMainWindow>
67 #include <QPixmapCache>
70 #include <QToolButton>
74 #include "support/bind.h"
78 int const TabIndicatorWidth = 3;
84 using namespace lyx::support;
89 /// return the LyX mouse button state from Qt's
90 static mouse_button::state q_button_state(Qt::MouseButton button)
92 mouse_button::state b = mouse_button::none;
95 b = mouse_button::button1;
98 b = mouse_button::button2;
100 case Qt::RightButton:
101 b = mouse_button::button3;
110 /// return the LyX mouse button state from Qt's
111 mouse_button::state q_motion_state(Qt::MouseButtons state)
113 mouse_button::state b = mouse_button::none;
114 if (state & Qt::LeftButton)
115 b |= mouse_button::button1;
116 if (state & Qt::MidButton)
117 b |= mouse_button::button2;
118 if (state & Qt::RightButton)
119 b |= mouse_button::button3;
132 void draw(QPainter & painter)
134 if (!show_ || !rect_.isValid())
138 int l = x_ - rect_.left();
139 int r = rect_.right() - x_;
140 int bot = rect_.bottom();
142 // draw vertical line
143 painter.fillRect(x_, y, cursor_width_, rect_.height(), color_);
145 // draw RTL/LTR indication
146 painter.setPen(color_);
149 painter.drawLine(x_, bot, x_ - l, bot);
151 painter.drawLine(x_, bot, x_ + cursor_width_ + r, bot);
154 // draw completion triangle
156 int m = y + rect_.height() / 2;
157 int d = TabIndicatorWidth - 1;
159 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
160 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
162 painter.drawLine(x_ + cursor_width_, m - d, x_ + cursor_width_ + d, m);
163 painter.drawLine(x_ + cursor_width_, m + d, x_ + cursor_width_ + d, m);
168 void update(int x, int y, int h, bool l_shape,
169 bool rtl, bool completable)
171 color_ = guiApp->colorCache().get(Color_cursor);
174 completable_ = completable;
177 // extension to left and right
181 // RTL/LTR indication
189 // completion triangle
192 l = max(l, TabIndicatorWidth);
194 r = max(r, TabIndicatorWidth);
197 // compute overall rectangle
198 rect_ = QRect(x - l, y, cursor_width_ + r + l, h);
201 void show(bool set_show = true) { show_ = set_show; }
202 void hide() { show_ = false; }
203 int cursorWidth() const { return cursor_width_; }
204 void recomputeWidth() {
205 cursor_width_ = lyxrc.cursor_width
207 : 1 + int((lyxrc.zoom + 50) / 200.0);
210 QRect const & rect() { return rect_; }
213 /// cursor is in RTL or LTR text
215 /// indication for RTL or LTR
217 /// triangle to show that a completion is available
223 /// rectangle, possibly with l_shape and completion triangle
225 /// x position (were the vertical line is drawn)
232 // This is a 'heartbeat' generating synthetic mouse move events when the
233 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
234 SyntheticMouseEvent::SyntheticMouseEvent()
235 : timeout(200), restart_timeout(true)
239 GuiWorkArea::Private::Private(GuiWorkArea * parent)
240 : p(parent), buffer_view_(0), read_only_(false), lyx_view_(0), cursor_visible_(false),
241 need_resize_(false), schedule_redraw_(false), preedit_lines_(1),
242 completer_(new GuiCompleter(p, p))
247 GuiWorkArea::GuiWorkArea(QWidget * w)
248 : d(new Private(this))
253 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
254 : d(new Private(this))
256 d->read_only_ = buffer.isReadonly();
263 void GuiWorkArea::init()
266 connect(&d->cursor_timeout_, SIGNAL(timeout()),
267 this, SLOT(toggleCursor()));
269 int const time = QApplication::cursorFlashTime() / 2;
271 d->cursor_timeout_.setInterval(time);
272 d->cursor_timeout_.start();
274 // let's initialize this just to be safe
275 d->cursor_timeout_.setInterval(500);
278 d->screen_ = QPixmap(viewport()->width(), viewport()->height());
279 // With Qt4.5 a mouse event will happen before the first paint event
280 // so make sure that the buffer view has an up to date metrics.
281 d->buffer_view_->resize(viewport()->width(), viewport()->height());
282 d->cursor_ = new frontend::CursorWidget();
285 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
286 setAcceptDrops(true);
287 setMouseTracking(true);
288 setMinimumSize(100, 70);
289 setFrameStyle(QFrame::NoFrame);
292 viewport()->setAutoFillBackground(false);
293 // We don't need double-buffering nor SystemBackground on
294 // the viewport because we have our own backing pixmap.
295 viewport()->setAttribute(Qt::WA_NoSystemBackground);
297 setFocusPolicy(Qt::StrongFocus);
299 d->setCursorShape(Qt::IBeamCursor);
301 d->synthetic_mouse_event_.timeout.timeout.connect(
302 bind(&GuiWorkArea::generateSyntheticMouseEvent,
305 // Initialize the vertical Scroll Bar
306 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
307 this, SLOT(scrollTo(int)));
309 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
310 << " viewport height: " << viewport()->height());
312 // Enables input methods for asian languages.
313 // Must be set when creating custom text editing widgets.
314 setAttribute(Qt::WA_InputMethodEnabled, true);
316 d->dialog_mode_ = false;
320 GuiWorkArea::~GuiWorkArea()
322 d->buffer_view_->buffer().workAreaManager().remove(this);
323 delete d->buffer_view_;
325 // Completer has a QObject parent and is thus automatically destroyed.
327 // delete completer_;
332 Qt::CursorShape GuiWorkArea::cursorShape() const
334 return viewport()->cursor().shape();
338 void GuiWorkArea::Private::setCursorShape(Qt::CursorShape shape)
340 p->viewport()->setCursor(shape);
344 void GuiWorkArea::Private::updateCursorShape()
346 setCursorShape(buffer_view_->clickableInset()
347 ? Qt::PointingHandCursor : Qt::IBeamCursor);
351 void GuiWorkArea::setGuiView(GuiView & gv)
357 void GuiWorkArea::setBuffer(Buffer & buffer)
359 delete d->buffer_view_;
360 d->buffer_view_ = new BufferView(buffer);
361 buffer.workAreaManager().add(this);
363 // HACK: Prevents an additional redraw when the scrollbar pops up
364 // which regularily happens on documents with more than one page.
365 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
366 // Since we have no geometry information yet, we assume that
367 // a document needs a scrollbar if there is more then four
368 // paragraph in the outermost text.
369 if (buffer.text().paragraphs().size() > 4)
370 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
371 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
375 void GuiWorkArea::fixVerticalScrollBar()
378 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
382 void GuiWorkArea::close()
384 d->lyx_view_->removeWorkArea(this);
388 void GuiWorkArea::setFullScreen(bool full_screen)
390 d->buffer_view_->setFullScreen(full_screen);
391 setFrameStyle(QFrame::NoFrame);
393 setFrameStyle(QFrame::NoFrame);
394 if (lyxrc.full_screen_scrollbar)
395 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
397 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
401 BufferView & GuiWorkArea::bufferView()
403 return *d->buffer_view_;
407 BufferView const & GuiWorkArea::bufferView() const
409 return *d->buffer_view_;
413 void GuiWorkArea::stopBlinkingCursor()
415 d->cursor_timeout_.stop();
420 void GuiWorkArea::startBlinkingCursor()
422 // do not show the cursor if the view is busy
428 d->buffer_view_->cursorPosAndHeight(p, h);
429 // Don't start blinking if the cursor isn't on screen.
430 if (!d->buffer_view_->cursorInView(p, h))
435 //we're not supposed to cache this value.
436 int const time = QApplication::cursorFlashTime() / 2;
439 d->cursor_timeout_.setInterval(time);
440 d->cursor_timeout_.start();
444 void GuiWorkArea::redraw(bool update_metrics)
447 // No need to redraw in this case.
450 // No need to do anything if this is the current view. The BufferView
451 // metrics are already up to date.
452 if (update_metrics || d->lyx_view_ != guiApp->currentView()
453 || d->lyx_view_->currentWorkArea() != this) {
454 // FIXME: it would be nice to optimize for the off-screen case.
455 d->buffer_view_->cursor().fixIfBroken();
456 d->buffer_view_->updateMetrics();
457 d->buffer_view_->cursor().fixIfBroken();
460 // update cursor position, because otherwise it has to wait until
461 // the blinking interval is over
462 if (d->cursor_visible_) {
467 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
469 update(0, 0, viewport()->width(), viewport()->height());
471 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
472 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
473 d->updateScrollbar();
474 d->lyx_view_->updateStatusBar();
476 if (lyxerr.debugging(Debug::WORKAREA))
477 d->buffer_view_->coordCache().dump();
479 d->setReadOnly(d->buffer_view_->buffer().isReadonly());
481 d->updateCursorShape();
485 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
487 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
488 && lyxrc.full_screen_menubar) {
489 // FIXME HACK: we should not have to do this here. See related comment
490 // in GuiView::event() (QEvent::ShortcutOverride)
491 d->lyx_view_->menuBar()->hide();
494 // In order to avoid bad surprise in the middle of an operation,
495 // we better stop the blinking cursor...
496 // the cursor gets restarted in GuiView::restartCursor()
497 stopBlinkingCursor();
498 guiApp->processKeySym(key, mod);
502 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd0, KeyModifier mod)
505 if (cmd0.action() == LFUN_FILE_OPEN) {
507 lyx_view_->dispatch(cmd0, dr);
513 if (cmd0.action() == LFUN_MOUSE_PRESS) {
514 if (mod == ShiftModifier)
515 cmd = FuncRequest(cmd0, "region-select");
516 else if (mod == ControlModifier)
517 cmd = FuncRequest(cmd0, "paragraph-select");
524 bool const notJustMovingTheMouse =
525 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
527 // In order to avoid bad surprise in the middle of an operation, we better stop
528 // the blinking cursor.
529 if (notJustMovingTheMouse)
530 p->stopBlinkingCursor();
532 buffer_view_->mouseEventDispatch(cmd);
534 // Skip these when selecting
535 if (cmd.action() != LFUN_MOUSE_MOTION) {
536 completer_->updateVisibility(false, false);
537 lyx_view_->updateDialogs();
538 lyx_view_->updateStatusBar();
541 // GUI tweaks except with mouse motion with no button pressed.
542 if (notJustMovingTheMouse) {
543 // Slight hack: this is only called currently when we
544 // clicked somewhere, so we force through the display
545 // of the new status here.
546 lyx_view_->clearMessage();
548 // Show the cursor immediately after any operation
549 p->startBlinkingCursor();
556 void GuiWorkArea::Private::resizeBufferView()
558 // WARNING: Please don't put any code that will trigger a repaint here!
559 // We are already inside a paint event.
560 lyx_view_->setBusy(true);
563 buffer_view_->cursorPosAndHeight(point, h);
564 bool const cursor_in_view = buffer_view_->cursorInView(point, h);
565 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
567 buffer_view_->scrollToCursor();
570 // Update scrollbars which might have changed due different
571 // BufferView dimension. This is especially important when the
572 // BufferView goes from zero-size to the real-size for the first time,
573 // as the scrollbar paramters are then set for the first time.
576 lyx_view_->updateLayoutList();
577 lyx_view_->setBusy(false);
578 need_resize_ = false;
582 void GuiWorkArea::Private::showCursor()
589 buffer_view_->cursorPosAndHeight(p, h);
590 if (!buffer_view_->cursorInView(p, h))
594 bool l_shape = false;
595 Font const & realfont = buffer_view_->cursor().real_current_font;
596 BufferParams const & bp = buffer_view_->buffer().params();
597 bool const samelang = realfont.language() == bp.language;
598 bool const isrtl = realfont.isVisibleRightToLeft();
600 if (!samelang || isrtl != bp.language->rightToLeft())
603 // The ERT language hack needs fixing up
604 if (realfont.language() == latex_language)
607 // show cursor on screen
608 Cursor & cur = buffer_view_->cursor();
609 bool completable = cur.inset().showCompletionCursor()
610 && completer_->completionAvailable()
611 && !completer_->popupVisible()
612 && !completer_->inlineVisible();
613 cursor_visible_ = true;
614 cursor_->recomputeWidth();
615 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
619 void GuiWorkArea::Private::hideCursor()
621 if (!cursor_visible_)
624 cursor_visible_ = false;
629 void GuiWorkArea::toggleCursor()
631 if (d->cursor_visible_)
638 void GuiWorkArea::Private::updateScrollbar()
640 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
641 // WARNING: don't touch at the scrollbar value like this:
642 // verticalScrollBar()->setValue(scroll_.position);
643 // because this would cause a recursive signal/slot calling with
644 // GuiWorkArea::scrollTo
645 p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
646 p->verticalScrollBar()->setPageStep(scroll_.page_step);
647 p->verticalScrollBar()->setSingleStep(scroll_.single_step);
648 p->verticalScrollBar()->setSliderPosition(scroll_.position);
652 void GuiWorkArea::scrollTo(int value)
654 stopBlinkingCursor();
655 d->buffer_view_->scrollDocView(value, true);
657 if (lyxrc.cursor_follows_scrollbar) {
658 d->buffer_view_->setCursorFromScrollbar();
659 d->lyx_view_->updateLayoutList();
661 // Show the cursor immediately after any operation.
662 startBlinkingCursor();
663 QApplication::syncX();
667 bool GuiWorkArea::event(QEvent * e)
670 case QEvent::ToolTip: {
671 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
672 if (lyxrc.use_tooltip) {
673 QPoint pos = helpEvent->pos();
674 if (pos.x() < viewport()->width()) {
675 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
676 QToolTip::showText(helpEvent->globalPos(), s);
679 QToolTip::hideText();
681 // Don't forget to accept the event!
686 case QEvent::ShortcutOverride: {
687 // We catch this event in order to catch the Tab or Shift+Tab key press
688 // which are otherwise reserved to focus switching between controls
690 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
691 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
692 || (ke->key() == Qt::Key_Backtab && (
693 ke->modifiers() == Qt::ShiftModifier
694 || ke->modifiers() == Qt::NoModifier))) {
698 return QAbstractScrollArea::event(e);
702 return QAbstractScrollArea::event(e);
708 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
711 if (e->reason() == QContextMenuEvent::Mouse)
712 // the menu name is set on mouse press
713 name = d->context_menu_name_;
715 QPoint pos = e->pos();
716 Cursor const & cur = d->buffer_view_->cursor();
717 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
718 // Do not access the context menu of math right in front of before
719 // the cursor. This does not work when the cursor is in text.
720 Inset * inset = cur.paragraph().getInset(cur.pos());
721 if (inset && inset->asInsetMath())
723 else if (cur.pos() > 0) {
724 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
729 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
733 QAbstractScrollArea::contextMenuEvent(e);
736 // always show mnemonics when the keyboard is used to show the context menu
737 // FIXME: This should be fixed in Qt itself
738 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
739 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
741 QAbstractScrollArea::contextMenuEvent(e);
744 // Position the menu to the right.
745 // FIXME: menu position should be different for RTL text.
746 menu->exec(e->globalPos());
751 void GuiWorkArea::focusInEvent(QFocusEvent * e)
753 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
754 if (d->lyx_view_->currentWorkArea() != this)
755 d->lyx_view_->setCurrentWorkArea(this);
757 startBlinkingCursor();
758 QAbstractScrollArea::focusInEvent(e);
762 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
764 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
765 stopBlinkingCursor();
766 QAbstractScrollArea::focusOutEvent(e);
770 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
772 if (d->dc_event_.active && d->dc_event_ == *e) {
773 d->dc_event_.active = false;
774 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
775 q_button_state(e->button()));
781 inputContext()->reset();
783 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
784 q_button_state(e->button()));
785 d->dispatch(cmd, q_key_state(e->modifiers()));
787 // Save the context menu on mouse press, because also the mouse
788 // cursor is set on mouse press. Afterwards, we can either release
789 // the mousebutton somewhere else, or the cursor might have moved
790 // due to the DEPM. We need to do this after the mouse has been
791 // set in dispatch(), because the selection state might change.
792 if (e->button() == Qt::RightButton)
793 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
799 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
801 if (d->synthetic_mouse_event_.timeout.running())
802 d->synthetic_mouse_event_.timeout.stop();
804 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
805 q_button_state(e->button()));
811 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
813 // we kill the triple click if we move
814 doubleClickTimeout();
815 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
816 q_motion_state(e->buttons()));
820 // If we're above or below the work area...
821 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
822 && e->buttons() == mouse_button::button1) {
823 // Make sure only a synthetic event can cause a page scroll,
824 // so they come at a steady rate:
826 // _Force_ a scroll up:
827 cmd.set_y(e->y() - 21);
829 cmd.set_y(e->y() + 21);
830 // Store the event, to be handled when the timeout expires.
831 d->synthetic_mouse_event_.cmd = cmd;
833 if (d->synthetic_mouse_event_.timeout.running()) {
834 // Discard the event. Note that it _may_ be handled
835 // when the timeout expires if
836 // synthetic_mouse_event_.cmd has not been overwritten.
837 // Ie, when the timeout expires, we handle the
838 // most recent event but discard all others that
839 // occurred after the one used to start the timeout
840 // in the first place.
844 d->synthetic_mouse_event_.restart_timeout = true;
845 d->synthetic_mouse_event_.timeout.start();
846 // Fall through to handle this event...
848 } else if (d->synthetic_mouse_event_.timeout.running()) {
849 // Store the event, to be possibly handled when the timeout
851 // Once the timeout has expired, normal control is returned
852 // to mouseMoveEvent (restart_timeout = false).
853 // This results in a much smoother 'feel' when moving the
854 // mouse back into the work area.
855 d->synthetic_mouse_event_.cmd = cmd;
856 d->synthetic_mouse_event_.restart_timeout = false;
863 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
865 // Wheel rotation by one notch results in a delta() of 120 (see
866 // documentation of QWheelEvent)
867 double const delta = ev->delta() / 120.0;
869 switch (lyxrc.scroll_wheel_zoom) {
870 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
871 zoom = ev->modifiers() & Qt::ControlModifier;
872 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
874 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
875 zoom = ev->modifiers() & Qt::ShiftModifier;
876 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
878 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
879 zoom = ev->modifiers() & Qt::AltModifier;
880 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
882 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
886 docstring arg = convert<docstring>(int(5 * delta));
887 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
891 // Take into account the desktop wide settings.
892 int const lines = qApp->wheelScrollLines();
893 int const page_step = verticalScrollBar()->pageStep();
894 // Test if the wheel mouse is set to one screen at a time.
895 int scroll_value = lines > page_step
896 ? page_step : lines * verticalScrollBar()->singleStep();
898 // Take into account the rotation and the user preferences.
899 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
900 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
901 << " delta = " << delta << " scroll_value = " << scroll_value
902 << " page_step = " << page_step);
904 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
910 void GuiWorkArea::generateSyntheticMouseEvent()
912 int const e_y = d->synthetic_mouse_event_.cmd.y();
913 int const wh = d->buffer_view_->workHeight();
914 bool const up = e_y < 0;
915 bool const down = e_y > wh;
917 // Set things off to generate the _next_ 'pseudo' event.
919 if (d->synthetic_mouse_event_.restart_timeout) {
920 // This is some magic formulae to determine the speed
921 // of scrolling related to the position of the mouse.
924 int dist = up ? -e_y : e_y - wh;
925 time = max(min(200, 250000 / (dist * dist)), 1) ;
928 step = 80000 / (time * time);
932 d->synthetic_mouse_event_.timeout.setTimeout(time);
933 d->synthetic_mouse_event_.timeout.start();
936 // Can we scroll further ?
937 int const value = verticalScrollBar()->value();
938 if (value == verticalScrollBar()->maximum()
939 || value == verticalScrollBar()->minimum()) {
940 d->synthetic_mouse_event_.timeout.stop();
945 if (step <= 2 * wh) {
946 d->buffer_view_->scroll(up ? -step : step);
947 d->buffer_view_->updateMetrics();
949 d->buffer_view_->scrollDocView(value + up ? -step : step, false);
952 // In which paragraph do we have to set the cursor ?
953 Cursor & cur = d->buffer_view_->cursor();
954 // FIXME: we don't know howto handle math.
955 Text * text = cur.text();
958 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
960 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
961 ParagraphMetrics const & pm = *pp.second;
962 pit_type const pit = pp.first;
964 if (pm.rows().empty())
967 // Find the row at which we set the cursor.
968 RowList::const_iterator rit = pm.rows().begin();
969 RowList::const_iterator rlast = pm.rows().end();
970 int yy = pm.position() - pm.ascent();
971 for (--rlast; rit != rlast; ++rit) {
972 int h = rit->height();
973 if ((up && yy + h > 0)
974 || (!up && yy + h > wh - defaultRowHeight()))
979 // Find the position of the cursor
981 int x = d->synthetic_mouse_event_.cmd.x();
982 pos_type const pos = rit->pos() + tm.getColumnNearX(pit, *rit, x, bound);
989 d->buffer_view_->buffer().changed(false);
994 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
996 // Do not process here some keys if dialog_mode_ is set
998 && (ev->modifiers() == Qt::NoModifier
999 || ev->modifiers() == Qt::ShiftModifier)
1000 && (ev->key() == Qt::Key_Escape
1001 || ev->key() == Qt::Key_Enter
1002 || ev->key() == Qt::Key_Return)
1008 // intercept some keys if completion popup is visible
1009 if (d->completer_->popupVisible()) {
1010 switch (ev->key()) {
1012 case Qt::Key_Return:
1013 d->completer_->activate();
1019 // do nothing if there are other events
1020 // (the auto repeated events come too fast)
1021 // it looks like this is only needed on X11
1023 if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1024 switch (ev->key()) {
1025 case Qt::Key_PageDown:
1026 case Qt::Key_PageUp:
1031 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1038 KeyModifier m = q_key_state(ev->modifiers());
1041 if (m & ShiftModifier)
1043 if (m & ControlModifier)
1045 if (m & AltModifier)
1047 if (m & MetaModifier)
1050 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1051 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1052 << " keyState: " << str);
1055 setKeySymbol(&sym, ev);
1057 processKeySym(sym, q_key_state(ev->modifiers()));
1065 void GuiWorkArea::doubleClickTimeout()
1067 d->dc_event_.active = false;
1071 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1073 d->dc_event_ = DoubleClick(ev);
1074 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1075 SLOT(doubleClickTimeout()));
1076 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1078 q_button_state(ev->button()));
1084 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1086 QAbstractScrollArea::resizeEvent(ev);
1087 d->need_resize_ = true;
1092 void GuiWorkArea::Private::update(int x, int y, int w, int h)
1094 p->viewport()->update(x, y, w, h);
1098 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1100 QRect const rc = ev->rect();
1101 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1102 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1104 if (d->need_resize_) {
1105 d->screen_ = QPixmap(viewport()->width(), viewport()->height());
1106 d->resizeBufferView();
1107 if (d->cursor_visible_) {
1113 QPainter pain(viewport());
1114 pain.drawPixmap(rc, d->screen_, rc);
1115 d->cursor_->draw(pain);
1120 void GuiWorkArea::Private::updateScreen()
1122 GuiPainter pain(&screen_);
1123 buffer_view_->draw(pain);
1127 void GuiWorkArea::Private::showCursor(int x, int y, int h,
1128 bool l_shape, bool rtl, bool completable)
1130 if (schedule_redraw_) {
1131 // This happens when a graphic conversion is finished. As we don't know
1132 // the size of the new graphics, it's better the update everything.
1133 // We can't use redraw() here because this would trigger a infinite
1134 // recursive loop with showCursor().
1135 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
1138 p->viewport()->update(QRect(0, 0, p->viewport()->width(), p->viewport()->height()));
1139 schedule_redraw_ = false;
1140 // Show the cursor immediately after the update.
1146 cursor_->update(x, y, h, l_shape, rtl, completable);
1148 p->viewport()->update(cursor_->rect());
1152 void GuiWorkArea::Private::removeCursor()
1155 //if (!qApp->focusWidget())
1156 p->viewport()->update(cursor_->rect());
1160 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1162 QString const & commit_string = e->commitString();
1163 docstring const & preedit_string
1164 = qstring_to_ucs4(e->preeditString());
1166 if (!commit_string.isEmpty()) {
1168 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1169 << " commitString: " << e->commitString());
1173 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1174 for (int i = 0; i != commit_string.size(); ++i) {
1175 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1180 // Hide the cursor during the kana-kanji transformation.
1181 if (preedit_string.empty())
1182 startBlinkingCursor();
1184 stopBlinkingCursor();
1186 // last_width : for checking if last preedit string was/wasn't empty.
1187 static bool last_width = false;
1188 if (!last_width && preedit_string.empty()) {
1189 // if last_width is last length of preedit string.
1194 GuiPainter pain(&d->screen_);
1195 d->buffer_view_->updateMetrics();
1196 d->buffer_view_->draw(pain);
1197 FontInfo font = d->buffer_view_->cursor().getFont().fontInfo();
1198 FontMetrics const & fm = theFontMetrics(font);
1199 int height = fm.maxHeight();
1200 int cur_x = d->cursor_->rect().left();
1201 int cur_y = d->cursor_->rect().bottom();
1203 // redraw area of preedit string.
1204 update(0, cur_y - height, viewport()->width(),
1205 (height + 1) * d->preedit_lines_);
1207 if (preedit_string.empty()) {
1209 d->preedit_lines_ = 1;
1215 // att : stores an IM attribute.
1216 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1218 // get attributes of input method cursor.
1219 // cursor_pos : cursor position in preedit string.
1220 size_t cursor_pos = 0;
1221 bool cursor_is_visible = false;
1222 for (int i = 0; i != att.size(); ++i) {
1223 if (att.at(i).type == QInputMethodEvent::Cursor) {
1224 cursor_pos = att.at(i).start;
1225 cursor_is_visible = att.at(i).length != 0;
1230 size_t preedit_length = preedit_string.length();
1232 // get position of selection in input method.
1233 // FIXME: isn't there a way to do this simplier?
1234 // rStart : cursor position in selected string in IM.
1236 // rLength : selected string length in IM.
1238 if (cursor_pos < preedit_length) {
1239 for (int i = 0; i != att.size(); ++i) {
1240 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1241 if (att.at(i).start <= int(cursor_pos)
1242 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1243 rStart = att.at(i).start;
1244 rLength = att.at(i).length;
1245 if (!cursor_is_visible)
1246 cursor_pos += rLength;
1253 rStart = cursor_pos;
1257 int const right_margin = d->buffer_view_->rightMargin();
1258 Painter::preedit_style ps;
1259 // Most often there would be only one line:
1260 d->preedit_lines_ = 1;
1261 for (size_t pos = 0; pos != preedit_length; ++pos) {
1262 char_type const typed_char = preedit_string[pos];
1263 // reset preedit string style
1264 ps = Painter::preedit_default;
1266 // if we reached the right extremity of the screen, go to next line.
1267 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1268 cur_x = right_margin;
1269 cur_y += height + 1;
1270 ++d->preedit_lines_;
1272 // preedit strings are displayed with dashed underline
1273 // and partial strings are displayed white on black indicating
1274 // that we are in selecting mode in the input method.
1275 // FIXME: rLength == preedit_length is not a changing condition
1276 // FIXME: should be put out of the loop.
1278 && pos < rStart + rLength
1279 && !(cursor_pos < rLength && rLength == preedit_length))
1280 ps = Painter::preedit_selecting;
1282 if (pos == cursor_pos
1283 && (cursor_pos < rLength && rLength == preedit_length))
1284 ps = Painter::preedit_cursor;
1286 // draw one character and update cur_x.
1287 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1290 // update the preedit string screen area.
1291 update(0, cur_y - d->preedit_lines_*height, viewport()->width(),
1292 (height + 1) * d->preedit_lines_);
1294 // Don't forget to accept the event!
1299 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1301 QRect cur_r(0, 0, 0, 0);
1303 // this is the CJK-specific composition window position and
1304 // the context menu position when the menu key is pressed.
1305 case Qt::ImMicroFocus:
1306 cur_r = d->cursor_->rect();
1307 if (d->preedit_lines_ != 1)
1309 cur_r.moveBottom(cur_r.bottom()
1310 + cur_r.height() * (d->preedit_lines_ - 1));
1311 // return lower right of cursor in LyX.
1314 return QWidget::inputMethodQuery(query);
1319 void GuiWorkArea::updateWindowTitle()
1321 docstring maximize_title;
1322 docstring minimize_title;
1324 Buffer const & buf = d->buffer_view_->buffer();
1325 FileName const file_name = buf.fileName();
1326 if (!file_name.empty()) {
1327 maximize_title = file_name.displayName(130);
1328 minimize_title = from_utf8(file_name.onlyFileName());
1329 if (buf.lyxvc().inUse()) {
1330 if (buf.lyxvc().locking())
1331 maximize_title += _(" (version control, locking)");
1333 maximize_title += _(" (version control)");
1335 if (!buf.isClean()) {
1336 maximize_title += _(" (changed)");
1337 minimize_title += char_type('*');
1339 if (buf.isReadonly())
1340 maximize_title += _(" (read only)");
1343 QString const new_title = toqstr(maximize_title);
1344 if (new_title != windowTitle()) {
1345 QWidget::setWindowTitle(new_title);
1346 QWidget::setWindowIconText(toqstr(minimize_title));
1352 void GuiWorkArea::Private::setReadOnly(bool read_only)
1354 if (read_only_ == read_only)
1356 read_only_ = read_only;
1357 p->updateWindowTitle();
1358 if (p == lyx_view_->currentWorkArea())
1359 lyx_view_->updateDialogs();
1363 bool GuiWorkArea::isFullScreen() const
1365 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1369 void GuiWorkArea::scheduleRedraw()
1371 d->schedule_redraw_ = true;
1375 bool GuiWorkArea::inDialogMode() const
1377 return d->dialog_mode_;
1381 void GuiWorkArea::setDialogMode(bool mode)
1383 d->dialog_mode_ = mode;
1387 GuiCompleter & GuiWorkArea::completer()
1389 return *d->completer_;
1392 GuiView const & GuiWorkArea::view() const
1394 return *d->lyx_view_;
1398 GuiView & GuiWorkArea::view()
1400 return *d->lyx_view_;
1403 ////////////////////////////////////////////////////////////////////
1407 ////////////////////////////////////////////////////////////////////
1410 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1412 buffer_ = theBufferList().newBuffer(
1413 support::FileName::tempName().absFileName() + "_embedded.internal");
1414 buffer_->setUnnamed(true);
1415 buffer_->setFullyLoaded(true);
1416 setBuffer(*buffer_);
1417 setDialogMode(true);
1421 EmbeddedWorkArea::~EmbeddedWorkArea()
1423 // No need to destroy buffer and bufferview here, because it is done
1424 // in theBufferList() destruction loop at application exit
1428 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1431 GuiWorkArea::closeEvent(ev);
1435 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1438 GuiWorkArea::hideEvent(ev);
1442 QSize EmbeddedWorkArea::sizeHint () const
1445 // GuiWorkArea sets the size to the screen's viewport
1446 // by returning a value this gets overridden
1447 // EmbeddedWorkArea is now sized to fit in the layout
1448 // of the parent, and has a minimum size set in GuiWorkArea
1449 // which is what we return here
1450 return QSize(100, 70);
1454 void EmbeddedWorkArea::disable()
1456 stopBlinkingCursor();
1457 if (view().currentWorkArea() != this)
1459 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1460 // tolerates it and shows the background logo), what happens if
1461 // an EmbeddedWorkArea is closed after closing all document WAs
1462 view().setCurrentWorkArea(view().currentMainWorkArea());
1465 ////////////////////////////////////////////////////////////////////
1469 ////////////////////////////////////////////////////////////////////
1472 class NoTabFrameMacStyle : public QMacStyle {
1475 QRect subElementRect(SubElement element, const QStyleOption * option,
1476 const QWidget * widget = 0) const
1478 QRect rect = QMacStyle::subElementRect(element, option, widget);
1479 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1481 // The Qt Mac style puts the contents into a 3 pixel wide box
1482 // which looks very ugly and not like other Mac applications.
1483 // Hence we remove this here, and moreover the 16 pixel round
1484 // frame above if the tab bar is hidden.
1485 if (element == QStyle::SE_TabWidgetTabContents) {
1486 rect.adjust(- rect.left(), 0, rect.left(), 0);
1495 NoTabFrameMacStyle noTabFrameMacStyle;
1499 TabWorkArea::TabWorkArea(QWidget * parent)
1500 : QTabWidget(parent), clicked_tab_(-1)
1503 setStyle(&noTabFrameMacStyle);
1505 #if QT_VERSION < 0x040500
1506 lyxrc.single_close_tab_button = true;
1509 QPalette pal = palette();
1510 pal.setColor(QPalette::Active, QPalette::Button,
1511 pal.color(QPalette::Active, QPalette::Window));
1512 pal.setColor(QPalette::Disabled, QPalette::Button,
1513 pal.color(QPalette::Disabled, QPalette::Window));
1514 pal.setColor(QPalette::Inactive, QPalette::Button,
1515 pal.color(QPalette::Inactive, QPalette::Window));
1517 QObject::connect(this, SIGNAL(currentChanged(int)),
1518 this, SLOT(on_currentTabChanged(int)));
1520 closeBufferButton = new QToolButton(this);
1521 closeBufferButton->setPalette(pal);
1522 // FIXME: rename the icon to closebuffer.png
1523 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1524 closeBufferButton->setText("Close File");
1525 closeBufferButton->setAutoRaise(true);
1526 closeBufferButton->setCursor(Qt::ArrowCursor);
1527 closeBufferButton->setToolTip(qt_("Close File"));
1528 closeBufferButton->setEnabled(true);
1529 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1530 this, SLOT(closeCurrentBuffer()));
1531 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1533 // setup drag'n'drop
1534 QTabBar* tb = new DragTabBar;
1535 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1536 this, SLOT(moveTab(int, int)));
1537 tb->setElideMode(Qt::ElideNone);
1540 // make us responsible for the context menu of the tabbar
1541 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1542 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1543 this, SLOT(showContextMenu(const QPoint &)));
1544 #if QT_VERSION >= 0x040500
1545 connect(tb, SIGNAL(tabCloseRequested(int)),
1546 this, SLOT(closeTab(int)));
1549 setUsesScrollButtons(true);
1553 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1555 if (event->button() != Qt::LeftButton)
1558 // return early if double click on existing tabs
1559 for (int i = 0; i < count(); ++i)
1560 if (tabBar()->tabRect(i).contains(event->pos()))
1563 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1567 void TabWorkArea::setFullScreen(bool full_screen)
1569 for (int i = 0; i != count(); ++i) {
1570 if (GuiWorkArea * wa = workArea(i))
1571 wa->setFullScreen(full_screen);
1574 if (lyxrc.full_screen_tabbar)
1575 showBar(!full_screen && count() > 1);
1579 void TabWorkArea::showBar(bool show)
1581 tabBar()->setEnabled(show);
1582 tabBar()->setVisible(show);
1583 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1584 #if QT_VERSION >= 0x040500
1585 setTabsClosable(!lyxrc.single_close_tab_button);
1590 GuiWorkArea * TabWorkArea::currentWorkArea()
1595 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1601 GuiWorkArea * TabWorkArea::workArea(int index)
1603 return dynamic_cast<GuiWorkArea *>(widget(index));
1607 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1609 // FIXME: this method doesn't work if we have more than work area
1610 // showing the same buffer.
1611 for (int i = 0; i != count(); ++i) {
1612 GuiWorkArea * wa = workArea(i);
1613 LASSERT(wa, return 0);
1614 if (&wa->bufferView().buffer() == &buffer)
1621 void TabWorkArea::closeAll()
1624 GuiWorkArea * wa = workArea(0);
1632 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1634 LASSERT(work_area, /**/);
1635 int index = indexOf(work_area);
1639 if (index == currentIndex())
1640 // Make sure the work area is up to date.
1641 on_currentTabChanged(index);
1643 // Switch to the work area.
1644 setCurrentIndex(index);
1645 work_area->setFocus();
1651 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1653 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1654 wa->setUpdatesEnabled(false);
1655 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1656 // when hiding it again below).
1657 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1658 showBar(count() > 0);
1659 addTab(wa, wa->windowTitle());
1660 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1661 this, SLOT(updateTabTexts()));
1662 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1663 setFullScreen(true);
1665 // Hide tabbar if there's only one tab.
1666 showBar(count() > 1);
1674 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1676 LASSERT(work_area, return false);
1677 int index = indexOf(work_area);
1681 work_area->setUpdatesEnabled(false);
1686 // make sure the next work area is enabled.
1687 currentWidget()->setUpdatesEnabled(true);
1688 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1689 setFullScreen(true);
1691 // Show tabbar only if there's more than one tab.
1692 showBar(count() > 1);
1694 lastWorkAreaRemoved();
1702 void TabWorkArea::on_currentTabChanged(int i)
1704 // returns e.g. on application destruction
1707 GuiWorkArea * wa = workArea(i);
1708 LASSERT(wa, return);
1709 wa->setUpdatesEnabled(true);
1713 currentWorkAreaChanged(wa);
1715 LYXERR(Debug::GUI, "currentTabChanged " << i
1716 << " File: " << wa->bufferView().buffer().absFileName());
1720 void TabWorkArea::closeCurrentBuffer()
1723 if (clicked_tab_ == -1)
1724 wa = currentWorkArea();
1726 wa = workArea(clicked_tab_);
1729 wa->view().closeWorkArea(wa);
1733 void TabWorkArea::hideCurrentTab()
1736 if (clicked_tab_ == -1)
1737 wa = currentWorkArea();
1739 wa = workArea(clicked_tab_);
1742 wa->view().hideWorkArea(wa);
1746 void TabWorkArea::closeTab(int index)
1748 on_currentTabChanged(index);
1751 wa = currentWorkArea();
1753 wa = workArea(index);
1756 wa->view().closeWorkArea(wa);
1763 /// make vector happy
1766 DisplayPath(int tab, FileName const & filename)
1769 filename_ = (filename.extension() == "lyx") ?
1770 toqstr(filename.onlyFileNameWithoutExt())
1771 : toqstr(filename.onlyFileName());
1772 postfix_ = toqstr(filename.absoluteFilePath()).
1773 split("/", QString::SkipEmptyParts);
1774 postfix_.pop_back();
1775 abs_ = toqstr(filename.absoluteFilePath());
1776 dottedPrefix_ = false;
1779 /// Absolute path for debugging.
1784 /// Add the first segment from the postfix or three dots to the prefix.
1785 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1786 /// when really needed.
1787 void shiftPathSegment(bool dotted)
1789 if (postfix_.count() <= 0)
1793 if (dottedPrefix_ && !prefix_.isEmpty())
1795 prefix_ += postfix_.front() + "/";
1797 dottedPrefix_ = dotted && !prefix_.isEmpty();
1798 postfix_.pop_front();
1801 QString displayString() const
1803 if (prefix_.isEmpty())
1806 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1807 return prefix_ + (dots ? ".../" : "") + filename_;
1810 QString forecastPathString() const
1812 if (postfix_.count() == 0)
1813 return displayString();
1816 + (dottedPrefix_ ? ".../" : "")
1817 + postfix_.front() + "/";
1820 bool final() const { return postfix_.empty(); }
1822 int tab() const { return tab_; }
1828 QStringList postfix_;
1841 bool operator<(DisplayPath const & a, DisplayPath const & b)
1843 return a.displayString() < b.displayString();
1847 bool operator==(DisplayPath const & a, DisplayPath const & b)
1849 return a.displayString() == b.displayString();
1853 void TabWorkArea::updateTabTexts()
1858 std::list<DisplayPath> paths;
1859 typedef std::list<DisplayPath>::iterator It;
1861 // collect full names first: path into postfix, empty prefix and
1862 // filename without extension
1863 for (size_t i = 0; i < n; ++i) {
1864 GuiWorkArea * i_wa = workArea(i);
1865 FileName const fn = i_wa->bufferView().buffer().fileName();
1866 paths.push_back(DisplayPath(i, fn));
1869 // go through path segments and see if it helps to make the path more unique
1870 bool somethingChanged = true;
1871 bool allFinal = false;
1872 while (somethingChanged && !allFinal) {
1873 // adding path segments changes order
1876 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1877 somethingChanged = false;
1880 // find segments which are not unique (i.e. non-atomic)
1881 It it = paths.begin();
1883 QString segString = it->displayString();
1884 for (; it != paths.end(); ++it) {
1885 // look to the next item
1890 allFinal = allFinal && it->final();
1892 LYXERR(Debug::GUI, "it = " << it->abs()
1893 << " => " << it->displayString());
1895 // still the same segment?
1897 if ((next != paths.end()
1898 && (nextString = next->displayString()) == segString))
1900 LYXERR(Debug::GUI, "segment ended");
1902 // only a trivial one with one element?
1903 if (it == segStart) {
1904 // start new segment
1906 segString = nextString;
1910 // we found a non-atomic segment segStart <= sit <= it < next.
1911 // Shift path segments and hope for the best
1912 // that it makes the path more unique.
1913 somethingChanged = true;
1915 QString dspString = sit->forecastPathString();
1916 LYXERR(Debug::GUI, "first forecast found for "
1917 << sit->abs() << " => " << dspString);
1919 bool moreUnique = false;
1920 for (; sit != next; ++sit) {
1921 if (sit->forecastPathString() != dspString) {
1922 LYXERR(Debug::GUI, "different forecast found for "
1923 << sit->abs() << " => " << sit->forecastPathString());
1927 LYXERR(Debug::GUI, "same forecast found for "
1928 << sit->abs() << " => " << dspString);
1931 // if the path segment helped, add it. Otherwise add dots
1932 bool dots = !moreUnique;
1933 LYXERR(Debug::GUI, "using dots = " << dots);
1934 for (sit = segStart; sit != next; ++sit) {
1935 sit->shiftPathSegment(dots);
1936 LYXERR(Debug::GUI, "shifting "
1937 << sit->abs() << " => " << sit->displayString());
1940 // start new segment
1942 segString = nextString;
1946 // set new tab titles
1947 for (It it = paths.begin(); it != paths.end(); ++it) {
1948 int const tab_index = it->tab();
1949 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
1950 QString tab_text = it->displayString();
1951 if (!buf.fileName().empty() && !buf.isClean())
1953 setTabText(tab_index, tab_text);
1954 setTabToolTip(tab_index, it->abs());
1959 void TabWorkArea::showContextMenu(const QPoint & pos)
1962 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1963 if (clicked_tab_ == -1)
1968 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
1969 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
1970 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
1971 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1972 popup.exec(tabBar()->mapToGlobal(pos));
1978 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1980 QWidget * w = widget(fromIndex);
1981 QIcon icon = tabIcon(fromIndex);
1982 QString text = tabText(fromIndex);
1984 setCurrentIndex(fromIndex);
1985 removeTab(fromIndex);
1986 insertTab(toIndex, w, icon, text);
1987 setCurrentIndex(toIndex);
1991 DragTabBar::DragTabBar(QWidget* parent)
1994 setAcceptDrops(true);
1995 #if QT_VERSION >= 0x040500
1996 setTabsClosable(!lyxrc.single_close_tab_button);
2001 #if QT_VERSION < 0x040300
2002 int DragTabBar::tabAt(QPoint const & position) const
2004 const int max = count();
2005 for (int i = 0; i < max; ++i) {
2006 if (tabRect(i).contains(position))
2014 void DragTabBar::mousePressEvent(QMouseEvent * event)
2016 if (event->button() == Qt::LeftButton)
2017 dragStartPos_ = event->pos();
2018 QTabBar::mousePressEvent(event);
2022 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2024 // If the left button isn't pressed anymore then return
2025 if (!(event->buttons() & Qt::LeftButton))
2028 // If the distance is too small then return
2029 if ((event->pos() - dragStartPos_).manhattanLength()
2030 < QApplication::startDragDistance())
2033 // did we hit something after all?
2034 int tab = tabAt(dragStartPos_);
2038 // simulate button release to remove highlight from button
2039 int i = currentIndex();
2040 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2041 event->button(), event->buttons(), 0);
2042 QTabBar::mouseReleaseEvent(&me);
2046 QDrag * drag = new QDrag(this);
2047 QMimeData * mimeData = new QMimeData;
2048 // a crude way to distinguish tab-reodering drops from other ones
2049 mimeData->setData("action", "tab-reordering") ;
2050 drag->setMimeData(mimeData);
2052 #if QT_VERSION >= 0x040300
2053 // get tab pixmap as cursor
2054 QRect r = tabRect(tab);
2055 QPixmap pixmap(r.size());
2056 render(&pixmap, - r.topLeft());
2057 drag->setPixmap(pixmap);
2060 drag->start(Qt::MoveAction);
2066 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2068 // Only accept if it's an tab-reordering request
2069 QMimeData const * m = event->mimeData();
2070 QStringList formats = m->formats();
2071 if (formats.contains("action")
2072 && m->data("action") == "tab-reordering")
2073 event->acceptProposedAction();
2077 void DragTabBar::dropEvent(QDropEvent * event)
2079 int fromIndex = tabAt(dragStartPos_);
2080 int toIndex = tabAt(event->pos());
2082 // Tell interested objects that
2083 if (fromIndex != toIndex)
2084 tabMoveRequested(fromIndex, toIndex);
2085 event->acceptProposedAction();
2089 } // namespace frontend
2092 #include "moc_GuiWorkArea.cpp"