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>
69 #include <QStylePainter>
71 #include <QToolButton>
75 #include "support/bind.h"
79 int const TabIndicatorWidth = 3;
85 using namespace lyx::support;
90 /// return the LyX mouse button state from Qt's
91 static mouse_button::state q_button_state(Qt::MouseButton button)
93 mouse_button::state b = mouse_button::none;
96 b = mouse_button::button1;
99 b = mouse_button::button2;
101 case Qt::RightButton:
102 b = mouse_button::button3;
111 /// return the LyX mouse button state from Qt's
112 mouse_button::state q_motion_state(Qt::MouseButtons state)
114 mouse_button::state b = mouse_button::none;
115 if (state & Qt::LeftButton)
116 b |= mouse_button::button1;
117 if (state & Qt::MidButton)
118 b |= mouse_button::button2;
119 if (state & Qt::RightButton)
120 b |= mouse_button::button3;
133 void draw(QPainter & painter)
135 if (!show_ || !rect_.isValid())
139 int l = x_ - rect_.left();
140 int r = rect_.right() - x_;
141 int bot = rect_.bottom();
143 // draw vertical line
144 painter.fillRect(x_, y, cursor_width_, rect_.height(), color_);
146 // draw RTL/LTR indication
147 painter.setPen(color_);
150 painter.drawLine(x_, bot, x_ - l, bot);
152 painter.drawLine(x_, bot, x_ + cursor_width_ + r, bot);
155 // draw completion triangle
157 int m = y + rect_.height() / 2;
158 int d = TabIndicatorWidth - 1;
160 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
161 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
163 painter.drawLine(x_ + cursor_width_, m - d, x_ + cursor_width_ + d, m);
164 painter.drawLine(x_ + cursor_width_, m + d, x_ + cursor_width_ + d, m);
169 void update(int x, int y, int h, bool l_shape,
170 bool rtl, bool completable)
172 color_ = guiApp->colorCache().get(Color_cursor);
175 completable_ = completable;
178 // extension to left and right
182 // RTL/LTR indication
190 // completion triangle
193 l = max(l, TabIndicatorWidth);
195 r = max(r, TabIndicatorWidth);
198 // compute overall rectangle
199 rect_ = QRect(x - l, y, cursor_width_ + r + l, h);
202 void show(bool set_show = true) { show_ = set_show; }
203 void hide() { show_ = false; }
204 int cursorWidth() const { return cursor_width_; }
205 void recomputeWidth() {
206 cursor_width_ = lyxrc.cursor_width
208 : 1 + int((lyxrc.zoom + 50) / 200.0);
211 QRect const & rect() { return rect_; }
214 /// cursor is in RTL or LTR text
216 /// indication for RTL or LTR
218 /// triangle to show that a completion is available
224 /// rectangle, possibly with l_shape and completion triangle
226 /// x position (were the vertical line is drawn)
233 // This is a 'heartbeat' generating synthetic mouse move events when the
234 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
235 SyntheticMouseEvent::SyntheticMouseEvent()
236 : timeout(200), restart_timeout(true)
240 GuiWorkArea::Private::Private(GuiWorkArea * parent)
241 : p(parent), screen_(0), buffer_view_(0), lyx_view_(0), cursor_visible_(false),
242 need_resize_(false), schedule_redraw_(false), preedit_lines_(1),
243 completer_(new GuiCompleter(p, p))
248 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
249 : d(new Private(this))
254 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
255 : d(new Private(this))
263 void GuiWorkArea::init()
266 connect(&d->cursor_timeout_, SIGNAL(timeout()),
267 this, SLOT(toggleCursor()));
269 int const time = QApplication::cursorFlashTime() / 2;
271 d->cursor_timeout_.setInterval(time);
272 d->cursor_timeout_.start();
274 // let's initialize this just to be safe
275 d->cursor_timeout_.setInterval(500);
279 // With Qt4.5 a mouse event will happen before the first paint event
280 // so make sure that the buffer view has an up to date metrics.
281 d->buffer_view_->resize(viewport()->width(), viewport()->height());
282 d->cursor_ = new frontend::CursorWidget();
285 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
286 setAcceptDrops(true);
287 setMouseTracking(true);
288 setMinimumSize(100, 70);
289 setFrameStyle(QFrame::NoFrame);
292 viewport()->setAutoFillBackground(false);
293 // We don't need double-buffering nor SystemBackground on
294 // the viewport because we have our own backing pixmap.
295 viewport()->setAttribute(Qt::WA_NoSystemBackground);
297 setFocusPolicy(Qt::StrongFocus);
299 d->setCursorShape(Qt::IBeamCursor);
301 d->synthetic_mouse_event_.timeout.timeout.connect(
302 bind(&GuiWorkArea::generateSyntheticMouseEvent,
305 // Initialize the vertical Scroll Bar
306 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
307 this, SLOT(scrollTo(int)));
309 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
310 << " viewport height: " << viewport()->height());
312 // Enables input methods for asian languages.
313 // Must be set when creating custom text editing widgets.
314 setAttribute(Qt::WA_InputMethodEnabled, true);
316 d->dialog_mode_ = false;
320 GuiWorkArea::~GuiWorkArea()
322 d->buffer_view_->buffer().workAreaManager().remove(this);
324 delete d->buffer_view_;
326 // Completer has a QObject parent and is thus automatically destroyed.
328 // delete completer_;
333 Qt::CursorShape GuiWorkArea::cursorShape() const
335 return viewport()->cursor().shape();
339 void GuiWorkArea::Private::setCursorShape(Qt::CursorShape shape)
341 p->viewport()->setCursor(shape);
345 void GuiWorkArea::Private::updateCursorShape()
347 setCursorShape(buffer_view_->clickableInset()
348 ? Qt::PointingHandCursor : Qt::IBeamCursor);
352 void GuiWorkArea::setGuiView(GuiView & gv)
358 void GuiWorkArea::setBuffer(Buffer & buffer)
360 delete d->buffer_view_;
361 d->buffer_view_ = new BufferView(buffer);
362 buffer.workAreaManager().add(this);
364 // HACK: Prevents an additional redraw when the scrollbar pops up
365 // which regularily happens on documents with more than one page.
366 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
367 // Since we have no geometry information yet, we assume that
368 // a document needs a scrollbar if there is more then four
369 // paragraph in the outermost text.
370 if (buffer.text().paragraphs().size() > 4)
371 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
372 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
376 void GuiWorkArea::fixVerticalScrollBar()
379 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
383 void GuiWorkArea::close()
385 d->lyx_view_->removeWorkArea(this);
389 void GuiWorkArea::setFullScreen(bool full_screen)
391 d->buffer_view_->setFullScreen(full_screen);
392 setFrameStyle(QFrame::NoFrame);
394 setFrameStyle(QFrame::NoFrame);
395 if (lyxrc.full_screen_scrollbar)
396 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
398 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
402 BufferView & GuiWorkArea::bufferView()
404 return *d->buffer_view_;
408 BufferView const & GuiWorkArea::bufferView() const
410 return *d->buffer_view_;
414 void GuiWorkArea::stopBlinkingCursor()
416 d->cursor_timeout_.stop();
421 void GuiWorkArea::startBlinkingCursor()
423 // do not show the cursor if the view is busy
429 d->buffer_view_->cursorPosAndHeight(p, h);
430 // Don't start blinking if the cursor isn't on screen.
431 if (!d->buffer_view_->cursorInView(p, h))
436 //we're not supposed to cache this value.
437 int const time = QApplication::cursorFlashTime() / 2;
440 d->cursor_timeout_.setInterval(time);
441 d->cursor_timeout_.start();
445 void GuiWorkArea::redraw(bool update_metrics)
448 // No need to redraw in this case.
451 // No need to do anything if this is the current view. The BufferView
452 // metrics are already up to date.
453 if (update_metrics || d->lyx_view_ != guiApp->currentView()
454 || d->lyx_view_->currentWorkArea() != this) {
455 // FIXME: it would be nice to optimize for the off-screen case.
456 d->buffer_view_->cursor().fixIfBroken();
457 d->buffer_view_->updateMetrics();
458 d->buffer_view_->cursor().fixIfBroken();
461 // update cursor position, because otherwise it has to wait until
462 // the blinking interval is over
463 if (d->cursor_visible_) {
468 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
470 update(0, 0, viewport()->width(), viewport()->height());
472 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
473 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
474 d->updateScrollbar();
475 d->lyx_view_->updateStatusBar();
477 if (lyxerr.debugging(Debug::WORKAREA))
478 d->buffer_view_->coordCache().dump();
482 d->updateCursorShape();
486 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
488 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
489 && lyxrc.full_screen_menubar) {
490 // FIXME HACK: we should not have to do this here. See related comment
491 // in GuiView::event() (QEvent::ShortcutOverride)
492 d->lyx_view_->menuBar()->hide();
495 // In order to avoid bad surprise in the middle of an operation,
496 // we better stop the blinking cursor...
497 // the cursor gets restarted in GuiView::restartCursor()
498 stopBlinkingCursor();
499 guiApp->processKeySym(key, mod);
503 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd0, KeyModifier mod)
506 if (cmd0.action() == LFUN_FILE_OPEN) {
508 lyx_view_->dispatch(cmd0, dr);
514 if (cmd0.action() == LFUN_MOUSE_PRESS) {
515 if (mod == ShiftModifier)
516 cmd = FuncRequest(cmd0, "region-select");
517 else if (mod == ControlModifier)
518 cmd = FuncRequest(cmd0, "paragraph-select");
525 bool const notJustMovingTheMouse =
526 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
528 // In order to avoid bad surprise in the middle of an operation, we better stop
529 // the blinking cursor.
530 if (notJustMovingTheMouse)
531 p->stopBlinkingCursor();
533 buffer_view_->mouseEventDispatch(cmd);
535 // Skip these when selecting
536 // FIXME: let GuiView take care of those.
537 if (cmd.action() != LFUN_MOUSE_MOTION) {
538 completer_->updateVisibility(false, false);
539 lyx_view_->updateDialogs();
540 lyx_view_->updateStatusBar();
543 // GUI tweaks except with mouse motion with no button pressed.
544 if (notJustMovingTheMouse) {
545 // Slight hack: this is only called currently when we
546 // clicked somewhere, so we force through the display
547 // of the new status here.
548 // FIXME: let GuiView take care of those.
549 lyx_view_->clearMessage();
551 // Show the cursor immediately after any operation
552 p->startBlinkingCursor();
559 void GuiWorkArea::Private::resizeBufferView()
561 // WARNING: Please don't put any code that will trigger a repaint here!
562 // We are already inside a paint event.
563 p->stopBlinkingCursor();
564 // Warn our container (GuiView).
569 buffer_view_->cursorPosAndHeight(point, h);
570 bool const cursor_in_view = buffer_view_->cursorInView(point, h);
571 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
573 buffer_view_->scrollToCursor();
576 // Update scrollbars which might have changed due different
577 // BufferView dimension. This is especially important when the
578 // BufferView goes from zero-size to the real-size for the first time,
579 // as the scrollbar paramters are then set for the first time.
582 need_resize_ = false;
584 // Eventually, restart the cursor after the resize event.
585 // We might be resizing even if the focus is on another widget so we only
586 // restart the cursor if we have the focus.
588 QTimer::singleShot(50, p, SLOT(startBlinkingCursor()));
592 void GuiWorkArea::Private::showCursor()
599 buffer_view_->cursorPosAndHeight(p, h);
600 if (!buffer_view_->cursorInView(p, h))
604 bool l_shape = false;
605 Font const & realfont = buffer_view_->cursor().real_current_font;
606 BufferParams const & bp = buffer_view_->buffer().params();
607 bool const samelang = realfont.language() == bp.language;
608 bool const isrtl = realfont.isVisibleRightToLeft();
610 if (!samelang || isrtl != bp.language->rightToLeft())
613 // The ERT language hack needs fixing up
614 if (realfont.language() == latex_language)
617 // show cursor on screen
618 Cursor & cur = buffer_view_->cursor();
619 bool completable = cur.inset().showCompletionCursor()
620 && completer_->completionAvailable()
621 && !completer_->popupVisible()
622 && !completer_->inlineVisible();
623 cursor_visible_ = true;
624 cursor_->recomputeWidth();
625 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
629 void GuiWorkArea::Private::hideCursor()
631 if (!cursor_visible_)
634 cursor_visible_ = false;
639 void GuiWorkArea::toggleCursor()
641 if (d->cursor_visible_)
648 void GuiWorkArea::Private::updateScrollbar()
650 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
651 // WARNING: don't touch at the scrollbar value like this:
652 // verticalScrollBar()->setValue(scroll_.position);
653 // because this would cause a recursive signal/slot calling with
654 // GuiWorkArea::scrollTo
655 p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
656 p->verticalScrollBar()->setPageStep(scroll_.page_step);
657 p->verticalScrollBar()->setSingleStep(scroll_.single_step);
658 p->verticalScrollBar()->setSliderPosition(scroll_.position);
662 void GuiWorkArea::scrollTo(int value)
664 stopBlinkingCursor();
665 d->buffer_view_->scrollDocView(value, true);
667 if (lyxrc.cursor_follows_scrollbar) {
668 d->buffer_view_->setCursorFromScrollbar();
669 // FIXME: let GuiView take care of those.
670 d->lyx_view_->updateLayoutList();
672 // Show the cursor immediately after any operation.
673 startBlinkingCursor();
674 QApplication::syncX();
678 bool GuiWorkArea::event(QEvent * e)
681 case QEvent::ToolTip: {
682 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
683 if (lyxrc.use_tooltip) {
684 QPoint pos = helpEvent->pos();
685 if (pos.x() < viewport()->width()) {
686 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
687 QToolTip::showText(helpEvent->globalPos(), s);
690 QToolTip::hideText();
692 // Don't forget to accept the event!
697 case QEvent::ShortcutOverride: {
698 // We catch this event in order to catch the Tab or Shift+Tab key press
699 // which are otherwise reserved to focus switching between controls
701 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
702 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
703 || (ke->key() == Qt::Key_Backtab && (
704 ke->modifiers() == Qt::ShiftModifier
705 || ke->modifiers() == Qt::NoModifier))) {
709 return QAbstractScrollArea::event(e);
713 return QAbstractScrollArea::event(e);
719 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
722 if (e->reason() == QContextMenuEvent::Mouse)
723 // the menu name is set on mouse press
724 name = d->context_menu_name_;
726 QPoint pos = e->pos();
727 Cursor const & cur = d->buffer_view_->cursor();
728 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
729 // Do not access the context menu of math right in front of before
730 // the cursor. This does not work when the cursor is in text.
731 Inset * inset = cur.paragraph().getInset(cur.pos());
732 if (inset && inset->asInsetMath())
734 else if (cur.pos() > 0) {
735 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
740 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
744 QAbstractScrollArea::contextMenuEvent(e);
747 // always show mnemonics when the keyboard is used to show the context menu
748 // FIXME: This should be fixed in Qt itself
749 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
750 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
752 QAbstractScrollArea::contextMenuEvent(e);
755 // Position the menu to the right.
756 // FIXME: menu position should be different for RTL text.
757 menu->exec(e->globalPos());
762 void GuiWorkArea::focusInEvent(QFocusEvent * e)
764 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
765 if (d->lyx_view_->currentWorkArea() != this) {
766 d->lyx_view_->setCurrentWorkArea(this);
767 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
770 startBlinkingCursor();
771 QAbstractScrollArea::focusInEvent(e);
775 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
777 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
778 stopBlinkingCursor();
779 QAbstractScrollArea::focusOutEvent(e);
783 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
785 if (d->dc_event_.active && d->dc_event_ == *e) {
786 d->dc_event_.active = false;
787 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
788 q_button_state(e->button()));
794 inputContext()->reset();
796 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
797 q_button_state(e->button()));
798 d->dispatch(cmd, q_key_state(e->modifiers()));
800 // Save the context menu on mouse press, because also the mouse
801 // cursor is set on mouse press. Afterwards, we can either release
802 // the mousebutton somewhere else, or the cursor might have moved
803 // due to the DEPM. We need to do this after the mouse has been
804 // set in dispatch(), because the selection state might change.
805 if (e->button() == Qt::RightButton)
806 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
812 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
814 if (d->synthetic_mouse_event_.timeout.running())
815 d->synthetic_mouse_event_.timeout.stop();
817 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
818 q_button_state(e->button()));
824 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
826 // we kill the triple click if we move
827 doubleClickTimeout();
828 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
829 q_motion_state(e->buttons()));
833 // If we're above or below the work area...
834 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
835 && e->buttons() == mouse_button::button1) {
836 // Make sure only a synthetic event can cause a page scroll,
837 // so they come at a steady rate:
839 // _Force_ a scroll up:
840 cmd.set_y(e->y() - 21);
842 cmd.set_y(e->y() + 21);
843 // Store the event, to be handled when the timeout expires.
844 d->synthetic_mouse_event_.cmd = cmd;
846 if (d->synthetic_mouse_event_.timeout.running()) {
847 // Discard the event. Note that it _may_ be handled
848 // when the timeout expires if
849 // synthetic_mouse_event_.cmd has not been overwritten.
850 // Ie, when the timeout expires, we handle the
851 // most recent event but discard all others that
852 // occurred after the one used to start the timeout
853 // in the first place.
857 d->synthetic_mouse_event_.restart_timeout = true;
858 d->synthetic_mouse_event_.timeout.start();
859 // Fall through to handle this event...
861 } else if (d->synthetic_mouse_event_.timeout.running()) {
862 // Store the event, to be possibly handled when the timeout
864 // Once the timeout has expired, normal control is returned
865 // to mouseMoveEvent (restart_timeout = false).
866 // This results in a much smoother 'feel' when moving the
867 // mouse back into the work area.
868 d->synthetic_mouse_event_.cmd = cmd;
869 d->synthetic_mouse_event_.restart_timeout = false;
876 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
878 // Wheel rotation by one notch results in a delta() of 120 (see
879 // documentation of QWheelEvent)
880 double const delta = ev->delta() / 120.0;
882 switch (lyxrc.scroll_wheel_zoom) {
883 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
884 zoom = ev->modifiers() & Qt::ControlModifier;
885 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
887 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
888 zoom = ev->modifiers() & Qt::ShiftModifier;
889 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
891 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
892 zoom = ev->modifiers() & Qt::AltModifier;
893 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
895 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
899 docstring arg = convert<docstring>(int(5 * delta));
900 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
904 // Take into account the desktop wide settings.
905 int const lines = qApp->wheelScrollLines();
906 int const page_step = verticalScrollBar()->pageStep();
907 // Test if the wheel mouse is set to one screen at a time.
908 int scroll_value = lines > page_step
909 ? page_step : lines * verticalScrollBar()->singleStep();
911 // Take into account the rotation and the user preferences.
912 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
913 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
914 << " delta = " << delta << " scroll_value = " << scroll_value
915 << " page_step = " << page_step);
917 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
923 void GuiWorkArea::generateSyntheticMouseEvent()
925 int const e_y = d->synthetic_mouse_event_.cmd.y();
926 int const wh = d->buffer_view_->workHeight();
927 bool const up = e_y < 0;
928 bool const down = e_y > wh;
930 // Set things off to generate the _next_ 'pseudo' event.
932 if (d->synthetic_mouse_event_.restart_timeout) {
933 // This is some magic formulae to determine the speed
934 // of scrolling related to the position of the mouse.
937 int dist = up ? -e_y : e_y - wh;
938 time = max(min(200, 250000 / (dist * dist)), 1) ;
941 step = 80000 / (time * time);
945 d->synthetic_mouse_event_.timeout.setTimeout(time);
946 d->synthetic_mouse_event_.timeout.start();
949 // Can we scroll further ?
950 int const value = verticalScrollBar()->value();
951 if (value == verticalScrollBar()->maximum()
952 || value == verticalScrollBar()->minimum()) {
953 d->synthetic_mouse_event_.timeout.stop();
958 if (step <= 2 * wh) {
959 d->buffer_view_->scroll(up ? -step : step);
960 d->buffer_view_->updateMetrics();
962 d->buffer_view_->scrollDocView(value + up ? -step : step, false);
965 // In which paragraph do we have to set the cursor ?
966 Cursor & cur = d->buffer_view_->cursor();
967 // FIXME: we don't know howto handle math.
968 Text * text = cur.text();
971 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
973 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
974 ParagraphMetrics const & pm = *pp.second;
975 pit_type const pit = pp.first;
977 if (pm.rows().empty())
980 // Find the row at which we set the cursor.
981 RowList::const_iterator rit = pm.rows().begin();
982 RowList::const_iterator rlast = pm.rows().end();
983 int yy = pm.position() - pm.ascent();
984 for (--rlast; rit != rlast; ++rit) {
985 int h = rit->height();
986 if ((up && yy + h > 0)
987 || (!up && yy + h > wh - defaultRowHeight()))
992 // Find the position of the cursor
994 int x = d->synthetic_mouse_event_.cmd.x();
995 pos_type const pos = rit->pos() + tm.getColumnNearX(pit, *rit, x, bound);
1000 cur.boundary(bound);
1002 d->buffer_view_->buffer().changed(false);
1007 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1009 // Do not process here some keys if dialog_mode_ is set
1011 && (ev->modifiers() == Qt::NoModifier
1012 || ev->modifiers() == Qt::ShiftModifier)
1013 && (ev->key() == Qt::Key_Escape
1014 || ev->key() == Qt::Key_Enter
1015 || ev->key() == Qt::Key_Return)
1021 // intercept some keys if completion popup is visible
1022 if (d->completer_->popupVisible()) {
1023 switch (ev->key()) {
1025 case Qt::Key_Return:
1026 d->completer_->activate();
1032 // do nothing if there are other events
1033 // (the auto repeated events come too fast)
1034 // it looks like this is only needed on X11
1036 if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1037 switch (ev->key()) {
1038 case Qt::Key_PageDown:
1039 case Qt::Key_PageUp:
1044 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1051 KeyModifier m = q_key_state(ev->modifiers());
1054 if (m & ShiftModifier)
1056 if (m & ControlModifier)
1058 if (m & AltModifier)
1060 if (m & MetaModifier)
1063 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1064 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1065 << " keyState: " << str);
1068 setKeySymbol(&sym, ev);
1070 processKeySym(sym, q_key_state(ev->modifiers()));
1078 void GuiWorkArea::doubleClickTimeout()
1080 d->dc_event_.active = false;
1084 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1086 d->dc_event_ = DoubleClick(ev);
1087 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1088 SLOT(doubleClickTimeout()));
1089 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1091 q_button_state(ev->button()));
1097 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1099 QAbstractScrollArea::resizeEvent(ev);
1100 d->need_resize_ = true;
1105 void GuiWorkArea::Private::update(int x, int y, int w, int h)
1107 p->viewport()->update(x, y, w, h);
1111 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1113 QRect const rc = ev->rect();
1114 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1115 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1117 if (d->need_resize_) {
1119 d->resizeBufferView();
1120 if (d->cursor_visible_) {
1126 QPainter pain(viewport());
1127 if (lyxrc.use_qimage) {
1128 pain.drawImage(rc, static_cast<QImage const &>(*d->screen_), rc);
1130 pain.drawPixmap(rc, static_cast<QPixmap const &>(*d->screen_), rc);
1132 d->cursor_->draw(pain);
1137 void GuiWorkArea::Private::updateScreen()
1139 GuiPainter pain(screen_);
1140 buffer_view_->draw(pain);
1144 void GuiWorkArea::Private::showCursor(int x, int y, int h,
1145 bool l_shape, bool rtl, bool completable)
1147 if (schedule_redraw_) {
1148 // This happens when a graphic conversion is finished. As we don't know
1149 // the size of the new graphics, it's better the update everything.
1150 // We can't use redraw() here because this would trigger a infinite
1151 // recursive loop with showCursor().
1152 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
1155 p->viewport()->update(QRect(0, 0, p->viewport()->width(), p->viewport()->height()));
1156 schedule_redraw_ = false;
1157 // Show the cursor immediately after the update.
1163 cursor_->update(x, y, h, l_shape, rtl, completable);
1165 p->viewport()->update(cursor_->rect());
1169 void GuiWorkArea::Private::removeCursor()
1172 //if (!qApp->focusWidget())
1173 p->viewport()->update(cursor_->rect());
1177 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1179 QString const & commit_string = e->commitString();
1180 docstring const & preedit_string
1181 = qstring_to_ucs4(e->preeditString());
1183 if (!commit_string.isEmpty()) {
1185 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1186 << " commitString: " << e->commitString());
1190 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1191 for (int i = 0; i != commit_string.size(); ++i) {
1192 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1197 // Hide the cursor during the kana-kanji transformation.
1198 if (preedit_string.empty())
1199 startBlinkingCursor();
1201 stopBlinkingCursor();
1203 // last_width : for checking if last preedit string was/wasn't empty.
1204 static bool last_width = false;
1205 if (!last_width && preedit_string.empty()) {
1206 // if last_width is last length of preedit string.
1211 GuiPainter pain(d->screen_);
1212 d->buffer_view_->updateMetrics();
1213 d->buffer_view_->draw(pain);
1214 FontInfo font = d->buffer_view_->cursor().getFont().fontInfo();
1215 FontMetrics const & fm = theFontMetrics(font);
1216 int height = fm.maxHeight();
1217 int cur_x = d->cursor_->rect().left();
1218 int cur_y = d->cursor_->rect().bottom();
1220 // redraw area of preedit string.
1221 update(0, cur_y - height, viewport()->width(),
1222 (height + 1) * d->preedit_lines_);
1224 if (preedit_string.empty()) {
1226 d->preedit_lines_ = 1;
1232 // att : stores an IM attribute.
1233 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1235 // get attributes of input method cursor.
1236 // cursor_pos : cursor position in preedit string.
1237 size_t cursor_pos = 0;
1238 bool cursor_is_visible = false;
1239 for (int i = 0; i != att.size(); ++i) {
1240 if (att.at(i).type == QInputMethodEvent::Cursor) {
1241 cursor_pos = att.at(i).start;
1242 cursor_is_visible = att.at(i).length != 0;
1247 size_t preedit_length = preedit_string.length();
1249 // get position of selection in input method.
1250 // FIXME: isn't there a way to do this simplier?
1251 // rStart : cursor position in selected string in IM.
1253 // rLength : selected string length in IM.
1255 if (cursor_pos < preedit_length) {
1256 for (int i = 0; i != att.size(); ++i) {
1257 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1258 if (att.at(i).start <= int(cursor_pos)
1259 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1260 rStart = att.at(i).start;
1261 rLength = att.at(i).length;
1262 if (!cursor_is_visible)
1263 cursor_pos += rLength;
1270 rStart = cursor_pos;
1274 int const right_margin = d->buffer_view_->rightMargin();
1275 Painter::preedit_style ps;
1276 // Most often there would be only one line:
1277 d->preedit_lines_ = 1;
1278 for (size_t pos = 0; pos != preedit_length; ++pos) {
1279 char_type const typed_char = preedit_string[pos];
1280 // reset preedit string style
1281 ps = Painter::preedit_default;
1283 // if we reached the right extremity of the screen, go to next line.
1284 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1285 cur_x = right_margin;
1286 cur_y += height + 1;
1287 ++d->preedit_lines_;
1289 // preedit strings are displayed with dashed underline
1290 // and partial strings are displayed white on black indicating
1291 // that we are in selecting mode in the input method.
1292 // FIXME: rLength == preedit_length is not a changing condition
1293 // FIXME: should be put out of the loop.
1295 && pos < rStart + rLength
1296 && !(cursor_pos < rLength && rLength == preedit_length))
1297 ps = Painter::preedit_selecting;
1299 if (pos == cursor_pos
1300 && (cursor_pos < rLength && rLength == preedit_length))
1301 ps = Painter::preedit_cursor;
1303 // draw one character and update cur_x.
1304 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1307 // update the preedit string screen area.
1308 update(0, cur_y - d->preedit_lines_*height, viewport()->width(),
1309 (height + 1) * d->preedit_lines_);
1311 // Don't forget to accept the event!
1316 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1318 QRect cur_r(0, 0, 0, 0);
1320 // this is the CJK-specific composition window position and
1321 // the context menu position when the menu key is pressed.
1322 case Qt::ImMicroFocus:
1323 cur_r = d->cursor_->rect();
1324 if (d->preedit_lines_ != 1)
1326 cur_r.moveBottom(cur_r.bottom()
1327 + cur_r.height() * (d->preedit_lines_ - 1));
1328 // return lower right of cursor in LyX.
1331 return QWidget::inputMethodQuery(query);
1336 void GuiWorkArea::updateWindowTitle()
1338 docstring maximize_title;
1339 docstring minimize_title;
1341 Buffer const & buf = d->buffer_view_->buffer();
1342 FileName const file_name = buf.fileName();
1343 if (!file_name.empty()) {
1344 maximize_title = file_name.displayName(130);
1345 minimize_title = from_utf8(file_name.onlyFileName());
1346 if (buf.lyxvc().inUse()) {
1347 if (buf.lyxvc().locking())
1348 maximize_title += _(" (version control, locking)");
1350 maximize_title += _(" (version control)");
1352 if (!buf.isClean()) {
1353 maximize_title += _(" (changed)");
1354 minimize_title += char_type('*');
1356 if (buf.isReadonly())
1357 maximize_title += _(" (read only)");
1360 QString const new_title = toqstr(maximize_title);
1361 if (new_title != windowTitle()) {
1362 QWidget::setWindowTitle(new_title);
1363 QWidget::setWindowIconText(toqstr(minimize_title));
1369 bool GuiWorkArea::isFullScreen() const
1371 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1375 void GuiWorkArea::scheduleRedraw()
1377 d->schedule_redraw_ = true;
1381 bool GuiWorkArea::inDialogMode() const
1383 return d->dialog_mode_;
1387 void GuiWorkArea::setDialogMode(bool mode)
1389 d->dialog_mode_ = mode;
1393 GuiCompleter & GuiWorkArea::completer()
1395 return *d->completer_;
1398 GuiView const & GuiWorkArea::view() const
1400 return *d->lyx_view_;
1404 GuiView & GuiWorkArea::view()
1406 return *d->lyx_view_;
1409 ////////////////////////////////////////////////////////////////////
1413 ////////////////////////////////////////////////////////////////////
1416 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1418 buffer_ = theBufferList().newInternalBuffer(
1419 support::FileName::tempName("embedded.internal").absFileName());
1420 buffer_->setUnnamed(true);
1421 buffer_->setFullyLoaded(true);
1422 setBuffer(*buffer_);
1423 setDialogMode(true);
1427 EmbeddedWorkArea::~EmbeddedWorkArea()
1429 // No need to destroy buffer and bufferview here, because it is done
1430 // in theBufferList() destruction loop at application exit
1434 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1437 GuiWorkArea::closeEvent(ev);
1441 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1444 GuiWorkArea::hideEvent(ev);
1448 QSize EmbeddedWorkArea::sizeHint () const
1451 // GuiWorkArea sets the size to the screen's viewport
1452 // by returning a value this gets overridden
1453 // EmbeddedWorkArea is now sized to fit in the layout
1454 // of the parent, and has a minimum size set in GuiWorkArea
1455 // which is what we return here
1456 return QSize(100, 70);
1460 void EmbeddedWorkArea::disable()
1462 stopBlinkingCursor();
1463 if (view().currentWorkArea() != this)
1465 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1466 // tolerates it and shows the background logo), what happens if
1467 // an EmbeddedWorkArea is closed after closing all document WAs
1468 view().setCurrentWorkArea(view().currentMainWorkArea());
1471 ////////////////////////////////////////////////////////////////////
1475 ////////////////////////////////////////////////////////////////////
1478 class NoTabFrameMacStyle : public QMacStyle {
1481 QRect subElementRect(SubElement element, const QStyleOption * option,
1482 const QWidget * widget = 0) const
1484 QRect rect = QMacStyle::subElementRect(element, option, widget);
1485 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1487 // The Qt Mac style puts the contents into a 3 pixel wide box
1488 // which looks very ugly and not like other Mac applications.
1489 // Hence we remove this here, and moreover the 16 pixel round
1490 // frame above if the tab bar is hidden.
1491 if (element == QStyle::SE_TabWidgetTabContents) {
1492 rect.adjust(- rect.left(), 0, rect.left(), 0);
1501 NoTabFrameMacStyle noTabFrameMacStyle;
1505 TabWorkArea::TabWorkArea(QWidget * parent)
1506 : QTabWidget(parent), clicked_tab_(-1)
1509 setStyle(&noTabFrameMacStyle);
1511 #if QT_VERSION < 0x040500
1512 lyxrc.single_close_tab_button = true;
1515 QPalette pal = palette();
1516 pal.setColor(QPalette::Active, QPalette::Button,
1517 pal.color(QPalette::Active, QPalette::Window));
1518 pal.setColor(QPalette::Disabled, QPalette::Button,
1519 pal.color(QPalette::Disabled, QPalette::Window));
1520 pal.setColor(QPalette::Inactive, QPalette::Button,
1521 pal.color(QPalette::Inactive, QPalette::Window));
1523 QObject::connect(this, SIGNAL(currentChanged(int)),
1524 this, SLOT(on_currentTabChanged(int)));
1526 closeBufferButton = new QToolButton(this);
1527 closeBufferButton->setPalette(pal);
1528 // FIXME: rename the icon to closebuffer.png
1529 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1530 closeBufferButton->setText("Close File");
1531 closeBufferButton->setAutoRaise(true);
1532 closeBufferButton->setCursor(Qt::ArrowCursor);
1533 closeBufferButton->setToolTip(qt_("Close File"));
1534 closeBufferButton->setEnabled(true);
1535 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1536 this, SLOT(closeCurrentBuffer()));
1537 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1539 // setup drag'n'drop
1540 QTabBar* tb = new DragTabBar;
1541 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1542 this, SLOT(moveTab(int, int)));
1543 tb->setElideMode(Qt::ElideNone);
1546 // make us responsible for the context menu of the tabbar
1547 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1548 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1549 this, SLOT(showContextMenu(const QPoint &)));
1550 #if QT_VERSION >= 0x040500
1551 connect(tb, SIGNAL(tabCloseRequested(int)),
1552 this, SLOT(closeTab(int)));
1555 setUsesScrollButtons(true);
1559 void TabWorkArea::paintEvent(QPaintEvent * event)
1561 if (tabBar()->isVisible()) {
1562 QTabWidget::paintEvent(event);
1564 // Prevent the selected tab to influence the
1565 // painting of the frame of the tab widget.
1566 // This is needed for gtk style in Qt.
1567 QStylePainter p(this);
1568 QStyleOptionTabWidgetFrameV2 opt;
1569 initStyleOption(&opt);
1570 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1572 opt.selectedTabRect = QRect();
1573 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1578 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1580 if (event->button() != Qt::LeftButton)
1583 // return early if double click on existing tabs
1584 for (int i = 0; i < count(); ++i)
1585 if (tabBar()->tabRect(i).contains(event->pos()))
1588 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1592 void TabWorkArea::setFullScreen(bool full_screen)
1594 for (int i = 0; i != count(); ++i) {
1595 if (GuiWorkArea * wa = workArea(i))
1596 wa->setFullScreen(full_screen);
1599 if (lyxrc.full_screen_tabbar)
1600 showBar(!full_screen && count() > 1);
1602 showBar(count() > 1);
1606 void TabWorkArea::showBar(bool show)
1608 tabBar()->setEnabled(show);
1609 tabBar()->setVisible(show);
1610 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1611 #if QT_VERSION >= 0x040500
1612 setTabsClosable(!lyxrc.single_close_tab_button);
1617 GuiWorkArea * TabWorkArea::currentWorkArea()
1622 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1628 GuiWorkArea * TabWorkArea::workArea(int index)
1630 return dynamic_cast<GuiWorkArea *>(widget(index));
1634 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1636 // FIXME: this method doesn't work if we have more than work area
1637 // showing the same buffer.
1638 for (int i = 0; i != count(); ++i) {
1639 GuiWorkArea * wa = workArea(i);
1640 LASSERT(wa, return 0);
1641 if (&wa->bufferView().buffer() == &buffer)
1648 void TabWorkArea::closeAll()
1651 GuiWorkArea * wa = workArea(0);
1659 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1661 LASSERT(work_area, /**/);
1662 int index = indexOf(work_area);
1666 if (index == currentIndex())
1667 // Make sure the work area is up to date.
1668 on_currentTabChanged(index);
1670 // Switch to the work area.
1671 setCurrentIndex(index);
1672 work_area->setFocus();
1678 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1680 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1681 wa->setUpdatesEnabled(false);
1682 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1683 // when hiding it again below).
1684 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1685 showBar(count() > 0);
1686 addTab(wa, wa->windowTitle());
1687 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1688 this, SLOT(updateTabTexts()));
1689 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1690 setFullScreen(true);
1692 // Hide tabbar if there's only one tab.
1693 showBar(count() > 1);
1701 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1703 LASSERT(work_area, return false);
1704 int index = indexOf(work_area);
1708 work_area->setUpdatesEnabled(false);
1713 // make sure the next work area is enabled.
1714 currentWidget()->setUpdatesEnabled(true);
1715 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1716 setFullScreen(true);
1718 // Show tabbar only if there's more than one tab.
1719 showBar(count() > 1);
1721 lastWorkAreaRemoved();
1729 void TabWorkArea::on_currentTabChanged(int i)
1731 // returns e.g. on application destruction
1734 GuiWorkArea * wa = workArea(i);
1735 LASSERT(wa, return);
1736 wa->setUpdatesEnabled(true);
1740 currentWorkAreaChanged(wa);
1742 LYXERR(Debug::GUI, "currentTabChanged " << i
1743 << " File: " << wa->bufferView().buffer().absFileName());
1747 void TabWorkArea::closeCurrentBuffer()
1750 if (clicked_tab_ == -1)
1751 wa = currentWorkArea();
1753 wa = workArea(clicked_tab_);
1756 wa->view().closeWorkArea(wa);
1760 void TabWorkArea::hideCurrentTab()
1763 if (clicked_tab_ == -1)
1764 wa = currentWorkArea();
1766 wa = workArea(clicked_tab_);
1769 wa->view().hideWorkArea(wa);
1773 void TabWorkArea::closeTab(int index)
1775 on_currentTabChanged(index);
1778 wa = currentWorkArea();
1780 wa = workArea(index);
1783 wa->view().closeWorkArea(wa);
1790 /// make vector happy
1793 DisplayPath(int tab, FileName const & filename)
1796 filename_ = (filename.extension() == "lyx") ?
1797 toqstr(filename.onlyFileNameWithoutExt())
1798 : toqstr(filename.onlyFileName());
1799 postfix_ = toqstr(filename.absoluteFilePath()).
1800 split("/", QString::SkipEmptyParts);
1801 postfix_.pop_back();
1802 abs_ = toqstr(filename.absoluteFilePath());
1803 dottedPrefix_ = false;
1806 /// Absolute path for debugging.
1811 /// Add the first segment from the postfix or three dots to the prefix.
1812 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1813 /// when really needed.
1814 void shiftPathSegment(bool dotted)
1816 if (postfix_.count() <= 0)
1820 if (dottedPrefix_ && !prefix_.isEmpty())
1822 prefix_ += postfix_.front() + "/";
1824 dottedPrefix_ = dotted && !prefix_.isEmpty();
1825 postfix_.pop_front();
1828 QString displayString() const
1830 if (prefix_.isEmpty())
1833 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1834 return prefix_ + (dots ? ".../" : "") + filename_;
1837 QString forecastPathString() const
1839 if (postfix_.count() == 0)
1840 return displayString();
1843 + (dottedPrefix_ ? ".../" : "")
1844 + postfix_.front() + "/";
1847 bool final() const { return postfix_.empty(); }
1849 int tab() const { return tab_; }
1855 QStringList postfix_;
1868 bool operator<(DisplayPath const & a, DisplayPath const & b)
1870 return a.displayString() < b.displayString();
1874 bool operator==(DisplayPath const & a, DisplayPath const & b)
1876 return a.displayString() == b.displayString();
1880 void TabWorkArea::updateTabTexts()
1885 std::list<DisplayPath> paths;
1886 typedef std::list<DisplayPath>::iterator It;
1888 // collect full names first: path into postfix, empty prefix and
1889 // filename without extension
1890 for (size_t i = 0; i < n; ++i) {
1891 GuiWorkArea * i_wa = workArea(i);
1892 FileName const fn = i_wa->bufferView().buffer().fileName();
1893 paths.push_back(DisplayPath(i, fn));
1896 // go through path segments and see if it helps to make the path more unique
1897 bool somethingChanged = true;
1898 bool allFinal = false;
1899 while (somethingChanged && !allFinal) {
1900 // adding path segments changes order
1903 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1904 somethingChanged = false;
1907 // find segments which are not unique (i.e. non-atomic)
1908 It it = paths.begin();
1910 QString segString = it->displayString();
1911 for (; it != paths.end(); ++it) {
1912 // look to the next item
1917 allFinal = allFinal && it->final();
1919 LYXERR(Debug::GUI, "it = " << it->abs()
1920 << " => " << it->displayString());
1922 // still the same segment?
1924 if ((next != paths.end()
1925 && (nextString = next->displayString()) == segString))
1927 LYXERR(Debug::GUI, "segment ended");
1929 // only a trivial one with one element?
1930 if (it == segStart) {
1931 // start new segment
1933 segString = nextString;
1937 // we found a non-atomic segment segStart <= sit <= it < next.
1938 // Shift path segments and hope for the best
1939 // that it makes the path more unique.
1940 somethingChanged = true;
1942 QString dspString = sit->forecastPathString();
1943 LYXERR(Debug::GUI, "first forecast found for "
1944 << sit->abs() << " => " << dspString);
1946 bool moreUnique = false;
1947 for (; sit != next; ++sit) {
1948 if (sit->forecastPathString() != dspString) {
1949 LYXERR(Debug::GUI, "different forecast found for "
1950 << sit->abs() << " => " << sit->forecastPathString());
1954 LYXERR(Debug::GUI, "same forecast found for "
1955 << sit->abs() << " => " << dspString);
1958 // if the path segment helped, add it. Otherwise add dots
1959 bool dots = !moreUnique;
1960 LYXERR(Debug::GUI, "using dots = " << dots);
1961 for (sit = segStart; sit != next; ++sit) {
1962 sit->shiftPathSegment(dots);
1963 LYXERR(Debug::GUI, "shifting "
1964 << sit->abs() << " => " << sit->displayString());
1967 // start new segment
1969 segString = nextString;
1973 // set new tab titles
1974 for (It it = paths.begin(); it != paths.end(); ++it) {
1975 int const tab_index = it->tab();
1976 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
1977 QString tab_text = it->displayString();
1978 if (!buf.fileName().empty() && !buf.isClean())
1980 setTabText(tab_index, tab_text);
1981 setTabToolTip(tab_index, it->abs());
1986 void TabWorkArea::showContextMenu(const QPoint & pos)
1989 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1990 if (clicked_tab_ == -1)
1995 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
1996 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
1997 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
1998 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1999 popup.exec(tabBar()->mapToGlobal(pos));
2005 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2007 QWidget * w = widget(fromIndex);
2008 QIcon icon = tabIcon(fromIndex);
2009 QString text = tabText(fromIndex);
2011 setCurrentIndex(fromIndex);
2012 removeTab(fromIndex);
2013 insertTab(toIndex, w, icon, text);
2014 setCurrentIndex(toIndex);
2018 DragTabBar::DragTabBar(QWidget* parent)
2021 setAcceptDrops(true);
2022 #if QT_VERSION >= 0x040500
2023 setTabsClosable(!lyxrc.single_close_tab_button);
2028 #if QT_VERSION < 0x040300
2029 int DragTabBar::tabAt(QPoint const & position) const
2031 const int max = count();
2032 for (int i = 0; i < max; ++i) {
2033 if (tabRect(i).contains(position))
2041 void DragTabBar::mousePressEvent(QMouseEvent * event)
2043 if (event->button() == Qt::LeftButton)
2044 dragStartPos_ = event->pos();
2045 QTabBar::mousePressEvent(event);
2049 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2051 // If the left button isn't pressed anymore then return
2052 if (!(event->buttons() & Qt::LeftButton))
2055 // If the distance is too small then return
2056 if ((event->pos() - dragStartPos_).manhattanLength()
2057 < QApplication::startDragDistance())
2060 // did we hit something after all?
2061 int tab = tabAt(dragStartPos_);
2065 // simulate button release to remove highlight from button
2066 int i = currentIndex();
2067 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2068 event->button(), event->buttons(), 0);
2069 QTabBar::mouseReleaseEvent(&me);
2073 QDrag * drag = new QDrag(this);
2074 QMimeData * mimeData = new QMimeData;
2075 // a crude way to distinguish tab-reodering drops from other ones
2076 mimeData->setData("action", "tab-reordering") ;
2077 drag->setMimeData(mimeData);
2079 #if QT_VERSION >= 0x040300
2080 // get tab pixmap as cursor
2081 QRect r = tabRect(tab);
2082 QPixmap pixmap(r.size());
2083 render(&pixmap, - r.topLeft());
2084 drag->setPixmap(pixmap);
2087 drag->start(Qt::MoveAction);
2093 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2095 // Only accept if it's an tab-reordering request
2096 QMimeData const * m = event->mimeData();
2097 QStringList formats = m->formats();
2098 if (formats.contains("action")
2099 && m->data("action") == "tab-reordering")
2100 event->acceptProposedAction();
2104 void DragTabBar::dropEvent(QDropEvent * event)
2106 int fromIndex = tabAt(dragStartPos_);
2107 int toIndex = tabAt(event->pos());
2109 // Tell interested objects that
2110 if (fromIndex != toIndex)
2111 tabMoveRequested(fromIndex, toIndex);
2112 event->acceptProposedAction();
2116 } // namespace frontend
2119 #include "moc_GuiWorkArea.cpp"