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>
65 #include <QProxyStyle>
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),
250 completer_(new GuiCompleter(p, p))
255 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
256 : d(new Private(this))
261 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
262 : d(new Private(this))
265 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
271 double GuiWorkArea::pixelRatio() const
273 #if QT_VERSION >= 0x050000
274 return devicePixelRatio();
281 void GuiWorkArea::init()
284 connect(&d->cursor_timeout_, SIGNAL(timeout()),
285 this, SLOT(toggleCursor()));
287 int const time = QApplication::cursorFlashTime() / 2;
289 d->cursor_timeout_.setInterval(time);
290 d->cursor_timeout_.start();
292 // let's initialize this just to be safe
293 d->cursor_timeout_.setInterval(500);
297 // With Qt4.5 a mouse event will happen before the first paint event
298 // so make sure that the buffer view has an up to date metrics.
299 d->buffer_view_->resize(viewport()->width(), viewport()->height());
300 d->cursor_ = new frontend::CursorWidget();
303 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
304 setAcceptDrops(true);
305 setMouseTracking(true);
306 setMinimumSize(100, 70);
307 setFrameStyle(QFrame::NoFrame);
310 viewport()->setAutoFillBackground(false);
311 // We don't need double-buffering nor SystemBackground on
312 // the viewport because we have our own backing pixmap.
313 viewport()->setAttribute(Qt::WA_NoSystemBackground);
315 setFocusPolicy(Qt::StrongFocus);
317 d->setCursorShape(Qt::IBeamCursor);
319 d->synthetic_mouse_event_.timeout.timeout.connect(
320 bind(&GuiWorkArea::generateSyntheticMouseEvent,
323 // Initialize the vertical Scroll Bar
324 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
325 this, SLOT(scrollTo(int)));
327 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
328 << " viewport height: " << viewport()->height());
330 // Enables input methods for asian languages.
331 // Must be set when creating custom text editing widgets.
332 setAttribute(Qt::WA_InputMethodEnabled, true);
334 d->dialog_mode_ = false;
338 GuiWorkArea::~GuiWorkArea()
340 d->buffer_view_->buffer().workAreaManager().remove(this);
342 delete d->buffer_view_;
344 // Completer has a QObject parent and is thus automatically destroyed.
346 // delete completer_;
351 Qt::CursorShape GuiWorkArea::cursorShape() const
353 return viewport()->cursor().shape();
357 void GuiWorkArea::Private::setCursorShape(Qt::CursorShape shape)
359 p->viewport()->setCursor(shape);
363 void GuiWorkArea::Private::updateCursorShape()
365 setCursorShape(buffer_view_->clickableInset()
366 ? Qt::PointingHandCursor : Qt::IBeamCursor);
370 void GuiWorkArea::setGuiView(GuiView & gv)
376 void GuiWorkArea::setBuffer(Buffer & buffer)
378 delete d->buffer_view_;
379 d->buffer_view_ = new BufferView(buffer);
380 buffer.workAreaManager().add(this);
382 // HACK: Prevents an additional redraw when the scrollbar pops up
383 // which regularily happens on documents with more than one page.
384 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
385 // Since we have no geometry information yet, we assume that
386 // a document needs a scrollbar if there is more then four
387 // paragraph in the outermost text.
388 if (buffer.text().paragraphs().size() > 4)
389 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
390 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
394 void GuiWorkArea::fixVerticalScrollBar()
397 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
401 void GuiWorkArea::close()
403 d->lyx_view_->removeWorkArea(this);
407 void GuiWorkArea::setFullScreen(bool full_screen)
409 d->buffer_view_->setFullScreen(full_screen);
410 setFrameStyle(QFrame::NoFrame);
412 setFrameStyle(QFrame::NoFrame);
413 if (lyxrc.full_screen_scrollbar)
414 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
416 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
420 BufferView & GuiWorkArea::bufferView()
422 return *d->buffer_view_;
426 BufferView const & GuiWorkArea::bufferView() const
428 return *d->buffer_view_;
432 void GuiWorkArea::stopBlinkingCursor()
434 d->cursor_timeout_.stop();
439 void GuiWorkArea::startBlinkingCursor()
441 // do not show the cursor if the view is busy
447 d->buffer_view_->cursorPosAndHeight(p, h);
448 // Don't start blinking if the cursor isn't on screen.
449 if (!d->buffer_view_->cursorInView(p, h))
454 //we're not supposed to cache this value.
455 int const time = QApplication::cursorFlashTime() / 2;
458 d->cursor_timeout_.setInterval(time);
459 d->cursor_timeout_.start();
463 void GuiWorkArea::redraw(bool update_metrics)
466 // No need to redraw in this case.
469 // No need to do anything if this is the current view. The BufferView
470 // metrics are already up to date.
471 if (update_metrics || d->lyx_view_ != guiApp->currentView()
472 || d->lyx_view_->currentWorkArea() != this) {
473 // FIXME: it would be nice to optimize for the off-screen case.
474 d->buffer_view_->cursor().fixIfBroken();
475 d->buffer_view_->updateMetrics();
476 d->buffer_view_->cursor().fixIfBroken();
479 // update cursor position, because otherwise it has to wait until
480 // the blinking interval is over
481 if (d->cursor_visible_) {
486 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
488 update(0, 0, viewport()->width(), viewport()->height());
490 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
491 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
492 d->updateScrollbar();
493 d->lyx_view_->updateStatusBar();
495 if (lyxerr.debugging(Debug::WORKAREA))
496 d->buffer_view_->coordCache().dump();
500 d->updateCursorShape();
504 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
506 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
507 && lyxrc.full_screen_menubar) {
508 // FIXME HACK: we should not have to do this here. See related comment
509 // in GuiView::event() (QEvent::ShortcutOverride)
510 d->lyx_view_->menuBar()->hide();
513 // In order to avoid bad surprise in the middle of an operation,
514 // we better stop the blinking cursor...
515 // the cursor gets restarted in GuiView::restartCursor()
516 stopBlinkingCursor();
517 guiApp->processKeySym(key, mod);
521 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd0, KeyModifier mod)
524 if (cmd0.action() == LFUN_FILE_OPEN) {
526 lyx_view_->dispatch(cmd0, dr);
532 if (cmd0.action() == LFUN_MOUSE_PRESS) {
533 if (mod == ShiftModifier)
534 cmd = FuncRequest(cmd0, "region-select");
535 else if (mod == ControlModifier)
536 cmd = FuncRequest(cmd0, "paragraph-select");
543 bool const notJustMovingTheMouse =
544 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
546 // In order to avoid bad surprise in the middle of an operation, we better stop
547 // the blinking cursor.
548 if (notJustMovingTheMouse)
549 p->stopBlinkingCursor();
551 buffer_view_->mouseEventDispatch(cmd);
553 // Skip these when selecting
554 // FIXME: let GuiView take care of those.
555 if (cmd.action() != LFUN_MOUSE_MOTION) {
556 completer_->updateVisibility(false, false);
557 lyx_view_->updateDialogs();
558 lyx_view_->updateStatusBar();
561 // GUI tweaks except with mouse motion with no button pressed.
562 if (notJustMovingTheMouse) {
563 // Slight hack: this is only called currently when we
564 // clicked somewhere, so we force through the display
565 // of the new status here.
566 // FIXME: let GuiView take care of those.
567 lyx_view_->clearMessage();
569 // Show the cursor immediately after any operation
570 p->startBlinkingCursor();
577 void GuiWorkArea::Private::resizeBufferView()
579 // WARNING: Please don't put any code that will trigger a repaint here!
580 // We are already inside a paint event.
581 p->stopBlinkingCursor();
582 // Warn our container (GuiView).
587 buffer_view_->cursorPosAndHeight(point, h);
588 bool const cursor_in_view = buffer_view_->cursorInView(point, h);
589 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
591 buffer_view_->scrollToCursor();
594 // Update scrollbars which might have changed due different
595 // BufferView dimension. This is especially important when the
596 // BufferView goes from zero-size to the real-size for the first time,
597 // as the scrollbar paramters are then set for the first time.
600 need_resize_ = false;
602 // Eventually, restart the cursor after the resize event.
603 // We might be resizing even if the focus is on another widget so we only
604 // restart the cursor if we have the focus.
606 QTimer::singleShot(50, p, SLOT(startBlinkingCursor()));
610 void GuiWorkArea::Private::showCursor()
617 buffer_view_->cursorPosAndHeight(p, h);
618 if (!buffer_view_->cursorInView(p, h))
622 bool l_shape = false;
623 Font const & realfont = buffer_view_->cursor().real_current_font;
624 BufferParams const & bp = buffer_view_->buffer().params();
625 bool const samelang = realfont.language() == bp.language;
626 bool const isrtl = realfont.isVisibleRightToLeft();
628 if (!samelang || isrtl != bp.language->rightToLeft())
631 // The ERT language hack needs fixing up
632 if (realfont.language() == latex_language)
635 // show cursor on screen
636 Cursor & cur = buffer_view_->cursor();
637 bool completable = cur.inset().showCompletionCursor()
638 && completer_->completionAvailable()
639 && !completer_->popupVisible()
640 && !completer_->inlineVisible();
641 cursor_visible_ = true;
642 cursor_->recomputeWidth();
644 //int cur_x = buffer_view_->getPos(cur).x_;
645 // We may have decided to slide the cursor row so that cursor
647 p.x_ -= buffer_view_->horizScrollOffset();
649 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
653 void GuiWorkArea::Private::hideCursor()
655 if (!cursor_visible_)
658 cursor_visible_ = false;
663 void GuiWorkArea::toggleCursor()
665 if (d->cursor_visible_)
672 void GuiWorkArea::Private::updateScrollbar()
674 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
675 // WARNING: don't touch at the scrollbar value like this:
676 // verticalScrollBar()->setValue(scroll_.position);
677 // because this would cause a recursive signal/slot calling with
678 // GuiWorkArea::scrollTo
679 p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
680 p->verticalScrollBar()->setPageStep(scroll_.page_step);
681 p->verticalScrollBar()->setSingleStep(scroll_.single_step);
682 p->verticalScrollBar()->setSliderPosition(scroll_.position);
686 void GuiWorkArea::scrollTo(int value)
688 stopBlinkingCursor();
689 d->buffer_view_->scrollDocView(value, true);
691 if (lyxrc.cursor_follows_scrollbar) {
692 d->buffer_view_->setCursorFromScrollbar();
693 // FIXME: let GuiView take care of those.
694 d->lyx_view_->updateLayoutList();
696 // Show the cursor immediately after any operation.
697 startBlinkingCursor();
699 QApplication::syncX();
704 bool GuiWorkArea::event(QEvent * e)
707 case QEvent::ToolTip: {
708 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
709 if (lyxrc.use_tooltip) {
710 QPoint pos = helpEvent->pos();
711 if (pos.x() < viewport()->width()) {
712 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
713 QToolTip::showText(helpEvent->globalPos(), s);
716 QToolTip::hideText();
718 // Don't forget to accept the event!
723 case QEvent::ShortcutOverride: {
724 // We catch this event in order to catch the Tab or Shift+Tab key press
725 // which are otherwise reserved to focus switching between controls
727 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
728 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
729 || (ke->key() == Qt::Key_Backtab && (
730 ke->modifiers() == Qt::ShiftModifier
731 || ke->modifiers() == Qt::NoModifier))) {
735 return QAbstractScrollArea::event(e);
739 return QAbstractScrollArea::event(e);
745 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
748 if (e->reason() == QContextMenuEvent::Mouse)
749 // the menu name is set on mouse press
750 name = d->context_menu_name_;
752 QPoint pos = e->pos();
753 Cursor const & cur = d->buffer_view_->cursor();
754 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
755 // Do not access the context menu of math right in front of before
756 // the cursor. This does not work when the cursor is in text.
757 Inset * inset = cur.paragraph().getInset(cur.pos());
758 if (inset && inset->asInsetMath())
760 else if (cur.pos() > 0) {
761 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
766 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
770 QAbstractScrollArea::contextMenuEvent(e);
773 // always show mnemonics when the keyboard is used to show the context menu
774 // FIXME: This should be fixed in Qt itself
775 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
776 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
778 QAbstractScrollArea::contextMenuEvent(e);
781 // Position the menu to the right.
782 // FIXME: menu position should be different for RTL text.
783 menu->exec(e->globalPos());
788 void GuiWorkArea::focusInEvent(QFocusEvent * e)
790 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
791 if (d->lyx_view_->currentWorkArea() != this) {
792 d->lyx_view_->setCurrentWorkArea(this);
793 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
796 startBlinkingCursor();
797 QAbstractScrollArea::focusInEvent(e);
801 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
803 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
804 stopBlinkingCursor();
805 QAbstractScrollArea::focusOutEvent(e);
809 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
811 if (d->dc_event_.active && d->dc_event_ == *e) {
812 d->dc_event_.active = false;
813 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
814 q_button_state(e->button()));
820 #if (QT_VERSION < 0x050000)
821 inputContext()->reset();
824 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
825 q_button_state(e->button()));
826 d->dispatch(cmd, q_key_state(e->modifiers()));
828 // Save the context menu on mouse press, because also the mouse
829 // cursor is set on mouse press. Afterwards, we can either release
830 // the mousebutton somewhere else, or the cursor might have moved
831 // due to the DEPM. We need to do this after the mouse has been
832 // set in dispatch(), because the selection state might change.
833 if (e->button() == Qt::RightButton)
834 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
840 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
842 if (d->synthetic_mouse_event_.timeout.running())
843 d->synthetic_mouse_event_.timeout.stop();
845 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
846 q_button_state(e->button()));
852 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
854 // we kill the triple click if we move
855 doubleClickTimeout();
856 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
857 q_motion_state(e->buttons()));
861 // If we're above or below the work area...
862 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
863 && e->buttons() == mouse_button::button1) {
864 // Make sure only a synthetic event can cause a page scroll,
865 // so they come at a steady rate:
867 // _Force_ a scroll up:
868 cmd.set_y(e->y() - 21);
870 cmd.set_y(e->y() + 21);
871 // Store the event, to be handled when the timeout expires.
872 d->synthetic_mouse_event_.cmd = cmd;
874 if (d->synthetic_mouse_event_.timeout.running()) {
875 // Discard the event. Note that it _may_ be handled
876 // when the timeout expires if
877 // synthetic_mouse_event_.cmd has not been overwritten.
878 // Ie, when the timeout expires, we handle the
879 // most recent event but discard all others that
880 // occurred after the one used to start the timeout
881 // in the first place.
885 d->synthetic_mouse_event_.restart_timeout = true;
886 d->synthetic_mouse_event_.timeout.start();
887 // Fall through to handle this event...
889 } else if (d->synthetic_mouse_event_.timeout.running()) {
890 // Store the event, to be possibly handled when the timeout
892 // Once the timeout has expired, normal control is returned
893 // to mouseMoveEvent (restart_timeout = false).
894 // This results in a much smoother 'feel' when moving the
895 // mouse back into the work area.
896 d->synthetic_mouse_event_.cmd = cmd;
897 d->synthetic_mouse_event_.restart_timeout = false;
904 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
906 // Wheel rotation by one notch results in a delta() of 120 (see
907 // documentation of QWheelEvent)
908 double const delta = ev->delta() / 120.0;
910 switch (lyxrc.scroll_wheel_zoom) {
911 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
912 zoom = ev->modifiers() & Qt::ControlModifier;
913 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
915 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
916 zoom = ev->modifiers() & Qt::ShiftModifier;
917 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
919 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
920 zoom = ev->modifiers() & Qt::AltModifier;
921 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
923 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
927 docstring arg = convert<docstring>(int(5 * delta));
928 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
932 // Take into account the desktop wide settings.
933 int const lines = qApp->wheelScrollLines();
934 int const page_step = verticalScrollBar()->pageStep();
935 // Test if the wheel mouse is set to one screen at a time.
936 int scroll_value = lines > page_step
937 ? page_step : lines * verticalScrollBar()->singleStep();
939 // Take into account the rotation and the user preferences.
940 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
941 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
942 << " delta = " << delta << " scroll_value = " << scroll_value
943 << " page_step = " << page_step);
945 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
951 void GuiWorkArea::generateSyntheticMouseEvent()
953 int const e_y = d->synthetic_mouse_event_.cmd.y();
954 int const wh = d->buffer_view_->workHeight();
955 bool const up = e_y < 0;
956 bool const down = e_y > wh;
958 // Set things off to generate the _next_ 'pseudo' event.
960 if (d->synthetic_mouse_event_.restart_timeout) {
961 // This is some magic formulae to determine the speed
962 // of scrolling related to the position of the mouse.
965 int dist = up ? -e_y : e_y - wh;
966 time = max(min(200, 250000 / (dist * dist)), 1) ;
969 step = 80000 / (time * time);
973 d->synthetic_mouse_event_.timeout.setTimeout(time);
974 d->synthetic_mouse_event_.timeout.start();
977 // Can we scroll further ?
978 int const value = verticalScrollBar()->value();
979 if (value == verticalScrollBar()->maximum()
980 || value == verticalScrollBar()->minimum()) {
981 d->synthetic_mouse_event_.timeout.stop();
986 if (step <= 2 * wh) {
987 d->buffer_view_->scroll(up ? -step : step);
988 d->buffer_view_->updateMetrics();
990 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
993 // In which paragraph do we have to set the cursor ?
994 Cursor & cur = d->buffer_view_->cursor();
995 // FIXME: we don't know howto handle math.
996 Text * text = cur.text();
999 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
1001 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
1002 ParagraphMetrics const & pm = *pp.second;
1003 pit_type const pit = pp.first;
1005 if (pm.rows().empty())
1008 // Find the row at which we set the cursor.
1009 RowList::const_iterator rit = pm.rows().begin();
1010 RowList::const_iterator rlast = pm.rows().end();
1011 int yy = pm.position() - pm.ascent();
1012 for (--rlast; rit != rlast; ++rit) {
1013 int h = rit->height();
1014 if ((up && yy + h > 0)
1015 || (!up && yy + h > wh - defaultRowHeight()))
1020 // Find the position of the cursor
1022 int x = d->synthetic_mouse_event_.cmd.x();
1023 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1028 cur.boundary(bound);
1030 d->buffer_view_->buffer().changed(false);
1035 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1037 // Do not process here some keys if dialog_mode_ is set
1039 && (ev->modifiers() == Qt::NoModifier
1040 || ev->modifiers() == Qt::ShiftModifier)
1041 && (ev->key() == Qt::Key_Escape
1042 || ev->key() == Qt::Key_Enter
1043 || ev->key() == Qt::Key_Return)
1049 // intercept some keys if completion popup is visible
1050 if (d->completer_->popupVisible()) {
1051 switch (ev->key()) {
1053 case Qt::Key_Return:
1054 d->completer_->activate();
1060 // do nothing if there are other events
1061 // (the auto repeated events come too fast)
1062 // it looks like this is only needed on X11
1064 if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1065 switch (ev->key()) {
1066 case Qt::Key_PageDown:
1067 case Qt::Key_PageUp:
1072 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1079 KeyModifier m = q_key_state(ev->modifiers());
1082 if (m & ShiftModifier)
1084 if (m & ControlModifier)
1086 if (m & AltModifier)
1088 if (m & MetaModifier)
1091 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1092 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1093 << " keyState: " << str);
1096 setKeySymbol(&sym, ev);
1098 processKeySym(sym, q_key_state(ev->modifiers()));
1106 void GuiWorkArea::doubleClickTimeout()
1108 d->dc_event_.active = false;
1112 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1114 d->dc_event_ = DoubleClick(ev);
1115 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1116 SLOT(doubleClickTimeout()));
1117 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1119 q_button_state(ev->button()));
1125 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1127 QAbstractScrollArea::resizeEvent(ev);
1128 d->need_resize_ = true;
1133 void GuiWorkArea::Private::update(int x, int y, int w, int h)
1135 p->viewport()->update(x, y, w, h);
1139 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1141 QRectF const rc = ev->rect();
1142 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1143 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1145 if (d->needResize()) {
1147 d->resizeBufferView();
1148 if (d->cursor_visible_) {
1154 QPainter pain(viewport());
1155 double const pr = pixelRatio();
1156 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr, rc.width() * pr, rc.height() * pr);
1158 if (lyxrc.use_qimage) {
1159 QImage const & image = static_cast<QImage const &>(*d->screen_);
1160 pain.drawImage(rc, image, rcs);
1162 QPixmap const & pixmap = static_cast<QPixmap const &>(*d->screen_);
1163 pain.drawPixmap(rc, pixmap, rcs);
1165 d->cursor_->draw(pain);
1170 void GuiWorkArea::Private::updateScreen()
1172 GuiPainter pain(screen_, p->pixelRatio());
1173 buffer_view_->draw(pain);
1177 void GuiWorkArea::Private::showCursor(int x, int y, int h,
1178 bool l_shape, bool rtl, bool completable)
1180 if (schedule_redraw_) {
1181 // This happens when a graphic conversion is finished. As we don't know
1182 // the size of the new graphics, it's better the update everything.
1183 // We can't use redraw() here because this would trigger a infinite
1184 // recursive loop with showCursor().
1185 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
1188 p->viewport()->update(QRect(0, 0, p->viewport()->width(), p->viewport()->height()));
1189 schedule_redraw_ = false;
1190 // Show the cursor immediately after the update.
1196 cursor_->update(x, y, h, l_shape, rtl, completable);
1198 p->viewport()->update(cursor_->rect());
1202 void GuiWorkArea::Private::removeCursor()
1205 //if (!qApp->focusWidget())
1206 p->viewport()->update(cursor_->rect());
1210 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1212 QString const & commit_string = e->commitString();
1213 docstring const & preedit_string
1214 = qstring_to_ucs4(e->preeditString());
1216 if (!commit_string.isEmpty()) {
1218 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1219 << " commitString: " << e->commitString());
1223 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1224 for (int i = 0; i != commit_string.size(); ++i) {
1225 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1230 // Hide the cursor during the kana-kanji transformation.
1231 if (preedit_string.empty())
1232 startBlinkingCursor();
1234 stopBlinkingCursor();
1236 // last_width : for checking if last preedit string was/wasn't empty.
1238 // We could have more than one work area, right?
1239 static bool last_width = false;
1240 if (!last_width && preedit_string.empty()) {
1241 // if last_width is last length of preedit string.
1246 GuiPainter pain(d->screen_, pixelRatio());
1247 d->buffer_view_->updateMetrics();
1248 d->buffer_view_->draw(pain);
1249 FontInfo font = d->buffer_view_->cursor().getFont().fontInfo();
1250 FontMetrics const & fm = theFontMetrics(font);
1251 int height = fm.maxHeight();
1252 int cur_x = d->cursor_->rect().left();
1253 int cur_y = d->cursor_->rect().bottom();
1255 // redraw area of preedit string.
1256 update(0, cur_y - height, viewport()->width(),
1257 (height + 1) * d->preedit_lines_);
1259 if (preedit_string.empty()) {
1261 d->preedit_lines_ = 1;
1267 // att : stores an IM attribute.
1268 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1270 // get attributes of input method cursor.
1271 // cursor_pos : cursor position in preedit string.
1272 size_t cursor_pos = 0;
1273 bool cursor_is_visible = false;
1274 for (int i = 0; i != att.size(); ++i) {
1275 if (att.at(i).type == QInputMethodEvent::Cursor) {
1276 cursor_pos = att.at(i).start;
1277 cursor_is_visible = att.at(i).length != 0;
1282 size_t preedit_length = preedit_string.length();
1284 // get position of selection in input method.
1285 // FIXME: isn't there a way to do this simplier?
1286 // rStart : cursor position in selected string in IM.
1288 // rLength : selected string length in IM.
1290 if (cursor_pos < preedit_length) {
1291 for (int i = 0; i != att.size(); ++i) {
1292 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1293 if (att.at(i).start <= int(cursor_pos)
1294 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1295 rStart = att.at(i).start;
1296 rLength = att.at(i).length;
1297 if (!cursor_is_visible)
1298 cursor_pos += rLength;
1305 rStart = cursor_pos;
1309 int const right_margin = d->buffer_view_->rightMargin();
1310 Painter::preedit_style ps;
1311 // Most often there would be only one line:
1312 d->preedit_lines_ = 1;
1313 for (size_t pos = 0; pos != preedit_length; ++pos) {
1314 char_type const typed_char = preedit_string[pos];
1315 // reset preedit string style
1316 ps = Painter::preedit_default;
1318 // if we reached the right extremity of the screen, go to next line.
1319 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1320 cur_x = right_margin;
1321 cur_y += height + 1;
1322 ++d->preedit_lines_;
1324 // preedit strings are displayed with dashed underline
1325 // and partial strings are displayed white on black indicating
1326 // that we are in selecting mode in the input method.
1327 // FIXME: rLength == preedit_length is not a changing condition
1328 // FIXME: should be put out of the loop.
1330 && pos < rStart + rLength
1331 && !(cursor_pos < rLength && rLength == preedit_length))
1332 ps = Painter::preedit_selecting;
1334 if (pos == cursor_pos
1335 && (cursor_pos < rLength && rLength == preedit_length))
1336 ps = Painter::preedit_cursor;
1338 // draw one character and update cur_x.
1339 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1342 // update the preedit string screen area.
1343 update(0, cur_y - d->preedit_lines_*height, viewport()->width(),
1344 (height + 1) * d->preedit_lines_);
1346 // Don't forget to accept the event!
1351 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1353 QRect cur_r(0, 0, 0, 0);
1355 // this is the CJK-specific composition window position and
1356 // the context menu position when the menu key is pressed.
1357 case Qt::ImMicroFocus:
1358 cur_r = d->cursor_->rect();
1359 if (d->preedit_lines_ != 1)
1361 cur_r.moveBottom(cur_r.bottom()
1362 + cur_r.height() * (d->preedit_lines_ - 1));
1363 // return lower right of cursor in LyX.
1366 return QWidget::inputMethodQuery(query);
1371 void GuiWorkArea::updateWindowTitle()
1373 docstring maximize_title;
1374 docstring minimize_title;
1376 Buffer const & buf = d->buffer_view_->buffer();
1377 FileName const file_name = buf.fileName();
1378 if (!file_name.empty()) {
1379 maximize_title = file_name.displayName(130);
1380 minimize_title = from_utf8(file_name.onlyFileName());
1381 if (buf.lyxvc().inUse()) {
1382 if (buf.lyxvc().locking())
1383 maximize_title += _(" (version control, locking)");
1385 maximize_title += _(" (version control)");
1387 if (!buf.isClean()) {
1388 maximize_title += _(" (changed)");
1389 minimize_title += char_type('*');
1391 if (buf.isReadonly())
1392 maximize_title += _(" (read only)");
1395 QString const new_title = toqstr(maximize_title);
1396 if (new_title != windowTitle()) {
1397 QWidget::setWindowTitle(new_title);
1398 QWidget::setWindowIconText(toqstr(minimize_title));
1404 bool GuiWorkArea::isFullScreen() const
1406 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1410 void GuiWorkArea::scheduleRedraw()
1412 d->schedule_redraw_ = true;
1416 bool GuiWorkArea::inDialogMode() const
1418 return d->dialog_mode_;
1422 void GuiWorkArea::setDialogMode(bool mode)
1424 d->dialog_mode_ = mode;
1428 GuiCompleter & GuiWorkArea::completer()
1430 return *d->completer_;
1433 GuiView const & GuiWorkArea::view() const
1435 return *d->lyx_view_;
1439 GuiView & GuiWorkArea::view()
1441 return *d->lyx_view_;
1444 ////////////////////////////////////////////////////////////////////
1448 ////////////////////////////////////////////////////////////////////
1451 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1453 support::TempFile tempfile("embedded.internal");
1454 tempfile.setAutoRemove(false);
1455 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1456 buffer_->setUnnamed(true);
1457 buffer_->setFullyLoaded(true);
1458 setBuffer(*buffer_);
1459 setDialogMode(true);
1463 EmbeddedWorkArea::~EmbeddedWorkArea()
1465 // No need to destroy buffer and bufferview here, because it is done
1466 // in theBufferList() destruction loop at application exit
1470 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1473 GuiWorkArea::closeEvent(ev);
1477 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1480 GuiWorkArea::hideEvent(ev);
1484 QSize EmbeddedWorkArea::sizeHint () const
1487 // GuiWorkArea sets the size to the screen's viewport
1488 // by returning a value this gets overridden
1489 // EmbeddedWorkArea is now sized to fit in the layout
1490 // of the parent, and has a minimum size set in GuiWorkArea
1491 // which is what we return here
1492 return QSize(100, 70);
1496 void EmbeddedWorkArea::disable()
1498 stopBlinkingCursor();
1499 if (view().currentWorkArea() != this)
1501 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1502 // tolerates it and shows the background logo), what happens if
1503 // an EmbeddedWorkArea is closed after closing all document WAs
1504 view().setCurrentWorkArea(view().currentMainWorkArea());
1507 ////////////////////////////////////////////////////////////////////
1511 ////////////////////////////////////////////////////////////////////
1514 class NoTabFrameMacStyle : public QProxyStyle {
1517 QRect subElementRect(SubElement element, const QStyleOption * option,
1518 const QWidget * widget = 0) const
1520 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1521 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1523 // The Qt Mac style puts the contents into a 3 pixel wide box
1524 // which looks very ugly and not like other Mac applications.
1525 // Hence we remove this here, and moreover the 16 pixel round
1526 // frame above if the tab bar is hidden.
1527 if (element == QStyle::SE_TabWidgetTabContents) {
1528 rect.adjust(- rect.left(), 0, rect.left(), 0);
1537 NoTabFrameMacStyle noTabFrameMacStyle;
1541 TabWorkArea::TabWorkArea(QWidget * parent)
1542 : QTabWidget(parent), clicked_tab_(-1)
1545 setStyle(&noTabFrameMacStyle);
1548 QPalette pal = palette();
1549 pal.setColor(QPalette::Active, QPalette::Button,
1550 pal.color(QPalette::Active, QPalette::Window));
1551 pal.setColor(QPalette::Disabled, QPalette::Button,
1552 pal.color(QPalette::Disabled, QPalette::Window));
1553 pal.setColor(QPalette::Inactive, QPalette::Button,
1554 pal.color(QPalette::Inactive, QPalette::Window));
1556 QObject::connect(this, SIGNAL(currentChanged(int)),
1557 this, SLOT(on_currentTabChanged(int)));
1559 closeBufferButton = new QToolButton(this);
1560 closeBufferButton->setPalette(pal);
1561 // FIXME: rename the icon to closebuffer.png
1562 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1563 closeBufferButton->setText("Close File");
1564 closeBufferButton->setAutoRaise(true);
1565 closeBufferButton->setCursor(Qt::ArrowCursor);
1566 closeBufferButton->setToolTip(qt_("Close File"));
1567 closeBufferButton->setEnabled(true);
1568 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1569 this, SLOT(closeCurrentBuffer()));
1570 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1572 // setup drag'n'drop
1573 QTabBar* tb = new DragTabBar;
1574 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1575 this, SLOT(moveTab(int, int)));
1576 tb->setElideMode(Qt::ElideNone);
1579 // make us responsible for the context menu of the tabbar
1580 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1581 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1582 this, SLOT(showContextMenu(const QPoint &)));
1583 connect(tb, SIGNAL(tabCloseRequested(int)),
1584 this, SLOT(closeTab(int)));
1586 setUsesScrollButtons(true);
1590 void TabWorkArea::paintEvent(QPaintEvent * event)
1592 if (tabBar()->isVisible()) {
1593 QTabWidget::paintEvent(event);
1595 // Prevent the selected tab to influence the
1596 // painting of the frame of the tab widget.
1597 // This is needed for gtk style in Qt.
1598 QStylePainter p(this);
1599 #if QT_VERSION < 0x050000
1600 QStyleOptionTabWidgetFrameV2 opt;
1602 QStyleOptionTabWidgetFrame opt;
1604 initStyleOption(&opt);
1605 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1607 opt.selectedTabRect = QRect();
1608 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1613 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1615 if (event->button() != Qt::LeftButton)
1618 // return early if double click on existing tabs
1619 for (int i = 0; i < count(); ++i)
1620 if (tabBar()->tabRect(i).contains(event->pos()))
1623 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1627 void TabWorkArea::setFullScreen(bool full_screen)
1629 for (int i = 0; i != count(); ++i) {
1630 if (GuiWorkArea * wa = workArea(i))
1631 wa->setFullScreen(full_screen);
1634 if (lyxrc.full_screen_tabbar)
1635 showBar(!full_screen && count() > 1);
1637 showBar(count() > 1);
1641 void TabWorkArea::showBar(bool show)
1643 tabBar()->setEnabled(show);
1644 tabBar()->setVisible(show);
1645 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1646 setTabsClosable(!lyxrc.single_close_tab_button);
1650 GuiWorkArea * TabWorkArea::currentWorkArea()
1655 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1661 GuiWorkArea * TabWorkArea::workArea(int index)
1663 return dynamic_cast<GuiWorkArea *>(widget(index));
1667 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1669 // FIXME: this method doesn't work if we have more than work area
1670 // showing the same buffer.
1671 for (int i = 0; i != count(); ++i) {
1672 GuiWorkArea * wa = workArea(i);
1673 LASSERT(wa, return 0);
1674 if (&wa->bufferView().buffer() == &buffer)
1681 void TabWorkArea::closeAll()
1684 GuiWorkArea * wa = workArea(0);
1685 LASSERT(wa, return);
1692 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1694 LASSERT(work_area, return false);
1695 int index = indexOf(work_area);
1699 if (index == currentIndex())
1700 // Make sure the work area is up to date.
1701 on_currentTabChanged(index);
1703 // Switch to the work area.
1704 setCurrentIndex(index);
1705 work_area->setFocus();
1711 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1713 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1714 wa->setUpdatesEnabled(false);
1715 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1716 // when hiding it again below).
1717 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1718 showBar(count() > 0);
1719 addTab(wa, wa->windowTitle());
1720 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1721 this, SLOT(updateTabTexts()));
1722 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1723 setFullScreen(true);
1725 // Hide tabbar if there's only one tab.
1726 showBar(count() > 1);
1734 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1736 LASSERT(work_area, return false);
1737 int index = indexOf(work_area);
1741 work_area->setUpdatesEnabled(false);
1746 // make sure the next work area is enabled.
1747 currentWidget()->setUpdatesEnabled(true);
1748 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1749 setFullScreen(true);
1751 // Show tabbar only if there's more than one tab.
1752 showBar(count() > 1);
1754 lastWorkAreaRemoved();
1762 void TabWorkArea::on_currentTabChanged(int i)
1764 // returns e.g. on application destruction
1767 GuiWorkArea * wa = workArea(i);
1768 LASSERT(wa, return);
1769 wa->setUpdatesEnabled(true);
1773 currentWorkAreaChanged(wa);
1775 LYXERR(Debug::GUI, "currentTabChanged " << i
1776 << " File: " << wa->bufferView().buffer().absFileName());
1780 void TabWorkArea::closeCurrentBuffer()
1783 if (clicked_tab_ == -1)
1784 wa = currentWorkArea();
1786 wa = workArea(clicked_tab_);
1787 LASSERT(wa, return);
1789 wa->view().closeWorkArea(wa);
1793 void TabWorkArea::hideCurrentTab()
1796 if (clicked_tab_ == -1)
1797 wa = currentWorkArea();
1799 wa = workArea(clicked_tab_);
1800 LASSERT(wa, return);
1802 wa->view().hideWorkArea(wa);
1806 void TabWorkArea::closeTab(int index)
1808 on_currentTabChanged(index);
1811 wa = currentWorkArea();
1813 wa = workArea(index);
1814 LASSERT(wa, return);
1816 wa->view().closeWorkArea(wa);
1823 /// make vector happy
1826 DisplayPath(int tab, FileName const & filename)
1829 filename_ = (filename.extension() == "lyx") ?
1830 toqstr(filename.onlyFileNameWithoutExt())
1831 : toqstr(filename.onlyFileName());
1832 postfix_ = toqstr(filename.absoluteFilePath()).
1833 split("/", QString::SkipEmptyParts);
1834 postfix_.pop_back();
1835 abs_ = toqstr(filename.absoluteFilePath());
1836 dottedPrefix_ = false;
1839 /// Absolute path for debugging.
1844 /// Add the first segment from the postfix or three dots to the prefix.
1845 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1846 /// when really needed.
1847 void shiftPathSegment(bool dotted)
1849 if (postfix_.count() <= 0)
1853 if (dottedPrefix_ && !prefix_.isEmpty())
1855 prefix_ += postfix_.front() + "/";
1857 dottedPrefix_ = dotted && !prefix_.isEmpty();
1858 postfix_.pop_front();
1861 QString displayString() const
1863 if (prefix_.isEmpty())
1866 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1867 return prefix_ + (dots ? ".../" : "") + filename_;
1870 QString forecastPathString() const
1872 if (postfix_.count() == 0)
1873 return displayString();
1876 + (dottedPrefix_ ? ".../" : "")
1877 + postfix_.front() + "/";
1880 bool final() const { return postfix_.empty(); }
1882 int tab() const { return tab_; }
1888 QStringList postfix_;
1901 bool operator<(DisplayPath const & a, DisplayPath const & b)
1903 return a.displayString() < b.displayString();
1907 bool operator==(DisplayPath const & a, DisplayPath const & b)
1909 return a.displayString() == b.displayString();
1913 void TabWorkArea::updateTabTexts()
1918 std::list<DisplayPath> paths;
1919 typedef std::list<DisplayPath>::iterator It;
1921 // collect full names first: path into postfix, empty prefix and
1922 // filename without extension
1923 for (size_t i = 0; i < n; ++i) {
1924 GuiWorkArea * i_wa = workArea(i);
1925 FileName const fn = i_wa->bufferView().buffer().fileName();
1926 paths.push_back(DisplayPath(i, fn));
1929 // go through path segments and see if it helps to make the path more unique
1930 bool somethingChanged = true;
1931 bool allFinal = false;
1932 while (somethingChanged && !allFinal) {
1933 // adding path segments changes order
1936 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1937 somethingChanged = false;
1940 // find segments which are not unique (i.e. non-atomic)
1941 It it = paths.begin();
1943 QString segString = it->displayString();
1944 for (; it != paths.end(); ++it) {
1945 // look to the next item
1950 allFinal = allFinal && it->final();
1952 LYXERR(Debug::GUI, "it = " << it->abs()
1953 << " => " << it->displayString());
1955 // still the same segment?
1957 if ((next != paths.end()
1958 && (nextString = next->displayString()) == segString))
1960 LYXERR(Debug::GUI, "segment ended");
1962 // only a trivial one with one element?
1963 if (it == segStart) {
1964 // start new segment
1966 segString = nextString;
1970 // we found a non-atomic segment segStart <= sit <= it < next.
1971 // Shift path segments and hope for the best
1972 // that it makes the path more unique.
1973 somethingChanged = true;
1975 QString dspString = sit->forecastPathString();
1976 LYXERR(Debug::GUI, "first forecast found for "
1977 << sit->abs() << " => " << dspString);
1979 bool moreUnique = false;
1980 for (; sit != next; ++sit) {
1981 if (sit->forecastPathString() != dspString) {
1982 LYXERR(Debug::GUI, "different forecast found for "
1983 << sit->abs() << " => " << sit->forecastPathString());
1987 LYXERR(Debug::GUI, "same forecast found for "
1988 << sit->abs() << " => " << dspString);
1991 // if the path segment helped, add it. Otherwise add dots
1992 bool dots = !moreUnique;
1993 LYXERR(Debug::GUI, "using dots = " << dots);
1994 for (sit = segStart; sit != next; ++sit) {
1995 sit->shiftPathSegment(dots);
1996 LYXERR(Debug::GUI, "shifting "
1997 << sit->abs() << " => " << sit->displayString());
2000 // start new segment
2002 segString = nextString;
2006 // set new tab titles
2007 for (It it = paths.begin(); it != paths.end(); ++it) {
2008 int const tab_index = it->tab();
2009 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2010 QString tab_text = it->displayString().replace("&", "&&");
2011 if (!buf.fileName().empty() && !buf.isClean())
2013 setTabText(tab_index, tab_text);
2014 setTabToolTip(tab_index, it->abs());
2019 void TabWorkArea::showContextMenu(const QPoint & pos)
2022 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
2023 if (clicked_tab_ == -1)
2028 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
2029 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2030 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
2031 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2032 popup.exec(tabBar()->mapToGlobal(pos));
2038 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2040 QWidget * w = widget(fromIndex);
2041 QIcon icon = tabIcon(fromIndex);
2042 QString text = tabText(fromIndex);
2044 setCurrentIndex(fromIndex);
2045 removeTab(fromIndex);
2046 insertTab(toIndex, w, icon, text);
2047 setCurrentIndex(toIndex);
2051 DragTabBar::DragTabBar(QWidget* parent)
2054 setAcceptDrops(true);
2055 setTabsClosable(!lyxrc.single_close_tab_button);
2059 void DragTabBar::mousePressEvent(QMouseEvent * event)
2061 if (event->button() == Qt::LeftButton)
2062 dragStartPos_ = event->pos();
2063 QTabBar::mousePressEvent(event);
2067 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2069 // If the left button isn't pressed anymore then return
2070 if (!(event->buttons() & Qt::LeftButton))
2073 // If the distance is too small then return
2074 if ((event->pos() - dragStartPos_).manhattanLength()
2075 < QApplication::startDragDistance())
2078 // did we hit something after all?
2079 int tab = tabAt(dragStartPos_);
2083 // simulate button release to remove highlight from button
2084 int i = currentIndex();
2085 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2086 event->button(), event->buttons(), 0);
2087 QTabBar::mouseReleaseEvent(&me);
2091 QDrag * drag = new QDrag(this);
2092 QMimeData * mimeData = new QMimeData;
2093 // a crude way to distinguish tab-reodering drops from other ones
2094 mimeData->setData("action", "tab-reordering") ;
2095 drag->setMimeData(mimeData);
2097 // get tab pixmap as cursor
2098 QRect r = tabRect(tab);
2099 QPixmap pixmap(r.size());
2100 render(&pixmap, - r.topLeft());
2101 drag->setPixmap(pixmap);
2106 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2108 // Only accept if it's an tab-reordering request
2109 QMimeData const * m = event->mimeData();
2110 QStringList formats = m->formats();
2111 if (formats.contains("action")
2112 && m->data("action") == "tab-reordering")
2113 event->acceptProposedAction();
2117 void DragTabBar::dropEvent(QDropEvent * event)
2119 int fromIndex = tabAt(dragStartPos_);
2120 int toIndex = tabAt(event->pos());
2122 // Tell interested objects that
2123 if (fromIndex != toIndex)
2124 tabMoveRequested(fromIndex, toIndex);
2125 event->acceptProposedAction();
2129 } // namespace frontend
2132 #include "moc_GuiWorkArea.cpp"