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"
52 #include "support/TempFile.h"
54 #include "frontends/Application.h"
55 #include "frontends/FontMetrics.h"
56 #include "frontends/WorkAreaManager.h"
58 #include <QContextMenuEvent>
59 #if (QT_VERSION < 0x050000)
60 #include <QInputContext>
67 #include <QMainWindow>
72 #include <QPixmapCache>
74 #include <QStyleOption>
75 #include <QStylePainter>
77 #include <QToolButton>
81 #include "support/bind.h"
85 int const TabIndicatorWidth = 3;
91 using namespace lyx::support;
96 /// return the LyX mouse button state from Qt's
97 static mouse_button::state q_button_state(Qt::MouseButton button)
99 mouse_button::state b = mouse_button::none;
102 b = mouse_button::button1;
105 b = mouse_button::button2;
107 case Qt::RightButton:
108 b = mouse_button::button3;
117 /// return the LyX mouse button state from Qt's
118 mouse_button::state q_motion_state(Qt::MouseButtons state)
120 mouse_button::state b = mouse_button::none;
121 if (state & Qt::LeftButton)
122 b |= mouse_button::button1;
123 if (state & Qt::MidButton)
124 b |= mouse_button::button2;
125 if (state & Qt::RightButton)
126 b |= mouse_button::button3;
139 void draw(QPainter & painter)
141 if (!show_ || !rect_.isValid())
145 int l = x_ - rect_.left();
146 int r = rect_.right() - x_;
147 int bot = rect_.bottom();
149 // draw vertical line
150 painter.fillRect(x_, y, cursor_width_, rect_.height(), color_);
152 // draw RTL/LTR indication
153 painter.setPen(color_);
156 painter.drawLine(x_, bot, x_ - l, bot);
158 painter.drawLine(x_, bot, x_ + cursor_width_ + r, bot);
161 // draw completion triangle
163 int m = y + rect_.height() / 2;
164 int d = TabIndicatorWidth - 1;
166 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
167 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
169 painter.drawLine(x_ + cursor_width_, m - d, x_ + cursor_width_ + d, m);
170 painter.drawLine(x_ + cursor_width_, m + d, x_ + cursor_width_ + d, m);
175 void update(int x, int y, int h, bool l_shape,
176 bool rtl, bool completable)
178 color_ = guiApp->colorCache().get(Color_cursor);
181 completable_ = completable;
184 // extension to left and right
188 // RTL/LTR indication
196 // completion triangle
199 l = max(l, TabIndicatorWidth);
201 r = max(r, TabIndicatorWidth);
204 // compute overall rectangle
205 rect_ = QRect(x - l, y, cursor_width_ + r + l, h);
208 void show(bool set_show = true) { show_ = set_show; }
209 void hide() { show_ = false; }
210 int cursorWidth() const { return cursor_width_; }
211 void recomputeWidth() {
212 cursor_width_ = lyxrc.cursor_width
214 : 1 + int((lyxrc.zoom + 50) / 200.0);
217 QRect const & rect() { return rect_; }
220 /// cursor is in RTL or LTR text
222 /// indication for RTL or LTR
224 /// triangle to show that a completion is available
230 /// rectangle, possibly with l_shape and completion triangle
232 /// x position (were the vertical line is drawn)
239 // This is a 'heartbeat' generating synthetic mouse move events when the
240 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
241 SyntheticMouseEvent::SyntheticMouseEvent()
242 : timeout(200), restart_timeout(true)
246 GuiWorkArea::Private::Private(GuiWorkArea * parent)
247 : p(parent), screen_(0), buffer_view_(0), lyx_view_(0), cursor_visible_(false),
248 need_resize_(false), schedule_redraw_(false), preedit_lines_(1),
249 completer_(new GuiCompleter(p, p))
254 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
255 : d(new Private(this))
260 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
261 : d(new Private(this))
269 void GuiWorkArea::init()
272 connect(&d->cursor_timeout_, SIGNAL(timeout()),
273 this, SLOT(toggleCursor()));
275 int const time = QApplication::cursorFlashTime() / 2;
277 d->cursor_timeout_.setInterval(time);
278 d->cursor_timeout_.start();
280 // let's initialize this just to be safe
281 d->cursor_timeout_.setInterval(500);
285 // With Qt4.5 a mouse event will happen before the first paint event
286 // so make sure that the buffer view has an up to date metrics.
287 d->buffer_view_->resize(viewport()->width(), viewport()->height());
288 d->cursor_ = new frontend::CursorWidget();
291 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
292 setAcceptDrops(true);
293 setMouseTracking(true);
294 setMinimumSize(100, 70);
295 setFrameStyle(QFrame::NoFrame);
298 viewport()->setAutoFillBackground(false);
299 // We don't need double-buffering nor SystemBackground on
300 // the viewport because we have our own backing pixmap.
301 viewport()->setAttribute(Qt::WA_NoSystemBackground);
303 setFocusPolicy(Qt::StrongFocus);
305 d->setCursorShape(Qt::IBeamCursor);
307 d->synthetic_mouse_event_.timeout.timeout.connect(
308 bind(&GuiWorkArea::generateSyntheticMouseEvent,
311 // Initialize the vertical Scroll Bar
312 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
313 this, SLOT(scrollTo(int)));
315 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
316 << " viewport height: " << viewport()->height());
318 // Enables input methods for asian languages.
319 // Must be set when creating custom text editing widgets.
320 setAttribute(Qt::WA_InputMethodEnabled, true);
322 d->dialog_mode_ = false;
326 GuiWorkArea::~GuiWorkArea()
328 d->buffer_view_->buffer().workAreaManager().remove(this);
330 delete d->buffer_view_;
332 // Completer has a QObject parent and is thus automatically destroyed.
334 // delete completer_;
339 Qt::CursorShape GuiWorkArea::cursorShape() const
341 return viewport()->cursor().shape();
345 void GuiWorkArea::Private::setCursorShape(Qt::CursorShape shape)
347 p->viewport()->setCursor(shape);
351 void GuiWorkArea::Private::updateCursorShape()
353 setCursorShape(buffer_view_->clickableInset()
354 ? Qt::PointingHandCursor : Qt::IBeamCursor);
358 void GuiWorkArea::setGuiView(GuiView & gv)
364 void GuiWorkArea::setBuffer(Buffer & buffer)
366 delete d->buffer_view_;
367 d->buffer_view_ = new BufferView(buffer);
368 buffer.workAreaManager().add(this);
370 // HACK: Prevents an additional redraw when the scrollbar pops up
371 // which regularily happens on documents with more than one page.
372 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
373 // Since we have no geometry information yet, we assume that
374 // a document needs a scrollbar if there is more then four
375 // paragraph in the outermost text.
376 if (buffer.text().paragraphs().size() > 4)
377 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
378 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
382 void GuiWorkArea::fixVerticalScrollBar()
385 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
389 void GuiWorkArea::close()
391 d->lyx_view_->removeWorkArea(this);
395 void GuiWorkArea::setFullScreen(bool full_screen)
397 d->buffer_view_->setFullScreen(full_screen);
398 setFrameStyle(QFrame::NoFrame);
400 setFrameStyle(QFrame::NoFrame);
401 if (lyxrc.full_screen_scrollbar)
402 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
404 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
408 BufferView & GuiWorkArea::bufferView()
410 return *d->buffer_view_;
414 BufferView const & GuiWorkArea::bufferView() const
416 return *d->buffer_view_;
420 void GuiWorkArea::stopBlinkingCursor()
422 d->cursor_timeout_.stop();
427 void GuiWorkArea::startBlinkingCursor()
429 // do not show the cursor if the view is busy
435 d->buffer_view_->cursorPosAndHeight(p, h);
436 // Don't start blinking if the cursor isn't on screen.
437 if (!d->buffer_view_->cursorInView(p, h))
442 //we're not supposed to cache this value.
443 int const time = QApplication::cursorFlashTime() / 2;
446 d->cursor_timeout_.setInterval(time);
447 d->cursor_timeout_.start();
451 void GuiWorkArea::redraw(bool update_metrics)
454 // No need to redraw in this case.
457 // No need to do anything if this is the current view. The BufferView
458 // metrics are already up to date.
459 if (update_metrics || d->lyx_view_ != guiApp->currentView()
460 || d->lyx_view_->currentWorkArea() != this) {
461 // FIXME: it would be nice to optimize for the off-screen case.
462 d->buffer_view_->cursor().fixIfBroken();
463 d->buffer_view_->updateMetrics();
464 d->buffer_view_->cursor().fixIfBroken();
467 // update cursor position, because otherwise it has to wait until
468 // the blinking interval is over
469 if (d->cursor_visible_) {
474 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
476 update(0, 0, viewport()->width(), viewport()->height());
478 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
479 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
480 d->updateScrollbar();
481 d->lyx_view_->updateStatusBar();
483 if (lyxerr.debugging(Debug::WORKAREA))
484 d->buffer_view_->coordCache().dump();
488 d->updateCursorShape();
492 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
494 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
495 && lyxrc.full_screen_menubar) {
496 // FIXME HACK: we should not have to do this here. See related comment
497 // in GuiView::event() (QEvent::ShortcutOverride)
498 d->lyx_view_->menuBar()->hide();
501 // In order to avoid bad surprise in the middle of an operation,
502 // we better stop the blinking cursor...
503 // the cursor gets restarted in GuiView::restartCursor()
504 stopBlinkingCursor();
505 guiApp->processKeySym(key, mod);
509 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd0, KeyModifier mod)
512 if (cmd0.action() == LFUN_FILE_OPEN) {
514 lyx_view_->dispatch(cmd0, dr);
520 if (cmd0.action() == LFUN_MOUSE_PRESS) {
521 if (mod == ShiftModifier)
522 cmd = FuncRequest(cmd0, "region-select");
523 else if (mod == ControlModifier)
524 cmd = FuncRequest(cmd0, "paragraph-select");
531 bool const notJustMovingTheMouse =
532 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
534 // In order to avoid bad surprise in the middle of an operation, we better stop
535 // the blinking cursor.
536 if (notJustMovingTheMouse)
537 p->stopBlinkingCursor();
539 buffer_view_->mouseEventDispatch(cmd);
541 // Skip these when selecting
542 // FIXME: let GuiView take care of those.
543 if (cmd.action() != LFUN_MOUSE_MOTION) {
544 completer_->updateVisibility(false, false);
545 lyx_view_->updateDialogs();
546 lyx_view_->updateStatusBar();
549 // GUI tweaks except with mouse motion with no button pressed.
550 if (notJustMovingTheMouse) {
551 // Slight hack: this is only called currently when we
552 // clicked somewhere, so we force through the display
553 // of the new status here.
554 // FIXME: let GuiView take care of those.
555 lyx_view_->clearMessage();
557 // Show the cursor immediately after any operation
558 p->startBlinkingCursor();
565 void GuiWorkArea::Private::resizeBufferView()
567 // WARNING: Please don't put any code that will trigger a repaint here!
568 // We are already inside a paint event.
569 p->stopBlinkingCursor();
570 // Warn our container (GuiView).
575 buffer_view_->cursorPosAndHeight(point, h);
576 bool const cursor_in_view = buffer_view_->cursorInView(point, h);
577 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
579 buffer_view_->scrollToCursor();
582 // Update scrollbars which might have changed due different
583 // BufferView dimension. This is especially important when the
584 // BufferView goes from zero-size to the real-size for the first time,
585 // as the scrollbar paramters are then set for the first time.
588 need_resize_ = false;
590 // Eventually, restart the cursor after the resize event.
591 // We might be resizing even if the focus is on another widget so we only
592 // restart the cursor if we have the focus.
594 QTimer::singleShot(50, p, SLOT(startBlinkingCursor()));
598 void GuiWorkArea::Private::showCursor()
605 buffer_view_->cursorPosAndHeight(p, h);
606 if (!buffer_view_->cursorInView(p, h))
610 bool l_shape = false;
611 Font const & realfont = buffer_view_->cursor().real_current_font;
612 BufferParams const & bp = buffer_view_->buffer().params();
613 bool const samelang = realfont.language() == bp.language;
614 bool const isrtl = realfont.isVisibleRightToLeft();
616 if (!samelang || isrtl != bp.language->rightToLeft())
619 // The ERT language hack needs fixing up
620 if (realfont.language() == latex_language)
623 // show cursor on screen
624 Cursor & cur = buffer_view_->cursor();
625 bool completable = cur.inset().showCompletionCursor()
626 && completer_->completionAvailable()
627 && !completer_->popupVisible()
628 && !completer_->inlineVisible();
629 cursor_visible_ = true;
630 cursor_->recomputeWidth();
631 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
635 void GuiWorkArea::Private::hideCursor()
637 if (!cursor_visible_)
640 cursor_visible_ = false;
645 void GuiWorkArea::toggleCursor()
647 if (d->cursor_visible_)
654 void GuiWorkArea::Private::updateScrollbar()
656 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
657 // WARNING: don't touch at the scrollbar value like this:
658 // verticalScrollBar()->setValue(scroll_.position);
659 // because this would cause a recursive signal/slot calling with
660 // GuiWorkArea::scrollTo
661 p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
662 p->verticalScrollBar()->setPageStep(scroll_.page_step);
663 p->verticalScrollBar()->setSingleStep(scroll_.single_step);
664 p->verticalScrollBar()->setSliderPosition(scroll_.position);
668 void GuiWorkArea::scrollTo(int value)
670 stopBlinkingCursor();
671 d->buffer_view_->scrollDocView(value, true);
673 if (lyxrc.cursor_follows_scrollbar) {
674 d->buffer_view_->setCursorFromScrollbar();
675 // FIXME: let GuiView take care of those.
676 d->lyx_view_->updateLayoutList();
678 // Show the cursor immediately after any operation.
679 startBlinkingCursor();
681 QApplication::syncX();
686 bool GuiWorkArea::event(QEvent * e)
689 case QEvent::ToolTip: {
690 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
691 if (lyxrc.use_tooltip) {
692 QPoint pos = helpEvent->pos();
693 if (pos.x() < viewport()->width()) {
694 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
695 QToolTip::showText(helpEvent->globalPos(), s);
698 QToolTip::hideText();
700 // Don't forget to accept the event!
705 case QEvent::ShortcutOverride: {
706 // We catch this event in order to catch the Tab or Shift+Tab key press
707 // which are otherwise reserved to focus switching between controls
709 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
710 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
711 || (ke->key() == Qt::Key_Backtab && (
712 ke->modifiers() == Qt::ShiftModifier
713 || ke->modifiers() == Qt::NoModifier))) {
717 return QAbstractScrollArea::event(e);
721 return QAbstractScrollArea::event(e);
727 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
730 if (e->reason() == QContextMenuEvent::Mouse)
731 // the menu name is set on mouse press
732 name = d->context_menu_name_;
734 QPoint pos = e->pos();
735 Cursor const & cur = d->buffer_view_->cursor();
736 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
737 // Do not access the context menu of math right in front of before
738 // the cursor. This does not work when the cursor is in text.
739 Inset * inset = cur.paragraph().getInset(cur.pos());
740 if (inset && inset->asInsetMath())
742 else if (cur.pos() > 0) {
743 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
748 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
752 QAbstractScrollArea::contextMenuEvent(e);
755 // always show mnemonics when the keyboard is used to show the context menu
756 // FIXME: This should be fixed in Qt itself
757 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
758 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
760 QAbstractScrollArea::contextMenuEvent(e);
763 // Position the menu to the right.
764 // FIXME: menu position should be different for RTL text.
765 menu->exec(e->globalPos());
770 void GuiWorkArea::focusInEvent(QFocusEvent * e)
772 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
773 if (d->lyx_view_->currentWorkArea() != this) {
774 d->lyx_view_->setCurrentWorkArea(this);
775 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
778 startBlinkingCursor();
779 QAbstractScrollArea::focusInEvent(e);
783 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
785 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
786 stopBlinkingCursor();
787 QAbstractScrollArea::focusOutEvent(e);
791 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
793 if (d->dc_event_.active && d->dc_event_ == *e) {
794 d->dc_event_.active = false;
795 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
796 q_button_state(e->button()));
802 #if (QT_VERSION < 0x050000)
803 inputContext()->reset();
806 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
807 q_button_state(e->button()));
808 d->dispatch(cmd, q_key_state(e->modifiers()));
810 // Save the context menu on mouse press, because also the mouse
811 // cursor is set on mouse press. Afterwards, we can either release
812 // the mousebutton somewhere else, or the cursor might have moved
813 // due to the DEPM. We need to do this after the mouse has been
814 // set in dispatch(), because the selection state might change.
815 if (e->button() == Qt::RightButton)
816 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
822 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
824 if (d->synthetic_mouse_event_.timeout.running())
825 d->synthetic_mouse_event_.timeout.stop();
827 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
828 q_button_state(e->button()));
834 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
836 // we kill the triple click if we move
837 doubleClickTimeout();
838 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
839 q_motion_state(e->buttons()));
843 // If we're above or below the work area...
844 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
845 && e->buttons() == mouse_button::button1) {
846 // Make sure only a synthetic event can cause a page scroll,
847 // so they come at a steady rate:
849 // _Force_ a scroll up:
850 cmd.set_y(e->y() - 21);
852 cmd.set_y(e->y() + 21);
853 // Store the event, to be handled when the timeout expires.
854 d->synthetic_mouse_event_.cmd = cmd;
856 if (d->synthetic_mouse_event_.timeout.running()) {
857 // Discard the event. Note that it _may_ be handled
858 // when the timeout expires if
859 // synthetic_mouse_event_.cmd has not been overwritten.
860 // Ie, when the timeout expires, we handle the
861 // most recent event but discard all others that
862 // occurred after the one used to start the timeout
863 // in the first place.
867 d->synthetic_mouse_event_.restart_timeout = true;
868 d->synthetic_mouse_event_.timeout.start();
869 // Fall through to handle this event...
871 } else if (d->synthetic_mouse_event_.timeout.running()) {
872 // Store the event, to be possibly handled when the timeout
874 // Once the timeout has expired, normal control is returned
875 // to mouseMoveEvent (restart_timeout = false).
876 // This results in a much smoother 'feel' when moving the
877 // mouse back into the work area.
878 d->synthetic_mouse_event_.cmd = cmd;
879 d->synthetic_mouse_event_.restart_timeout = false;
886 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
888 // Wheel rotation by one notch results in a delta() of 120 (see
889 // documentation of QWheelEvent)
890 double const delta = ev->delta() / 120.0;
892 switch (lyxrc.scroll_wheel_zoom) {
893 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
894 zoom = ev->modifiers() & Qt::ControlModifier;
895 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
897 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
898 zoom = ev->modifiers() & Qt::ShiftModifier;
899 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
901 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
902 zoom = ev->modifiers() & Qt::AltModifier;
903 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
905 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
909 docstring arg = convert<docstring>(int(5 * delta));
910 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
914 // Take into account the desktop wide settings.
915 int const lines = qApp->wheelScrollLines();
916 int const page_step = verticalScrollBar()->pageStep();
917 // Test if the wheel mouse is set to one screen at a time.
918 int scroll_value = lines > page_step
919 ? page_step : lines * verticalScrollBar()->singleStep();
921 // Take into account the rotation and the user preferences.
922 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
923 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
924 << " delta = " << delta << " scroll_value = " << scroll_value
925 << " page_step = " << page_step);
927 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
933 void GuiWorkArea::generateSyntheticMouseEvent()
935 int const e_y = d->synthetic_mouse_event_.cmd.y();
936 int const wh = d->buffer_view_->workHeight();
937 bool const up = e_y < 0;
938 bool const down = e_y > wh;
940 // Set things off to generate the _next_ 'pseudo' event.
942 if (d->synthetic_mouse_event_.restart_timeout) {
943 // This is some magic formulae to determine the speed
944 // of scrolling related to the position of the mouse.
947 int dist = up ? -e_y : e_y - wh;
948 time = max(min(200, 250000 / (dist * dist)), 1) ;
951 step = 80000 / (time * time);
955 d->synthetic_mouse_event_.timeout.setTimeout(time);
956 d->synthetic_mouse_event_.timeout.start();
959 // Can we scroll further ?
960 int const value = verticalScrollBar()->value();
961 if (value == verticalScrollBar()->maximum()
962 || value == verticalScrollBar()->minimum()) {
963 d->synthetic_mouse_event_.timeout.stop();
968 if (step <= 2 * wh) {
969 d->buffer_view_->scroll(up ? -step : step);
970 d->buffer_view_->updateMetrics();
972 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
975 // In which paragraph do we have to set the cursor ?
976 Cursor & cur = d->buffer_view_->cursor();
977 // FIXME: we don't know howto handle math.
978 Text * text = cur.text();
981 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
983 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
984 ParagraphMetrics const & pm = *pp.second;
985 pit_type const pit = pp.first;
987 if (pm.rows().empty())
990 // Find the row at which we set the cursor.
991 RowList::const_iterator rit = pm.rows().begin();
992 RowList::const_iterator rlast = pm.rows().end();
993 int yy = pm.position() - pm.ascent();
994 for (--rlast; rit != rlast; ++rit) {
995 int h = rit->height();
996 if ((up && yy + h > 0)
997 || (!up && yy + h > wh - defaultRowHeight()))
1002 // Find the position of the cursor
1004 int x = d->synthetic_mouse_event_.cmd.x();
1005 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1010 cur.boundary(bound);
1012 d->buffer_view_->buffer().changed(false);
1017 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1019 // Do not process here some keys if dialog_mode_ is set
1021 && (ev->modifiers() == Qt::NoModifier
1022 || ev->modifiers() == Qt::ShiftModifier)
1023 && (ev->key() == Qt::Key_Escape
1024 || ev->key() == Qt::Key_Enter
1025 || ev->key() == Qt::Key_Return)
1031 // intercept some keys if completion popup is visible
1032 if (d->completer_->popupVisible()) {
1033 switch (ev->key()) {
1035 case Qt::Key_Return:
1036 d->completer_->activate();
1042 // do nothing if there are other events
1043 // (the auto repeated events come too fast)
1044 // it looks like this is only needed on X11
1046 if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1047 switch (ev->key()) {
1048 case Qt::Key_PageDown:
1049 case Qt::Key_PageUp:
1054 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1061 KeyModifier m = q_key_state(ev->modifiers());
1064 if (m & ShiftModifier)
1066 if (m & ControlModifier)
1068 if (m & AltModifier)
1070 if (m & MetaModifier)
1073 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1074 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1075 << " keyState: " << str);
1078 setKeySymbol(&sym, ev);
1080 processKeySym(sym, q_key_state(ev->modifiers()));
1088 void GuiWorkArea::doubleClickTimeout()
1090 d->dc_event_.active = false;
1094 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1096 d->dc_event_ = DoubleClick(ev);
1097 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1098 SLOT(doubleClickTimeout()));
1099 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1101 q_button_state(ev->button()));
1107 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1109 QAbstractScrollArea::resizeEvent(ev);
1110 d->need_resize_ = true;
1115 void GuiWorkArea::Private::update(int x, int y, int w, int h)
1117 p->viewport()->update(x, y, w, h);
1121 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1123 QRect const rc = ev->rect();
1124 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1125 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1127 if (d->need_resize_) {
1129 d->resizeBufferView();
1130 if (d->cursor_visible_) {
1136 QPainter pain(viewport());
1137 if (lyxrc.use_qimage) {
1138 pain.drawImage(rc, static_cast<QImage const &>(*d->screen_), rc);
1140 pain.drawPixmap(rc, static_cast<QPixmap const &>(*d->screen_), rc);
1142 d->cursor_->draw(pain);
1147 void GuiWorkArea::Private::updateScreen()
1149 GuiPainter pain(screen_);
1150 buffer_view_->draw(pain);
1154 void GuiWorkArea::Private::showCursor(int x, int y, int h,
1155 bool l_shape, bool rtl, bool completable)
1157 if (schedule_redraw_) {
1158 // This happens when a graphic conversion is finished. As we don't know
1159 // the size of the new graphics, it's better the update everything.
1160 // We can't use redraw() here because this would trigger a infinite
1161 // recursive loop with showCursor().
1162 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
1165 p->viewport()->update(QRect(0, 0, p->viewport()->width(), p->viewport()->height()));
1166 schedule_redraw_ = false;
1167 // Show the cursor immediately after the update.
1173 cursor_->update(x, y, h, l_shape, rtl, completable);
1175 p->viewport()->update(cursor_->rect());
1179 void GuiWorkArea::Private::removeCursor()
1182 //if (!qApp->focusWidget())
1183 p->viewport()->update(cursor_->rect());
1187 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1189 QString const & commit_string = e->commitString();
1190 docstring const & preedit_string
1191 = qstring_to_ucs4(e->preeditString());
1193 if (!commit_string.isEmpty()) {
1195 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1196 << " commitString: " << e->commitString());
1200 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1201 for (int i = 0; i != commit_string.size(); ++i) {
1202 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1207 // Hide the cursor during the kana-kanji transformation.
1208 if (preedit_string.empty())
1209 startBlinkingCursor();
1211 stopBlinkingCursor();
1213 // last_width : for checking if last preedit string was/wasn't empty.
1215 // We could have more than one work area, right?
1216 static bool last_width = false;
1217 if (!last_width && preedit_string.empty()) {
1218 // if last_width is last length of preedit string.
1223 GuiPainter pain(d->screen_);
1224 d->buffer_view_->updateMetrics();
1225 d->buffer_view_->draw(pain);
1226 FontInfo font = d->buffer_view_->cursor().getFont().fontInfo();
1227 FontMetrics const & fm = theFontMetrics(font);
1228 int height = fm.maxHeight();
1229 int cur_x = d->cursor_->rect().left();
1230 int cur_y = d->cursor_->rect().bottom();
1232 // redraw area of preedit string.
1233 update(0, cur_y - height, viewport()->width(),
1234 (height + 1) * d->preedit_lines_);
1236 if (preedit_string.empty()) {
1238 d->preedit_lines_ = 1;
1244 // att : stores an IM attribute.
1245 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1247 // get attributes of input method cursor.
1248 // cursor_pos : cursor position in preedit string.
1249 size_t cursor_pos = 0;
1250 bool cursor_is_visible = false;
1251 for (int i = 0; i != att.size(); ++i) {
1252 if (att.at(i).type == QInputMethodEvent::Cursor) {
1253 cursor_pos = att.at(i).start;
1254 cursor_is_visible = att.at(i).length != 0;
1259 size_t preedit_length = preedit_string.length();
1261 // get position of selection in input method.
1262 // FIXME: isn't there a way to do this simplier?
1263 // rStart : cursor position in selected string in IM.
1265 // rLength : selected string length in IM.
1267 if (cursor_pos < preedit_length) {
1268 for (int i = 0; i != att.size(); ++i) {
1269 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1270 if (att.at(i).start <= int(cursor_pos)
1271 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1272 rStart = att.at(i).start;
1273 rLength = att.at(i).length;
1274 if (!cursor_is_visible)
1275 cursor_pos += rLength;
1282 rStart = cursor_pos;
1286 int const right_margin = d->buffer_view_->rightMargin();
1287 Painter::preedit_style ps;
1288 // Most often there would be only one line:
1289 d->preedit_lines_ = 1;
1290 for (size_t pos = 0; pos != preedit_length; ++pos) {
1291 char_type const typed_char = preedit_string[pos];
1292 // reset preedit string style
1293 ps = Painter::preedit_default;
1295 // if we reached the right extremity of the screen, go to next line.
1296 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1297 cur_x = right_margin;
1298 cur_y += height + 1;
1299 ++d->preedit_lines_;
1301 // preedit strings are displayed with dashed underline
1302 // and partial strings are displayed white on black indicating
1303 // that we are in selecting mode in the input method.
1304 // FIXME: rLength == preedit_length is not a changing condition
1305 // FIXME: should be put out of the loop.
1307 && pos < rStart + rLength
1308 && !(cursor_pos < rLength && rLength == preedit_length))
1309 ps = Painter::preedit_selecting;
1311 if (pos == cursor_pos
1312 && (cursor_pos < rLength && rLength == preedit_length))
1313 ps = Painter::preedit_cursor;
1315 // draw one character and update cur_x.
1316 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1319 // update the preedit string screen area.
1320 update(0, cur_y - d->preedit_lines_*height, viewport()->width(),
1321 (height + 1) * d->preedit_lines_);
1323 // Don't forget to accept the event!
1328 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1330 QRect cur_r(0, 0, 0, 0);
1332 // this is the CJK-specific composition window position and
1333 // the context menu position when the menu key is pressed.
1334 case Qt::ImMicroFocus:
1335 cur_r = d->cursor_->rect();
1336 if (d->preedit_lines_ != 1)
1338 cur_r.moveBottom(cur_r.bottom()
1339 + cur_r.height() * (d->preedit_lines_ - 1));
1340 // return lower right of cursor in LyX.
1343 return QWidget::inputMethodQuery(query);
1348 void GuiWorkArea::updateWindowTitle()
1350 docstring maximize_title;
1351 docstring minimize_title;
1353 Buffer const & buf = d->buffer_view_->buffer();
1354 FileName const file_name = buf.fileName();
1355 if (!file_name.empty()) {
1356 maximize_title = file_name.displayName(130);
1357 minimize_title = from_utf8(file_name.onlyFileName());
1358 if (buf.lyxvc().inUse()) {
1359 if (buf.lyxvc().locking())
1360 maximize_title += _(" (version control, locking)");
1362 maximize_title += _(" (version control)");
1364 if (!buf.isClean()) {
1365 maximize_title += _(" (changed)");
1366 minimize_title += char_type('*');
1368 if (buf.isReadonly())
1369 maximize_title += _(" (read only)");
1372 QString const new_title = toqstr(maximize_title);
1373 if (new_title != windowTitle()) {
1374 QWidget::setWindowTitle(new_title);
1375 QWidget::setWindowIconText(toqstr(minimize_title));
1381 bool GuiWorkArea::isFullScreen() const
1383 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1387 void GuiWorkArea::scheduleRedraw()
1389 d->schedule_redraw_ = true;
1393 bool GuiWorkArea::inDialogMode() const
1395 return d->dialog_mode_;
1399 void GuiWorkArea::setDialogMode(bool mode)
1401 d->dialog_mode_ = mode;
1405 GuiCompleter & GuiWorkArea::completer()
1407 return *d->completer_;
1410 GuiView const & GuiWorkArea::view() const
1412 return *d->lyx_view_;
1416 GuiView & GuiWorkArea::view()
1418 return *d->lyx_view_;
1421 ////////////////////////////////////////////////////////////////////
1425 ////////////////////////////////////////////////////////////////////
1428 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1430 support::TempFile tempfile("embedded.internal");
1431 tempfile.setAutoRemove(false);
1432 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1433 buffer_->setUnnamed(true);
1434 buffer_->setFullyLoaded(true);
1435 setBuffer(*buffer_);
1436 setDialogMode(true);
1440 EmbeddedWorkArea::~EmbeddedWorkArea()
1442 // No need to destroy buffer and bufferview here, because it is done
1443 // in theBufferList() destruction loop at application exit
1447 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1450 GuiWorkArea::closeEvent(ev);
1454 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1457 GuiWorkArea::hideEvent(ev);
1461 QSize EmbeddedWorkArea::sizeHint () const
1464 // GuiWorkArea sets the size to the screen's viewport
1465 // by returning a value this gets overridden
1466 // EmbeddedWorkArea is now sized to fit in the layout
1467 // of the parent, and has a minimum size set in GuiWorkArea
1468 // which is what we return here
1469 return QSize(100, 70);
1473 void EmbeddedWorkArea::disable()
1475 stopBlinkingCursor();
1476 if (view().currentWorkArea() != this)
1478 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1479 // tolerates it and shows the background logo), what happens if
1480 // an EmbeddedWorkArea is closed after closing all document WAs
1481 view().setCurrentWorkArea(view().currentMainWorkArea());
1484 ////////////////////////////////////////////////////////////////////
1488 ////////////////////////////////////////////////////////////////////
1491 class NoTabFrameMacStyle : public QMacStyle {
1494 QRect subElementRect(SubElement element, const QStyleOption * option,
1495 const QWidget * widget = 0) const
1497 QRect rect = QMacStyle::subElementRect(element, option, widget);
1498 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1500 // The Qt Mac style puts the contents into a 3 pixel wide box
1501 // which looks very ugly and not like other Mac applications.
1502 // Hence we remove this here, and moreover the 16 pixel round
1503 // frame above if the tab bar is hidden.
1504 if (element == QStyle::SE_TabWidgetTabContents) {
1505 rect.adjust(- rect.left(), 0, rect.left(), 0);
1514 NoTabFrameMacStyle noTabFrameMacStyle;
1518 TabWorkArea::TabWorkArea(QWidget * parent)
1519 : QTabWidget(parent), clicked_tab_(-1)
1522 setStyle(&noTabFrameMacStyle);
1525 QPalette pal = palette();
1526 pal.setColor(QPalette::Active, QPalette::Button,
1527 pal.color(QPalette::Active, QPalette::Window));
1528 pal.setColor(QPalette::Disabled, QPalette::Button,
1529 pal.color(QPalette::Disabled, QPalette::Window));
1530 pal.setColor(QPalette::Inactive, QPalette::Button,
1531 pal.color(QPalette::Inactive, QPalette::Window));
1533 QObject::connect(this, SIGNAL(currentChanged(int)),
1534 this, SLOT(on_currentTabChanged(int)));
1536 closeBufferButton = new QToolButton(this);
1537 closeBufferButton->setPalette(pal);
1538 // FIXME: rename the icon to closebuffer.png
1539 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1540 closeBufferButton->setText("Close File");
1541 closeBufferButton->setAutoRaise(true);
1542 closeBufferButton->setCursor(Qt::ArrowCursor);
1543 closeBufferButton->setToolTip(qt_("Close File"));
1544 closeBufferButton->setEnabled(true);
1545 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1546 this, SLOT(closeCurrentBuffer()));
1547 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1549 // setup drag'n'drop
1550 QTabBar* tb = new DragTabBar;
1551 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1552 this, SLOT(moveTab(int, int)));
1553 tb->setElideMode(Qt::ElideNone);
1556 // make us responsible for the context menu of the tabbar
1557 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1558 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1559 this, SLOT(showContextMenu(const QPoint &)));
1560 connect(tb, SIGNAL(tabCloseRequested(int)),
1561 this, SLOT(closeTab(int)));
1563 setUsesScrollButtons(true);
1567 void TabWorkArea::paintEvent(QPaintEvent * event)
1569 if (tabBar()->isVisible()) {
1570 QTabWidget::paintEvent(event);
1572 // Prevent the selected tab to influence the
1573 // painting of the frame of the tab widget.
1574 // This is needed for gtk style in Qt.
1575 QStylePainter p(this);
1576 #if QT_VERSION < 0x050000
1577 QStyleOptionTabWidgetFrameV2 opt;
1579 QStyleOptionTabWidgetFrame opt;
1581 initStyleOption(&opt);
1582 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1584 opt.selectedTabRect = QRect();
1585 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1590 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1592 if (event->button() != Qt::LeftButton)
1595 // return early if double click on existing tabs
1596 for (int i = 0; i < count(); ++i)
1597 if (tabBar()->tabRect(i).contains(event->pos()))
1600 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1604 void TabWorkArea::setFullScreen(bool full_screen)
1606 for (int i = 0; i != count(); ++i) {
1607 if (GuiWorkArea * wa = workArea(i))
1608 wa->setFullScreen(full_screen);
1611 if (lyxrc.full_screen_tabbar)
1612 showBar(!full_screen && count() > 1);
1614 showBar(count() > 1);
1618 void TabWorkArea::showBar(bool show)
1620 tabBar()->setEnabled(show);
1621 tabBar()->setVisible(show);
1622 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1623 setTabsClosable(!lyxrc.single_close_tab_button);
1627 GuiWorkArea * TabWorkArea::currentWorkArea()
1632 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1638 GuiWorkArea * TabWorkArea::workArea(int index)
1640 return dynamic_cast<GuiWorkArea *>(widget(index));
1644 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1646 // FIXME: this method doesn't work if we have more than work area
1647 // showing the same buffer.
1648 for (int i = 0; i != count(); ++i) {
1649 GuiWorkArea * wa = workArea(i);
1650 LASSERT(wa, return 0);
1651 if (&wa->bufferView().buffer() == &buffer)
1658 void TabWorkArea::closeAll()
1661 GuiWorkArea * wa = workArea(0);
1662 LASSERT(wa, return);
1669 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1671 LASSERT(work_area, return false);
1672 int index = indexOf(work_area);
1676 if (index == currentIndex())
1677 // Make sure the work area is up to date.
1678 on_currentTabChanged(index);
1680 // Switch to the work area.
1681 setCurrentIndex(index);
1682 work_area->setFocus();
1688 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1690 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1691 wa->setUpdatesEnabled(false);
1692 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1693 // when hiding it again below).
1694 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1695 showBar(count() > 0);
1696 addTab(wa, wa->windowTitle());
1697 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1698 this, SLOT(updateTabTexts()));
1699 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1700 setFullScreen(true);
1702 // Hide tabbar if there's only one tab.
1703 showBar(count() > 1);
1711 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1713 LASSERT(work_area, return false);
1714 int index = indexOf(work_area);
1718 work_area->setUpdatesEnabled(false);
1723 // make sure the next work area is enabled.
1724 currentWidget()->setUpdatesEnabled(true);
1725 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1726 setFullScreen(true);
1728 // Show tabbar only if there's more than one tab.
1729 showBar(count() > 1);
1731 lastWorkAreaRemoved();
1739 void TabWorkArea::on_currentTabChanged(int i)
1741 // returns e.g. on application destruction
1744 GuiWorkArea * wa = workArea(i);
1745 LASSERT(wa, return);
1746 wa->setUpdatesEnabled(true);
1750 currentWorkAreaChanged(wa);
1752 LYXERR(Debug::GUI, "currentTabChanged " << i
1753 << " File: " << wa->bufferView().buffer().absFileName());
1757 void TabWorkArea::closeCurrentBuffer()
1760 if (clicked_tab_ == -1)
1761 wa = currentWorkArea();
1763 wa = workArea(clicked_tab_);
1764 LASSERT(wa, return);
1766 wa->view().closeWorkArea(wa);
1770 void TabWorkArea::hideCurrentTab()
1773 if (clicked_tab_ == -1)
1774 wa = currentWorkArea();
1776 wa = workArea(clicked_tab_);
1777 LASSERT(wa, return);
1779 wa->view().hideWorkArea(wa);
1783 void TabWorkArea::closeTab(int index)
1785 on_currentTabChanged(index);
1788 wa = currentWorkArea();
1790 wa = workArea(index);
1791 LASSERT(wa, return);
1793 wa->view().closeWorkArea(wa);
1800 /// make vector happy
1803 DisplayPath(int tab, FileName const & filename)
1806 filename_ = (filename.extension() == "lyx") ?
1807 toqstr(filename.onlyFileNameWithoutExt())
1808 : toqstr(filename.onlyFileName());
1809 postfix_ = toqstr(filename.absoluteFilePath()).
1810 split("/", QString::SkipEmptyParts);
1811 postfix_.pop_back();
1812 abs_ = toqstr(filename.absoluteFilePath());
1813 dottedPrefix_ = false;
1816 /// Absolute path for debugging.
1821 /// Add the first segment from the postfix or three dots to the prefix.
1822 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1823 /// when really needed.
1824 void shiftPathSegment(bool dotted)
1826 if (postfix_.count() <= 0)
1830 if (dottedPrefix_ && !prefix_.isEmpty())
1832 prefix_ += postfix_.front() + "/";
1834 dottedPrefix_ = dotted && !prefix_.isEmpty();
1835 postfix_.pop_front();
1838 QString displayString() const
1840 if (prefix_.isEmpty())
1843 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1844 return prefix_ + (dots ? ".../" : "") + filename_;
1847 QString forecastPathString() const
1849 if (postfix_.count() == 0)
1850 return displayString();
1853 + (dottedPrefix_ ? ".../" : "")
1854 + postfix_.front() + "/";
1857 bool final() const { return postfix_.empty(); }
1859 int tab() const { return tab_; }
1865 QStringList postfix_;
1878 bool operator<(DisplayPath const & a, DisplayPath const & b)
1880 return a.displayString() < b.displayString();
1884 bool operator==(DisplayPath const & a, DisplayPath const & b)
1886 return a.displayString() == b.displayString();
1890 void TabWorkArea::updateTabTexts()
1895 std::list<DisplayPath> paths;
1896 typedef std::list<DisplayPath>::iterator It;
1898 // collect full names first: path into postfix, empty prefix and
1899 // filename without extension
1900 for (size_t i = 0; i < n; ++i) {
1901 GuiWorkArea * i_wa = workArea(i);
1902 FileName const fn = i_wa->bufferView().buffer().fileName();
1903 paths.push_back(DisplayPath(i, fn));
1906 // go through path segments and see if it helps to make the path more unique
1907 bool somethingChanged = true;
1908 bool allFinal = false;
1909 while (somethingChanged && !allFinal) {
1910 // adding path segments changes order
1913 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1914 somethingChanged = false;
1917 // find segments which are not unique (i.e. non-atomic)
1918 It it = paths.begin();
1920 QString segString = it->displayString();
1921 for (; it != paths.end(); ++it) {
1922 // look to the next item
1927 allFinal = allFinal && it->final();
1929 LYXERR(Debug::GUI, "it = " << it->abs()
1930 << " => " << it->displayString());
1932 // still the same segment?
1934 if ((next != paths.end()
1935 && (nextString = next->displayString()) == segString))
1937 LYXERR(Debug::GUI, "segment ended");
1939 // only a trivial one with one element?
1940 if (it == segStart) {
1941 // start new segment
1943 segString = nextString;
1947 // we found a non-atomic segment segStart <= sit <= it < next.
1948 // Shift path segments and hope for the best
1949 // that it makes the path more unique.
1950 somethingChanged = true;
1952 QString dspString = sit->forecastPathString();
1953 LYXERR(Debug::GUI, "first forecast found for "
1954 << sit->abs() << " => " << dspString);
1956 bool moreUnique = false;
1957 for (; sit != next; ++sit) {
1958 if (sit->forecastPathString() != dspString) {
1959 LYXERR(Debug::GUI, "different forecast found for "
1960 << sit->abs() << " => " << sit->forecastPathString());
1964 LYXERR(Debug::GUI, "same forecast found for "
1965 << sit->abs() << " => " << dspString);
1968 // if the path segment helped, add it. Otherwise add dots
1969 bool dots = !moreUnique;
1970 LYXERR(Debug::GUI, "using dots = " << dots);
1971 for (sit = segStart; sit != next; ++sit) {
1972 sit->shiftPathSegment(dots);
1973 LYXERR(Debug::GUI, "shifting "
1974 << sit->abs() << " => " << sit->displayString());
1977 // start new segment
1979 segString = nextString;
1983 // set new tab titles
1984 for (It it = paths.begin(); it != paths.end(); ++it) {
1985 int const tab_index = it->tab();
1986 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
1987 QString tab_text = it->displayString().replace("&", "&&");
1988 if (!buf.fileName().empty() && !buf.isClean())
1990 setTabText(tab_index, tab_text);
1991 setTabToolTip(tab_index, it->abs());
1996 void TabWorkArea::showContextMenu(const QPoint & pos)
1999 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
2000 if (clicked_tab_ == -1)
2005 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
2006 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2007 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
2008 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2009 popup.exec(tabBar()->mapToGlobal(pos));
2015 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2017 QWidget * w = widget(fromIndex);
2018 QIcon icon = tabIcon(fromIndex);
2019 QString text = tabText(fromIndex);
2021 setCurrentIndex(fromIndex);
2022 removeTab(fromIndex);
2023 insertTab(toIndex, w, icon, text);
2024 setCurrentIndex(toIndex);
2028 DragTabBar::DragTabBar(QWidget* parent)
2031 setAcceptDrops(true);
2032 setTabsClosable(!lyxrc.single_close_tab_button);
2036 void DragTabBar::mousePressEvent(QMouseEvent * event)
2038 if (event->button() == Qt::LeftButton)
2039 dragStartPos_ = event->pos();
2040 QTabBar::mousePressEvent(event);
2044 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2046 // If the left button isn't pressed anymore then return
2047 if (!(event->buttons() & Qt::LeftButton))
2050 // If the distance is too small then return
2051 if ((event->pos() - dragStartPos_).manhattanLength()
2052 < QApplication::startDragDistance())
2055 // did we hit something after all?
2056 int tab = tabAt(dragStartPos_);
2060 // simulate button release to remove highlight from button
2061 int i = currentIndex();
2062 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2063 event->button(), event->buttons(), 0);
2064 QTabBar::mouseReleaseEvent(&me);
2068 QDrag * drag = new QDrag(this);
2069 QMimeData * mimeData = new QMimeData;
2070 // a crude way to distinguish tab-reodering drops from other ones
2071 mimeData->setData("action", "tab-reordering") ;
2072 drag->setMimeData(mimeData);
2074 // get tab pixmap as cursor
2075 QRect r = tabRect(tab);
2076 QPixmap pixmap(r.size());
2077 render(&pixmap, - r.topLeft());
2078 drag->setPixmap(pixmap);
2083 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2085 // Only accept if it's an tab-reordering request
2086 QMimeData const * m = event->mimeData();
2087 QStringList formats = m->formats();
2088 if (formats.contains("action")
2089 && m->data("action") == "tab-reordering")
2090 event->acceptProposedAction();
2094 void DragTabBar::dropEvent(QDropEvent * event)
2096 int fromIndex = tabAt(dragStartPos_);
2097 int toIndex = tabAt(event->pos());
2099 // Tell interested objects that
2100 if (fromIndex != toIndex)
2101 tabMoveRequested(fromIndex, toIndex);
2102 event->acceptProposedAction();
2106 } // namespace frontend
2109 #include "moc_GuiWorkArea.cpp"