2 * \file GuiWorkArea.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Abdelrazak Younes
9 * Full author contact details are available in file CREDITS.
14 #include "GuiWorkArea.h"
15 #include "GuiWorkArea_Private.h"
17 #include "ColorCache.h"
18 #include "FontLoader.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "CoordCache.h"
28 #include "FuncRequest.h"
29 #include "GuiApplication.h"
30 #include "GuiCompleter.h"
31 #include "GuiKeySymbol.h"
32 #include "GuiPainter.h"
34 #include "KeySymbol.h"
39 #include "qt_helpers.h"
41 #include "TextMetrics.h"
44 #include "graphics/GraphicsImage.h"
45 #include "graphics/GraphicsLoader.h"
47 #include "support/convert.h"
48 #include "support/debug.h"
49 #include "support/gettext.h"
50 #include "support/FileName.h"
51 #include "support/lassert.h"
53 #include "frontends/Application.h"
54 #include "frontends/FontMetrics.h"
55 #include "frontends/WorkAreaManager.h"
57 #include <QContextMenuEvent>
58 #include <QInputContext>
63 #include <QMainWindow>
67 #include <QPixmapCache>
70 #include <QToolButton>
74 #include "support/bind.h"
78 int const TabIndicatorWidth = 3;
84 using namespace lyx::support;
89 /// return the LyX mouse button state from Qt's
90 static mouse_button::state q_button_state(Qt::MouseButton button)
92 mouse_button::state b = mouse_button::none;
95 b = mouse_button::button1;
98 b = mouse_button::button2;
100 case Qt::RightButton:
101 b = mouse_button::button3;
110 /// return the LyX mouse button state from Qt's
111 mouse_button::state q_motion_state(Qt::MouseButtons state)
113 mouse_button::state b = mouse_button::none;
114 if (state & Qt::LeftButton)
115 b |= mouse_button::button1;
116 if (state & Qt::MidButton)
117 b |= mouse_button::button2;
118 if (state & Qt::RightButton)
119 b |= mouse_button::button3;
132 void draw(QPainter & painter)
134 if (!show_ || !rect_.isValid())
138 int l = x_ - rect_.left();
139 int r = rect_.right() - x_;
140 int bot = rect_.bottom();
142 // draw vertical line
143 painter.fillRect(x_, y, cursor_width_, rect_.height(), color_);
145 // draw RTL/LTR indication
146 painter.setPen(color_);
149 painter.drawLine(x_, bot, x_ - l, bot);
151 painter.drawLine(x_, bot, x_ + cursor_width_ + r, bot);
154 // draw completion triangle
156 int m = y + rect_.height() / 2;
157 int d = TabIndicatorWidth - 1;
159 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
160 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
162 painter.drawLine(x_ + cursor_width_, m - d, x_ + cursor_width_ + d, m);
163 painter.drawLine(x_ + cursor_width_, m + d, x_ + cursor_width_ + d, m);
168 void update(int x, int y, int h, bool l_shape,
169 bool rtl, bool completable)
171 color_ = guiApp->colorCache().get(Color_cursor);
174 completable_ = completable;
177 // extension to left and right
181 // RTL/LTR indication
189 // completion triangle
192 l = max(l, TabIndicatorWidth);
194 r = max(r, TabIndicatorWidth);
197 // compute overall rectangle
198 rect_ = QRect(x - l, y, cursor_width_ + r + l, h);
201 void show(bool set_show = true) { show_ = set_show; }
202 void hide() { show_ = false; }
203 int cursorWidth() const { return cursor_width_; }
204 void recomputeWidth() {
205 cursor_width_ = lyxrc.cursor_width
207 : 1 + int((lyxrc.zoom + 50) / 200.0);
210 QRect const & rect() { return rect_; }
213 /// cursor is in RTL or LTR text
215 /// indication for RTL or LTR
217 /// triangle to show that a completion is available
223 /// rectangle, possibly with l_shape and completion triangle
225 /// x position (were the vertical line is drawn)
232 // This is a 'heartbeat' generating synthetic mouse move events when the
233 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
234 SyntheticMouseEvent::SyntheticMouseEvent()
235 : timeout(200), restart_timeout(true)
239 GuiWorkArea::Private::Private(GuiWorkArea * parent)
240 : p(parent), screen_(0), buffer_view_(0), lyx_view_(0), cursor_visible_(false),
241 need_resize_(false), schedule_redraw_(false), preedit_lines_(1),
242 completer_(new GuiCompleter(p, p))
247 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
248 : d(new Private(this))
253 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
254 : d(new Private(this))
262 void GuiWorkArea::init()
265 connect(&d->cursor_timeout_, SIGNAL(timeout()),
266 this, SLOT(toggleCursor()));
268 int const time = QApplication::cursorFlashTime() / 2;
270 d->cursor_timeout_.setInterval(time);
271 d->cursor_timeout_.start();
273 // let's initialize this just to be safe
274 d->cursor_timeout_.setInterval(500);
278 // With Qt4.5 a mouse event will happen before the first paint event
279 // so make sure that the buffer view has an up to date metrics.
280 d->buffer_view_->resize(viewport()->width(), viewport()->height());
281 d->cursor_ = new frontend::CursorWidget();
284 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
285 setAcceptDrops(true);
286 setMouseTracking(true);
287 setMinimumSize(100, 70);
288 setFrameStyle(QFrame::NoFrame);
291 viewport()->setAutoFillBackground(false);
292 // We don't need double-buffering nor SystemBackground on
293 // the viewport because we have our own backing pixmap.
294 viewport()->setAttribute(Qt::WA_NoSystemBackground);
296 setFocusPolicy(Qt::StrongFocus);
298 d->setCursorShape(Qt::IBeamCursor);
300 d->synthetic_mouse_event_.timeout.timeout.connect(
301 bind(&GuiWorkArea::generateSyntheticMouseEvent,
304 // Initialize the vertical Scroll Bar
305 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
306 this, SLOT(scrollTo(int)));
308 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
309 << " viewport height: " << viewport()->height());
311 // Enables input methods for asian languages.
312 // Must be set when creating custom text editing widgets.
313 setAttribute(Qt::WA_InputMethodEnabled, true);
315 d->dialog_mode_ = false;
319 GuiWorkArea::~GuiWorkArea()
321 d->buffer_view_->buffer().workAreaManager().remove(this);
323 delete d->buffer_view_;
325 // Completer has a QObject parent and is thus automatically destroyed.
327 // delete completer_;
332 Qt::CursorShape GuiWorkArea::cursorShape() const
334 return viewport()->cursor().shape();
338 void GuiWorkArea::Private::setCursorShape(Qt::CursorShape shape)
340 p->viewport()->setCursor(shape);
344 void GuiWorkArea::Private::updateCursorShape()
346 setCursorShape(buffer_view_->clickableInset()
347 ? Qt::PointingHandCursor : Qt::IBeamCursor);
351 void GuiWorkArea::setGuiView(GuiView & gv)
357 void GuiWorkArea::setBuffer(Buffer & buffer)
359 delete d->buffer_view_;
360 d->buffer_view_ = new BufferView(buffer);
361 buffer.workAreaManager().add(this);
363 // HACK: Prevents an additional redraw when the scrollbar pops up
364 // which regularily happens on documents with more than one page.
365 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
366 // Since we have no geometry information yet, we assume that
367 // a document needs a scrollbar if there is more then four
368 // paragraph in the outermost text.
369 if (buffer.text().paragraphs().size() > 4)
370 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
371 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
375 void GuiWorkArea::fixVerticalScrollBar()
378 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
382 void GuiWorkArea::close()
384 d->lyx_view_->removeWorkArea(this);
388 void GuiWorkArea::setFullScreen(bool full_screen)
390 d->buffer_view_->setFullScreen(full_screen);
391 setFrameStyle(QFrame::NoFrame);
393 setFrameStyle(QFrame::NoFrame);
394 if (lyxrc.full_screen_scrollbar)
395 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
397 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
401 BufferView & GuiWorkArea::bufferView()
403 return *d->buffer_view_;
407 BufferView const & GuiWorkArea::bufferView() const
409 return *d->buffer_view_;
413 void GuiWorkArea::stopBlinkingCursor()
415 d->cursor_timeout_.stop();
420 void GuiWorkArea::startBlinkingCursor()
422 // do not show the cursor if the view is busy
428 d->buffer_view_->cursorPosAndHeight(p, h);
429 // Don't start blinking if the cursor isn't on screen.
430 if (!d->buffer_view_->cursorInView(p, h))
435 //we're not supposed to cache this value.
436 int const time = QApplication::cursorFlashTime() / 2;
439 d->cursor_timeout_.setInterval(time);
440 d->cursor_timeout_.start();
444 void GuiWorkArea::redraw(bool update_metrics)
447 // No need to redraw in this case.
450 // No need to do anything if this is the current view. The BufferView
451 // metrics are already up to date.
452 if (update_metrics || d->lyx_view_ != guiApp->currentView()
453 || d->lyx_view_->currentWorkArea() != this) {
454 // FIXME: it would be nice to optimize for the off-screen case.
455 d->buffer_view_->cursor().fixIfBroken();
456 d->buffer_view_->updateMetrics();
457 d->buffer_view_->cursor().fixIfBroken();
460 // update cursor position, because otherwise it has to wait until
461 // the blinking interval is over
462 if (d->cursor_visible_) {
467 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
469 update(0, 0, viewport()->width(), viewport()->height());
471 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
472 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
473 d->updateScrollbar();
474 d->lyx_view_->updateStatusBar();
476 if (lyxerr.debugging(Debug::WORKAREA))
477 d->buffer_view_->coordCache().dump();
481 d->updateCursorShape();
485 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
487 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
488 && lyxrc.full_screen_menubar) {
489 // FIXME HACK: we should not have to do this here. See related comment
490 // in GuiView::event() (QEvent::ShortcutOverride)
491 d->lyx_view_->menuBar()->hide();
494 // In order to avoid bad surprise in the middle of an operation,
495 // we better stop the blinking cursor...
496 // the cursor gets restarted in GuiView::restartCursor()
497 stopBlinkingCursor();
498 guiApp->processKeySym(key, mod);
502 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd0, KeyModifier mod)
505 if (cmd0.action() == LFUN_FILE_OPEN) {
507 lyx_view_->dispatch(cmd0, dr);
513 if (cmd0.action() == LFUN_MOUSE_PRESS) {
514 if (mod == ShiftModifier)
515 cmd = FuncRequest(cmd0, "region-select");
516 else if (mod == ControlModifier)
517 cmd = FuncRequest(cmd0, "paragraph-select");
524 bool const notJustMovingTheMouse =
525 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
527 // In order to avoid bad surprise in the middle of an operation, we better stop
528 // the blinking cursor.
529 if (notJustMovingTheMouse)
530 p->stopBlinkingCursor();
532 buffer_view_->mouseEventDispatch(cmd);
534 // Skip these when selecting
535 // FIXME: let GuiView take care of those.
536 if (cmd.action() != LFUN_MOUSE_MOTION) {
537 completer_->updateVisibility(false, false);
538 lyx_view_->updateDialogs();
539 lyx_view_->updateStatusBar();
542 // GUI tweaks except with mouse motion with no button pressed.
543 if (notJustMovingTheMouse) {
544 // Slight hack: this is only called currently when we
545 // clicked somewhere, so we force through the display
546 // of the new status here.
547 // FIXME: let GuiView take care of those.
548 lyx_view_->clearMessage();
550 // Show the cursor immediately after any operation
551 p->startBlinkingCursor();
558 void GuiWorkArea::Private::resizeBufferView()
560 // WARNING: Please don't put any code that will trigger a repaint here!
561 // We are already inside a paint event.
562 p->stopBlinkingCursor();
563 // Warn our container (GuiView).
568 buffer_view_->cursorPosAndHeight(point, h);
569 bool const cursor_in_view = buffer_view_->cursorInView(point, h);
570 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
572 buffer_view_->scrollToCursor();
575 // Update scrollbars which might have changed due different
576 // BufferView dimension. This is especially important when the
577 // BufferView goes from zero-size to the real-size for the first time,
578 // as the scrollbar paramters are then set for the first time.
581 need_resize_ = false;
583 // Eventually, restart the cursor after the resize event.
584 // We might be resizing even if the focus is on another widget so we only
585 // restart the cursor if we have the focus.
587 QTimer::singleShot(50, p, SLOT(startBlinkingCursor()));
591 void GuiWorkArea::Private::showCursor()
598 buffer_view_->cursorPosAndHeight(p, h);
599 if (!buffer_view_->cursorInView(p, h))
603 bool l_shape = false;
604 Font const & realfont = buffer_view_->cursor().real_current_font;
605 BufferParams const & bp = buffer_view_->buffer().params();
606 bool const samelang = realfont.language() == bp.language;
607 bool const isrtl = realfont.isVisibleRightToLeft();
609 if (!samelang || isrtl != bp.language->rightToLeft())
612 // The ERT language hack needs fixing up
613 if (realfont.language() == latex_language)
616 // show cursor on screen
617 Cursor & cur = buffer_view_->cursor();
618 bool completable = cur.inset().showCompletionCursor()
619 && completer_->completionAvailable()
620 && !completer_->popupVisible()
621 && !completer_->inlineVisible();
622 cursor_visible_ = true;
623 cursor_->recomputeWidth();
624 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
628 void GuiWorkArea::Private::hideCursor()
630 if (!cursor_visible_)
633 cursor_visible_ = false;
638 void GuiWorkArea::toggleCursor()
640 if (d->cursor_visible_)
647 void GuiWorkArea::Private::updateScrollbar()
649 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
650 // WARNING: don't touch at the scrollbar value like this:
651 // verticalScrollBar()->setValue(scroll_.position);
652 // because this would cause a recursive signal/slot calling with
653 // GuiWorkArea::scrollTo
654 p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
655 p->verticalScrollBar()->setPageStep(scroll_.page_step);
656 p->verticalScrollBar()->setSingleStep(scroll_.single_step);
657 p->verticalScrollBar()->setSliderPosition(scroll_.position);
661 void GuiWorkArea::scrollTo(int value)
663 stopBlinkingCursor();
664 d->buffer_view_->scrollDocView(value, true);
666 if (lyxrc.cursor_follows_scrollbar) {
667 d->buffer_view_->setCursorFromScrollbar();
668 // FIXME: let GuiView take care of those.
669 d->lyx_view_->updateLayoutList();
671 // Show the cursor immediately after any operation.
672 startBlinkingCursor();
673 QApplication::syncX();
677 bool GuiWorkArea::event(QEvent * e)
680 case QEvent::ToolTip: {
681 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
682 if (lyxrc.use_tooltip) {
683 QPoint pos = helpEvent->pos();
684 if (pos.x() < viewport()->width()) {
685 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
686 QToolTip::showText(helpEvent->globalPos(), s);
689 QToolTip::hideText();
691 // Don't forget to accept the event!
696 case QEvent::ShortcutOverride: {
697 // We catch this event in order to catch the Tab or Shift+Tab key press
698 // which are otherwise reserved to focus switching between controls
700 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
701 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
702 || (ke->key() == Qt::Key_Backtab && (
703 ke->modifiers() == Qt::ShiftModifier
704 || ke->modifiers() == Qt::NoModifier))) {
708 return QAbstractScrollArea::event(e);
712 return QAbstractScrollArea::event(e);
718 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
721 if (e->reason() == QContextMenuEvent::Mouse)
722 // the menu name is set on mouse press
723 name = d->context_menu_name_;
725 QPoint pos = e->pos();
726 Cursor const & cur = d->buffer_view_->cursor();
727 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
728 // Do not access the context menu of math right in front of before
729 // the cursor. This does not work when the cursor is in text.
730 Inset * inset = cur.paragraph().getInset(cur.pos());
731 if (inset && inset->asInsetMath())
733 else if (cur.pos() > 0) {
734 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
739 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
743 QAbstractScrollArea::contextMenuEvent(e);
746 // always show mnemonics when the keyboard is used to show the context menu
747 // FIXME: This should be fixed in Qt itself
748 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
749 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
751 QAbstractScrollArea::contextMenuEvent(e);
754 // Position the menu to the right.
755 // FIXME: menu position should be different for RTL text.
756 menu->exec(e->globalPos());
761 void GuiWorkArea::focusInEvent(QFocusEvent * e)
763 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
764 if (d->lyx_view_->currentWorkArea() != this)
765 d->lyx_view_->setCurrentWorkArea(this);
767 startBlinkingCursor();
768 QAbstractScrollArea::focusInEvent(e);
772 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
774 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
775 stopBlinkingCursor();
776 QAbstractScrollArea::focusOutEvent(e);
780 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
782 if (d->dc_event_.active && d->dc_event_ == *e) {
783 d->dc_event_.active = false;
784 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
785 q_button_state(e->button()));
791 inputContext()->reset();
793 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
794 q_button_state(e->button()));
795 d->dispatch(cmd, q_key_state(e->modifiers()));
797 // Save the context menu on mouse press, because also the mouse
798 // cursor is set on mouse press. Afterwards, we can either release
799 // the mousebutton somewhere else, or the cursor might have moved
800 // due to the DEPM. We need to do this after the mouse has been
801 // set in dispatch(), because the selection state might change.
802 if (e->button() == Qt::RightButton)
803 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
809 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
811 if (d->synthetic_mouse_event_.timeout.running())
812 d->synthetic_mouse_event_.timeout.stop();
814 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
815 q_button_state(e->button()));
821 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
823 // we kill the triple click if we move
824 doubleClickTimeout();
825 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
826 q_motion_state(e->buttons()));
830 // If we're above or below the work area...
831 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
832 && e->buttons() == mouse_button::button1) {
833 // Make sure only a synthetic event can cause a page scroll,
834 // so they come at a steady rate:
836 // _Force_ a scroll up:
837 cmd.set_y(e->y() - 21);
839 cmd.set_y(e->y() + 21);
840 // Store the event, to be handled when the timeout expires.
841 d->synthetic_mouse_event_.cmd = cmd;
843 if (d->synthetic_mouse_event_.timeout.running()) {
844 // Discard the event. Note that it _may_ be handled
845 // when the timeout expires if
846 // synthetic_mouse_event_.cmd has not been overwritten.
847 // Ie, when the timeout expires, we handle the
848 // most recent event but discard all others that
849 // occurred after the one used to start the timeout
850 // in the first place.
854 d->synthetic_mouse_event_.restart_timeout = true;
855 d->synthetic_mouse_event_.timeout.start();
856 // Fall through to handle this event...
858 } else if (d->synthetic_mouse_event_.timeout.running()) {
859 // Store the event, to be possibly handled when the timeout
861 // Once the timeout has expired, normal control is returned
862 // to mouseMoveEvent (restart_timeout = false).
863 // This results in a much smoother 'feel' when moving the
864 // mouse back into the work area.
865 d->synthetic_mouse_event_.cmd = cmd;
866 d->synthetic_mouse_event_.restart_timeout = false;
873 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
875 // Wheel rotation by one notch results in a delta() of 120 (see
876 // documentation of QWheelEvent)
877 double const delta = ev->delta() / 120.0;
879 switch (lyxrc.scroll_wheel_zoom) {
880 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
881 zoom = ev->modifiers() & Qt::ControlModifier;
882 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
884 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
885 zoom = ev->modifiers() & Qt::ShiftModifier;
886 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
888 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
889 zoom = ev->modifiers() & Qt::AltModifier;
890 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
892 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
896 docstring arg = convert<docstring>(int(5 * delta));
897 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
901 // Take into account the desktop wide settings.
902 int const lines = qApp->wheelScrollLines();
903 int const page_step = verticalScrollBar()->pageStep();
904 // Test if the wheel mouse is set to one screen at a time.
905 int scroll_value = lines > page_step
906 ? page_step : lines * verticalScrollBar()->singleStep();
908 // Take into account the rotation and the user preferences.
909 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
910 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
911 << " delta = " << delta << " scroll_value = " << scroll_value
912 << " page_step = " << page_step);
914 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
920 void GuiWorkArea::generateSyntheticMouseEvent()
922 int const e_y = d->synthetic_mouse_event_.cmd.y();
923 int const wh = d->buffer_view_->workHeight();
924 bool const up = e_y < 0;
925 bool const down = e_y > wh;
927 // Set things off to generate the _next_ 'pseudo' event.
929 if (d->synthetic_mouse_event_.restart_timeout) {
930 // This is some magic formulae to determine the speed
931 // of scrolling related to the position of the mouse.
934 int dist = up ? -e_y : e_y - wh;
935 time = max(min(200, 250000 / (dist * dist)), 1) ;
938 step = 80000 / (time * time);
942 d->synthetic_mouse_event_.timeout.setTimeout(time);
943 d->synthetic_mouse_event_.timeout.start();
946 // Can we scroll further ?
947 int const value = verticalScrollBar()->value();
948 if (value == verticalScrollBar()->maximum()
949 || value == verticalScrollBar()->minimum()) {
950 d->synthetic_mouse_event_.timeout.stop();
955 if (step <= 2 * wh) {
956 d->buffer_view_->scroll(up ? -step : step);
957 d->buffer_view_->updateMetrics();
959 d->buffer_view_->scrollDocView(value + up ? -step : step, false);
962 // In which paragraph do we have to set the cursor ?
963 Cursor & cur = d->buffer_view_->cursor();
964 // FIXME: we don't know howto handle math.
965 Text * text = cur.text();
968 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
970 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
971 ParagraphMetrics const & pm = *pp.second;
972 pit_type const pit = pp.first;
974 if (pm.rows().empty())
977 // Find the row at which we set the cursor.
978 RowList::const_iterator rit = pm.rows().begin();
979 RowList::const_iterator rlast = pm.rows().end();
980 int yy = pm.position() - pm.ascent();
981 for (--rlast; rit != rlast; ++rit) {
982 int h = rit->height();
983 if ((up && yy + h > 0)
984 || (!up && yy + h > wh - defaultRowHeight()))
989 // Find the position of the cursor
991 int x = d->synthetic_mouse_event_.cmd.x();
992 pos_type const pos = rit->pos() + tm.getColumnNearX(pit, *rit, x, bound);
999 d->buffer_view_->buffer().changed(false);
1004 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1006 // Do not process here some keys if dialog_mode_ is set
1008 && (ev->modifiers() == Qt::NoModifier
1009 || ev->modifiers() == Qt::ShiftModifier)
1010 && (ev->key() == Qt::Key_Escape
1011 || ev->key() == Qt::Key_Enter
1012 || ev->key() == Qt::Key_Return)
1018 // intercept some keys if completion popup is visible
1019 if (d->completer_->popupVisible()) {
1020 switch (ev->key()) {
1022 case Qt::Key_Return:
1023 d->completer_->activate();
1029 // do nothing if there are other events
1030 // (the auto repeated events come too fast)
1031 // it looks like this is only needed on X11
1033 if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1034 switch (ev->key()) {
1035 case Qt::Key_PageDown:
1036 case Qt::Key_PageUp:
1041 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1048 KeyModifier m = q_key_state(ev->modifiers());
1051 if (m & ShiftModifier)
1053 if (m & ControlModifier)
1055 if (m & AltModifier)
1057 if (m & MetaModifier)
1060 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1061 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1062 << " keyState: " << str);
1065 setKeySymbol(&sym, ev);
1067 processKeySym(sym, q_key_state(ev->modifiers()));
1075 void GuiWorkArea::doubleClickTimeout()
1077 d->dc_event_.active = false;
1081 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1083 d->dc_event_ = DoubleClick(ev);
1084 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1085 SLOT(doubleClickTimeout()));
1086 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1088 q_button_state(ev->button()));
1094 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1096 QAbstractScrollArea::resizeEvent(ev);
1097 d->need_resize_ = true;
1102 void GuiWorkArea::Private::update(int x, int y, int w, int h)
1104 p->viewport()->update(x, y, w, h);
1108 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1110 QRect const rc = ev->rect();
1111 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1112 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1114 if (d->need_resize_) {
1116 d->resizeBufferView();
1117 if (d->cursor_visible_) {
1123 QPainter pain(viewport());
1124 if (lyxrc.use_qimage) {
1125 pain.drawImage(rc, static_cast<QImage const &>(*d->screen_), rc);
1127 pain.drawPixmap(rc, static_cast<QPixmap const &>(*d->screen_), rc);
1129 d->cursor_->draw(pain);
1134 void GuiWorkArea::Private::updateScreen()
1136 GuiPainter pain(screen_);
1137 buffer_view_->draw(pain);
1141 void GuiWorkArea::Private::showCursor(int x, int y, int h,
1142 bool l_shape, bool rtl, bool completable)
1144 if (schedule_redraw_) {
1145 // This happens when a graphic conversion is finished. As we don't know
1146 // the size of the new graphics, it's better the update everything.
1147 // We can't use redraw() here because this would trigger a infinite
1148 // recursive loop with showCursor().
1149 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
1152 p->viewport()->update(QRect(0, 0, p->viewport()->width(), p->viewport()->height()));
1153 schedule_redraw_ = false;
1154 // Show the cursor immediately after the update.
1160 cursor_->update(x, y, h, l_shape, rtl, completable);
1162 p->viewport()->update(cursor_->rect());
1166 void GuiWorkArea::Private::removeCursor()
1169 //if (!qApp->focusWidget())
1170 p->viewport()->update(cursor_->rect());
1174 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1176 QString const & commit_string = e->commitString();
1177 docstring const & preedit_string
1178 = qstring_to_ucs4(e->preeditString());
1180 if (!commit_string.isEmpty()) {
1182 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1183 << " commitString: " << e->commitString());
1187 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1188 for (int i = 0; i != commit_string.size(); ++i) {
1189 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1194 // Hide the cursor during the kana-kanji transformation.
1195 if (preedit_string.empty())
1196 startBlinkingCursor();
1198 stopBlinkingCursor();
1200 // last_width : for checking if last preedit string was/wasn't empty.
1201 static bool last_width = false;
1202 if (!last_width && preedit_string.empty()) {
1203 // if last_width is last length of preedit string.
1208 GuiPainter pain(d->screen_);
1209 d->buffer_view_->updateMetrics();
1210 d->buffer_view_->draw(pain);
1211 FontInfo font = d->buffer_view_->cursor().getFont().fontInfo();
1212 FontMetrics const & fm = theFontMetrics(font);
1213 int height = fm.maxHeight();
1214 int cur_x = d->cursor_->rect().left();
1215 int cur_y = d->cursor_->rect().bottom();
1217 // redraw area of preedit string.
1218 update(0, cur_y - height, viewport()->width(),
1219 (height + 1) * d->preedit_lines_);
1221 if (preedit_string.empty()) {
1223 d->preedit_lines_ = 1;
1229 // att : stores an IM attribute.
1230 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1232 // get attributes of input method cursor.
1233 // cursor_pos : cursor position in preedit string.
1234 size_t cursor_pos = 0;
1235 bool cursor_is_visible = false;
1236 for (int i = 0; i != att.size(); ++i) {
1237 if (att.at(i).type == QInputMethodEvent::Cursor) {
1238 cursor_pos = att.at(i).start;
1239 cursor_is_visible = att.at(i).length != 0;
1244 size_t preedit_length = preedit_string.length();
1246 // get position of selection in input method.
1247 // FIXME: isn't there a way to do this simplier?
1248 // rStart : cursor position in selected string in IM.
1250 // rLength : selected string length in IM.
1252 if (cursor_pos < preedit_length) {
1253 for (int i = 0; i != att.size(); ++i) {
1254 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1255 if (att.at(i).start <= int(cursor_pos)
1256 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1257 rStart = att.at(i).start;
1258 rLength = att.at(i).length;
1259 if (!cursor_is_visible)
1260 cursor_pos += rLength;
1267 rStart = cursor_pos;
1271 int const right_margin = d->buffer_view_->rightMargin();
1272 Painter::preedit_style ps;
1273 // Most often there would be only one line:
1274 d->preedit_lines_ = 1;
1275 for (size_t pos = 0; pos != preedit_length; ++pos) {
1276 char_type const typed_char = preedit_string[pos];
1277 // reset preedit string style
1278 ps = Painter::preedit_default;
1280 // if we reached the right extremity of the screen, go to next line.
1281 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1282 cur_x = right_margin;
1283 cur_y += height + 1;
1284 ++d->preedit_lines_;
1286 // preedit strings are displayed with dashed underline
1287 // and partial strings are displayed white on black indicating
1288 // that we are in selecting mode in the input method.
1289 // FIXME: rLength == preedit_length is not a changing condition
1290 // FIXME: should be put out of the loop.
1292 && pos < rStart + rLength
1293 && !(cursor_pos < rLength && rLength == preedit_length))
1294 ps = Painter::preedit_selecting;
1296 if (pos == cursor_pos
1297 && (cursor_pos < rLength && rLength == preedit_length))
1298 ps = Painter::preedit_cursor;
1300 // draw one character and update cur_x.
1301 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1304 // update the preedit string screen area.
1305 update(0, cur_y - d->preedit_lines_*height, viewport()->width(),
1306 (height + 1) * d->preedit_lines_);
1308 // Don't forget to accept the event!
1313 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1315 QRect cur_r(0, 0, 0, 0);
1317 // this is the CJK-specific composition window position and
1318 // the context menu position when the menu key is pressed.
1319 case Qt::ImMicroFocus:
1320 cur_r = d->cursor_->rect();
1321 if (d->preedit_lines_ != 1)
1323 cur_r.moveBottom(cur_r.bottom()
1324 + cur_r.height() * (d->preedit_lines_ - 1));
1325 // return lower right of cursor in LyX.
1328 return QWidget::inputMethodQuery(query);
1333 void GuiWorkArea::updateWindowTitle()
1335 docstring maximize_title;
1336 docstring minimize_title;
1338 Buffer const & buf = d->buffer_view_->buffer();
1339 FileName const file_name = buf.fileName();
1340 if (!file_name.empty()) {
1341 maximize_title = file_name.displayName(130);
1342 minimize_title = from_utf8(file_name.onlyFileName());
1343 if (buf.lyxvc().inUse()) {
1344 if (buf.lyxvc().locking())
1345 maximize_title += _(" (version control, locking)");
1347 maximize_title += _(" (version control)");
1349 if (!buf.isClean()) {
1350 maximize_title += _(" (changed)");
1351 minimize_title += char_type('*');
1353 if (buf.isReadonly())
1354 maximize_title += _(" (read only)");
1357 QString const new_title = toqstr(maximize_title);
1358 if (new_title != windowTitle()) {
1359 QWidget::setWindowTitle(new_title);
1360 QWidget::setWindowIconText(toqstr(minimize_title));
1366 bool GuiWorkArea::isFullScreen() const
1368 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1372 void GuiWorkArea::scheduleRedraw()
1374 d->schedule_redraw_ = true;
1378 bool GuiWorkArea::inDialogMode() const
1380 return d->dialog_mode_;
1384 void GuiWorkArea::setDialogMode(bool mode)
1386 d->dialog_mode_ = mode;
1390 GuiCompleter & GuiWorkArea::completer()
1392 return *d->completer_;
1395 GuiView const & GuiWorkArea::view() const
1397 return *d->lyx_view_;
1401 GuiView & GuiWorkArea::view()
1403 return *d->lyx_view_;
1406 ////////////////////////////////////////////////////////////////////
1410 ////////////////////////////////////////////////////////////////////
1413 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1415 buffer_ = theBufferList().newBuffer(
1416 support::FileName::tempName().absFileName() + "_embedded.internal");
1417 buffer_->setUnnamed(true);
1418 buffer_->setFullyLoaded(true);
1419 setBuffer(*buffer_);
1420 setDialogMode(true);
1424 EmbeddedWorkArea::~EmbeddedWorkArea()
1426 // No need to destroy buffer and bufferview here, because it is done
1427 // in theBufferList() destruction loop at application exit
1431 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1434 GuiWorkArea::closeEvent(ev);
1438 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1441 GuiWorkArea::hideEvent(ev);
1445 QSize EmbeddedWorkArea::sizeHint () const
1448 // GuiWorkArea sets the size to the screen's viewport
1449 // by returning a value this gets overridden
1450 // EmbeddedWorkArea is now sized to fit in the layout
1451 // of the parent, and has a minimum size set in GuiWorkArea
1452 // which is what we return here
1453 return QSize(100, 70);
1457 void EmbeddedWorkArea::disable()
1459 stopBlinkingCursor();
1460 if (view().currentWorkArea() != this)
1462 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1463 // tolerates it and shows the background logo), what happens if
1464 // an EmbeddedWorkArea is closed after closing all document WAs
1465 view().setCurrentWorkArea(view().currentMainWorkArea());
1468 ////////////////////////////////////////////////////////////////////
1472 ////////////////////////////////////////////////////////////////////
1475 class NoTabFrameMacStyle : public QMacStyle {
1478 QRect subElementRect(SubElement element, const QStyleOption * option,
1479 const QWidget * widget = 0) const
1481 QRect rect = QMacStyle::subElementRect(element, option, widget);
1482 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1484 // The Qt Mac style puts the contents into a 3 pixel wide box
1485 // which looks very ugly and not like other Mac applications.
1486 // Hence we remove this here, and moreover the 16 pixel round
1487 // frame above if the tab bar is hidden.
1488 if (element == QStyle::SE_TabWidgetTabContents) {
1489 rect.adjust(- rect.left(), 0, rect.left(), 0);
1498 NoTabFrameMacStyle noTabFrameMacStyle;
1502 TabWorkArea::TabWorkArea(QWidget * parent)
1503 : QTabWidget(parent), clicked_tab_(-1)
1506 setStyle(&noTabFrameMacStyle);
1508 #if QT_VERSION < 0x040500
1509 lyxrc.single_close_tab_button = true;
1512 QPalette pal = palette();
1513 pal.setColor(QPalette::Active, QPalette::Button,
1514 pal.color(QPalette::Active, QPalette::Window));
1515 pal.setColor(QPalette::Disabled, QPalette::Button,
1516 pal.color(QPalette::Disabled, QPalette::Window));
1517 pal.setColor(QPalette::Inactive, QPalette::Button,
1518 pal.color(QPalette::Inactive, QPalette::Window));
1520 QObject::connect(this, SIGNAL(currentChanged(int)),
1521 this, SLOT(on_currentTabChanged(int)));
1523 closeBufferButton = new QToolButton(this);
1524 closeBufferButton->setPalette(pal);
1525 // FIXME: rename the icon to closebuffer.png
1526 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1527 closeBufferButton->setText("Close File");
1528 closeBufferButton->setAutoRaise(true);
1529 closeBufferButton->setCursor(Qt::ArrowCursor);
1530 closeBufferButton->setToolTip(qt_("Close File"));
1531 closeBufferButton->setEnabled(true);
1532 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1533 this, SLOT(closeCurrentBuffer()));
1534 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1536 // setup drag'n'drop
1537 QTabBar* tb = new DragTabBar;
1538 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1539 this, SLOT(moveTab(int, int)));
1540 tb->setElideMode(Qt::ElideNone);
1543 // make us responsible for the context menu of the tabbar
1544 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1545 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1546 this, SLOT(showContextMenu(const QPoint &)));
1547 #if QT_VERSION >= 0x040500
1548 connect(tb, SIGNAL(tabCloseRequested(int)),
1549 this, SLOT(closeTab(int)));
1552 setUsesScrollButtons(true);
1556 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1558 if (event->button() != Qt::LeftButton)
1561 // return early if double click on existing tabs
1562 for (int i = 0; i < count(); ++i)
1563 if (tabBar()->tabRect(i).contains(event->pos()))
1566 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1570 void TabWorkArea::setFullScreen(bool full_screen)
1572 for (int i = 0; i != count(); ++i) {
1573 if (GuiWorkArea * wa = workArea(i))
1574 wa->setFullScreen(full_screen);
1577 if (lyxrc.full_screen_tabbar)
1578 showBar(!full_screen && count() > 1);
1580 showBar(count() > 1);
1584 void TabWorkArea::showBar(bool show)
1586 tabBar()->setEnabled(show);
1587 tabBar()->setVisible(show);
1588 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1589 #if QT_VERSION >= 0x040500
1590 setTabsClosable(!lyxrc.single_close_tab_button);
1595 GuiWorkArea * TabWorkArea::currentWorkArea()
1600 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1606 GuiWorkArea * TabWorkArea::workArea(int index)
1608 return dynamic_cast<GuiWorkArea *>(widget(index));
1612 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1614 // FIXME: this method doesn't work if we have more than work area
1615 // showing the same buffer.
1616 for (int i = 0; i != count(); ++i) {
1617 GuiWorkArea * wa = workArea(i);
1618 LASSERT(wa, return 0);
1619 if (&wa->bufferView().buffer() == &buffer)
1626 void TabWorkArea::closeAll()
1629 GuiWorkArea * wa = workArea(0);
1637 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1639 LASSERT(work_area, /**/);
1640 int index = indexOf(work_area);
1644 if (index == currentIndex())
1645 // Make sure the work area is up to date.
1646 on_currentTabChanged(index);
1648 // Switch to the work area.
1649 setCurrentIndex(index);
1650 work_area->setFocus();
1656 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1658 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1659 wa->setUpdatesEnabled(false);
1660 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1661 // when hiding it again below).
1662 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1663 showBar(count() > 0);
1664 addTab(wa, wa->windowTitle());
1665 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1666 this, SLOT(updateTabTexts()));
1667 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1668 setFullScreen(true);
1670 // Hide tabbar if there's only one tab.
1671 showBar(count() > 1);
1679 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1681 LASSERT(work_area, return false);
1682 int index = indexOf(work_area);
1686 work_area->setUpdatesEnabled(false);
1691 // make sure the next work area is enabled.
1692 currentWidget()->setUpdatesEnabled(true);
1693 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1694 setFullScreen(true);
1696 // Show tabbar only if there's more than one tab.
1697 showBar(count() > 1);
1699 lastWorkAreaRemoved();
1707 void TabWorkArea::on_currentTabChanged(int i)
1709 // returns e.g. on application destruction
1712 GuiWorkArea * wa = workArea(i);
1713 LASSERT(wa, return);
1714 wa->setUpdatesEnabled(true);
1718 currentWorkAreaChanged(wa);
1720 LYXERR(Debug::GUI, "currentTabChanged " << i
1721 << " File: " << wa->bufferView().buffer().absFileName());
1725 void TabWorkArea::closeCurrentBuffer()
1728 if (clicked_tab_ == -1)
1729 wa = currentWorkArea();
1731 wa = workArea(clicked_tab_);
1734 wa->view().closeWorkArea(wa);
1738 void TabWorkArea::hideCurrentTab()
1741 if (clicked_tab_ == -1)
1742 wa = currentWorkArea();
1744 wa = workArea(clicked_tab_);
1747 wa->view().hideWorkArea(wa);
1751 void TabWorkArea::closeTab(int index)
1753 on_currentTabChanged(index);
1756 wa = currentWorkArea();
1758 wa = workArea(index);
1761 wa->view().closeWorkArea(wa);
1768 /// make vector happy
1771 DisplayPath(int tab, FileName const & filename)
1774 filename_ = (filename.extension() == "lyx") ?
1775 toqstr(filename.onlyFileNameWithoutExt())
1776 : toqstr(filename.onlyFileName());
1777 postfix_ = toqstr(filename.absoluteFilePath()).
1778 split("/", QString::SkipEmptyParts);
1779 postfix_.pop_back();
1780 abs_ = toqstr(filename.absoluteFilePath());
1781 dottedPrefix_ = false;
1784 /// Absolute path for debugging.
1789 /// Add the first segment from the postfix or three dots to the prefix.
1790 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1791 /// when really needed.
1792 void shiftPathSegment(bool dotted)
1794 if (postfix_.count() <= 0)
1798 if (dottedPrefix_ && !prefix_.isEmpty())
1800 prefix_ += postfix_.front() + "/";
1802 dottedPrefix_ = dotted && !prefix_.isEmpty();
1803 postfix_.pop_front();
1806 QString displayString() const
1808 if (prefix_.isEmpty())
1811 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1812 return prefix_ + (dots ? ".../" : "") + filename_;
1815 QString forecastPathString() const
1817 if (postfix_.count() == 0)
1818 return displayString();
1821 + (dottedPrefix_ ? ".../" : "")
1822 + postfix_.front() + "/";
1825 bool final() const { return postfix_.empty(); }
1827 int tab() const { return tab_; }
1833 QStringList postfix_;
1846 bool operator<(DisplayPath const & a, DisplayPath const & b)
1848 return a.displayString() < b.displayString();
1852 bool operator==(DisplayPath const & a, DisplayPath const & b)
1854 return a.displayString() == b.displayString();
1858 void TabWorkArea::updateTabTexts()
1863 std::list<DisplayPath> paths;
1864 typedef std::list<DisplayPath>::iterator It;
1866 // collect full names first: path into postfix, empty prefix and
1867 // filename without extension
1868 for (size_t i = 0; i < n; ++i) {
1869 GuiWorkArea * i_wa = workArea(i);
1870 FileName const fn = i_wa->bufferView().buffer().fileName();
1871 paths.push_back(DisplayPath(i, fn));
1874 // go through path segments and see if it helps to make the path more unique
1875 bool somethingChanged = true;
1876 bool allFinal = false;
1877 while (somethingChanged && !allFinal) {
1878 // adding path segments changes order
1881 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1882 somethingChanged = false;
1885 // find segments which are not unique (i.e. non-atomic)
1886 It it = paths.begin();
1888 QString segString = it->displayString();
1889 for (; it != paths.end(); ++it) {
1890 // look to the next item
1895 allFinal = allFinal && it->final();
1897 LYXERR(Debug::GUI, "it = " << it->abs()
1898 << " => " << it->displayString());
1900 // still the same segment?
1902 if ((next != paths.end()
1903 && (nextString = next->displayString()) == segString))
1905 LYXERR(Debug::GUI, "segment ended");
1907 // only a trivial one with one element?
1908 if (it == segStart) {
1909 // start new segment
1911 segString = nextString;
1915 // we found a non-atomic segment segStart <= sit <= it < next.
1916 // Shift path segments and hope for the best
1917 // that it makes the path more unique.
1918 somethingChanged = true;
1920 QString dspString = sit->forecastPathString();
1921 LYXERR(Debug::GUI, "first forecast found for "
1922 << sit->abs() << " => " << dspString);
1924 bool moreUnique = false;
1925 for (; sit != next; ++sit) {
1926 if (sit->forecastPathString() != dspString) {
1927 LYXERR(Debug::GUI, "different forecast found for "
1928 << sit->abs() << " => " << sit->forecastPathString());
1932 LYXERR(Debug::GUI, "same forecast found for "
1933 << sit->abs() << " => " << dspString);
1936 // if the path segment helped, add it. Otherwise add dots
1937 bool dots = !moreUnique;
1938 LYXERR(Debug::GUI, "using dots = " << dots);
1939 for (sit = segStart; sit != next; ++sit) {
1940 sit->shiftPathSegment(dots);
1941 LYXERR(Debug::GUI, "shifting "
1942 << sit->abs() << " => " << sit->displayString());
1945 // start new segment
1947 segString = nextString;
1951 // set new tab titles
1952 for (It it = paths.begin(); it != paths.end(); ++it) {
1953 int const tab_index = it->tab();
1954 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
1955 QString tab_text = it->displayString();
1956 if (!buf.fileName().empty() && !buf.isClean())
1958 setTabText(tab_index, tab_text);
1959 setTabToolTip(tab_index, it->abs());
1964 void TabWorkArea::showContextMenu(const QPoint & pos)
1967 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1968 if (clicked_tab_ == -1)
1973 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
1974 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
1975 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
1976 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1977 popup.exec(tabBar()->mapToGlobal(pos));
1983 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1985 QWidget * w = widget(fromIndex);
1986 QIcon icon = tabIcon(fromIndex);
1987 QString text = tabText(fromIndex);
1989 setCurrentIndex(fromIndex);
1990 removeTab(fromIndex);
1991 insertTab(toIndex, w, icon, text);
1992 setCurrentIndex(toIndex);
1996 DragTabBar::DragTabBar(QWidget* parent)
1999 setAcceptDrops(true);
2000 #if QT_VERSION >= 0x040500
2001 setTabsClosable(!lyxrc.single_close_tab_button);
2006 #if QT_VERSION < 0x040300
2007 int DragTabBar::tabAt(QPoint const & position) const
2009 const int max = count();
2010 for (int i = 0; i < max; ++i) {
2011 if (tabRect(i).contains(position))
2019 void DragTabBar::mousePressEvent(QMouseEvent * event)
2021 if (event->button() == Qt::LeftButton)
2022 dragStartPos_ = event->pos();
2023 QTabBar::mousePressEvent(event);
2027 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2029 // If the left button isn't pressed anymore then return
2030 if (!(event->buttons() & Qt::LeftButton))
2033 // If the distance is too small then return
2034 if ((event->pos() - dragStartPos_).manhattanLength()
2035 < QApplication::startDragDistance())
2038 // did we hit something after all?
2039 int tab = tabAt(dragStartPos_);
2043 // simulate button release to remove highlight from button
2044 int i = currentIndex();
2045 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2046 event->button(), event->buttons(), 0);
2047 QTabBar::mouseReleaseEvent(&me);
2051 QDrag * drag = new QDrag(this);
2052 QMimeData * mimeData = new QMimeData;
2053 // a crude way to distinguish tab-reodering drops from other ones
2054 mimeData->setData("action", "tab-reordering") ;
2055 drag->setMimeData(mimeData);
2057 #if QT_VERSION >= 0x040300
2058 // get tab pixmap as cursor
2059 QRect r = tabRect(tab);
2060 QPixmap pixmap(r.size());
2061 render(&pixmap, - r.topLeft());
2062 drag->setPixmap(pixmap);
2065 drag->start(Qt::MoveAction);
2071 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2073 // Only accept if it's an tab-reordering request
2074 QMimeData const * m = event->mimeData();
2075 QStringList formats = m->formats();
2076 if (formats.contains("action")
2077 && m->data("action") == "tab-reordering")
2078 event->acceptProposedAction();
2082 void DragTabBar::dropEvent(QDropEvent * event)
2084 int fromIndex = tabAt(dragStartPos_);
2085 int toIndex = tabAt(event->pos());
2087 // Tell interested objects that
2088 if (fromIndex != toIndex)
2089 tabMoveRequested(fromIndex, toIndex);
2090 event->acceptProposedAction();
2094 } // namespace frontend
2097 #include "moc_GuiWorkArea.cpp"