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 #if (QT_VERSION < 0x050000)
59 #include <QInputContext>
66 #include <QMainWindow>
71 #include <QPixmapCache>
73 #include <QStyleOption>
74 #include <QStylePainter>
76 #include <QToolButton>
80 #include "support/bind.h"
84 int const TabIndicatorWidth = 3;
90 using namespace lyx::support;
95 /// return the LyX mouse button state from Qt's
96 static mouse_button::state q_button_state(Qt::MouseButton button)
98 mouse_button::state b = mouse_button::none;
101 b = mouse_button::button1;
104 b = mouse_button::button2;
106 case Qt::RightButton:
107 b = mouse_button::button3;
116 /// return the LyX mouse button state from Qt's
117 mouse_button::state q_motion_state(Qt::MouseButtons state)
119 mouse_button::state b = mouse_button::none;
120 if (state & Qt::LeftButton)
121 b |= mouse_button::button1;
122 if (state & Qt::MidButton)
123 b |= mouse_button::button2;
124 if (state & Qt::RightButton)
125 b |= mouse_button::button3;
138 void draw(QPainter & painter)
140 if (!show_ || !rect_.isValid())
144 int l = x_ - rect_.left();
145 int r = rect_.right() - x_;
146 int bot = rect_.bottom();
148 // draw vertical line
149 painter.fillRect(x_, y, cursor_width_, rect_.height(), color_);
151 // draw RTL/LTR indication
152 painter.setPen(color_);
155 painter.drawLine(x_, bot, x_ - l, bot);
157 painter.drawLine(x_, bot, x_ + cursor_width_ + r, bot);
160 // draw completion triangle
162 int m = y + rect_.height() / 2;
163 int d = TabIndicatorWidth - 1;
165 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
166 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
168 painter.drawLine(x_ + cursor_width_, m - d, x_ + cursor_width_ + d, m);
169 painter.drawLine(x_ + cursor_width_, m + d, x_ + cursor_width_ + d, m);
174 void update(int x, int y, int h, bool l_shape,
175 bool rtl, bool completable)
177 color_ = guiApp->colorCache().get(Color_cursor);
180 completable_ = completable;
183 // extension to left and right
187 // RTL/LTR indication
195 // completion triangle
198 l = max(l, TabIndicatorWidth);
200 r = max(r, TabIndicatorWidth);
203 // compute overall rectangle
204 rect_ = QRect(x - l, y, cursor_width_ + r + l, h);
207 void show(bool set_show = true) { show_ = set_show; }
208 void hide() { show_ = false; }
209 int cursorWidth() const { return cursor_width_; }
210 void recomputeWidth() {
211 cursor_width_ = lyxrc.cursor_width
213 : 1 + int((lyxrc.zoom + 50) / 200.0);
216 QRect const & rect() { return rect_; }
219 /// cursor is in RTL or LTR text
221 /// indication for RTL or LTR
223 /// triangle to show that a completion is available
229 /// rectangle, possibly with l_shape and completion triangle
231 /// x position (were the vertical line is drawn)
238 // This is a 'heartbeat' generating synthetic mouse move events when the
239 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
240 SyntheticMouseEvent::SyntheticMouseEvent()
241 : timeout(200), restart_timeout(true)
245 GuiWorkArea::Private::Private(GuiWorkArea * parent)
246 : p(parent), screen_(0), buffer_view_(0), lyx_view_(0), cursor_visible_(false),
247 need_resize_(false), schedule_redraw_(false), preedit_lines_(1),
248 completer_(new GuiCompleter(p, p))
253 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
254 : d(new Private(this))
259 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
260 : d(new Private(this))
268 void GuiWorkArea::init()
271 connect(&d->cursor_timeout_, SIGNAL(timeout()),
272 this, SLOT(toggleCursor()));
274 int const time = QApplication::cursorFlashTime() / 2;
276 d->cursor_timeout_.setInterval(time);
277 d->cursor_timeout_.start();
279 // let's initialize this just to be safe
280 d->cursor_timeout_.setInterval(500);
284 // With Qt4.5 a mouse event will happen before the first paint event
285 // so make sure that the buffer view has an up to date metrics.
286 d->buffer_view_->resize(viewport()->width(), viewport()->height());
287 d->cursor_ = new frontend::CursorWidget();
290 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
291 setAcceptDrops(true);
292 setMouseTracking(true);
293 setMinimumSize(100, 70);
294 setFrameStyle(QFrame::NoFrame);
297 viewport()->setAutoFillBackground(false);
298 // We don't need double-buffering nor SystemBackground on
299 // the viewport because we have our own backing pixmap.
300 viewport()->setAttribute(Qt::WA_NoSystemBackground);
302 setFocusPolicy(Qt::StrongFocus);
304 d->setCursorShape(Qt::IBeamCursor);
306 d->synthetic_mouse_event_.timeout.timeout.connect(
307 bind(&GuiWorkArea::generateSyntheticMouseEvent,
310 // Initialize the vertical Scroll Bar
311 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
312 this, SLOT(scrollTo(int)));
314 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
315 << " viewport height: " << viewport()->height());
317 // Enables input methods for asian languages.
318 // Must be set when creating custom text editing widgets.
319 setAttribute(Qt::WA_InputMethodEnabled, true);
321 d->dialog_mode_ = false;
325 GuiWorkArea::~GuiWorkArea()
327 d->buffer_view_->buffer().workAreaManager().remove(this);
329 delete d->buffer_view_;
331 // Completer has a QObject parent and is thus automatically destroyed.
333 // delete completer_;
338 Qt::CursorShape GuiWorkArea::cursorShape() const
340 return viewport()->cursor().shape();
344 void GuiWorkArea::Private::setCursorShape(Qt::CursorShape shape)
346 p->viewport()->setCursor(shape);
350 void GuiWorkArea::Private::updateCursorShape()
352 setCursorShape(buffer_view_->clickableInset()
353 ? Qt::PointingHandCursor : Qt::IBeamCursor);
357 void GuiWorkArea::setGuiView(GuiView & gv)
363 void GuiWorkArea::setBuffer(Buffer & buffer)
365 delete d->buffer_view_;
366 d->buffer_view_ = new BufferView(buffer);
367 buffer.workAreaManager().add(this);
369 // HACK: Prevents an additional redraw when the scrollbar pops up
370 // which regularily happens on documents with more than one page.
371 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
372 // Since we have no geometry information yet, we assume that
373 // a document needs a scrollbar if there is more then four
374 // paragraph in the outermost text.
375 if (buffer.text().paragraphs().size() > 4)
376 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
377 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
381 void GuiWorkArea::fixVerticalScrollBar()
384 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
388 void GuiWorkArea::close()
390 d->lyx_view_->removeWorkArea(this);
394 void GuiWorkArea::setFullScreen(bool full_screen)
396 d->buffer_view_->setFullScreen(full_screen);
397 setFrameStyle(QFrame::NoFrame);
399 setFrameStyle(QFrame::NoFrame);
400 if (lyxrc.full_screen_scrollbar)
401 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
403 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
407 BufferView & GuiWorkArea::bufferView()
409 return *d->buffer_view_;
413 BufferView const & GuiWorkArea::bufferView() const
415 return *d->buffer_view_;
419 void GuiWorkArea::stopBlinkingCursor()
421 d->cursor_timeout_.stop();
426 void GuiWorkArea::startBlinkingCursor()
428 // do not show the cursor if the view is busy
434 d->buffer_view_->cursorPosAndHeight(p, h);
435 // Don't start blinking if the cursor isn't on screen.
436 if (!d->buffer_view_->cursorInView(p, h))
441 //we're not supposed to cache this value.
442 int const time = QApplication::cursorFlashTime() / 2;
445 d->cursor_timeout_.setInterval(time);
446 d->cursor_timeout_.start();
450 void GuiWorkArea::redraw(bool update_metrics)
453 // No need to redraw in this case.
456 // No need to do anything if this is the current view. The BufferView
457 // metrics are already up to date.
458 if (update_metrics || d->lyx_view_ != guiApp->currentView()
459 || d->lyx_view_->currentWorkArea() != this) {
460 // FIXME: it would be nice to optimize for the off-screen case.
461 d->buffer_view_->cursor().fixIfBroken();
462 d->buffer_view_->updateMetrics();
463 d->buffer_view_->cursor().fixIfBroken();
466 // update cursor position, because otherwise it has to wait until
467 // the blinking interval is over
468 if (d->cursor_visible_) {
473 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
475 update(0, 0, viewport()->width(), viewport()->height());
477 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
478 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
479 d->updateScrollbar();
480 d->lyx_view_->updateStatusBar();
482 if (lyxerr.debugging(Debug::WORKAREA))
483 d->buffer_view_->coordCache().dump();
487 d->updateCursorShape();
491 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
493 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
494 && lyxrc.full_screen_menubar) {
495 // FIXME HACK: we should not have to do this here. See related comment
496 // in GuiView::event() (QEvent::ShortcutOverride)
497 d->lyx_view_->menuBar()->hide();
500 // In order to avoid bad surprise in the middle of an operation,
501 // we better stop the blinking cursor...
502 // the cursor gets restarted in GuiView::restartCursor()
503 stopBlinkingCursor();
504 guiApp->processKeySym(key, mod);
508 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd0, KeyModifier mod)
511 if (cmd0.action() == LFUN_FILE_OPEN) {
513 lyx_view_->dispatch(cmd0, dr);
519 if (cmd0.action() == LFUN_MOUSE_PRESS) {
520 if (mod == ShiftModifier)
521 cmd = FuncRequest(cmd0, "region-select");
522 else if (mod == ControlModifier)
523 cmd = FuncRequest(cmd0, "paragraph-select");
530 bool const notJustMovingTheMouse =
531 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
533 // In order to avoid bad surprise in the middle of an operation, we better stop
534 // the blinking cursor.
535 if (notJustMovingTheMouse)
536 p->stopBlinkingCursor();
538 buffer_view_->mouseEventDispatch(cmd);
540 // Skip these when selecting
541 // FIXME: let GuiView take care of those.
542 if (cmd.action() != LFUN_MOUSE_MOTION) {
543 completer_->updateVisibility(false, false);
544 lyx_view_->updateDialogs();
545 lyx_view_->updateStatusBar();
548 // GUI tweaks except with mouse motion with no button pressed.
549 if (notJustMovingTheMouse) {
550 // Slight hack: this is only called currently when we
551 // clicked somewhere, so we force through the display
552 // of the new status here.
553 // FIXME: let GuiView take care of those.
554 lyx_view_->clearMessage();
556 // Show the cursor immediately after any operation
557 p->startBlinkingCursor();
564 void GuiWorkArea::Private::resizeBufferView()
566 // WARNING: Please don't put any code that will trigger a repaint here!
567 // We are already inside a paint event.
568 p->stopBlinkingCursor();
569 // Warn our container (GuiView).
574 buffer_view_->cursorPosAndHeight(point, h);
575 bool const cursor_in_view = buffer_view_->cursorInView(point, h);
576 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
578 buffer_view_->scrollToCursor();
581 // Update scrollbars which might have changed due different
582 // BufferView dimension. This is especially important when the
583 // BufferView goes from zero-size to the real-size for the first time,
584 // as the scrollbar paramters are then set for the first time.
587 need_resize_ = false;
589 // Eventually, restart the cursor after the resize event.
590 // We might be resizing even if the focus is on another widget so we only
591 // restart the cursor if we have the focus.
593 QTimer::singleShot(50, p, SLOT(startBlinkingCursor()));
597 void GuiWorkArea::Private::showCursor()
604 buffer_view_->cursorPosAndHeight(p, h);
605 if (!buffer_view_->cursorInView(p, h))
609 bool l_shape = false;
610 Font const & realfont = buffer_view_->cursor().real_current_font;
611 BufferParams const & bp = buffer_view_->buffer().params();
612 bool const samelang = realfont.language() == bp.language;
613 bool const isrtl = realfont.isVisibleRightToLeft();
615 if (!samelang || isrtl != bp.language->rightToLeft())
618 // The ERT language hack needs fixing up
619 if (realfont.language() == latex_language)
622 // show cursor on screen
623 Cursor & cur = buffer_view_->cursor();
624 bool completable = cur.inset().showCompletionCursor()
625 && completer_->completionAvailable()
626 && !completer_->popupVisible()
627 && !completer_->inlineVisible();
628 cursor_visible_ = true;
629 cursor_->recomputeWidth();
630 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
634 void GuiWorkArea::Private::hideCursor()
636 if (!cursor_visible_)
639 cursor_visible_ = false;
644 void GuiWorkArea::toggleCursor()
646 if (d->cursor_visible_)
653 void GuiWorkArea::Private::updateScrollbar()
655 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
656 // WARNING: don't touch at the scrollbar value like this:
657 // verticalScrollBar()->setValue(scroll_.position);
658 // because this would cause a recursive signal/slot calling with
659 // GuiWorkArea::scrollTo
660 p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
661 p->verticalScrollBar()->setPageStep(scroll_.page_step);
662 p->verticalScrollBar()->setSingleStep(scroll_.single_step);
663 p->verticalScrollBar()->setSliderPosition(scroll_.position);
667 void GuiWorkArea::scrollTo(int value)
669 stopBlinkingCursor();
670 d->buffer_view_->scrollDocView(value, true);
672 if (lyxrc.cursor_follows_scrollbar) {
673 d->buffer_view_->setCursorFromScrollbar();
674 // FIXME: let GuiView take care of those.
675 d->lyx_view_->updateLayoutList();
677 // Show the cursor immediately after any operation.
678 startBlinkingCursor();
680 QApplication::syncX();
685 bool GuiWorkArea::event(QEvent * e)
688 case QEvent::ToolTip: {
689 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
690 if (lyxrc.use_tooltip) {
691 QPoint pos = helpEvent->pos();
692 if (pos.x() < viewport()->width()) {
693 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
694 QToolTip::showText(helpEvent->globalPos(), s);
697 QToolTip::hideText();
699 // Don't forget to accept the event!
704 case QEvent::ShortcutOverride: {
705 // We catch this event in order to catch the Tab or Shift+Tab key press
706 // which are otherwise reserved to focus switching between controls
708 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
709 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
710 || (ke->key() == Qt::Key_Backtab && (
711 ke->modifiers() == Qt::ShiftModifier
712 || ke->modifiers() == Qt::NoModifier))) {
716 return QAbstractScrollArea::event(e);
720 return QAbstractScrollArea::event(e);
726 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
729 if (e->reason() == QContextMenuEvent::Mouse)
730 // the menu name is set on mouse press
731 name = d->context_menu_name_;
733 QPoint pos = e->pos();
734 Cursor const & cur = d->buffer_view_->cursor();
735 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
736 // Do not access the context menu of math right in front of before
737 // the cursor. This does not work when the cursor is in text.
738 Inset * inset = cur.paragraph().getInset(cur.pos());
739 if (inset && inset->asInsetMath())
741 else if (cur.pos() > 0) {
742 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
747 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
751 QAbstractScrollArea::contextMenuEvent(e);
754 // always show mnemonics when the keyboard is used to show the context menu
755 // FIXME: This should be fixed in Qt itself
756 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
757 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
759 QAbstractScrollArea::contextMenuEvent(e);
762 // Position the menu to the right.
763 // FIXME: menu position should be different for RTL text.
764 menu->exec(e->globalPos());
769 void GuiWorkArea::focusInEvent(QFocusEvent * e)
771 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
772 if (d->lyx_view_->currentWorkArea() != this) {
773 d->lyx_view_->setCurrentWorkArea(this);
774 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
777 startBlinkingCursor();
778 QAbstractScrollArea::focusInEvent(e);
782 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
784 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
785 stopBlinkingCursor();
786 QAbstractScrollArea::focusOutEvent(e);
790 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
792 if (d->dc_event_.active && d->dc_event_ == *e) {
793 d->dc_event_.active = false;
794 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
795 q_button_state(e->button()));
801 #if (QT_VERSION < 0x050000)
802 inputContext()->reset();
805 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
806 q_button_state(e->button()));
807 d->dispatch(cmd, q_key_state(e->modifiers()));
809 // Save the context menu on mouse press, because also the mouse
810 // cursor is set on mouse press. Afterwards, we can either release
811 // the mousebutton somewhere else, or the cursor might have moved
812 // due to the DEPM. We need to do this after the mouse has been
813 // set in dispatch(), because the selection state might change.
814 if (e->button() == Qt::RightButton)
815 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
821 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
823 if (d->synthetic_mouse_event_.timeout.running())
824 d->synthetic_mouse_event_.timeout.stop();
826 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
827 q_button_state(e->button()));
833 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
835 // we kill the triple click if we move
836 doubleClickTimeout();
837 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
838 q_motion_state(e->buttons()));
842 // If we're above or below the work area...
843 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
844 && e->buttons() == mouse_button::button1) {
845 // Make sure only a synthetic event can cause a page scroll,
846 // so they come at a steady rate:
848 // _Force_ a scroll up:
849 cmd.set_y(e->y() - 21);
851 cmd.set_y(e->y() + 21);
852 // Store the event, to be handled when the timeout expires.
853 d->synthetic_mouse_event_.cmd = cmd;
855 if (d->synthetic_mouse_event_.timeout.running()) {
856 // Discard the event. Note that it _may_ be handled
857 // when the timeout expires if
858 // synthetic_mouse_event_.cmd has not been overwritten.
859 // Ie, when the timeout expires, we handle the
860 // most recent event but discard all others that
861 // occurred after the one used to start the timeout
862 // in the first place.
866 d->synthetic_mouse_event_.restart_timeout = true;
867 d->synthetic_mouse_event_.timeout.start();
868 // Fall through to handle this event...
870 } else if (d->synthetic_mouse_event_.timeout.running()) {
871 // Store the event, to be possibly handled when the timeout
873 // Once the timeout has expired, normal control is returned
874 // to mouseMoveEvent (restart_timeout = false).
875 // This results in a much smoother 'feel' when moving the
876 // mouse back into the work area.
877 d->synthetic_mouse_event_.cmd = cmd;
878 d->synthetic_mouse_event_.restart_timeout = false;
885 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
887 // Wheel rotation by one notch results in a delta() of 120 (see
888 // documentation of QWheelEvent)
889 double const delta = ev->delta() / 120.0;
891 switch (lyxrc.scroll_wheel_zoom) {
892 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
893 zoom = ev->modifiers() & Qt::ControlModifier;
894 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
896 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
897 zoom = ev->modifiers() & Qt::ShiftModifier;
898 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
900 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
901 zoom = ev->modifiers() & Qt::AltModifier;
902 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
904 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
908 docstring arg = convert<docstring>(int(5 * delta));
909 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
913 // Take into account the desktop wide settings.
914 int const lines = qApp->wheelScrollLines();
915 int const page_step = verticalScrollBar()->pageStep();
916 // Test if the wheel mouse is set to one screen at a time.
917 int scroll_value = lines > page_step
918 ? page_step : lines * verticalScrollBar()->singleStep();
920 // Take into account the rotation and the user preferences.
921 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
922 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
923 << " delta = " << delta << " scroll_value = " << scroll_value
924 << " page_step = " << page_step);
926 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
932 void GuiWorkArea::generateSyntheticMouseEvent()
934 int const e_y = d->synthetic_mouse_event_.cmd.y();
935 int const wh = d->buffer_view_->workHeight();
936 bool const up = e_y < 0;
937 bool const down = e_y > wh;
939 // Set things off to generate the _next_ 'pseudo' event.
941 if (d->synthetic_mouse_event_.restart_timeout) {
942 // This is some magic formulae to determine the speed
943 // of scrolling related to the position of the mouse.
946 int dist = up ? -e_y : e_y - wh;
947 time = max(min(200, 250000 / (dist * dist)), 1) ;
950 step = 80000 / (time * time);
954 d->synthetic_mouse_event_.timeout.setTimeout(time);
955 d->synthetic_mouse_event_.timeout.start();
958 // Can we scroll further ?
959 int const value = verticalScrollBar()->value();
960 if (value == verticalScrollBar()->maximum()
961 || value == verticalScrollBar()->minimum()) {
962 d->synthetic_mouse_event_.timeout.stop();
967 if (step <= 2 * wh) {
968 d->buffer_view_->scroll(up ? -step : step);
969 d->buffer_view_->updateMetrics();
971 d->buffer_view_->scrollDocView(value + up ? -step : step, false);
974 // In which paragraph do we have to set the cursor ?
975 Cursor & cur = d->buffer_view_->cursor();
976 // FIXME: we don't know howto handle math.
977 Text * text = cur.text();
980 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
982 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
983 ParagraphMetrics const & pm = *pp.second;
984 pit_type const pit = pp.first;
986 if (pm.rows().empty())
989 // Find the row at which we set the cursor.
990 RowList::const_iterator rit = pm.rows().begin();
991 RowList::const_iterator rlast = pm.rows().end();
992 int yy = pm.position() - pm.ascent();
993 for (--rlast; rit != rlast; ++rit) {
994 int h = rit->height();
995 if ((up && yy + h > 0)
996 || (!up && yy + h > wh - defaultRowHeight()))
1001 // Find the position of the cursor
1003 int x = d->synthetic_mouse_event_.cmd.x();
1004 pos_type const pos = rit->pos() + tm.getColumnNearX(pit, *rit, x, bound);
1009 cur.boundary(bound);
1011 d->buffer_view_->buffer().changed(false);
1016 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1018 // Do not process here some keys if dialog_mode_ is set
1020 && (ev->modifiers() == Qt::NoModifier
1021 || ev->modifiers() == Qt::ShiftModifier)
1022 && (ev->key() == Qt::Key_Escape
1023 || ev->key() == Qt::Key_Enter
1024 || ev->key() == Qt::Key_Return)
1030 // intercept some keys if completion popup is visible
1031 if (d->completer_->popupVisible()) {
1032 switch (ev->key()) {
1034 case Qt::Key_Return:
1035 d->completer_->activate();
1041 // do nothing if there are other events
1042 // (the auto repeated events come too fast)
1043 // it looks like this is only needed on X11
1045 if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1046 switch (ev->key()) {
1047 case Qt::Key_PageDown:
1048 case Qt::Key_PageUp:
1053 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1060 KeyModifier m = q_key_state(ev->modifiers());
1063 if (m & ShiftModifier)
1065 if (m & ControlModifier)
1067 if (m & AltModifier)
1069 if (m & MetaModifier)
1072 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1073 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1074 << " keyState: " << str);
1077 setKeySymbol(&sym, ev);
1079 processKeySym(sym, q_key_state(ev->modifiers()));
1087 void GuiWorkArea::doubleClickTimeout()
1089 d->dc_event_.active = false;
1093 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1095 d->dc_event_ = DoubleClick(ev);
1096 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1097 SLOT(doubleClickTimeout()));
1098 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1100 q_button_state(ev->button()));
1106 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1108 QAbstractScrollArea::resizeEvent(ev);
1109 d->need_resize_ = true;
1114 void GuiWorkArea::Private::update(int x, int y, int w, int h)
1116 p->viewport()->update(x, y, w, h);
1120 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1122 QRect const rc = ev->rect();
1123 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1124 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1126 if (d->need_resize_) {
1128 d->resizeBufferView();
1129 if (d->cursor_visible_) {
1135 QPainter pain(viewport());
1136 if (lyxrc.use_qimage) {
1137 pain.drawImage(rc, static_cast<QImage const &>(*d->screen_), rc);
1139 pain.drawPixmap(rc, static_cast<QPixmap const &>(*d->screen_), rc);
1141 d->cursor_->draw(pain);
1146 void GuiWorkArea::Private::updateScreen()
1148 GuiPainter pain(screen_);
1149 buffer_view_->draw(pain);
1153 void GuiWorkArea::Private::showCursor(int x, int y, int h,
1154 bool l_shape, bool rtl, bool completable)
1156 if (schedule_redraw_) {
1157 // This happens when a graphic conversion is finished. As we don't know
1158 // the size of the new graphics, it's better the update everything.
1159 // We can't use redraw() here because this would trigger a infinite
1160 // recursive loop with showCursor().
1161 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
1164 p->viewport()->update(QRect(0, 0, p->viewport()->width(), p->viewport()->height()));
1165 schedule_redraw_ = false;
1166 // Show the cursor immediately after the update.
1172 cursor_->update(x, y, h, l_shape, rtl, completable);
1174 p->viewport()->update(cursor_->rect());
1178 void GuiWorkArea::Private::removeCursor()
1181 //if (!qApp->focusWidget())
1182 p->viewport()->update(cursor_->rect());
1186 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1188 QString const & commit_string = e->commitString();
1189 docstring const & preedit_string
1190 = qstring_to_ucs4(e->preeditString());
1192 if (!commit_string.isEmpty()) {
1194 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1195 << " commitString: " << e->commitString());
1199 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1200 for (int i = 0; i != commit_string.size(); ++i) {
1201 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1206 // Hide the cursor during the kana-kanji transformation.
1207 if (preedit_string.empty())
1208 startBlinkingCursor();
1210 stopBlinkingCursor();
1212 // last_width : for checking if last preedit string was/wasn't empty.
1213 static bool last_width = false;
1214 if (!last_width && preedit_string.empty()) {
1215 // if last_width is last length of preedit string.
1220 GuiPainter pain(d->screen_);
1221 d->buffer_view_->updateMetrics();
1222 d->buffer_view_->draw(pain);
1223 FontInfo font = d->buffer_view_->cursor().getFont().fontInfo();
1224 FontMetrics const & fm = theFontMetrics(font);
1225 int height = fm.maxHeight();
1226 int cur_x = d->cursor_->rect().left();
1227 int cur_y = d->cursor_->rect().bottom();
1229 // redraw area of preedit string.
1230 update(0, cur_y - height, viewport()->width(),
1231 (height + 1) * d->preedit_lines_);
1233 if (preedit_string.empty()) {
1235 d->preedit_lines_ = 1;
1241 // att : stores an IM attribute.
1242 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1244 // get attributes of input method cursor.
1245 // cursor_pos : cursor position in preedit string.
1246 size_t cursor_pos = 0;
1247 bool cursor_is_visible = false;
1248 for (int i = 0; i != att.size(); ++i) {
1249 if (att.at(i).type == QInputMethodEvent::Cursor) {
1250 cursor_pos = att.at(i).start;
1251 cursor_is_visible = att.at(i).length != 0;
1256 size_t preedit_length = preedit_string.length();
1258 // get position of selection in input method.
1259 // FIXME: isn't there a way to do this simplier?
1260 // rStart : cursor position in selected string in IM.
1262 // rLength : selected string length in IM.
1264 if (cursor_pos < preedit_length) {
1265 for (int i = 0; i != att.size(); ++i) {
1266 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1267 if (att.at(i).start <= int(cursor_pos)
1268 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1269 rStart = att.at(i).start;
1270 rLength = att.at(i).length;
1271 if (!cursor_is_visible)
1272 cursor_pos += rLength;
1279 rStart = cursor_pos;
1283 int const right_margin = d->buffer_view_->rightMargin();
1284 Painter::preedit_style ps;
1285 // Most often there would be only one line:
1286 d->preedit_lines_ = 1;
1287 for (size_t pos = 0; pos != preedit_length; ++pos) {
1288 char_type const typed_char = preedit_string[pos];
1289 // reset preedit string style
1290 ps = Painter::preedit_default;
1292 // if we reached the right extremity of the screen, go to next line.
1293 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1294 cur_x = right_margin;
1295 cur_y += height + 1;
1296 ++d->preedit_lines_;
1298 // preedit strings are displayed with dashed underline
1299 // and partial strings are displayed white on black indicating
1300 // that we are in selecting mode in the input method.
1301 // FIXME: rLength == preedit_length is not a changing condition
1302 // FIXME: should be put out of the loop.
1304 && pos < rStart + rLength
1305 && !(cursor_pos < rLength && rLength == preedit_length))
1306 ps = Painter::preedit_selecting;
1308 if (pos == cursor_pos
1309 && (cursor_pos < rLength && rLength == preedit_length))
1310 ps = Painter::preedit_cursor;
1312 // draw one character and update cur_x.
1313 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1316 // update the preedit string screen area.
1317 update(0, cur_y - d->preedit_lines_*height, viewport()->width(),
1318 (height + 1) * d->preedit_lines_);
1320 // Don't forget to accept the event!
1325 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1327 QRect cur_r(0, 0, 0, 0);
1329 // this is the CJK-specific composition window position and
1330 // the context menu position when the menu key is pressed.
1331 case Qt::ImMicroFocus:
1332 cur_r = d->cursor_->rect();
1333 if (d->preedit_lines_ != 1)
1335 cur_r.moveBottom(cur_r.bottom()
1336 + cur_r.height() * (d->preedit_lines_ - 1));
1337 // return lower right of cursor in LyX.
1340 return QWidget::inputMethodQuery(query);
1345 void GuiWorkArea::updateWindowTitle()
1347 docstring maximize_title;
1348 docstring minimize_title;
1350 Buffer const & buf = d->buffer_view_->buffer();
1351 FileName const file_name = buf.fileName();
1352 if (!file_name.empty()) {
1353 maximize_title = file_name.displayName(130);
1354 minimize_title = from_utf8(file_name.onlyFileName());
1355 if (buf.lyxvc().inUse()) {
1356 if (buf.lyxvc().locking())
1357 maximize_title += _(" (version control, locking)");
1359 maximize_title += _(" (version control)");
1361 if (!buf.isClean()) {
1362 maximize_title += _(" (changed)");
1363 minimize_title += char_type('*');
1365 if (buf.isReadonly())
1366 maximize_title += _(" (read only)");
1369 QString const new_title = toqstr(maximize_title);
1370 if (new_title != windowTitle()) {
1371 QWidget::setWindowTitle(new_title);
1372 QWidget::setWindowIconText(toqstr(minimize_title));
1378 bool GuiWorkArea::isFullScreen() const
1380 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1384 void GuiWorkArea::scheduleRedraw()
1386 d->schedule_redraw_ = true;
1390 bool GuiWorkArea::inDialogMode() const
1392 return d->dialog_mode_;
1396 void GuiWorkArea::setDialogMode(bool mode)
1398 d->dialog_mode_ = mode;
1402 GuiCompleter & GuiWorkArea::completer()
1404 return *d->completer_;
1407 GuiView const & GuiWorkArea::view() const
1409 return *d->lyx_view_;
1413 GuiView & GuiWorkArea::view()
1415 return *d->lyx_view_;
1418 ////////////////////////////////////////////////////////////////////
1422 ////////////////////////////////////////////////////////////////////
1425 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1427 buffer_ = theBufferList().newInternalBuffer(
1428 support::FileName::tempName("embedded.internal").absFileName());
1429 buffer_->setUnnamed(true);
1430 buffer_->setFullyLoaded(true);
1431 setBuffer(*buffer_);
1432 setDialogMode(true);
1436 EmbeddedWorkArea::~EmbeddedWorkArea()
1438 // No need to destroy buffer and bufferview here, because it is done
1439 // in theBufferList() destruction loop at application exit
1443 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1446 GuiWorkArea::closeEvent(ev);
1450 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1453 GuiWorkArea::hideEvent(ev);
1457 QSize EmbeddedWorkArea::sizeHint () const
1460 // GuiWorkArea sets the size to the screen's viewport
1461 // by returning a value this gets overridden
1462 // EmbeddedWorkArea is now sized to fit in the layout
1463 // of the parent, and has a minimum size set in GuiWorkArea
1464 // which is what we return here
1465 return QSize(100, 70);
1469 void EmbeddedWorkArea::disable()
1471 stopBlinkingCursor();
1472 if (view().currentWorkArea() != this)
1474 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1475 // tolerates it and shows the background logo), what happens if
1476 // an EmbeddedWorkArea is closed after closing all document WAs
1477 view().setCurrentWorkArea(view().currentMainWorkArea());
1480 ////////////////////////////////////////////////////////////////////
1484 ////////////////////////////////////////////////////////////////////
1487 class NoTabFrameMacStyle : public QMacStyle {
1490 QRect subElementRect(SubElement element, const QStyleOption * option,
1491 const QWidget * widget = 0) const
1493 QRect rect = QMacStyle::subElementRect(element, option, widget);
1494 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1496 // The Qt Mac style puts the contents into a 3 pixel wide box
1497 // which looks very ugly and not like other Mac applications.
1498 // Hence we remove this here, and moreover the 16 pixel round
1499 // frame above if the tab bar is hidden.
1500 if (element == QStyle::SE_TabWidgetTabContents) {
1501 rect.adjust(- rect.left(), 0, rect.left(), 0);
1510 NoTabFrameMacStyle noTabFrameMacStyle;
1514 TabWorkArea::TabWorkArea(QWidget * parent)
1515 : QTabWidget(parent), clicked_tab_(-1)
1518 setStyle(&noTabFrameMacStyle);
1521 QPalette pal = palette();
1522 pal.setColor(QPalette::Active, QPalette::Button,
1523 pal.color(QPalette::Active, QPalette::Window));
1524 pal.setColor(QPalette::Disabled, QPalette::Button,
1525 pal.color(QPalette::Disabled, QPalette::Window));
1526 pal.setColor(QPalette::Inactive, QPalette::Button,
1527 pal.color(QPalette::Inactive, QPalette::Window));
1529 QObject::connect(this, SIGNAL(currentChanged(int)),
1530 this, SLOT(on_currentTabChanged(int)));
1532 closeBufferButton = new QToolButton(this);
1533 closeBufferButton->setPalette(pal);
1534 // FIXME: rename the icon to closebuffer.png
1535 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1536 closeBufferButton->setText("Close File");
1537 closeBufferButton->setAutoRaise(true);
1538 closeBufferButton->setCursor(Qt::ArrowCursor);
1539 closeBufferButton->setToolTip(qt_("Close File"));
1540 closeBufferButton->setEnabled(true);
1541 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1542 this, SLOT(closeCurrentBuffer()));
1543 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1545 // setup drag'n'drop
1546 QTabBar* tb = new DragTabBar;
1547 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1548 this, SLOT(moveTab(int, int)));
1549 tb->setElideMode(Qt::ElideNone);
1552 // make us responsible for the context menu of the tabbar
1553 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1554 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1555 this, SLOT(showContextMenu(const QPoint &)));
1556 connect(tb, SIGNAL(tabCloseRequested(int)),
1557 this, SLOT(closeTab(int)));
1559 setUsesScrollButtons(true);
1563 void TabWorkArea::paintEvent(QPaintEvent * event)
1565 if (tabBar()->isVisible()) {
1566 QTabWidget::paintEvent(event);
1568 // Prevent the selected tab to influence the
1569 // painting of the frame of the tab widget.
1570 // This is needed for gtk style in Qt.
1571 QStylePainter p(this);
1572 #if QT_VERSION < 0x050000
1573 QStyleOptionTabWidgetFrameV2 opt;
1575 QStyleOptionTabWidgetFrame opt;
1577 initStyleOption(&opt);
1578 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1580 opt.selectedTabRect = QRect();
1581 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1586 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1588 if (event->button() != Qt::LeftButton)
1591 // return early if double click on existing tabs
1592 for (int i = 0; i < count(); ++i)
1593 if (tabBar()->tabRect(i).contains(event->pos()))
1596 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1600 void TabWorkArea::setFullScreen(bool full_screen)
1602 for (int i = 0; i != count(); ++i) {
1603 if (GuiWorkArea * wa = workArea(i))
1604 wa->setFullScreen(full_screen);
1607 if (lyxrc.full_screen_tabbar)
1608 showBar(!full_screen && count() > 1);
1610 showBar(count() > 1);
1614 void TabWorkArea::showBar(bool show)
1616 tabBar()->setEnabled(show);
1617 tabBar()->setVisible(show);
1618 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1619 setTabsClosable(!lyxrc.single_close_tab_button);
1623 GuiWorkArea * TabWorkArea::currentWorkArea()
1628 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1634 GuiWorkArea * TabWorkArea::workArea(int index)
1636 return dynamic_cast<GuiWorkArea *>(widget(index));
1640 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1642 // FIXME: this method doesn't work if we have more than work area
1643 // showing the same buffer.
1644 for (int i = 0; i != count(); ++i) {
1645 GuiWorkArea * wa = workArea(i);
1646 LASSERT(wa, return 0);
1647 if (&wa->bufferView().buffer() == &buffer)
1654 void TabWorkArea::closeAll()
1657 GuiWorkArea * wa = workArea(0);
1665 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1667 LASSERT(work_area, /**/);
1668 int index = indexOf(work_area);
1672 if (index == currentIndex())
1673 // Make sure the work area is up to date.
1674 on_currentTabChanged(index);
1676 // Switch to the work area.
1677 setCurrentIndex(index);
1678 work_area->setFocus();
1684 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1686 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1687 wa->setUpdatesEnabled(false);
1688 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1689 // when hiding it again below).
1690 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1691 showBar(count() > 0);
1692 addTab(wa, wa->windowTitle());
1693 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1694 this, SLOT(updateTabTexts()));
1695 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1696 setFullScreen(true);
1698 // Hide tabbar if there's only one tab.
1699 showBar(count() > 1);
1707 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1709 LASSERT(work_area, return false);
1710 int index = indexOf(work_area);
1714 work_area->setUpdatesEnabled(false);
1719 // make sure the next work area is enabled.
1720 currentWidget()->setUpdatesEnabled(true);
1721 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1722 setFullScreen(true);
1724 // Show tabbar only if there's more than one tab.
1725 showBar(count() > 1);
1727 lastWorkAreaRemoved();
1735 void TabWorkArea::on_currentTabChanged(int i)
1737 // returns e.g. on application destruction
1740 GuiWorkArea * wa = workArea(i);
1741 LASSERT(wa, return);
1742 wa->setUpdatesEnabled(true);
1746 currentWorkAreaChanged(wa);
1748 LYXERR(Debug::GUI, "currentTabChanged " << i
1749 << " File: " << wa->bufferView().buffer().absFileName());
1753 void TabWorkArea::closeCurrentBuffer()
1756 if (clicked_tab_ == -1)
1757 wa = currentWorkArea();
1759 wa = workArea(clicked_tab_);
1762 wa->view().closeWorkArea(wa);
1766 void TabWorkArea::hideCurrentTab()
1769 if (clicked_tab_ == -1)
1770 wa = currentWorkArea();
1772 wa = workArea(clicked_tab_);
1775 wa->view().hideWorkArea(wa);
1779 void TabWorkArea::closeTab(int index)
1781 on_currentTabChanged(index);
1784 wa = currentWorkArea();
1786 wa = workArea(index);
1789 wa->view().closeWorkArea(wa);
1796 /// make vector happy
1799 DisplayPath(int tab, FileName const & filename)
1802 filename_ = (filename.extension() == "lyx") ?
1803 toqstr(filename.onlyFileNameWithoutExt())
1804 : toqstr(filename.onlyFileName());
1805 postfix_ = toqstr(filename.absoluteFilePath()).
1806 split("/", QString::SkipEmptyParts);
1807 postfix_.pop_back();
1808 abs_ = toqstr(filename.absoluteFilePath());
1809 dottedPrefix_ = false;
1812 /// Absolute path for debugging.
1817 /// Add the first segment from the postfix or three dots to the prefix.
1818 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1819 /// when really needed.
1820 void shiftPathSegment(bool dotted)
1822 if (postfix_.count() <= 0)
1826 if (dottedPrefix_ && !prefix_.isEmpty())
1828 prefix_ += postfix_.front() + "/";
1830 dottedPrefix_ = dotted && !prefix_.isEmpty();
1831 postfix_.pop_front();
1834 QString displayString() const
1836 if (prefix_.isEmpty())
1839 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1840 return prefix_ + (dots ? ".../" : "") + filename_;
1843 QString forecastPathString() const
1845 if (postfix_.count() == 0)
1846 return displayString();
1849 + (dottedPrefix_ ? ".../" : "")
1850 + postfix_.front() + "/";
1853 bool final() const { return postfix_.empty(); }
1855 int tab() const { return tab_; }
1861 QStringList postfix_;
1874 bool operator<(DisplayPath const & a, DisplayPath const & b)
1876 return a.displayString() < b.displayString();
1880 bool operator==(DisplayPath const & a, DisplayPath const & b)
1882 return a.displayString() == b.displayString();
1886 void TabWorkArea::updateTabTexts()
1891 std::list<DisplayPath> paths;
1892 typedef std::list<DisplayPath>::iterator It;
1894 // collect full names first: path into postfix, empty prefix and
1895 // filename without extension
1896 for (size_t i = 0; i < n; ++i) {
1897 GuiWorkArea * i_wa = workArea(i);
1898 FileName const fn = i_wa->bufferView().buffer().fileName();
1899 paths.push_back(DisplayPath(i, fn));
1902 // go through path segments and see if it helps to make the path more unique
1903 bool somethingChanged = true;
1904 bool allFinal = false;
1905 while (somethingChanged && !allFinal) {
1906 // adding path segments changes order
1909 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1910 somethingChanged = false;
1913 // find segments which are not unique (i.e. non-atomic)
1914 It it = paths.begin();
1916 QString segString = it->displayString();
1917 for (; it != paths.end(); ++it) {
1918 // look to the next item
1923 allFinal = allFinal && it->final();
1925 LYXERR(Debug::GUI, "it = " << it->abs()
1926 << " => " << it->displayString());
1928 // still the same segment?
1930 if ((next != paths.end()
1931 && (nextString = next->displayString()) == segString))
1933 LYXERR(Debug::GUI, "segment ended");
1935 // only a trivial one with one element?
1936 if (it == segStart) {
1937 // start new segment
1939 segString = nextString;
1943 // we found a non-atomic segment segStart <= sit <= it < next.
1944 // Shift path segments and hope for the best
1945 // that it makes the path more unique.
1946 somethingChanged = true;
1948 QString dspString = sit->forecastPathString();
1949 LYXERR(Debug::GUI, "first forecast found for "
1950 << sit->abs() << " => " << dspString);
1952 bool moreUnique = false;
1953 for (; sit != next; ++sit) {
1954 if (sit->forecastPathString() != dspString) {
1955 LYXERR(Debug::GUI, "different forecast found for "
1956 << sit->abs() << " => " << sit->forecastPathString());
1960 LYXERR(Debug::GUI, "same forecast found for "
1961 << sit->abs() << " => " << dspString);
1964 // if the path segment helped, add it. Otherwise add dots
1965 bool dots = !moreUnique;
1966 LYXERR(Debug::GUI, "using dots = " << dots);
1967 for (sit = segStart; sit != next; ++sit) {
1968 sit->shiftPathSegment(dots);
1969 LYXERR(Debug::GUI, "shifting "
1970 << sit->abs() << " => " << sit->displayString());
1973 // start new segment
1975 segString = nextString;
1979 // set new tab titles
1980 for (It it = paths.begin(); it != paths.end(); ++it) {
1981 int const tab_index = it->tab();
1982 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
1983 QString tab_text = it->displayString();
1984 if (!buf.fileName().empty() && !buf.isClean())
1986 setTabText(tab_index, tab_text);
1987 setTabToolTip(tab_index, it->abs());
1992 void TabWorkArea::showContextMenu(const QPoint & pos)
1995 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1996 if (clicked_tab_ == -1)
2001 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
2002 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2003 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
2004 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2005 popup.exec(tabBar()->mapToGlobal(pos));
2011 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2013 QWidget * w = widget(fromIndex);
2014 QIcon icon = tabIcon(fromIndex);
2015 QString text = tabText(fromIndex);
2017 setCurrentIndex(fromIndex);
2018 removeTab(fromIndex);
2019 insertTab(toIndex, w, icon, text);
2020 setCurrentIndex(toIndex);
2024 DragTabBar::DragTabBar(QWidget* parent)
2027 setAcceptDrops(true);
2028 setTabsClosable(!lyxrc.single_close_tab_button);
2032 void DragTabBar::mousePressEvent(QMouseEvent * event)
2034 if (event->button() == Qt::LeftButton)
2035 dragStartPos_ = event->pos();
2036 QTabBar::mousePressEvent(event);
2040 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2042 // If the left button isn't pressed anymore then return
2043 if (!(event->buttons() & Qt::LeftButton))
2046 // If the distance is too small then return
2047 if ((event->pos() - dragStartPos_).manhattanLength()
2048 < QApplication::startDragDistance())
2051 // did we hit something after all?
2052 int tab = tabAt(dragStartPos_);
2056 // simulate button release to remove highlight from button
2057 int i = currentIndex();
2058 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2059 event->button(), event->buttons(), 0);
2060 QTabBar::mouseReleaseEvent(&me);
2064 QDrag * drag = new QDrag(this);
2065 QMimeData * mimeData = new QMimeData;
2066 // a crude way to distinguish tab-reodering drops from other ones
2067 mimeData->setData("action", "tab-reordering") ;
2068 drag->setMimeData(mimeData);
2070 // get tab pixmap as cursor
2071 QRect r = tabRect(tab);
2072 QPixmap pixmap(r.size());
2073 render(&pixmap, - r.topLeft());
2074 drag->setPixmap(pixmap);
2079 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2081 // Only accept if it's an tab-reordering request
2082 QMimeData const * m = event->mimeData();
2083 QStringList formats = m->formats();
2084 if (formats.contains("action")
2085 && m->data("action") == "tab-reordering")
2086 event->acceptProposedAction();
2090 void DragTabBar::dropEvent(QDropEvent * event)
2092 int fromIndex = tabAt(dragStartPos_);
2093 int toIndex = tabAt(event->pos());
2095 // Tell interested objects that
2096 if (fromIndex != toIndex)
2097 tabMoveRequested(fromIndex, toIndex);
2098 event->acceptProposedAction();
2102 } // namespace frontend
2105 #include "moc_GuiWorkArea.cpp"