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), 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);
322 delete d->buffer_view_;
324 // Completer has a QObject parent and is thus automatically destroyed.
326 // delete completer_;
331 Qt::CursorShape GuiWorkArea::cursorShape() const
333 return viewport()->cursor().shape();
337 void GuiWorkArea::Private::setCursorShape(Qt::CursorShape shape)
339 p->viewport()->setCursor(shape);
343 void GuiWorkArea::Private::updateCursorShape()
345 setCursorShape(buffer_view_->clickableInset()
346 ? Qt::PointingHandCursor : Qt::IBeamCursor);
350 void GuiWorkArea::setGuiView(GuiView & gv)
356 void GuiWorkArea::setBuffer(Buffer & buffer)
358 delete d->buffer_view_;
359 d->buffer_view_ = new BufferView(buffer);
360 buffer.workAreaManager().add(this);
362 // HACK: Prevents an additional redraw when the scrollbar pops up
363 // which regularily happens on documents with more than one page.
364 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
365 // Since we have no geometry information yet, we assume that
366 // a document needs a scrollbar if there is more then four
367 // paragraph in the outermost text.
368 if (buffer.text().paragraphs().size() > 4)
369 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
370 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
374 void GuiWorkArea::fixVerticalScrollBar()
377 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
381 void GuiWorkArea::close()
383 d->lyx_view_->removeWorkArea(this);
387 void GuiWorkArea::setFullScreen(bool full_screen)
389 d->buffer_view_->setFullScreen(full_screen);
390 setFrameStyle(QFrame::NoFrame);
392 setFrameStyle(QFrame::NoFrame);
393 if (lyxrc.full_screen_scrollbar)
394 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
396 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
400 BufferView & GuiWorkArea::bufferView()
402 return *d->buffer_view_;
406 BufferView const & GuiWorkArea::bufferView() const
408 return *d->buffer_view_;
412 void GuiWorkArea::stopBlinkingCursor()
414 d->cursor_timeout_.stop();
419 void GuiWorkArea::startBlinkingCursor()
421 // do not show the cursor if the view is busy
427 d->buffer_view_->cursorPosAndHeight(p, h);
428 // Don't start blinking if the cursor isn't on screen.
429 if (!d->buffer_view_->cursorInView(p, h))
434 //we're not supposed to cache this value.
435 int const time = QApplication::cursorFlashTime() / 2;
438 d->cursor_timeout_.setInterval(time);
439 d->cursor_timeout_.start();
443 void GuiWorkArea::redraw(bool update_metrics)
446 // No need to redraw in this case.
449 // No need to do anything if this is the current view. The BufferView
450 // metrics are already up to date.
451 if (update_metrics || d->lyx_view_ != guiApp->currentView()
452 || d->lyx_view_->currentWorkArea() != this) {
453 // FIXME: it would be nice to optimize for the off-screen case.
454 d->buffer_view_->cursor().fixIfBroken();
455 d->buffer_view_->updateMetrics();
456 d->buffer_view_->cursor().fixIfBroken();
459 // update cursor position, because otherwise it has to wait until
460 // the blinking interval is over
461 if (d->cursor_visible_) {
466 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
468 update(0, 0, viewport()->width(), viewport()->height());
470 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
471 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
472 d->updateScrollbar();
473 d->lyx_view_->updateStatusBar();
475 if (lyxerr.debugging(Debug::WORKAREA))
476 d->buffer_view_->coordCache().dump();
480 d->updateCursorShape();
484 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
486 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
487 && lyxrc.full_screen_menubar) {
488 // FIXME HACK: we should not have to do this here. See related comment
489 // in GuiView::event() (QEvent::ShortcutOverride)
490 d->lyx_view_->menuBar()->hide();
493 // In order to avoid bad surprise in the middle of an operation,
494 // we better stop the blinking cursor...
495 // the cursor gets restarted in GuiView::restartCursor()
496 stopBlinkingCursor();
497 guiApp->processKeySym(key, mod);
501 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd0, KeyModifier mod)
504 if (cmd0.action() == LFUN_FILE_OPEN) {
506 lyx_view_->dispatch(cmd0, dr);
512 if (cmd0.action() == LFUN_MOUSE_PRESS) {
513 if (mod == ShiftModifier)
514 cmd = FuncRequest(cmd0, "region-select");
515 else if (mod == ControlModifier)
516 cmd = FuncRequest(cmd0, "paragraph-select");
523 bool const notJustMovingTheMouse =
524 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
526 // In order to avoid bad surprise in the middle of an operation, we better stop
527 // the blinking cursor.
528 if (notJustMovingTheMouse)
529 p->stopBlinkingCursor();
531 buffer_view_->mouseEventDispatch(cmd);
533 // Skip these when selecting
534 if (cmd.action() != LFUN_MOUSE_MOTION) {
535 completer_->updateVisibility(false, false);
536 lyx_view_->updateDialogs();
537 lyx_view_->updateStatusBar();
540 // GUI tweaks except with mouse motion with no button pressed.
541 if (notJustMovingTheMouse) {
542 // Slight hack: this is only called currently when we
543 // clicked somewhere, so we force through the display
544 // of the new status here.
545 lyx_view_->clearMessage();
547 // Show the cursor immediately after any operation
548 p->startBlinkingCursor();
555 void GuiWorkArea::Private::resizeBufferView()
557 // WARNING: Please don't put any code that will trigger a repaint here!
558 // We are already inside a paint event.
559 lyx_view_->setBusy(true);
562 buffer_view_->cursorPosAndHeight(point, h);
563 bool const cursor_in_view = buffer_view_->cursorInView(point, h);
564 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
566 buffer_view_->scrollToCursor();
569 // Update scrollbars which might have changed due different
570 // BufferView dimension. This is especially important when the
571 // BufferView goes from zero-size to the real-size for the first time,
572 // as the scrollbar paramters are then set for the first time.
575 lyx_view_->updateLayoutList();
576 lyx_view_->setBusy(false);
577 need_resize_ = false;
581 void GuiWorkArea::Private::showCursor()
588 buffer_view_->cursorPosAndHeight(p, h);
589 if (!buffer_view_->cursorInView(p, h))
593 bool l_shape = false;
594 Font const & realfont = buffer_view_->cursor().real_current_font;
595 BufferParams const & bp = buffer_view_->buffer().params();
596 bool const samelang = realfont.language() == bp.language;
597 bool const isrtl = realfont.isVisibleRightToLeft();
599 if (!samelang || isrtl != bp.language->rightToLeft())
602 // The ERT language hack needs fixing up
603 if (realfont.language() == latex_language)
606 // show cursor on screen
607 Cursor & cur = buffer_view_->cursor();
608 bool completable = cur.inset().showCompletionCursor()
609 && completer_->completionAvailable()
610 && !completer_->popupVisible()
611 && !completer_->inlineVisible();
612 cursor_visible_ = true;
613 cursor_->recomputeWidth();
614 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
618 void GuiWorkArea::Private::hideCursor()
620 if (!cursor_visible_)
623 cursor_visible_ = false;
628 void GuiWorkArea::toggleCursor()
630 if (d->cursor_visible_)
637 void GuiWorkArea::Private::updateScrollbar()
639 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
640 // WARNING: don't touch at the scrollbar value like this:
641 // verticalScrollBar()->setValue(scroll_.position);
642 // because this would cause a recursive signal/slot calling with
643 // GuiWorkArea::scrollTo
644 p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
645 p->verticalScrollBar()->setPageStep(scroll_.page_step);
646 p->verticalScrollBar()->setSingleStep(scroll_.single_step);
647 p->verticalScrollBar()->setSliderPosition(scroll_.position);
651 void GuiWorkArea::scrollTo(int value)
653 stopBlinkingCursor();
654 d->buffer_view_->scrollDocView(value, true);
656 if (lyxrc.cursor_follows_scrollbar) {
657 d->buffer_view_->setCursorFromScrollbar();
658 d->lyx_view_->updateLayoutList();
660 // Show the cursor immediately after any operation.
661 startBlinkingCursor();
662 QApplication::syncX();
666 bool GuiWorkArea::event(QEvent * e)
669 case QEvent::ToolTip: {
670 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
671 if (lyxrc.use_tooltip) {
672 QPoint pos = helpEvent->pos();
673 if (pos.x() < viewport()->width()) {
674 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
675 QToolTip::showText(helpEvent->globalPos(), s);
678 QToolTip::hideText();
680 // Don't forget to accept the event!
685 case QEvent::ShortcutOverride: {
686 // We catch this event in order to catch the Tab or Shift+Tab key press
687 // which are otherwise reserved to focus switching between controls
689 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
690 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
691 || (ke->key() == Qt::Key_Backtab && (
692 ke->modifiers() == Qt::ShiftModifier
693 || ke->modifiers() == Qt::NoModifier))) {
697 return QAbstractScrollArea::event(e);
701 return QAbstractScrollArea::event(e);
707 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
710 if (e->reason() == QContextMenuEvent::Mouse)
711 // the menu name is set on mouse press
712 name = d->context_menu_name_;
714 QPoint pos = e->pos();
715 Cursor const & cur = d->buffer_view_->cursor();
716 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
717 // Do not access the context menu of math right in front of before
718 // the cursor. This does not work when the cursor is in text.
719 Inset * inset = cur.paragraph().getInset(cur.pos());
720 if (inset && inset->asInsetMath())
722 else if (cur.pos() > 0) {
723 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
728 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
732 QAbstractScrollArea::contextMenuEvent(e);
735 // always show mnemonics when the keyboard is used to show the context menu
736 // FIXME: This should be fixed in Qt itself
737 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
738 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
740 QAbstractScrollArea::contextMenuEvent(e);
743 // Position the menu to the right.
744 // FIXME: menu position should be different for RTL text.
745 menu->exec(e->globalPos());
750 void GuiWorkArea::focusInEvent(QFocusEvent * e)
752 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
753 if (d->lyx_view_->currentWorkArea() != this)
754 d->lyx_view_->setCurrentWorkArea(this);
756 startBlinkingCursor();
757 QAbstractScrollArea::focusInEvent(e);
761 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
763 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
764 stopBlinkingCursor();
765 QAbstractScrollArea::focusOutEvent(e);
769 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
771 if (d->dc_event_.active && d->dc_event_ == *e) {
772 d->dc_event_.active = false;
773 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
774 q_button_state(e->button()));
780 inputContext()->reset();
782 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
783 q_button_state(e->button()));
784 d->dispatch(cmd, q_key_state(e->modifiers()));
786 // Save the context menu on mouse press, because also the mouse
787 // cursor is set on mouse press. Afterwards, we can either release
788 // the mousebutton somewhere else, or the cursor might have moved
789 // due to the DEPM. We need to do this after the mouse has been
790 // set in dispatch(), because the selection state might change.
791 if (e->button() == Qt::RightButton)
792 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
798 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
800 if (d->synthetic_mouse_event_.timeout.running())
801 d->synthetic_mouse_event_.timeout.stop();
803 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
804 q_button_state(e->button()));
810 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
812 // we kill the triple click if we move
813 doubleClickTimeout();
814 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
815 q_motion_state(e->buttons()));
819 // If we're above or below the work area...
820 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
821 && e->buttons() == mouse_button::button1) {
822 // Make sure only a synthetic event can cause a page scroll,
823 // so they come at a steady rate:
825 // _Force_ a scroll up:
826 cmd.set_y(e->y() - 21);
828 cmd.set_y(e->y() + 21);
829 // Store the event, to be handled when the timeout expires.
830 d->synthetic_mouse_event_.cmd = cmd;
832 if (d->synthetic_mouse_event_.timeout.running()) {
833 // Discard the event. Note that it _may_ be handled
834 // when the timeout expires if
835 // synthetic_mouse_event_.cmd has not been overwritten.
836 // Ie, when the timeout expires, we handle the
837 // most recent event but discard all others that
838 // occurred after the one used to start the timeout
839 // in the first place.
843 d->synthetic_mouse_event_.restart_timeout = true;
844 d->synthetic_mouse_event_.timeout.start();
845 // Fall through to handle this event...
847 } else if (d->synthetic_mouse_event_.timeout.running()) {
848 // Store the event, to be possibly handled when the timeout
850 // Once the timeout has expired, normal control is returned
851 // to mouseMoveEvent (restart_timeout = false).
852 // This results in a much smoother 'feel' when moving the
853 // mouse back into the work area.
854 d->synthetic_mouse_event_.cmd = cmd;
855 d->synthetic_mouse_event_.restart_timeout = false;
862 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
864 // Wheel rotation by one notch results in a delta() of 120 (see
865 // documentation of QWheelEvent)
866 double const delta = ev->delta() / 120.0;
868 switch (lyxrc.scroll_wheel_zoom) {
869 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
870 zoom = ev->modifiers() & Qt::ControlModifier;
871 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
873 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
874 zoom = ev->modifiers() & Qt::ShiftModifier;
875 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
877 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
878 zoom = ev->modifiers() & Qt::AltModifier;
879 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
881 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
885 docstring arg = convert<docstring>(int(5 * delta));
886 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
890 // Take into account the desktop wide settings.
891 int const lines = qApp->wheelScrollLines();
892 int const page_step = verticalScrollBar()->pageStep();
893 // Test if the wheel mouse is set to one screen at a time.
894 int scroll_value = lines > page_step
895 ? page_step : lines * verticalScrollBar()->singleStep();
897 // Take into account the rotation and the user preferences.
898 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
899 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
900 << " delta = " << delta << " scroll_value = " << scroll_value
901 << " page_step = " << page_step);
903 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
909 void GuiWorkArea::generateSyntheticMouseEvent()
911 int const e_y = d->synthetic_mouse_event_.cmd.y();
912 int const wh = d->buffer_view_->workHeight();
913 bool const up = e_y < 0;
914 bool const down = e_y > wh;
916 // Set things off to generate the _next_ 'pseudo' event.
918 if (d->synthetic_mouse_event_.restart_timeout) {
919 // This is some magic formulae to determine the speed
920 // of scrolling related to the position of the mouse.
923 int dist = up ? -e_y : e_y - wh;
924 time = max(min(200, 250000 / (dist * dist)), 1) ;
927 step = 80000 / (time * time);
931 d->synthetic_mouse_event_.timeout.setTimeout(time);
932 d->synthetic_mouse_event_.timeout.start();
935 // Can we scroll further ?
936 int const value = verticalScrollBar()->value();
937 if (value == verticalScrollBar()->maximum()
938 || value == verticalScrollBar()->minimum()) {
939 d->synthetic_mouse_event_.timeout.stop();
944 if (step <= 2 * wh) {
945 d->buffer_view_->scroll(up ? -step : step);
946 d->buffer_view_->updateMetrics();
948 d->buffer_view_->scrollDocView(value + up ? -step : step, false);
951 // In which paragraph do we have to set the cursor ?
952 Cursor & cur = d->buffer_view_->cursor();
953 // FIXME: we don't know howto handle math.
954 Text * text = cur.text();
957 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
959 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
960 ParagraphMetrics const & pm = *pp.second;
961 pit_type const pit = pp.first;
963 if (pm.rows().empty())
966 // Find the row at which we set the cursor.
967 RowList::const_iterator rit = pm.rows().begin();
968 RowList::const_iterator rlast = pm.rows().end();
969 int yy = pm.position() - pm.ascent();
970 for (--rlast; rit != rlast; ++rit) {
971 int h = rit->height();
972 if ((up && yy + h > 0)
973 || (!up && yy + h > wh - defaultRowHeight()))
978 // Find the position of the cursor
980 int x = d->synthetic_mouse_event_.cmd.x();
981 pos_type const pos = rit->pos() + tm.getColumnNearX(pit, *rit, x, bound);
988 d->buffer_view_->buffer().changed(false);
993 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
995 // Do not process here some keys if dialog_mode_ is set
997 && (ev->modifiers() == Qt::NoModifier
998 || ev->modifiers() == Qt::ShiftModifier)
999 && (ev->key() == Qt::Key_Escape
1000 || ev->key() == Qt::Key_Enter
1001 || ev->key() == Qt::Key_Return)
1007 // intercept some keys if completion popup is visible
1008 if (d->completer_->popupVisible()) {
1009 switch (ev->key()) {
1011 case Qt::Key_Return:
1012 d->completer_->activate();
1018 // do nothing if there are other events
1019 // (the auto repeated events come too fast)
1020 // it looks like this is only needed on X11
1022 if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1023 switch (ev->key()) {
1024 case Qt::Key_PageDown:
1025 case Qt::Key_PageUp:
1030 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1037 KeyModifier m = q_key_state(ev->modifiers());
1040 if (m & ShiftModifier)
1042 if (m & ControlModifier)
1044 if (m & AltModifier)
1046 if (m & MetaModifier)
1049 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1050 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1051 << " keyState: " << str);
1054 setKeySymbol(&sym, ev);
1056 processKeySym(sym, q_key_state(ev->modifiers()));
1064 void GuiWorkArea::doubleClickTimeout()
1066 d->dc_event_.active = false;
1070 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1072 d->dc_event_ = DoubleClick(ev);
1073 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1074 SLOT(doubleClickTimeout()));
1075 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1077 q_button_state(ev->button()));
1083 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1085 QAbstractScrollArea::resizeEvent(ev);
1086 d->need_resize_ = true;
1091 void GuiWorkArea::Private::update(int x, int y, int w, int h)
1093 p->viewport()->update(x, y, w, h);
1097 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1099 QRect const rc = ev->rect();
1100 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1101 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1103 if (d->need_resize_) {
1105 d->resizeBufferView();
1106 if (d->cursor_visible_) {
1112 QPainter pain(viewport());
1114 pain.drawImage(rc, d->screen_, rc);
1116 pain.drawPixmap(rc, d->screen_, rc);
1118 d->cursor_->draw(pain);
1123 void GuiWorkArea::Private::updateScreen()
1125 GuiPainter pain(&screen_);
1126 buffer_view_->draw(pain);
1130 void GuiWorkArea::Private::showCursor(int x, int y, int h,
1131 bool l_shape, bool rtl, bool completable)
1133 if (schedule_redraw_) {
1134 // This happens when a graphic conversion is finished. As we don't know
1135 // the size of the new graphics, it's better the update everything.
1136 // We can't use redraw() here because this would trigger a infinite
1137 // recursive loop with showCursor().
1138 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
1141 p->viewport()->update(QRect(0, 0, p->viewport()->width(), p->viewport()->height()));
1142 schedule_redraw_ = false;
1143 // Show the cursor immediately after the update.
1149 cursor_->update(x, y, h, l_shape, rtl, completable);
1151 p->viewport()->update(cursor_->rect());
1155 void GuiWorkArea::Private::removeCursor()
1158 //if (!qApp->focusWidget())
1159 p->viewport()->update(cursor_->rect());
1163 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1165 QString const & commit_string = e->commitString();
1166 docstring const & preedit_string
1167 = qstring_to_ucs4(e->preeditString());
1169 if (!commit_string.isEmpty()) {
1171 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1172 << " commitString: " << e->commitString());
1176 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1177 for (int i = 0; i != commit_string.size(); ++i) {
1178 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1183 // Hide the cursor during the kana-kanji transformation.
1184 if (preedit_string.empty())
1185 startBlinkingCursor();
1187 stopBlinkingCursor();
1189 // last_width : for checking if last preedit string was/wasn't empty.
1190 static bool last_width = false;
1191 if (!last_width && preedit_string.empty()) {
1192 // if last_width is last length of preedit string.
1197 GuiPainter pain(&d->screen_);
1198 d->buffer_view_->updateMetrics();
1199 d->buffer_view_->draw(pain);
1200 FontInfo font = d->buffer_view_->cursor().getFont().fontInfo();
1201 FontMetrics const & fm = theFontMetrics(font);
1202 int height = fm.maxHeight();
1203 int cur_x = d->cursor_->rect().left();
1204 int cur_y = d->cursor_->rect().bottom();
1206 // redraw area of preedit string.
1207 update(0, cur_y - height, viewport()->width(),
1208 (height + 1) * d->preedit_lines_);
1210 if (preedit_string.empty()) {
1212 d->preedit_lines_ = 1;
1218 // att : stores an IM attribute.
1219 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1221 // get attributes of input method cursor.
1222 // cursor_pos : cursor position in preedit string.
1223 size_t cursor_pos = 0;
1224 bool cursor_is_visible = false;
1225 for (int i = 0; i != att.size(); ++i) {
1226 if (att.at(i).type == QInputMethodEvent::Cursor) {
1227 cursor_pos = att.at(i).start;
1228 cursor_is_visible = att.at(i).length != 0;
1233 size_t preedit_length = preedit_string.length();
1235 // get position of selection in input method.
1236 // FIXME: isn't there a way to do this simplier?
1237 // rStart : cursor position in selected string in IM.
1239 // rLength : selected string length in IM.
1241 if (cursor_pos < preedit_length) {
1242 for (int i = 0; i != att.size(); ++i) {
1243 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1244 if (att.at(i).start <= int(cursor_pos)
1245 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1246 rStart = att.at(i).start;
1247 rLength = att.at(i).length;
1248 if (!cursor_is_visible)
1249 cursor_pos += rLength;
1256 rStart = cursor_pos;
1260 int const right_margin = d->buffer_view_->rightMargin();
1261 Painter::preedit_style ps;
1262 // Most often there would be only one line:
1263 d->preedit_lines_ = 1;
1264 for (size_t pos = 0; pos != preedit_length; ++pos) {
1265 char_type const typed_char = preedit_string[pos];
1266 // reset preedit string style
1267 ps = Painter::preedit_default;
1269 // if we reached the right extremity of the screen, go to next line.
1270 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1271 cur_x = right_margin;
1272 cur_y += height + 1;
1273 ++d->preedit_lines_;
1275 // preedit strings are displayed with dashed underline
1276 // and partial strings are displayed white on black indicating
1277 // that we are in selecting mode in the input method.
1278 // FIXME: rLength == preedit_length is not a changing condition
1279 // FIXME: should be put out of the loop.
1281 && pos < rStart + rLength
1282 && !(cursor_pos < rLength && rLength == preedit_length))
1283 ps = Painter::preedit_selecting;
1285 if (pos == cursor_pos
1286 && (cursor_pos < rLength && rLength == preedit_length))
1287 ps = Painter::preedit_cursor;
1289 // draw one character and update cur_x.
1290 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1293 // update the preedit string screen area.
1294 update(0, cur_y - d->preedit_lines_*height, viewport()->width(),
1295 (height + 1) * d->preedit_lines_);
1297 // Don't forget to accept the event!
1302 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1304 QRect cur_r(0, 0, 0, 0);
1306 // this is the CJK-specific composition window position and
1307 // the context menu position when the menu key is pressed.
1308 case Qt::ImMicroFocus:
1309 cur_r = d->cursor_->rect();
1310 if (d->preedit_lines_ != 1)
1312 cur_r.moveBottom(cur_r.bottom()
1313 + cur_r.height() * (d->preedit_lines_ - 1));
1314 // return lower right of cursor in LyX.
1317 return QWidget::inputMethodQuery(query);
1322 void GuiWorkArea::updateWindowTitle()
1324 docstring maximize_title;
1325 docstring minimize_title;
1327 Buffer const & buf = d->buffer_view_->buffer();
1328 FileName const file_name = buf.fileName();
1329 if (!file_name.empty()) {
1330 maximize_title = file_name.displayName(130);
1331 minimize_title = from_utf8(file_name.onlyFileName());
1332 if (buf.lyxvc().inUse()) {
1333 if (buf.lyxvc().locking())
1334 maximize_title += _(" (version control, locking)");
1336 maximize_title += _(" (version control)");
1338 if (!buf.isClean()) {
1339 maximize_title += _(" (changed)");
1340 minimize_title += char_type('*');
1342 if (buf.isReadonly())
1343 maximize_title += _(" (read only)");
1346 QString const new_title = toqstr(maximize_title);
1347 if (new_title != windowTitle()) {
1348 QWidget::setWindowTitle(new_title);
1349 QWidget::setWindowIconText(toqstr(minimize_title));
1355 bool GuiWorkArea::isFullScreen() const
1357 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1361 void GuiWorkArea::scheduleRedraw()
1363 d->schedule_redraw_ = true;
1367 bool GuiWorkArea::inDialogMode() const
1369 return d->dialog_mode_;
1373 void GuiWorkArea::setDialogMode(bool mode)
1375 d->dialog_mode_ = mode;
1379 GuiCompleter & GuiWorkArea::completer()
1381 return *d->completer_;
1384 GuiView const & GuiWorkArea::view() const
1386 return *d->lyx_view_;
1390 GuiView & GuiWorkArea::view()
1392 return *d->lyx_view_;
1395 ////////////////////////////////////////////////////////////////////
1399 ////////////////////////////////////////////////////////////////////
1402 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1404 buffer_ = theBufferList().newBuffer(
1405 support::FileName::tempName().absFileName() + "_embedded.internal");
1406 buffer_->setUnnamed(true);
1407 buffer_->setFullyLoaded(true);
1408 setBuffer(*buffer_);
1409 setDialogMode(true);
1413 EmbeddedWorkArea::~EmbeddedWorkArea()
1415 // No need to destroy buffer and bufferview here, because it is done
1416 // in theBufferList() destruction loop at application exit
1420 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1423 GuiWorkArea::closeEvent(ev);
1427 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1430 GuiWorkArea::hideEvent(ev);
1434 QSize EmbeddedWorkArea::sizeHint () const
1437 // GuiWorkArea sets the size to the screen's viewport
1438 // by returning a value this gets overridden
1439 // EmbeddedWorkArea is now sized to fit in the layout
1440 // of the parent, and has a minimum size set in GuiWorkArea
1441 // which is what we return here
1442 return QSize(100, 70);
1446 void EmbeddedWorkArea::disable()
1448 stopBlinkingCursor();
1449 if (view().currentWorkArea() != this)
1451 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1452 // tolerates it and shows the background logo), what happens if
1453 // an EmbeddedWorkArea is closed after closing all document WAs
1454 view().setCurrentWorkArea(view().currentMainWorkArea());
1457 ////////////////////////////////////////////////////////////////////
1461 ////////////////////////////////////////////////////////////////////
1464 class NoTabFrameMacStyle : public QMacStyle {
1467 QRect subElementRect(SubElement element, const QStyleOption * option,
1468 const QWidget * widget = 0) const
1470 QRect rect = QMacStyle::subElementRect(element, option, widget);
1471 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1473 // The Qt Mac style puts the contents into a 3 pixel wide box
1474 // which looks very ugly and not like other Mac applications.
1475 // Hence we remove this here, and moreover the 16 pixel round
1476 // frame above if the tab bar is hidden.
1477 if (element == QStyle::SE_TabWidgetTabContents) {
1478 rect.adjust(- rect.left(), 0, rect.left(), 0);
1487 NoTabFrameMacStyle noTabFrameMacStyle;
1491 TabWorkArea::TabWorkArea(QWidget * parent)
1492 : QTabWidget(parent), clicked_tab_(-1)
1495 setStyle(&noTabFrameMacStyle);
1497 #if QT_VERSION < 0x040500
1498 lyxrc.single_close_tab_button = true;
1501 QPalette pal = palette();
1502 pal.setColor(QPalette::Active, QPalette::Button,
1503 pal.color(QPalette::Active, QPalette::Window));
1504 pal.setColor(QPalette::Disabled, QPalette::Button,
1505 pal.color(QPalette::Disabled, QPalette::Window));
1506 pal.setColor(QPalette::Inactive, QPalette::Button,
1507 pal.color(QPalette::Inactive, QPalette::Window));
1509 QObject::connect(this, SIGNAL(currentChanged(int)),
1510 this, SLOT(on_currentTabChanged(int)));
1512 closeBufferButton = new QToolButton(this);
1513 closeBufferButton->setPalette(pal);
1514 // FIXME: rename the icon to closebuffer.png
1515 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1516 closeBufferButton->setText("Close File");
1517 closeBufferButton->setAutoRaise(true);
1518 closeBufferButton->setCursor(Qt::ArrowCursor);
1519 closeBufferButton->setToolTip(qt_("Close File"));
1520 closeBufferButton->setEnabled(true);
1521 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1522 this, SLOT(closeCurrentBuffer()));
1523 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1525 // setup drag'n'drop
1526 QTabBar* tb = new DragTabBar;
1527 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1528 this, SLOT(moveTab(int, int)));
1529 tb->setElideMode(Qt::ElideNone);
1532 // make us responsible for the context menu of the tabbar
1533 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1534 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1535 this, SLOT(showContextMenu(const QPoint &)));
1536 #if QT_VERSION >= 0x040500
1537 connect(tb, SIGNAL(tabCloseRequested(int)),
1538 this, SLOT(closeTab(int)));
1541 setUsesScrollButtons(true);
1545 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1547 if (event->button() != Qt::LeftButton)
1550 // return early if double click on existing tabs
1551 for (int i = 0; i < count(); ++i)
1552 if (tabBar()->tabRect(i).contains(event->pos()))
1555 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1559 void TabWorkArea::setFullScreen(bool full_screen)
1561 for (int i = 0; i != count(); ++i) {
1562 if (GuiWorkArea * wa = workArea(i))
1563 wa->setFullScreen(full_screen);
1566 if (lyxrc.full_screen_tabbar)
1567 showBar(!full_screen && count() > 1);
1571 void TabWorkArea::showBar(bool show)
1573 tabBar()->setEnabled(show);
1574 tabBar()->setVisible(show);
1575 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1576 #if QT_VERSION >= 0x040500
1577 setTabsClosable(!lyxrc.single_close_tab_button);
1582 GuiWorkArea * TabWorkArea::currentWorkArea()
1587 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1593 GuiWorkArea * TabWorkArea::workArea(int index)
1595 return dynamic_cast<GuiWorkArea *>(widget(index));
1599 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1601 // FIXME: this method doesn't work if we have more than work area
1602 // showing the same buffer.
1603 for (int i = 0; i != count(); ++i) {
1604 GuiWorkArea * wa = workArea(i);
1605 LASSERT(wa, return 0);
1606 if (&wa->bufferView().buffer() == &buffer)
1613 void TabWorkArea::closeAll()
1616 GuiWorkArea * wa = workArea(0);
1624 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1626 LASSERT(work_area, /**/);
1627 int index = indexOf(work_area);
1631 if (index == currentIndex())
1632 // Make sure the work area is up to date.
1633 on_currentTabChanged(index);
1635 // Switch to the work area.
1636 setCurrentIndex(index);
1637 work_area->setFocus();
1643 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1645 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1646 wa->setUpdatesEnabled(false);
1647 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1648 // when hiding it again below).
1649 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1650 showBar(count() > 0);
1651 addTab(wa, wa->windowTitle());
1652 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1653 this, SLOT(updateTabTexts()));
1654 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1655 setFullScreen(true);
1657 // Hide tabbar if there's only one tab.
1658 showBar(count() > 1);
1666 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1668 LASSERT(work_area, return false);
1669 int index = indexOf(work_area);
1673 work_area->setUpdatesEnabled(false);
1678 // make sure the next work area is enabled.
1679 currentWidget()->setUpdatesEnabled(true);
1680 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1681 setFullScreen(true);
1683 // Show tabbar only if there's more than one tab.
1684 showBar(count() > 1);
1686 lastWorkAreaRemoved();
1694 void TabWorkArea::on_currentTabChanged(int i)
1696 // returns e.g. on application destruction
1699 GuiWorkArea * wa = workArea(i);
1700 LASSERT(wa, return);
1701 wa->setUpdatesEnabled(true);
1705 currentWorkAreaChanged(wa);
1707 LYXERR(Debug::GUI, "currentTabChanged " << i
1708 << " File: " << wa->bufferView().buffer().absFileName());
1712 void TabWorkArea::closeCurrentBuffer()
1715 if (clicked_tab_ == -1)
1716 wa = currentWorkArea();
1718 wa = workArea(clicked_tab_);
1721 wa->view().closeWorkArea(wa);
1725 void TabWorkArea::hideCurrentTab()
1728 if (clicked_tab_ == -1)
1729 wa = currentWorkArea();
1731 wa = workArea(clicked_tab_);
1734 wa->view().hideWorkArea(wa);
1738 void TabWorkArea::closeTab(int index)
1740 on_currentTabChanged(index);
1743 wa = currentWorkArea();
1745 wa = workArea(index);
1748 wa->view().closeWorkArea(wa);
1755 /// make vector happy
1758 DisplayPath(int tab, FileName const & filename)
1761 filename_ = (filename.extension() == "lyx") ?
1762 toqstr(filename.onlyFileNameWithoutExt())
1763 : toqstr(filename.onlyFileName());
1764 postfix_ = toqstr(filename.absoluteFilePath()).
1765 split("/", QString::SkipEmptyParts);
1766 postfix_.pop_back();
1767 abs_ = toqstr(filename.absoluteFilePath());
1768 dottedPrefix_ = false;
1771 /// Absolute path for debugging.
1776 /// Add the first segment from the postfix or three dots to the prefix.
1777 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1778 /// when really needed.
1779 void shiftPathSegment(bool dotted)
1781 if (postfix_.count() <= 0)
1785 if (dottedPrefix_ && !prefix_.isEmpty())
1787 prefix_ += postfix_.front() + "/";
1789 dottedPrefix_ = dotted && !prefix_.isEmpty();
1790 postfix_.pop_front();
1793 QString displayString() const
1795 if (prefix_.isEmpty())
1798 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1799 return prefix_ + (dots ? ".../" : "") + filename_;
1802 QString forecastPathString() const
1804 if (postfix_.count() == 0)
1805 return displayString();
1808 + (dottedPrefix_ ? ".../" : "")
1809 + postfix_.front() + "/";
1812 bool final() const { return postfix_.empty(); }
1814 int tab() const { return tab_; }
1820 QStringList postfix_;
1833 bool operator<(DisplayPath const & a, DisplayPath const & b)
1835 return a.displayString() < b.displayString();
1839 bool operator==(DisplayPath const & a, DisplayPath const & b)
1841 return a.displayString() == b.displayString();
1845 void TabWorkArea::updateTabTexts()
1850 std::list<DisplayPath> paths;
1851 typedef std::list<DisplayPath>::iterator It;
1853 // collect full names first: path into postfix, empty prefix and
1854 // filename without extension
1855 for (size_t i = 0; i < n; ++i) {
1856 GuiWorkArea * i_wa = workArea(i);
1857 FileName const fn = i_wa->bufferView().buffer().fileName();
1858 paths.push_back(DisplayPath(i, fn));
1861 // go through path segments and see if it helps to make the path more unique
1862 bool somethingChanged = true;
1863 bool allFinal = false;
1864 while (somethingChanged && !allFinal) {
1865 // adding path segments changes order
1868 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1869 somethingChanged = false;
1872 // find segments which are not unique (i.e. non-atomic)
1873 It it = paths.begin();
1875 QString segString = it->displayString();
1876 for (; it != paths.end(); ++it) {
1877 // look to the next item
1882 allFinal = allFinal && it->final();
1884 LYXERR(Debug::GUI, "it = " << it->abs()
1885 << " => " << it->displayString());
1887 // still the same segment?
1889 if ((next != paths.end()
1890 && (nextString = next->displayString()) == segString))
1892 LYXERR(Debug::GUI, "segment ended");
1894 // only a trivial one with one element?
1895 if (it == segStart) {
1896 // start new segment
1898 segString = nextString;
1902 // we found a non-atomic segment segStart <= sit <= it < next.
1903 // Shift path segments and hope for the best
1904 // that it makes the path more unique.
1905 somethingChanged = true;
1907 QString dspString = sit->forecastPathString();
1908 LYXERR(Debug::GUI, "first forecast found for "
1909 << sit->abs() << " => " << dspString);
1911 bool moreUnique = false;
1912 for (; sit != next; ++sit) {
1913 if (sit->forecastPathString() != dspString) {
1914 LYXERR(Debug::GUI, "different forecast found for "
1915 << sit->abs() << " => " << sit->forecastPathString());
1919 LYXERR(Debug::GUI, "same forecast found for "
1920 << sit->abs() << " => " << dspString);
1923 // if the path segment helped, add it. Otherwise add dots
1924 bool dots = !moreUnique;
1925 LYXERR(Debug::GUI, "using dots = " << dots);
1926 for (sit = segStart; sit != next; ++sit) {
1927 sit->shiftPathSegment(dots);
1928 LYXERR(Debug::GUI, "shifting "
1929 << sit->abs() << " => " << sit->displayString());
1932 // start new segment
1934 segString = nextString;
1938 // set new tab titles
1939 for (It it = paths.begin(); it != paths.end(); ++it) {
1940 int const tab_index = it->tab();
1941 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
1942 QString tab_text = it->displayString();
1943 if (!buf.fileName().empty() && !buf.isClean())
1945 setTabText(tab_index, tab_text);
1946 setTabToolTip(tab_index, it->abs());
1951 void TabWorkArea::showContextMenu(const QPoint & pos)
1954 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1955 if (clicked_tab_ == -1)
1960 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
1961 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
1962 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
1963 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1964 popup.exec(tabBar()->mapToGlobal(pos));
1970 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1972 QWidget * w = widget(fromIndex);
1973 QIcon icon = tabIcon(fromIndex);
1974 QString text = tabText(fromIndex);
1976 setCurrentIndex(fromIndex);
1977 removeTab(fromIndex);
1978 insertTab(toIndex, w, icon, text);
1979 setCurrentIndex(toIndex);
1983 DragTabBar::DragTabBar(QWidget* parent)
1986 setAcceptDrops(true);
1987 #if QT_VERSION >= 0x040500
1988 setTabsClosable(!lyxrc.single_close_tab_button);
1993 #if QT_VERSION < 0x040300
1994 int DragTabBar::tabAt(QPoint const & position) const
1996 const int max = count();
1997 for (int i = 0; i < max; ++i) {
1998 if (tabRect(i).contains(position))
2006 void DragTabBar::mousePressEvent(QMouseEvent * event)
2008 if (event->button() == Qt::LeftButton)
2009 dragStartPos_ = event->pos();
2010 QTabBar::mousePressEvent(event);
2014 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2016 // If the left button isn't pressed anymore then return
2017 if (!(event->buttons() & Qt::LeftButton))
2020 // If the distance is too small then return
2021 if ((event->pos() - dragStartPos_).manhattanLength()
2022 < QApplication::startDragDistance())
2025 // did we hit something after all?
2026 int tab = tabAt(dragStartPos_);
2030 // simulate button release to remove highlight from button
2031 int i = currentIndex();
2032 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2033 event->button(), event->buttons(), 0);
2034 QTabBar::mouseReleaseEvent(&me);
2038 QDrag * drag = new QDrag(this);
2039 QMimeData * mimeData = new QMimeData;
2040 // a crude way to distinguish tab-reodering drops from other ones
2041 mimeData->setData("action", "tab-reordering") ;
2042 drag->setMimeData(mimeData);
2044 #if QT_VERSION >= 0x040300
2045 // get tab pixmap as cursor
2046 QRect r = tabRect(tab);
2047 QPixmap pixmap(r.size());
2048 render(&pixmap, - r.topLeft());
2049 drag->setPixmap(pixmap);
2052 drag->start(Qt::MoveAction);
2058 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2060 // Only accept if it's an tab-reordering request
2061 QMimeData const * m = event->mimeData();
2062 QStringList formats = m->formats();
2063 if (formats.contains("action")
2064 && m->data("action") == "tab-reordering")
2065 event->acceptProposedAction();
2069 void DragTabBar::dropEvent(QDropEvent * event)
2071 int fromIndex = tabAt(dragStartPos_);
2072 int toIndex = tabAt(event->pos());
2074 // Tell interested objects that
2075 if (fromIndex != toIndex)
2076 tabMoveRequested(fromIndex, toIndex);
2077 event->acceptProposedAction();
2081 } // namespace frontend
2084 #include "moc_GuiWorkArea.cpp"