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), screen_(0), buffer_view_(0), 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))
262 void GuiWorkArea::init()
265 connect(&d->cursor_timeout_, SIGNAL(timeout()),
266 this, SLOT(toggleCursor()));
268 int const time = QApplication::cursorFlashTime() / 2;
270 d->cursor_timeout_.setInterval(time);
271 d->cursor_timeout_.start();
273 // let's initialize this just to be safe
274 d->cursor_timeout_.setInterval(500);
278 // With Qt4.5 a mouse event will happen before the first paint event
279 // so make sure that the buffer view has an up to date metrics.
280 d->buffer_view_->resize(viewport()->width(), viewport()->height());
281 d->cursor_ = new frontend::CursorWidget();
284 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
285 setAcceptDrops(true);
286 setMouseTracking(true);
287 setMinimumSize(100, 70);
288 setFrameStyle(QFrame::NoFrame);
291 viewport()->setAutoFillBackground(false);
292 // We don't need double-buffering nor SystemBackground on
293 // the viewport because we have our own backing pixmap.
294 viewport()->setAttribute(Qt::WA_NoSystemBackground);
296 setFocusPolicy(Qt::StrongFocus);
298 d->setCursorShape(Qt::IBeamCursor);
300 d->synthetic_mouse_event_.timeout.timeout.connect(
301 bind(&GuiWorkArea::generateSyntheticMouseEvent,
304 // Initialize the vertical Scroll Bar
305 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
306 this, SLOT(scrollTo(int)));
308 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
309 << " viewport height: " << viewport()->height());
311 // Enables input methods for asian languages.
312 // Must be set when creating custom text editing widgets.
313 setAttribute(Qt::WA_InputMethodEnabled, true);
315 d->dialog_mode_ = false;
319 GuiWorkArea::~GuiWorkArea()
321 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();
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 // FIXME: let GuiView take care of those.
536 if (cmd.action() != LFUN_MOUSE_MOTION) {
537 completer_->updateVisibility(false, false);
538 lyx_view_->updateDialogs();
539 lyx_view_->updateStatusBar();
542 // GUI tweaks except with mouse motion with no button pressed.
543 if (notJustMovingTheMouse) {
544 // Slight hack: this is only called currently when we
545 // clicked somewhere, so we force through the display
546 // of the new status here.
547 // FIXME: let GuiView take care of those.
548 lyx_view_->clearMessage();
550 // Show the cursor immediately after any operation
551 p->startBlinkingCursor();
558 void GuiWorkArea::Private::resizeBufferView()
560 // WARNING: Please don't put any code that will trigger a repaint here!
561 // We are already inside a paint event.
562 p->stopBlinkingCursor();
563 // Warn our container (GuiView).
568 buffer_view_->cursorPosAndHeight(point, h);
569 bool const cursor_in_view = buffer_view_->cursorInView(point, h);
570 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
572 buffer_view_->scrollToCursor();
575 // Update scrollbars which might have changed due different
576 // BufferView dimension. This is especially important when the
577 // BufferView goes from zero-size to the real-size for the first time,
578 // as the scrollbar paramters are then set for the first time.
581 need_resize_ = false;
583 // Eventually, restart the cursor after the resize event.
584 // We might be resizing even if the focus is on another widget so we only
585 // restart the cursor if we have the focus.
587 QTimer::singleShot(50, p, SLOT(startBlinkingCursor()));
591 void GuiWorkArea::Private::showCursor()
598 buffer_view_->cursorPosAndHeight(p, h);
599 if (!buffer_view_->cursorInView(p, h))
603 bool l_shape = false;
604 Font const & realfont = buffer_view_->cursor().real_current_font;
605 BufferParams const & bp = buffer_view_->buffer().params();
606 bool const samelang = realfont.language() == bp.language;
607 bool const isrtl = realfont.isVisibleRightToLeft();
609 if (!samelang || isrtl != bp.language->rightToLeft())
612 // The ERT language hack needs fixing up
613 if (realfont.language() == latex_language)
616 // show cursor on screen
617 Cursor & cur = buffer_view_->cursor();
618 bool completable = cur.inset().showCompletionCursor()
619 && completer_->completionAvailable()
620 && !completer_->popupVisible()
621 && !completer_->inlineVisible();
622 cursor_visible_ = true;
623 cursor_->recomputeWidth();
624 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
628 void GuiWorkArea::Private::hideCursor()
630 if (!cursor_visible_)
633 cursor_visible_ = false;
638 void GuiWorkArea::toggleCursor()
640 if (d->cursor_visible_)
647 void GuiWorkArea::Private::updateScrollbar()
649 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
650 // WARNING: don't touch at the scrollbar value like this:
651 // verticalScrollBar()->setValue(scroll_.position);
652 // because this would cause a recursive signal/slot calling with
653 // GuiWorkArea::scrollTo
654 p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
655 p->verticalScrollBar()->setPageStep(scroll_.page_step);
656 p->verticalScrollBar()->setSingleStep(scroll_.single_step);
657 p->verticalScrollBar()->setSliderPosition(scroll_.position);
661 void GuiWorkArea::scrollTo(int value)
663 stopBlinkingCursor();
664 d->buffer_view_->scrollDocView(value, true);
666 if (lyxrc.cursor_follows_scrollbar) {
667 d->buffer_view_->setCursorFromScrollbar();
668 // FIXME: let GuiView take care of those.
669 d->lyx_view_->updateLayoutList();
671 // Show the cursor immediately after any operation.
672 startBlinkingCursor();
673 QApplication::syncX();
677 bool GuiWorkArea::event(QEvent * e)
680 case QEvent::ToolTip: {
681 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
682 if (lyxrc.use_tooltip) {
683 QPoint pos = helpEvent->pos();
684 if (pos.x() < viewport()->width()) {
685 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
686 QToolTip::showText(helpEvent->globalPos(), s);
689 QToolTip::hideText();
691 // Don't forget to accept the event!
696 case QEvent::ShortcutOverride: {
697 // We catch this event in order to catch the Tab or Shift+Tab key press
698 // which are otherwise reserved to focus switching between controls
700 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
701 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
702 || (ke->key() == Qt::Key_Backtab && (
703 ke->modifiers() == Qt::ShiftModifier
704 || ke->modifiers() == Qt::NoModifier))) {
708 return QAbstractScrollArea::event(e);
712 return QAbstractScrollArea::event(e);
718 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
721 if (e->reason() == QContextMenuEvent::Mouse)
722 // the menu name is set on mouse press
723 name = d->context_menu_name_;
725 QPoint pos = e->pos();
726 Cursor const & cur = d->buffer_view_->cursor();
727 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
728 // Do not access the context menu of math right in front of before
729 // the cursor. This does not work when the cursor is in text.
730 Inset * inset = cur.paragraph().getInset(cur.pos());
731 if (inset && inset->asInsetMath())
733 else if (cur.pos() > 0) {
734 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
739 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
743 QAbstractScrollArea::contextMenuEvent(e);
746 // always show mnemonics when the keyboard is used to show the context menu
747 // FIXME: This should be fixed in Qt itself
748 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
749 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
751 QAbstractScrollArea::contextMenuEvent(e);
754 // Position the menu to the right.
755 // FIXME: menu position should be different for RTL text.
756 menu->exec(e->globalPos());
761 void GuiWorkArea::focusInEvent(QFocusEvent * e)
763 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
764 if (d->lyx_view_->currentWorkArea() != this) {
765 d->lyx_view_->setCurrentWorkArea(this);
766 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
769 startBlinkingCursor();
770 QAbstractScrollArea::focusInEvent(e);
774 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
776 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
777 stopBlinkingCursor();
778 QAbstractScrollArea::focusOutEvent(e);
782 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
784 if (d->dc_event_.active && d->dc_event_ == *e) {
785 d->dc_event_.active = false;
786 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
787 q_button_state(e->button()));
793 inputContext()->reset();
795 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
796 q_button_state(e->button()));
797 d->dispatch(cmd, q_key_state(e->modifiers()));
799 // Save the context menu on mouse press, because also the mouse
800 // cursor is set on mouse press. Afterwards, we can either release
801 // the mousebutton somewhere else, or the cursor might have moved
802 // due to the DEPM. We need to do this after the mouse has been
803 // set in dispatch(), because the selection state might change.
804 if (e->button() == Qt::RightButton)
805 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
811 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
813 if (d->synthetic_mouse_event_.timeout.running())
814 d->synthetic_mouse_event_.timeout.stop();
816 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
817 q_button_state(e->button()));
823 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
825 // we kill the triple click if we move
826 doubleClickTimeout();
827 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
828 q_motion_state(e->buttons()));
832 // If we're above or below the work area...
833 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
834 && e->buttons() == mouse_button::button1) {
835 // Make sure only a synthetic event can cause a page scroll,
836 // so they come at a steady rate:
838 // _Force_ a scroll up:
839 cmd.set_y(e->y() - 21);
841 cmd.set_y(e->y() + 21);
842 // Store the event, to be handled when the timeout expires.
843 d->synthetic_mouse_event_.cmd = cmd;
845 if (d->synthetic_mouse_event_.timeout.running()) {
846 // Discard the event. Note that it _may_ be handled
847 // when the timeout expires if
848 // synthetic_mouse_event_.cmd has not been overwritten.
849 // Ie, when the timeout expires, we handle the
850 // most recent event but discard all others that
851 // occurred after the one used to start the timeout
852 // in the first place.
856 d->synthetic_mouse_event_.restart_timeout = true;
857 d->synthetic_mouse_event_.timeout.start();
858 // Fall through to handle this event...
860 } else if (d->synthetic_mouse_event_.timeout.running()) {
861 // Store the event, to be possibly handled when the timeout
863 // Once the timeout has expired, normal control is returned
864 // to mouseMoveEvent (restart_timeout = false).
865 // This results in a much smoother 'feel' when moving the
866 // mouse back into the work area.
867 d->synthetic_mouse_event_.cmd = cmd;
868 d->synthetic_mouse_event_.restart_timeout = false;
875 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
877 // Wheel rotation by one notch results in a delta() of 120 (see
878 // documentation of QWheelEvent)
879 double const delta = ev->delta() / 120.0;
881 switch (lyxrc.scroll_wheel_zoom) {
882 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
883 zoom = ev->modifiers() & Qt::ControlModifier;
884 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
886 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
887 zoom = ev->modifiers() & Qt::ShiftModifier;
888 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
890 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
891 zoom = ev->modifiers() & Qt::AltModifier;
892 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
894 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
898 docstring arg = convert<docstring>(int(5 * delta));
899 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
903 // Take into account the desktop wide settings.
904 int const lines = qApp->wheelScrollLines();
905 int const page_step = verticalScrollBar()->pageStep();
906 // Test if the wheel mouse is set to one screen at a time.
907 int scroll_value = lines > page_step
908 ? page_step : lines * verticalScrollBar()->singleStep();
910 // Take into account the rotation and the user preferences.
911 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
912 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
913 << " delta = " << delta << " scroll_value = " << scroll_value
914 << " page_step = " << page_step);
916 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
922 void GuiWorkArea::generateSyntheticMouseEvent()
924 int const e_y = d->synthetic_mouse_event_.cmd.y();
925 int const wh = d->buffer_view_->workHeight();
926 bool const up = e_y < 0;
927 bool const down = e_y > wh;
929 // Set things off to generate the _next_ 'pseudo' event.
931 if (d->synthetic_mouse_event_.restart_timeout) {
932 // This is some magic formulae to determine the speed
933 // of scrolling related to the position of the mouse.
936 int dist = up ? -e_y : e_y - wh;
937 time = max(min(200, 250000 / (dist * dist)), 1) ;
940 step = 80000 / (time * time);
944 d->synthetic_mouse_event_.timeout.setTimeout(time);
945 d->synthetic_mouse_event_.timeout.start();
948 // Can we scroll further ?
949 int const value = verticalScrollBar()->value();
950 if (value == verticalScrollBar()->maximum()
951 || value == verticalScrollBar()->minimum()) {
952 d->synthetic_mouse_event_.timeout.stop();
957 if (step <= 2 * wh) {
958 d->buffer_view_->scroll(up ? -step : step);
959 d->buffer_view_->updateMetrics();
961 d->buffer_view_->scrollDocView(value + up ? -step : step, false);
964 // In which paragraph do we have to set the cursor ?
965 Cursor & cur = d->buffer_view_->cursor();
966 // FIXME: we don't know howto handle math.
967 Text * text = cur.text();
970 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
972 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
973 ParagraphMetrics const & pm = *pp.second;
974 pit_type const pit = pp.first;
976 if (pm.rows().empty())
979 // Find the row at which we set the cursor.
980 RowList::const_iterator rit = pm.rows().begin();
981 RowList::const_iterator rlast = pm.rows().end();
982 int yy = pm.position() - pm.ascent();
983 for (--rlast; rit != rlast; ++rit) {
984 int h = rit->height();
985 if ((up && yy + h > 0)
986 || (!up && yy + h > wh - defaultRowHeight()))
991 // Find the position of the cursor
993 int x = d->synthetic_mouse_event_.cmd.x();
994 pos_type const pos = rit->pos() + tm.getColumnNearX(pit, *rit, x, bound);
1001 d->buffer_view_->buffer().changed(false);
1006 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1008 // Do not process here some keys if dialog_mode_ is set
1010 && (ev->modifiers() == Qt::NoModifier
1011 || ev->modifiers() == Qt::ShiftModifier)
1012 && (ev->key() == Qt::Key_Escape
1013 || ev->key() == Qt::Key_Enter
1014 || ev->key() == Qt::Key_Return)
1020 // intercept some keys if completion popup is visible
1021 if (d->completer_->popupVisible()) {
1022 switch (ev->key()) {
1024 case Qt::Key_Return:
1025 d->completer_->activate();
1031 // do nothing if there are other events
1032 // (the auto repeated events come too fast)
1033 // it looks like this is only needed on X11
1035 if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1036 switch (ev->key()) {
1037 case Qt::Key_PageDown:
1038 case Qt::Key_PageUp:
1043 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1050 KeyModifier m = q_key_state(ev->modifiers());
1053 if (m & ShiftModifier)
1055 if (m & ControlModifier)
1057 if (m & AltModifier)
1059 if (m & MetaModifier)
1062 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1063 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1064 << " keyState: " << str);
1067 setKeySymbol(&sym, ev);
1069 processKeySym(sym, q_key_state(ev->modifiers()));
1077 void GuiWorkArea::doubleClickTimeout()
1079 d->dc_event_.active = false;
1083 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1085 d->dc_event_ = DoubleClick(ev);
1086 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1087 SLOT(doubleClickTimeout()));
1088 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1090 q_button_state(ev->button()));
1096 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1098 QAbstractScrollArea::resizeEvent(ev);
1099 d->need_resize_ = true;
1104 void GuiWorkArea::Private::update(int x, int y, int w, int h)
1106 p->viewport()->update(x, y, w, h);
1110 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1112 QRect const rc = ev->rect();
1113 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1114 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1116 if (d->need_resize_) {
1118 d->resizeBufferView();
1119 if (d->cursor_visible_) {
1125 QPainter pain(viewport());
1126 if (lyxrc.use_qimage) {
1127 pain.drawImage(rc, static_cast<QImage const &>(*d->screen_), rc);
1129 pain.drawPixmap(rc, static_cast<QPixmap const &>(*d->screen_), rc);
1131 d->cursor_->draw(pain);
1136 void GuiWorkArea::Private::updateScreen()
1138 GuiPainter pain(screen_);
1139 buffer_view_->draw(pain);
1143 void GuiWorkArea::Private::showCursor(int x, int y, int h,
1144 bool l_shape, bool rtl, bool completable)
1146 if (schedule_redraw_) {
1147 // This happens when a graphic conversion is finished. As we don't know
1148 // the size of the new graphics, it's better the update everything.
1149 // We can't use redraw() here because this would trigger a infinite
1150 // recursive loop with showCursor().
1151 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
1154 p->viewport()->update(QRect(0, 0, p->viewport()->width(), p->viewport()->height()));
1155 schedule_redraw_ = false;
1156 // Show the cursor immediately after the update.
1162 cursor_->update(x, y, h, l_shape, rtl, completable);
1164 p->viewport()->update(cursor_->rect());
1168 void GuiWorkArea::Private::removeCursor()
1171 //if (!qApp->focusWidget())
1172 p->viewport()->update(cursor_->rect());
1176 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1178 QString const & commit_string = e->commitString();
1179 docstring const & preedit_string
1180 = qstring_to_ucs4(e->preeditString());
1182 if (!commit_string.isEmpty()) {
1184 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1185 << " commitString: " << e->commitString());
1189 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1190 for (int i = 0; i != commit_string.size(); ++i) {
1191 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1196 // Hide the cursor during the kana-kanji transformation.
1197 if (preedit_string.empty())
1198 startBlinkingCursor();
1200 stopBlinkingCursor();
1202 // last_width : for checking if last preedit string was/wasn't empty.
1203 static bool last_width = false;
1204 if (!last_width && preedit_string.empty()) {
1205 // if last_width is last length of preedit string.
1210 GuiPainter pain(d->screen_);
1211 d->buffer_view_->updateMetrics();
1212 d->buffer_view_->draw(pain);
1213 FontInfo font = d->buffer_view_->cursor().getFont().fontInfo();
1214 FontMetrics const & fm = theFontMetrics(font);
1215 int height = fm.maxHeight();
1216 int cur_x = d->cursor_->rect().left();
1217 int cur_y = d->cursor_->rect().bottom();
1219 // redraw area of preedit string.
1220 update(0, cur_y - height, viewport()->width(),
1221 (height + 1) * d->preedit_lines_);
1223 if (preedit_string.empty()) {
1225 d->preedit_lines_ = 1;
1231 // att : stores an IM attribute.
1232 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1234 // get attributes of input method cursor.
1235 // cursor_pos : cursor position in preedit string.
1236 size_t cursor_pos = 0;
1237 bool cursor_is_visible = false;
1238 for (int i = 0; i != att.size(); ++i) {
1239 if (att.at(i).type == QInputMethodEvent::Cursor) {
1240 cursor_pos = att.at(i).start;
1241 cursor_is_visible = att.at(i).length != 0;
1246 size_t preedit_length = preedit_string.length();
1248 // get position of selection in input method.
1249 // FIXME: isn't there a way to do this simplier?
1250 // rStart : cursor position in selected string in IM.
1252 // rLength : selected string length in IM.
1254 if (cursor_pos < preedit_length) {
1255 for (int i = 0; i != att.size(); ++i) {
1256 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1257 if (att.at(i).start <= int(cursor_pos)
1258 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1259 rStart = att.at(i).start;
1260 rLength = att.at(i).length;
1261 if (!cursor_is_visible)
1262 cursor_pos += rLength;
1269 rStart = cursor_pos;
1273 int const right_margin = d->buffer_view_->rightMargin();
1274 Painter::preedit_style ps;
1275 // Most often there would be only one line:
1276 d->preedit_lines_ = 1;
1277 for (size_t pos = 0; pos != preedit_length; ++pos) {
1278 char_type const typed_char = preedit_string[pos];
1279 // reset preedit string style
1280 ps = Painter::preedit_default;
1282 // if we reached the right extremity of the screen, go to next line.
1283 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1284 cur_x = right_margin;
1285 cur_y += height + 1;
1286 ++d->preedit_lines_;
1288 // preedit strings are displayed with dashed underline
1289 // and partial strings are displayed white on black indicating
1290 // that we are in selecting mode in the input method.
1291 // FIXME: rLength == preedit_length is not a changing condition
1292 // FIXME: should be put out of the loop.
1294 && pos < rStart + rLength
1295 && !(cursor_pos < rLength && rLength == preedit_length))
1296 ps = Painter::preedit_selecting;
1298 if (pos == cursor_pos
1299 && (cursor_pos < rLength && rLength == preedit_length))
1300 ps = Painter::preedit_cursor;
1302 // draw one character and update cur_x.
1303 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1306 // update the preedit string screen area.
1307 update(0, cur_y - d->preedit_lines_*height, viewport()->width(),
1308 (height + 1) * d->preedit_lines_);
1310 // Don't forget to accept the event!
1315 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1317 QRect cur_r(0, 0, 0, 0);
1319 // this is the CJK-specific composition window position and
1320 // the context menu position when the menu key is pressed.
1321 case Qt::ImMicroFocus:
1322 cur_r = d->cursor_->rect();
1323 if (d->preedit_lines_ != 1)
1325 cur_r.moveBottom(cur_r.bottom()
1326 + cur_r.height() * (d->preedit_lines_ - 1));
1327 // return lower right of cursor in LyX.
1330 return QWidget::inputMethodQuery(query);
1335 void GuiWorkArea::updateWindowTitle()
1337 docstring maximize_title;
1338 docstring minimize_title;
1340 Buffer const & buf = d->buffer_view_->buffer();
1341 FileName const file_name = buf.fileName();
1342 if (!file_name.empty()) {
1343 maximize_title = file_name.displayName(130);
1344 minimize_title = from_utf8(file_name.onlyFileName());
1345 if (buf.lyxvc().inUse()) {
1346 if (buf.lyxvc().locking())
1347 maximize_title += _(" (version control, locking)");
1349 maximize_title += _(" (version control)");
1351 if (!buf.isClean()) {
1352 maximize_title += _(" (changed)");
1353 minimize_title += char_type('*');
1355 if (buf.isReadonly())
1356 maximize_title += _(" (read only)");
1359 QString const new_title = toqstr(maximize_title);
1360 if (new_title != windowTitle()) {
1361 QWidget::setWindowTitle(new_title);
1362 QWidget::setWindowIconText(toqstr(minimize_title));
1368 bool GuiWorkArea::isFullScreen() const
1370 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1374 void GuiWorkArea::scheduleRedraw()
1376 d->schedule_redraw_ = true;
1380 bool GuiWorkArea::inDialogMode() const
1382 return d->dialog_mode_;
1386 void GuiWorkArea::setDialogMode(bool mode)
1388 d->dialog_mode_ = mode;
1392 GuiCompleter & GuiWorkArea::completer()
1394 return *d->completer_;
1397 GuiView const & GuiWorkArea::view() const
1399 return *d->lyx_view_;
1403 GuiView & GuiWorkArea::view()
1405 return *d->lyx_view_;
1408 ////////////////////////////////////////////////////////////////////
1412 ////////////////////////////////////////////////////////////////////
1415 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1417 buffer_ = theBufferList().newBuffer(
1418 support::FileName::tempName().absFileName() + "_embedded.internal");
1419 buffer_->setUnnamed(true);
1420 buffer_->setFullyLoaded(true);
1421 setBuffer(*buffer_);
1422 setDialogMode(true);
1426 EmbeddedWorkArea::~EmbeddedWorkArea()
1428 // No need to destroy buffer and bufferview here, because it is done
1429 // in theBufferList() destruction loop at application exit
1433 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1436 GuiWorkArea::closeEvent(ev);
1440 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1443 GuiWorkArea::hideEvent(ev);
1447 QSize EmbeddedWorkArea::sizeHint () const
1450 // GuiWorkArea sets the size to the screen's viewport
1451 // by returning a value this gets overridden
1452 // EmbeddedWorkArea is now sized to fit in the layout
1453 // of the parent, and has a minimum size set in GuiWorkArea
1454 // which is what we return here
1455 return QSize(100, 70);
1459 void EmbeddedWorkArea::disable()
1461 stopBlinkingCursor();
1462 if (view().currentWorkArea() != this)
1464 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1465 // tolerates it and shows the background logo), what happens if
1466 // an EmbeddedWorkArea is closed after closing all document WAs
1467 view().setCurrentWorkArea(view().currentMainWorkArea());
1470 ////////////////////////////////////////////////////////////////////
1474 ////////////////////////////////////////////////////////////////////
1477 class NoTabFrameMacStyle : public QMacStyle {
1480 QRect subElementRect(SubElement element, const QStyleOption * option,
1481 const QWidget * widget = 0) const
1483 QRect rect = QMacStyle::subElementRect(element, option, widget);
1484 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1486 // The Qt Mac style puts the contents into a 3 pixel wide box
1487 // which looks very ugly and not like other Mac applications.
1488 // Hence we remove this here, and moreover the 16 pixel round
1489 // frame above if the tab bar is hidden.
1490 if (element == QStyle::SE_TabWidgetTabContents) {
1491 rect.adjust(- rect.left(), 0, rect.left(), 0);
1500 NoTabFrameMacStyle noTabFrameMacStyle;
1504 TabWorkArea::TabWorkArea(QWidget * parent)
1505 : QTabWidget(parent), clicked_tab_(-1)
1508 setStyle(&noTabFrameMacStyle);
1510 #if QT_VERSION < 0x040500
1511 lyxrc.single_close_tab_button = true;
1514 QPalette pal = palette();
1515 pal.setColor(QPalette::Active, QPalette::Button,
1516 pal.color(QPalette::Active, QPalette::Window));
1517 pal.setColor(QPalette::Disabled, QPalette::Button,
1518 pal.color(QPalette::Disabled, QPalette::Window));
1519 pal.setColor(QPalette::Inactive, QPalette::Button,
1520 pal.color(QPalette::Inactive, QPalette::Window));
1522 QObject::connect(this, SIGNAL(currentChanged(int)),
1523 this, SLOT(on_currentTabChanged(int)));
1525 closeBufferButton = new QToolButton(this);
1526 closeBufferButton->setPalette(pal);
1527 // FIXME: rename the icon to closebuffer.png
1528 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1529 closeBufferButton->setText("Close File");
1530 closeBufferButton->setAutoRaise(true);
1531 closeBufferButton->setCursor(Qt::ArrowCursor);
1532 closeBufferButton->setToolTip(qt_("Close File"));
1533 closeBufferButton->setEnabled(true);
1534 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1535 this, SLOT(closeCurrentBuffer()));
1536 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1538 // setup drag'n'drop
1539 QTabBar* tb = new DragTabBar;
1540 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1541 this, SLOT(moveTab(int, int)));
1542 tb->setElideMode(Qt::ElideNone);
1545 // make us responsible for the context menu of the tabbar
1546 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1547 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1548 this, SLOT(showContextMenu(const QPoint &)));
1549 #if QT_VERSION >= 0x040500
1550 connect(tb, SIGNAL(tabCloseRequested(int)),
1551 this, SLOT(closeTab(int)));
1554 setUsesScrollButtons(true);
1558 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1560 if (event->button() != Qt::LeftButton)
1563 // return early if double click on existing tabs
1564 for (int i = 0; i < count(); ++i)
1565 if (tabBar()->tabRect(i).contains(event->pos()))
1568 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1572 void TabWorkArea::setFullScreen(bool full_screen)
1574 for (int i = 0; i != count(); ++i) {
1575 if (GuiWorkArea * wa = workArea(i))
1576 wa->setFullScreen(full_screen);
1579 if (lyxrc.full_screen_tabbar)
1580 showBar(!full_screen && count() > 1);
1582 showBar(count() > 1);
1586 void TabWorkArea::showBar(bool show)
1588 tabBar()->setEnabled(show);
1589 tabBar()->setVisible(show);
1590 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1591 #if QT_VERSION >= 0x040500
1592 setTabsClosable(!lyxrc.single_close_tab_button);
1597 GuiWorkArea * TabWorkArea::currentWorkArea()
1602 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1608 GuiWorkArea * TabWorkArea::workArea(int index)
1610 return dynamic_cast<GuiWorkArea *>(widget(index));
1614 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1616 // FIXME: this method doesn't work if we have more than work area
1617 // showing the same buffer.
1618 for (int i = 0; i != count(); ++i) {
1619 GuiWorkArea * wa = workArea(i);
1620 LASSERT(wa, return 0);
1621 if (&wa->bufferView().buffer() == &buffer)
1628 void TabWorkArea::closeAll()
1631 GuiWorkArea * wa = workArea(0);
1639 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1641 LASSERT(work_area, /**/);
1642 int index = indexOf(work_area);
1646 if (index == currentIndex())
1647 // Make sure the work area is up to date.
1648 on_currentTabChanged(index);
1650 // Switch to the work area.
1651 setCurrentIndex(index);
1652 work_area->setFocus();
1658 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1660 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1661 wa->setUpdatesEnabled(false);
1662 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1663 // when hiding it again below).
1664 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1665 showBar(count() > 0);
1666 addTab(wa, wa->windowTitle());
1667 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1668 this, SLOT(updateTabTexts()));
1669 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1670 setFullScreen(true);
1672 // Hide tabbar if there's only one tab.
1673 showBar(count() > 1);
1681 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1683 LASSERT(work_area, return false);
1684 int index = indexOf(work_area);
1688 work_area->setUpdatesEnabled(false);
1693 // make sure the next work area is enabled.
1694 currentWidget()->setUpdatesEnabled(true);
1695 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1696 setFullScreen(true);
1698 // Show tabbar only if there's more than one tab.
1699 showBar(count() > 1);
1701 lastWorkAreaRemoved();
1709 void TabWorkArea::on_currentTabChanged(int i)
1711 // returns e.g. on application destruction
1714 GuiWorkArea * wa = workArea(i);
1715 LASSERT(wa, return);
1716 wa->setUpdatesEnabled(true);
1720 currentWorkAreaChanged(wa);
1722 LYXERR(Debug::GUI, "currentTabChanged " << i
1723 << " File: " << wa->bufferView().buffer().absFileName());
1727 void TabWorkArea::closeCurrentBuffer()
1730 if (clicked_tab_ == -1)
1731 wa = currentWorkArea();
1733 wa = workArea(clicked_tab_);
1736 wa->view().closeWorkArea(wa);
1740 void TabWorkArea::hideCurrentTab()
1743 if (clicked_tab_ == -1)
1744 wa = currentWorkArea();
1746 wa = workArea(clicked_tab_);
1749 wa->view().hideWorkArea(wa);
1753 void TabWorkArea::closeTab(int index)
1755 on_currentTabChanged(index);
1758 wa = currentWorkArea();
1760 wa = workArea(index);
1763 wa->view().closeWorkArea(wa);
1770 /// make vector happy
1773 DisplayPath(int tab, FileName const & filename)
1776 filename_ = (filename.extension() == "lyx") ?
1777 toqstr(filename.onlyFileNameWithoutExt())
1778 : toqstr(filename.onlyFileName());
1779 postfix_ = toqstr(filename.absoluteFilePath()).
1780 split("/", QString::SkipEmptyParts);
1781 postfix_.pop_back();
1782 abs_ = toqstr(filename.absoluteFilePath());
1783 dottedPrefix_ = false;
1786 /// Absolute path for debugging.
1791 /// Add the first segment from the postfix or three dots to the prefix.
1792 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1793 /// when really needed.
1794 void shiftPathSegment(bool dotted)
1796 if (postfix_.count() <= 0)
1800 if (dottedPrefix_ && !prefix_.isEmpty())
1802 prefix_ += postfix_.front() + "/";
1804 dottedPrefix_ = dotted && !prefix_.isEmpty();
1805 postfix_.pop_front();
1808 QString displayString() const
1810 if (prefix_.isEmpty())
1813 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1814 return prefix_ + (dots ? ".../" : "") + filename_;
1817 QString forecastPathString() const
1819 if (postfix_.count() == 0)
1820 return displayString();
1823 + (dottedPrefix_ ? ".../" : "")
1824 + postfix_.front() + "/";
1827 bool final() const { return postfix_.empty(); }
1829 int tab() const { return tab_; }
1835 QStringList postfix_;
1848 bool operator<(DisplayPath const & a, DisplayPath const & b)
1850 return a.displayString() < b.displayString();
1854 bool operator==(DisplayPath const & a, DisplayPath const & b)
1856 return a.displayString() == b.displayString();
1860 void TabWorkArea::updateTabTexts()
1865 std::list<DisplayPath> paths;
1866 typedef std::list<DisplayPath>::iterator It;
1868 // collect full names first: path into postfix, empty prefix and
1869 // filename without extension
1870 for (size_t i = 0; i < n; ++i) {
1871 GuiWorkArea * i_wa = workArea(i);
1872 FileName const fn = i_wa->bufferView().buffer().fileName();
1873 paths.push_back(DisplayPath(i, fn));
1876 // go through path segments and see if it helps to make the path more unique
1877 bool somethingChanged = true;
1878 bool allFinal = false;
1879 while (somethingChanged && !allFinal) {
1880 // adding path segments changes order
1883 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1884 somethingChanged = false;
1887 // find segments which are not unique (i.e. non-atomic)
1888 It it = paths.begin();
1890 QString segString = it->displayString();
1891 for (; it != paths.end(); ++it) {
1892 // look to the next item
1897 allFinal = allFinal && it->final();
1899 LYXERR(Debug::GUI, "it = " << it->abs()
1900 << " => " << it->displayString());
1902 // still the same segment?
1904 if ((next != paths.end()
1905 && (nextString = next->displayString()) == segString))
1907 LYXERR(Debug::GUI, "segment ended");
1909 // only a trivial one with one element?
1910 if (it == segStart) {
1911 // start new segment
1913 segString = nextString;
1917 // we found a non-atomic segment segStart <= sit <= it < next.
1918 // Shift path segments and hope for the best
1919 // that it makes the path more unique.
1920 somethingChanged = true;
1922 QString dspString = sit->forecastPathString();
1923 LYXERR(Debug::GUI, "first forecast found for "
1924 << sit->abs() << " => " << dspString);
1926 bool moreUnique = false;
1927 for (; sit != next; ++sit) {
1928 if (sit->forecastPathString() != dspString) {
1929 LYXERR(Debug::GUI, "different forecast found for "
1930 << sit->abs() << " => " << sit->forecastPathString());
1934 LYXERR(Debug::GUI, "same forecast found for "
1935 << sit->abs() << " => " << dspString);
1938 // if the path segment helped, add it. Otherwise add dots
1939 bool dots = !moreUnique;
1940 LYXERR(Debug::GUI, "using dots = " << dots);
1941 for (sit = segStart; sit != next; ++sit) {
1942 sit->shiftPathSegment(dots);
1943 LYXERR(Debug::GUI, "shifting "
1944 << sit->abs() << " => " << sit->displayString());
1947 // start new segment
1949 segString = nextString;
1953 // set new tab titles
1954 for (It it = paths.begin(); it != paths.end(); ++it) {
1955 int const tab_index = it->tab();
1956 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
1957 QString tab_text = it->displayString();
1958 if (!buf.fileName().empty() && !buf.isClean())
1960 setTabText(tab_index, tab_text);
1961 setTabToolTip(tab_index, it->abs());
1966 void TabWorkArea::showContextMenu(const QPoint & pos)
1969 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1970 if (clicked_tab_ == -1)
1975 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
1976 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
1977 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
1978 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1979 popup.exec(tabBar()->mapToGlobal(pos));
1985 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1987 QWidget * w = widget(fromIndex);
1988 QIcon icon = tabIcon(fromIndex);
1989 QString text = tabText(fromIndex);
1991 setCurrentIndex(fromIndex);
1992 removeTab(fromIndex);
1993 insertTab(toIndex, w, icon, text);
1994 setCurrentIndex(toIndex);
1998 DragTabBar::DragTabBar(QWidget* parent)
2001 setAcceptDrops(true);
2002 #if QT_VERSION >= 0x040500
2003 setTabsClosable(!lyxrc.single_close_tab_button);
2008 #if QT_VERSION < 0x040300
2009 int DragTabBar::tabAt(QPoint const & position) const
2011 const int max = count();
2012 for (int i = 0; i < max; ++i) {
2013 if (tabRect(i).contains(position))
2021 void DragTabBar::mousePressEvent(QMouseEvent * event)
2023 if (event->button() == Qt::LeftButton)
2024 dragStartPos_ = event->pos();
2025 QTabBar::mousePressEvent(event);
2029 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2031 // If the left button isn't pressed anymore then return
2032 if (!(event->buttons() & Qt::LeftButton))
2035 // If the distance is too small then return
2036 if ((event->pos() - dragStartPos_).manhattanLength()
2037 < QApplication::startDragDistance())
2040 // did we hit something after all?
2041 int tab = tabAt(dragStartPos_);
2045 // simulate button release to remove highlight from button
2046 int i = currentIndex();
2047 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2048 event->button(), event->buttons(), 0);
2049 QTabBar::mouseReleaseEvent(&me);
2053 QDrag * drag = new QDrag(this);
2054 QMimeData * mimeData = new QMimeData;
2055 // a crude way to distinguish tab-reodering drops from other ones
2056 mimeData->setData("action", "tab-reordering") ;
2057 drag->setMimeData(mimeData);
2059 #if QT_VERSION >= 0x040300
2060 // get tab pixmap as cursor
2061 QRect r = tabRect(tab);
2062 QPixmap pixmap(r.size());
2063 render(&pixmap, - r.topLeft());
2064 drag->setPixmap(pixmap);
2067 drag->start(Qt::MoveAction);
2073 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2075 // Only accept if it's an tab-reordering request
2076 QMimeData const * m = event->mimeData();
2077 QStringList formats = m->formats();
2078 if (formats.contains("action")
2079 && m->data("action") == "tab-reordering")
2080 event->acceptProposedAction();
2084 void DragTabBar::dropEvent(QDropEvent * event)
2086 int fromIndex = tabAt(dragStartPos_);
2087 int toIndex = tabAt(event->pos());
2089 // Tell interested objects that
2090 if (fromIndex != toIndex)
2091 tabMoveRequested(fromIndex, toIndex);
2092 event->acceptProposedAction();
2096 } // namespace frontend
2099 #include "moc_GuiWorkArea.cpp"