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>
64 #include <QMainWindow>
69 #include <QPixmapCache>
71 #include <QStyleOption>
72 #include <QStylePainter>
74 #include <QToolButton>
78 #include "support/bind.h"
82 int const TabIndicatorWidth = 3;
88 using namespace lyx::support;
93 /// return the LyX mouse button state from Qt's
94 static mouse_button::state q_button_state(Qt::MouseButton button)
96 mouse_button::state b = mouse_button::none;
99 b = mouse_button::button1;
102 b = mouse_button::button2;
104 case Qt::RightButton:
105 b = mouse_button::button3;
114 /// return the LyX mouse button state from Qt's
115 mouse_button::state q_motion_state(Qt::MouseButtons state)
117 mouse_button::state b = mouse_button::none;
118 if (state & Qt::LeftButton)
119 b |= mouse_button::button1;
120 if (state & Qt::MidButton)
121 b |= mouse_button::button2;
122 if (state & Qt::RightButton)
123 b |= mouse_button::button3;
136 void draw(QPainter & painter)
138 if (!show_ || !rect_.isValid())
142 int l = x_ - rect_.left();
143 int r = rect_.right() - x_;
144 int bot = rect_.bottom();
146 // draw vertical line
147 painter.fillRect(x_, y, cursor_width_, rect_.height(), color_);
149 // draw RTL/LTR indication
150 painter.setPen(color_);
153 painter.drawLine(x_, bot, x_ - l, bot);
155 painter.drawLine(x_, bot, x_ + cursor_width_ + r, bot);
158 // draw completion triangle
160 int m = y + rect_.height() / 2;
161 int d = TabIndicatorWidth - 1;
163 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
164 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
166 painter.drawLine(x_ + cursor_width_, m - d, x_ + cursor_width_ + d, m);
167 painter.drawLine(x_ + cursor_width_, m + d, x_ + cursor_width_ + d, m);
172 void update(int x, int y, int h, bool l_shape,
173 bool rtl, bool completable)
175 color_ = guiApp->colorCache().get(Color_cursor);
178 completable_ = completable;
181 // extension to left and right
185 // RTL/LTR indication
193 // completion triangle
196 l = max(l, TabIndicatorWidth);
198 r = max(r, TabIndicatorWidth);
201 // compute overall rectangle
202 rect_ = QRect(x - l, y, cursor_width_ + r + l, h);
205 void show(bool set_show = true) { show_ = set_show; }
206 void hide() { show_ = false; }
207 int cursorWidth() const { return cursor_width_; }
208 void recomputeWidth() {
209 cursor_width_ = lyxrc.cursor_width
211 : 1 + int((lyxrc.zoom + 50) / 200.0);
214 QRect const & rect() { return rect_; }
217 /// cursor is in RTL or LTR text
219 /// indication for RTL or LTR
221 /// triangle to show that a completion is available
227 /// rectangle, possibly with l_shape and completion triangle
229 /// x position (were the vertical line is drawn)
236 // This is a 'heartbeat' generating synthetic mouse move events when the
237 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
238 SyntheticMouseEvent::SyntheticMouseEvent()
239 : timeout(200), restart_timeout(true)
243 GuiWorkArea::Private::Private(GuiWorkArea * parent)
244 : p(parent), screen_(0), buffer_view_(0), lyx_view_(0), cursor_visible_(false),
245 need_resize_(false), schedule_redraw_(false), preedit_lines_(1),
246 completer_(new GuiCompleter(p, p))
251 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
252 : d(new Private(this))
257 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
258 : d(new Private(this))
266 void GuiWorkArea::init()
269 connect(&d->cursor_timeout_, SIGNAL(timeout()),
270 this, SLOT(toggleCursor()));
272 int const time = QApplication::cursorFlashTime() / 2;
274 d->cursor_timeout_.setInterval(time);
275 d->cursor_timeout_.start();
277 // let's initialize this just to be safe
278 d->cursor_timeout_.setInterval(500);
282 // With Qt4.5 a mouse event will happen before the first paint event
283 // so make sure that the buffer view has an up to date metrics.
284 d->buffer_view_->resize(viewport()->width(), viewport()->height());
285 d->cursor_ = new frontend::CursorWidget();
288 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
289 setAcceptDrops(true);
290 setMouseTracking(true);
291 setMinimumSize(100, 70);
292 setFrameStyle(QFrame::NoFrame);
295 viewport()->setAutoFillBackground(false);
296 // We don't need double-buffering nor SystemBackground on
297 // the viewport because we have our own backing pixmap.
298 viewport()->setAttribute(Qt::WA_NoSystemBackground);
300 setFocusPolicy(Qt::StrongFocus);
302 d->setCursorShape(Qt::IBeamCursor);
304 d->synthetic_mouse_event_.timeout.timeout.connect(
305 bind(&GuiWorkArea::generateSyntheticMouseEvent,
308 // Initialize the vertical Scroll Bar
309 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
310 this, SLOT(scrollTo(int)));
312 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
313 << " viewport height: " << viewport()->height());
315 // Enables input methods for asian languages.
316 // Must be set when creating custom text editing widgets.
317 setAttribute(Qt::WA_InputMethodEnabled, true);
319 d->dialog_mode_ = false;
323 GuiWorkArea::~GuiWorkArea()
325 d->buffer_view_->buffer().workAreaManager().remove(this);
327 delete d->buffer_view_;
329 // Completer has a QObject parent and is thus automatically destroyed.
331 // delete completer_;
336 Qt::CursorShape GuiWorkArea::cursorShape() const
338 return viewport()->cursor().shape();
342 void GuiWorkArea::Private::setCursorShape(Qt::CursorShape shape)
344 p->viewport()->setCursor(shape);
348 void GuiWorkArea::Private::updateCursorShape()
350 setCursorShape(buffer_view_->clickableInset()
351 ? Qt::PointingHandCursor : Qt::IBeamCursor);
355 void GuiWorkArea::setGuiView(GuiView & gv)
361 void GuiWorkArea::setBuffer(Buffer & buffer)
363 delete d->buffer_view_;
364 d->buffer_view_ = new BufferView(buffer);
365 buffer.workAreaManager().add(this);
367 // HACK: Prevents an additional redraw when the scrollbar pops up
368 // which regularily happens on documents with more than one page.
369 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
370 // Since we have no geometry information yet, we assume that
371 // a document needs a scrollbar if there is more then four
372 // paragraph in the outermost text.
373 if (buffer.text().paragraphs().size() > 4)
374 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
375 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
379 void GuiWorkArea::fixVerticalScrollBar()
382 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
386 void GuiWorkArea::close()
388 d->lyx_view_->removeWorkArea(this);
392 void GuiWorkArea::setFullScreen(bool full_screen)
394 d->buffer_view_->setFullScreen(full_screen);
395 setFrameStyle(QFrame::NoFrame);
397 setFrameStyle(QFrame::NoFrame);
398 if (lyxrc.full_screen_scrollbar)
399 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
401 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
405 BufferView & GuiWorkArea::bufferView()
407 return *d->buffer_view_;
411 BufferView const & GuiWorkArea::bufferView() const
413 return *d->buffer_view_;
417 void GuiWorkArea::stopBlinkingCursor()
419 d->cursor_timeout_.stop();
424 void GuiWorkArea::startBlinkingCursor()
426 // do not show the cursor if the view is busy
432 d->buffer_view_->cursorPosAndHeight(p, h);
433 // Don't start blinking if the cursor isn't on screen.
434 if (!d->buffer_view_->cursorInView(p, h))
439 //we're not supposed to cache this value.
440 int const time = QApplication::cursorFlashTime() / 2;
443 d->cursor_timeout_.setInterval(time);
444 d->cursor_timeout_.start();
448 void GuiWorkArea::redraw(bool update_metrics)
451 // No need to redraw in this case.
454 // No need to do anything if this is the current view. The BufferView
455 // metrics are already up to date.
456 if (update_metrics || d->lyx_view_ != guiApp->currentView()
457 || d->lyx_view_->currentWorkArea() != this) {
458 // FIXME: it would be nice to optimize for the off-screen case.
459 d->buffer_view_->cursor().fixIfBroken();
460 d->buffer_view_->updateMetrics();
461 d->buffer_view_->cursor().fixIfBroken();
464 // update cursor position, because otherwise it has to wait until
465 // the blinking interval is over
466 if (d->cursor_visible_) {
471 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
473 update(0, 0, viewport()->width(), viewport()->height());
475 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
476 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
477 d->updateScrollbar();
478 d->lyx_view_->updateStatusBar();
480 if (lyxerr.debugging(Debug::WORKAREA))
481 d->buffer_view_->coordCache().dump();
485 d->updateCursorShape();
489 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
491 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
492 && lyxrc.full_screen_menubar) {
493 // FIXME HACK: we should not have to do this here. See related comment
494 // in GuiView::event() (QEvent::ShortcutOverride)
495 d->lyx_view_->menuBar()->hide();
498 // In order to avoid bad surprise in the middle of an operation,
499 // we better stop the blinking cursor...
500 // the cursor gets restarted in GuiView::restartCursor()
501 stopBlinkingCursor();
502 guiApp->processKeySym(key, mod);
506 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd0, KeyModifier mod)
509 if (cmd0.action() == LFUN_FILE_OPEN) {
511 lyx_view_->dispatch(cmd0, dr);
517 if (cmd0.action() == LFUN_MOUSE_PRESS) {
518 if (mod == ShiftModifier)
519 cmd = FuncRequest(cmd0, "region-select");
520 else if (mod == ControlModifier)
521 cmd = FuncRequest(cmd0, "paragraph-select");
528 bool const notJustMovingTheMouse =
529 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
531 // In order to avoid bad surprise in the middle of an operation, we better stop
532 // the blinking cursor.
533 if (notJustMovingTheMouse)
534 p->stopBlinkingCursor();
536 buffer_view_->mouseEventDispatch(cmd);
538 // Skip these when selecting
539 // FIXME: let GuiView take care of those.
540 if (cmd.action() != LFUN_MOUSE_MOTION) {
541 completer_->updateVisibility(false, false);
542 lyx_view_->updateDialogs();
543 lyx_view_->updateStatusBar();
546 // GUI tweaks except with mouse motion with no button pressed.
547 if (notJustMovingTheMouse) {
548 // Slight hack: this is only called currently when we
549 // clicked somewhere, so we force through the display
550 // of the new status here.
551 // FIXME: let GuiView take care of those.
552 lyx_view_->clearMessage();
554 // Show the cursor immediately after any operation
555 p->startBlinkingCursor();
562 void GuiWorkArea::Private::resizeBufferView()
564 // WARNING: Please don't put any code that will trigger a repaint here!
565 // We are already inside a paint event.
566 p->stopBlinkingCursor();
567 // Warn our container (GuiView).
572 buffer_view_->cursorPosAndHeight(point, h);
573 bool const cursor_in_view = buffer_view_->cursorInView(point, h);
574 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
576 buffer_view_->scrollToCursor();
579 // Update scrollbars which might have changed due different
580 // BufferView dimension. This is especially important when the
581 // BufferView goes from zero-size to the real-size for the first time,
582 // as the scrollbar paramters are then set for the first time.
585 need_resize_ = false;
587 // Eventually, restart the cursor after the resize event.
588 // We might be resizing even if the focus is on another widget so we only
589 // restart the cursor if we have the focus.
591 QTimer::singleShot(50, p, SLOT(startBlinkingCursor()));
595 void GuiWorkArea::Private::showCursor()
602 buffer_view_->cursorPosAndHeight(p, h);
603 if (!buffer_view_->cursorInView(p, h))
607 bool l_shape = false;
608 Font const & realfont = buffer_view_->cursor().real_current_font;
609 BufferParams const & bp = buffer_view_->buffer().params();
610 bool const samelang = realfont.language() == bp.language;
611 bool const isrtl = realfont.isVisibleRightToLeft();
613 if (!samelang || isrtl != bp.language->rightToLeft())
616 // The ERT language hack needs fixing up
617 if (realfont.language() == latex_language)
620 // show cursor on screen
621 Cursor & cur = buffer_view_->cursor();
622 bool completable = cur.inset().showCompletionCursor()
623 && completer_->completionAvailable()
624 && !completer_->popupVisible()
625 && !completer_->inlineVisible();
626 cursor_visible_ = true;
627 cursor_->recomputeWidth();
628 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
632 void GuiWorkArea::Private::hideCursor()
634 if (!cursor_visible_)
637 cursor_visible_ = false;
642 void GuiWorkArea::toggleCursor()
644 if (d->cursor_visible_)
651 void GuiWorkArea::Private::updateScrollbar()
653 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
654 // WARNING: don't touch at the scrollbar value like this:
655 // verticalScrollBar()->setValue(scroll_.position);
656 // because this would cause a recursive signal/slot calling with
657 // GuiWorkArea::scrollTo
658 p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
659 p->verticalScrollBar()->setPageStep(scroll_.page_step);
660 p->verticalScrollBar()->setSingleStep(scroll_.single_step);
661 p->verticalScrollBar()->setSliderPosition(scroll_.position);
665 void GuiWorkArea::scrollTo(int value)
667 stopBlinkingCursor();
668 d->buffer_view_->scrollDocView(value, true);
670 if (lyxrc.cursor_follows_scrollbar) {
671 d->buffer_view_->setCursorFromScrollbar();
672 // FIXME: let GuiView take care of those.
673 d->lyx_view_->updateLayoutList();
675 // Show the cursor immediately after any operation.
676 startBlinkingCursor();
677 QApplication::syncX();
681 bool GuiWorkArea::event(QEvent * e)
684 case QEvent::ToolTip: {
685 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
686 if (lyxrc.use_tooltip) {
687 QPoint pos = helpEvent->pos();
688 if (pos.x() < viewport()->width()) {
689 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
690 QToolTip::showText(helpEvent->globalPos(), s);
693 QToolTip::hideText();
695 // Don't forget to accept the event!
700 case QEvent::ShortcutOverride: {
701 // We catch this event in order to catch the Tab or Shift+Tab key press
702 // which are otherwise reserved to focus switching between controls
704 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
705 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
706 || (ke->key() == Qt::Key_Backtab && (
707 ke->modifiers() == Qt::ShiftModifier
708 || ke->modifiers() == Qt::NoModifier))) {
712 return QAbstractScrollArea::event(e);
716 return QAbstractScrollArea::event(e);
722 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
725 if (e->reason() == QContextMenuEvent::Mouse)
726 // the menu name is set on mouse press
727 name = d->context_menu_name_;
729 QPoint pos = e->pos();
730 Cursor const & cur = d->buffer_view_->cursor();
731 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
732 // Do not access the context menu of math right in front of before
733 // the cursor. This does not work when the cursor is in text.
734 Inset * inset = cur.paragraph().getInset(cur.pos());
735 if (inset && inset->asInsetMath())
737 else if (cur.pos() > 0) {
738 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
743 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
747 QAbstractScrollArea::contextMenuEvent(e);
750 // always show mnemonics when the keyboard is used to show the context menu
751 // FIXME: This should be fixed in Qt itself
752 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
753 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
755 QAbstractScrollArea::contextMenuEvent(e);
758 // Position the menu to the right.
759 // FIXME: menu position should be different for RTL text.
760 menu->exec(e->globalPos());
765 void GuiWorkArea::focusInEvent(QFocusEvent * e)
767 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
768 if (d->lyx_view_->currentWorkArea() != this) {
769 d->lyx_view_->setCurrentWorkArea(this);
770 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
773 startBlinkingCursor();
774 QAbstractScrollArea::focusInEvent(e);
778 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
780 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
781 stopBlinkingCursor();
782 QAbstractScrollArea::focusOutEvent(e);
786 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
788 if (d->dc_event_.active && d->dc_event_ == *e) {
789 d->dc_event_.active = false;
790 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
791 q_button_state(e->button()));
797 inputContext()->reset();
799 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
800 q_button_state(e->button()));
801 d->dispatch(cmd, q_key_state(e->modifiers()));
803 // Save the context menu on mouse press, because also the mouse
804 // cursor is set on mouse press. Afterwards, we can either release
805 // the mousebutton somewhere else, or the cursor might have moved
806 // due to the DEPM. We need to do this after the mouse has been
807 // set in dispatch(), because the selection state might change.
808 if (e->button() == Qt::RightButton)
809 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
815 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
817 if (d->synthetic_mouse_event_.timeout.running())
818 d->synthetic_mouse_event_.timeout.stop();
820 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
821 q_button_state(e->button()));
827 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
829 // we kill the triple click if we move
830 doubleClickTimeout();
831 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
832 q_motion_state(e->buttons()));
836 // If we're above or below the work area...
837 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
838 && e->buttons() == mouse_button::button1) {
839 // Make sure only a synthetic event can cause a page scroll,
840 // so they come at a steady rate:
842 // _Force_ a scroll up:
843 cmd.set_y(e->y() - 21);
845 cmd.set_y(e->y() + 21);
846 // Store the event, to be handled when the timeout expires.
847 d->synthetic_mouse_event_.cmd = cmd;
849 if (d->synthetic_mouse_event_.timeout.running()) {
850 // Discard the event. Note that it _may_ be handled
851 // when the timeout expires if
852 // synthetic_mouse_event_.cmd has not been overwritten.
853 // Ie, when the timeout expires, we handle the
854 // most recent event but discard all others that
855 // occurred after the one used to start the timeout
856 // in the first place.
860 d->synthetic_mouse_event_.restart_timeout = true;
861 d->synthetic_mouse_event_.timeout.start();
862 // Fall through to handle this event...
864 } else if (d->synthetic_mouse_event_.timeout.running()) {
865 // Store the event, to be possibly handled when the timeout
867 // Once the timeout has expired, normal control is returned
868 // to mouseMoveEvent (restart_timeout = false).
869 // This results in a much smoother 'feel' when moving the
870 // mouse back into the work area.
871 d->synthetic_mouse_event_.cmd = cmd;
872 d->synthetic_mouse_event_.restart_timeout = false;
879 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
881 // Wheel rotation by one notch results in a delta() of 120 (see
882 // documentation of QWheelEvent)
883 double const delta = ev->delta() / 120.0;
885 switch (lyxrc.scroll_wheel_zoom) {
886 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
887 zoom = ev->modifiers() & Qt::ControlModifier;
888 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
890 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
891 zoom = ev->modifiers() & Qt::ShiftModifier;
892 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
894 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
895 zoom = ev->modifiers() & Qt::AltModifier;
896 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
898 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
902 docstring arg = convert<docstring>(int(5 * delta));
903 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
907 // Take into account the desktop wide settings.
908 int const lines = qApp->wheelScrollLines();
909 int const page_step = verticalScrollBar()->pageStep();
910 // Test if the wheel mouse is set to one screen at a time.
911 int scroll_value = lines > page_step
912 ? page_step : lines * verticalScrollBar()->singleStep();
914 // Take into account the rotation and the user preferences.
915 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
916 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
917 << " delta = " << delta << " scroll_value = " << scroll_value
918 << " page_step = " << page_step);
920 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
926 void GuiWorkArea::generateSyntheticMouseEvent()
928 int const e_y = d->synthetic_mouse_event_.cmd.y();
929 int const wh = d->buffer_view_->workHeight();
930 bool const up = e_y < 0;
931 bool const down = e_y > wh;
933 // Set things off to generate the _next_ 'pseudo' event.
935 if (d->synthetic_mouse_event_.restart_timeout) {
936 // This is some magic formulae to determine the speed
937 // of scrolling related to the position of the mouse.
940 int dist = up ? -e_y : e_y - wh;
941 time = max(min(200, 250000 / (dist * dist)), 1) ;
944 step = 80000 / (time * time);
948 d->synthetic_mouse_event_.timeout.setTimeout(time);
949 d->synthetic_mouse_event_.timeout.start();
952 // Can we scroll further ?
953 int const value = verticalScrollBar()->value();
954 if (value == verticalScrollBar()->maximum()
955 || value == verticalScrollBar()->minimum()) {
956 d->synthetic_mouse_event_.timeout.stop();
961 if (step <= 2 * wh) {
962 d->buffer_view_->scroll(up ? -step : step);
963 d->buffer_view_->updateMetrics();
965 d->buffer_view_->scrollDocView(value + up ? -step : step, false);
968 // In which paragraph do we have to set the cursor ?
969 Cursor & cur = d->buffer_view_->cursor();
970 // FIXME: we don't know howto handle math.
971 Text * text = cur.text();
974 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
976 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
977 ParagraphMetrics const & pm = *pp.second;
978 pit_type const pit = pp.first;
980 if (pm.rows().empty())
983 // Find the row at which we set the cursor.
984 RowList::const_iterator rit = pm.rows().begin();
985 RowList::const_iterator rlast = pm.rows().end();
986 int yy = pm.position() - pm.ascent();
987 for (--rlast; rit != rlast; ++rit) {
988 int h = rit->height();
989 if ((up && yy + h > 0)
990 || (!up && yy + h > wh - defaultRowHeight()))
995 // Find the position of the cursor
997 int x = d->synthetic_mouse_event_.cmd.x();
998 pos_type const pos = rit->pos() + tm.getColumnNearX(pit, *rit, x, bound);
1003 cur.boundary(bound);
1005 d->buffer_view_->buffer().changed(false);
1010 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1012 // Do not process here some keys if dialog_mode_ is set
1014 && (ev->modifiers() == Qt::NoModifier
1015 || ev->modifiers() == Qt::ShiftModifier)
1016 && (ev->key() == Qt::Key_Escape
1017 || ev->key() == Qt::Key_Enter
1018 || ev->key() == Qt::Key_Return)
1024 // intercept some keys if completion popup is visible
1025 if (d->completer_->popupVisible()) {
1026 switch (ev->key()) {
1028 case Qt::Key_Return:
1029 d->completer_->activate();
1035 // do nothing if there are other events
1036 // (the auto repeated events come too fast)
1037 // it looks like this is only needed on X11
1039 if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1040 switch (ev->key()) {
1041 case Qt::Key_PageDown:
1042 case Qt::Key_PageUp:
1047 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1054 KeyModifier m = q_key_state(ev->modifiers());
1057 if (m & ShiftModifier)
1059 if (m & ControlModifier)
1061 if (m & AltModifier)
1063 if (m & MetaModifier)
1066 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1067 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1068 << " keyState: " << str);
1071 setKeySymbol(&sym, ev);
1073 processKeySym(sym, q_key_state(ev->modifiers()));
1081 void GuiWorkArea::doubleClickTimeout()
1083 d->dc_event_.active = false;
1087 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1089 d->dc_event_ = DoubleClick(ev);
1090 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1091 SLOT(doubleClickTimeout()));
1092 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1094 q_button_state(ev->button()));
1100 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1102 QAbstractScrollArea::resizeEvent(ev);
1103 d->need_resize_ = true;
1108 void GuiWorkArea::Private::update(int x, int y, int w, int h)
1110 p->viewport()->update(x, y, w, h);
1114 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1116 QRect const rc = ev->rect();
1117 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1118 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1120 if (d->need_resize_) {
1122 d->resizeBufferView();
1123 if (d->cursor_visible_) {
1129 QPainter pain(viewport());
1130 if (lyxrc.use_qimage) {
1131 pain.drawImage(rc, static_cast<QImage const &>(*d->screen_), rc);
1133 pain.drawPixmap(rc, static_cast<QPixmap const &>(*d->screen_), rc);
1135 d->cursor_->draw(pain);
1140 void GuiWorkArea::Private::updateScreen()
1142 GuiPainter pain(screen_);
1143 buffer_view_->draw(pain);
1147 void GuiWorkArea::Private::showCursor(int x, int y, int h,
1148 bool l_shape, bool rtl, bool completable)
1150 if (schedule_redraw_) {
1151 // This happens when a graphic conversion is finished. As we don't know
1152 // the size of the new graphics, it's better the update everything.
1153 // We can't use redraw() here because this would trigger a infinite
1154 // recursive loop with showCursor().
1155 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
1158 p->viewport()->update(QRect(0, 0, p->viewport()->width(), p->viewport()->height()));
1159 schedule_redraw_ = false;
1160 // Show the cursor immediately after the update.
1166 cursor_->update(x, y, h, l_shape, rtl, completable);
1168 p->viewport()->update(cursor_->rect());
1172 void GuiWorkArea::Private::removeCursor()
1175 //if (!qApp->focusWidget())
1176 p->viewport()->update(cursor_->rect());
1180 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1182 QString const & commit_string = e->commitString();
1183 docstring const & preedit_string
1184 = qstring_to_ucs4(e->preeditString());
1186 if (!commit_string.isEmpty()) {
1188 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1189 << " commitString: " << e->commitString());
1193 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1194 for (int i = 0; i != commit_string.size(); ++i) {
1195 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1200 // Hide the cursor during the kana-kanji transformation.
1201 if (preedit_string.empty())
1202 startBlinkingCursor();
1204 stopBlinkingCursor();
1206 // last_width : for checking if last preedit string was/wasn't empty.
1207 static bool last_width = false;
1208 if (!last_width && preedit_string.empty()) {
1209 // if last_width is last length of preedit string.
1214 GuiPainter pain(d->screen_);
1215 d->buffer_view_->updateMetrics();
1216 d->buffer_view_->draw(pain);
1217 FontInfo font = d->buffer_view_->cursor().getFont().fontInfo();
1218 FontMetrics const & fm = theFontMetrics(font);
1219 int height = fm.maxHeight();
1220 int cur_x = d->cursor_->rect().left();
1221 int cur_y = d->cursor_->rect().bottom();
1223 // redraw area of preedit string.
1224 update(0, cur_y - height, viewport()->width(),
1225 (height + 1) * d->preedit_lines_);
1227 if (preedit_string.empty()) {
1229 d->preedit_lines_ = 1;
1235 // att : stores an IM attribute.
1236 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1238 // get attributes of input method cursor.
1239 // cursor_pos : cursor position in preedit string.
1240 size_t cursor_pos = 0;
1241 bool cursor_is_visible = false;
1242 for (int i = 0; i != att.size(); ++i) {
1243 if (att.at(i).type == QInputMethodEvent::Cursor) {
1244 cursor_pos = att.at(i).start;
1245 cursor_is_visible = att.at(i).length != 0;
1250 size_t preedit_length = preedit_string.length();
1252 // get position of selection in input method.
1253 // FIXME: isn't there a way to do this simplier?
1254 // rStart : cursor position in selected string in IM.
1256 // rLength : selected string length in IM.
1258 if (cursor_pos < preedit_length) {
1259 for (int i = 0; i != att.size(); ++i) {
1260 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1261 if (att.at(i).start <= int(cursor_pos)
1262 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1263 rStart = att.at(i).start;
1264 rLength = att.at(i).length;
1265 if (!cursor_is_visible)
1266 cursor_pos += rLength;
1273 rStart = cursor_pos;
1277 int const right_margin = d->buffer_view_->rightMargin();
1278 Painter::preedit_style ps;
1279 // Most often there would be only one line:
1280 d->preedit_lines_ = 1;
1281 for (size_t pos = 0; pos != preedit_length; ++pos) {
1282 char_type const typed_char = preedit_string[pos];
1283 // reset preedit string style
1284 ps = Painter::preedit_default;
1286 // if we reached the right extremity of the screen, go to next line.
1287 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1288 cur_x = right_margin;
1289 cur_y += height + 1;
1290 ++d->preedit_lines_;
1292 // preedit strings are displayed with dashed underline
1293 // and partial strings are displayed white on black indicating
1294 // that we are in selecting mode in the input method.
1295 // FIXME: rLength == preedit_length is not a changing condition
1296 // FIXME: should be put out of the loop.
1298 && pos < rStart + rLength
1299 && !(cursor_pos < rLength && rLength == preedit_length))
1300 ps = Painter::preedit_selecting;
1302 if (pos == cursor_pos
1303 && (cursor_pos < rLength && rLength == preedit_length))
1304 ps = Painter::preedit_cursor;
1306 // draw one character and update cur_x.
1307 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1310 // update the preedit string screen area.
1311 update(0, cur_y - d->preedit_lines_*height, viewport()->width(),
1312 (height + 1) * d->preedit_lines_);
1314 // Don't forget to accept the event!
1319 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1321 QRect cur_r(0, 0, 0, 0);
1323 // this is the CJK-specific composition window position and
1324 // the context menu position when the menu key is pressed.
1325 case Qt::ImMicroFocus:
1326 cur_r = d->cursor_->rect();
1327 if (d->preedit_lines_ != 1)
1329 cur_r.moveBottom(cur_r.bottom()
1330 + cur_r.height() * (d->preedit_lines_ - 1));
1331 // return lower right of cursor in LyX.
1334 return QWidget::inputMethodQuery(query);
1339 void GuiWorkArea::updateWindowTitle()
1341 docstring maximize_title;
1342 docstring minimize_title;
1344 Buffer const & buf = d->buffer_view_->buffer();
1345 FileName const file_name = buf.fileName();
1346 if (!file_name.empty()) {
1347 maximize_title = file_name.displayName(130);
1348 minimize_title = from_utf8(file_name.onlyFileName());
1349 if (buf.lyxvc().inUse()) {
1350 if (buf.lyxvc().locking())
1351 maximize_title += _(" (version control, locking)");
1353 maximize_title += _(" (version control)");
1355 if (!buf.isClean()) {
1356 maximize_title += _(" (changed)");
1357 minimize_title += char_type('*');
1359 if (buf.isReadonly())
1360 maximize_title += _(" (read only)");
1363 QString const new_title = toqstr(maximize_title);
1364 if (new_title != windowTitle()) {
1365 QWidget::setWindowTitle(new_title);
1366 QWidget::setWindowIconText(toqstr(minimize_title));
1372 bool GuiWorkArea::isFullScreen() const
1374 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1378 void GuiWorkArea::scheduleRedraw()
1380 d->schedule_redraw_ = true;
1384 bool GuiWorkArea::inDialogMode() const
1386 return d->dialog_mode_;
1390 void GuiWorkArea::setDialogMode(bool mode)
1392 d->dialog_mode_ = mode;
1396 GuiCompleter & GuiWorkArea::completer()
1398 return *d->completer_;
1401 GuiView const & GuiWorkArea::view() const
1403 return *d->lyx_view_;
1407 GuiView & GuiWorkArea::view()
1409 return *d->lyx_view_;
1412 ////////////////////////////////////////////////////////////////////
1416 ////////////////////////////////////////////////////////////////////
1419 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1421 buffer_ = theBufferList().newInternalBuffer(
1422 support::FileName::tempName("embedded.internal").absFileName());
1423 buffer_->setUnnamed(true);
1424 buffer_->setFullyLoaded(true);
1425 setBuffer(*buffer_);
1426 setDialogMode(true);
1430 EmbeddedWorkArea::~EmbeddedWorkArea()
1432 // No need to destroy buffer and bufferview here, because it is done
1433 // in theBufferList() destruction loop at application exit
1437 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1440 GuiWorkArea::closeEvent(ev);
1444 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1447 GuiWorkArea::hideEvent(ev);
1451 QSize EmbeddedWorkArea::sizeHint () const
1454 // GuiWorkArea sets the size to the screen's viewport
1455 // by returning a value this gets overridden
1456 // EmbeddedWorkArea is now sized to fit in the layout
1457 // of the parent, and has a minimum size set in GuiWorkArea
1458 // which is what we return here
1459 return QSize(100, 70);
1463 void EmbeddedWorkArea::disable()
1465 stopBlinkingCursor();
1466 if (view().currentWorkArea() != this)
1468 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1469 // tolerates it and shows the background logo), what happens if
1470 // an EmbeddedWorkArea is closed after closing all document WAs
1471 view().setCurrentWorkArea(view().currentMainWorkArea());
1474 ////////////////////////////////////////////////////////////////////
1478 ////////////////////////////////////////////////////////////////////
1481 class NoTabFrameMacStyle : public QMacStyle {
1484 QRect subElementRect(SubElement element, const QStyleOption * option,
1485 const QWidget * widget = 0) const
1487 QRect rect = QMacStyle::subElementRect(element, option, widget);
1488 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1490 // The Qt Mac style puts the contents into a 3 pixel wide box
1491 // which looks very ugly and not like other Mac applications.
1492 // Hence we remove this here, and moreover the 16 pixel round
1493 // frame above if the tab bar is hidden.
1494 if (element == QStyle::SE_TabWidgetTabContents) {
1495 rect.adjust(- rect.left(), 0, rect.left(), 0);
1504 NoTabFrameMacStyle noTabFrameMacStyle;
1508 TabWorkArea::TabWorkArea(QWidget * parent)
1509 : QTabWidget(parent), clicked_tab_(-1)
1512 setStyle(&noTabFrameMacStyle);
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 connect(tb, SIGNAL(tabCloseRequested(int)),
1551 this, SLOT(closeTab(int)));
1553 setUsesScrollButtons(true);
1557 void TabWorkArea::paintEvent(QPaintEvent * event)
1559 if (tabBar()->isVisible()) {
1560 QTabWidget::paintEvent(event);
1562 // Prevent the selected tab to influence the
1563 // painting of the frame of the tab widget.
1564 // This is needed for gtk style in Qt.
1565 QStylePainter p(this);
1566 QStyleOptionTabWidgetFrameV2 opt;
1567 initStyleOption(&opt);
1568 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1570 opt.selectedTabRect = QRect();
1571 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1576 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1578 if (event->button() != Qt::LeftButton)
1581 // return early if double click on existing tabs
1582 for (int i = 0; i < count(); ++i)
1583 if (tabBar()->tabRect(i).contains(event->pos()))
1586 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1590 void TabWorkArea::setFullScreen(bool full_screen)
1592 for (int i = 0; i != count(); ++i) {
1593 if (GuiWorkArea * wa = workArea(i))
1594 wa->setFullScreen(full_screen);
1597 if (lyxrc.full_screen_tabbar)
1598 showBar(!full_screen && count() > 1);
1600 showBar(count() > 1);
1604 void TabWorkArea::showBar(bool show)
1606 tabBar()->setEnabled(show);
1607 tabBar()->setVisible(show);
1608 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1609 setTabsClosable(!lyxrc.single_close_tab_button);
1613 GuiWorkArea * TabWorkArea::currentWorkArea()
1618 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1624 GuiWorkArea * TabWorkArea::workArea(int index)
1626 return dynamic_cast<GuiWorkArea *>(widget(index));
1630 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1632 // FIXME: this method doesn't work if we have more than work area
1633 // showing the same buffer.
1634 for (int i = 0; i != count(); ++i) {
1635 GuiWorkArea * wa = workArea(i);
1636 LASSERT(wa, return 0);
1637 if (&wa->bufferView().buffer() == &buffer)
1644 void TabWorkArea::closeAll()
1647 GuiWorkArea * wa = workArea(0);
1655 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1657 LASSERT(work_area, /**/);
1658 int index = indexOf(work_area);
1662 if (index == currentIndex())
1663 // Make sure the work area is up to date.
1664 on_currentTabChanged(index);
1666 // Switch to the work area.
1667 setCurrentIndex(index);
1668 work_area->setFocus();
1674 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1676 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1677 wa->setUpdatesEnabled(false);
1678 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1679 // when hiding it again below).
1680 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1681 showBar(count() > 0);
1682 addTab(wa, wa->windowTitle());
1683 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1684 this, SLOT(updateTabTexts()));
1685 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1686 setFullScreen(true);
1688 // Hide tabbar if there's only one tab.
1689 showBar(count() > 1);
1697 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1699 LASSERT(work_area, return false);
1700 int index = indexOf(work_area);
1704 work_area->setUpdatesEnabled(false);
1709 // make sure the next work area is enabled.
1710 currentWidget()->setUpdatesEnabled(true);
1711 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1712 setFullScreen(true);
1714 // Show tabbar only if there's more than one tab.
1715 showBar(count() > 1);
1717 lastWorkAreaRemoved();
1725 void TabWorkArea::on_currentTabChanged(int i)
1727 // returns e.g. on application destruction
1730 GuiWorkArea * wa = workArea(i);
1731 LASSERT(wa, return);
1732 wa->setUpdatesEnabled(true);
1736 currentWorkAreaChanged(wa);
1738 LYXERR(Debug::GUI, "currentTabChanged " << i
1739 << " File: " << wa->bufferView().buffer().absFileName());
1743 void TabWorkArea::closeCurrentBuffer()
1746 if (clicked_tab_ == -1)
1747 wa = currentWorkArea();
1749 wa = workArea(clicked_tab_);
1752 wa->view().closeWorkArea(wa);
1756 void TabWorkArea::hideCurrentTab()
1759 if (clicked_tab_ == -1)
1760 wa = currentWorkArea();
1762 wa = workArea(clicked_tab_);
1765 wa->view().hideWorkArea(wa);
1769 void TabWorkArea::closeTab(int index)
1771 on_currentTabChanged(index);
1774 wa = currentWorkArea();
1776 wa = workArea(index);
1779 wa->view().closeWorkArea(wa);
1786 /// make vector happy
1789 DisplayPath(int tab, FileName const & filename)
1792 filename_ = (filename.extension() == "lyx") ?
1793 toqstr(filename.onlyFileNameWithoutExt())
1794 : toqstr(filename.onlyFileName());
1795 postfix_ = toqstr(filename.absoluteFilePath()).
1796 split("/", QString::SkipEmptyParts);
1797 postfix_.pop_back();
1798 abs_ = toqstr(filename.absoluteFilePath());
1799 dottedPrefix_ = false;
1802 /// Absolute path for debugging.
1807 /// Add the first segment from the postfix or three dots to the prefix.
1808 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1809 /// when really needed.
1810 void shiftPathSegment(bool dotted)
1812 if (postfix_.count() <= 0)
1816 if (dottedPrefix_ && !prefix_.isEmpty())
1818 prefix_ += postfix_.front() + "/";
1820 dottedPrefix_ = dotted && !prefix_.isEmpty();
1821 postfix_.pop_front();
1824 QString displayString() const
1826 if (prefix_.isEmpty())
1829 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1830 return prefix_ + (dots ? ".../" : "") + filename_;
1833 QString forecastPathString() const
1835 if (postfix_.count() == 0)
1836 return displayString();
1839 + (dottedPrefix_ ? ".../" : "")
1840 + postfix_.front() + "/";
1843 bool final() const { return postfix_.empty(); }
1845 int tab() const { return tab_; }
1851 QStringList postfix_;
1864 bool operator<(DisplayPath const & a, DisplayPath const & b)
1866 return a.displayString() < b.displayString();
1870 bool operator==(DisplayPath const & a, DisplayPath const & b)
1872 return a.displayString() == b.displayString();
1876 void TabWorkArea::updateTabTexts()
1881 std::list<DisplayPath> paths;
1882 typedef std::list<DisplayPath>::iterator It;
1884 // collect full names first: path into postfix, empty prefix and
1885 // filename without extension
1886 for (size_t i = 0; i < n; ++i) {
1887 GuiWorkArea * i_wa = workArea(i);
1888 FileName const fn = i_wa->bufferView().buffer().fileName();
1889 paths.push_back(DisplayPath(i, fn));
1892 // go through path segments and see if it helps to make the path more unique
1893 bool somethingChanged = true;
1894 bool allFinal = false;
1895 while (somethingChanged && !allFinal) {
1896 // adding path segments changes order
1899 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1900 somethingChanged = false;
1903 // find segments which are not unique (i.e. non-atomic)
1904 It it = paths.begin();
1906 QString segString = it->displayString();
1907 for (; it != paths.end(); ++it) {
1908 // look to the next item
1913 allFinal = allFinal && it->final();
1915 LYXERR(Debug::GUI, "it = " << it->abs()
1916 << " => " << it->displayString());
1918 // still the same segment?
1920 if ((next != paths.end()
1921 && (nextString = next->displayString()) == segString))
1923 LYXERR(Debug::GUI, "segment ended");
1925 // only a trivial one with one element?
1926 if (it == segStart) {
1927 // start new segment
1929 segString = nextString;
1933 // we found a non-atomic segment segStart <= sit <= it < next.
1934 // Shift path segments and hope for the best
1935 // that it makes the path more unique.
1936 somethingChanged = true;
1938 QString dspString = sit->forecastPathString();
1939 LYXERR(Debug::GUI, "first forecast found for "
1940 << sit->abs() << " => " << dspString);
1942 bool moreUnique = false;
1943 for (; sit != next; ++sit) {
1944 if (sit->forecastPathString() != dspString) {
1945 LYXERR(Debug::GUI, "different forecast found for "
1946 << sit->abs() << " => " << sit->forecastPathString());
1950 LYXERR(Debug::GUI, "same forecast found for "
1951 << sit->abs() << " => " << dspString);
1954 // if the path segment helped, add it. Otherwise add dots
1955 bool dots = !moreUnique;
1956 LYXERR(Debug::GUI, "using dots = " << dots);
1957 for (sit = segStart; sit != next; ++sit) {
1958 sit->shiftPathSegment(dots);
1959 LYXERR(Debug::GUI, "shifting "
1960 << sit->abs() << " => " << sit->displayString());
1963 // start new segment
1965 segString = nextString;
1969 // set new tab titles
1970 for (It it = paths.begin(); it != paths.end(); ++it) {
1971 int const tab_index = it->tab();
1972 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
1973 QString tab_text = it->displayString();
1974 if (!buf.fileName().empty() && !buf.isClean())
1976 setTabText(tab_index, tab_text);
1977 setTabToolTip(tab_index, it->abs());
1982 void TabWorkArea::showContextMenu(const QPoint & pos)
1985 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1986 if (clicked_tab_ == -1)
1991 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
1992 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
1993 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
1994 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1995 popup.exec(tabBar()->mapToGlobal(pos));
2001 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2003 QWidget * w = widget(fromIndex);
2004 QIcon icon = tabIcon(fromIndex);
2005 QString text = tabText(fromIndex);
2007 setCurrentIndex(fromIndex);
2008 removeTab(fromIndex);
2009 insertTab(toIndex, w, icon, text);
2010 setCurrentIndex(toIndex);
2014 DragTabBar::DragTabBar(QWidget* parent)
2017 setAcceptDrops(true);
2018 setTabsClosable(!lyxrc.single_close_tab_button);
2022 void DragTabBar::mousePressEvent(QMouseEvent * event)
2024 if (event->button() == Qt::LeftButton)
2025 dragStartPos_ = event->pos();
2026 QTabBar::mousePressEvent(event);
2030 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2032 // If the left button isn't pressed anymore then return
2033 if (!(event->buttons() & Qt::LeftButton))
2036 // If the distance is too small then return
2037 if ((event->pos() - dragStartPos_).manhattanLength()
2038 < QApplication::startDragDistance())
2041 // did we hit something after all?
2042 int tab = tabAt(dragStartPos_);
2046 // simulate button release to remove highlight from button
2047 int i = currentIndex();
2048 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2049 event->button(), event->buttons(), 0);
2050 QTabBar::mouseReleaseEvent(&me);
2054 QDrag * drag = new QDrag(this);
2055 QMimeData * mimeData = new QMimeData;
2056 // a crude way to distinguish tab-reodering drops from other ones
2057 mimeData->setData("action", "tab-reordering") ;
2058 drag->setMimeData(mimeData);
2060 // get tab pixmap as cursor
2061 QRect r = tabRect(tab);
2062 QPixmap pixmap(r.size());
2063 render(&pixmap, - r.topLeft());
2064 drag->setPixmap(pixmap);
2069 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2071 // Only accept if it's an tab-reordering request
2072 QMimeData const * m = event->mimeData();
2073 QStringList formats = m->formats();
2074 if (formats.contains("action")
2075 && m->data("action") == "tab-reordering")
2076 event->acceptProposedAction();
2080 void DragTabBar::dropEvent(QDropEvent * event)
2082 int fromIndex = tabAt(dragStartPos_);
2083 int toIndex = tabAt(event->pos());
2085 // Tell interested objects that
2086 if (fromIndex != toIndex)
2087 tabMoveRequested(fromIndex, toIndex);
2088 event->acceptProposedAction();
2092 } // namespace frontend
2095 #include "moc_GuiWorkArea.cpp"