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"
16 #include "ColorCache.h"
17 #include "FontLoader.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
24 #include "CoordCache.h"
27 #include "FuncRequest.h"
28 #include "GuiApplication.h"
29 #include "GuiCompleter.h"
30 #include "GuiKeySymbol.h"
31 #include "GuiPainter.h"
33 #include "KeySymbol.h"
38 #include "qt_helpers.h"
40 #include "TextMetrics.h"
43 #include "graphics/GraphicsImage.h"
44 #include "graphics/GraphicsLoader.h"
46 #include "support/convert.h"
47 #include "support/debug.h"
48 #include "support/gettext.h"
49 #include "support/FileName.h"
51 #include "frontends/Application.h"
52 #include "frontends/FontMetrics.h"
53 #include "frontends/WorkAreaManager.h"
55 #include <QContextMenuEvent>
56 #include <QInputContext>
61 #include <QMainWindow>
65 #include <QPixmapCache>
68 #include <QToolButton>
72 #include "support/bind.h"
76 int const TabIndicatorWidth = 3;
82 using namespace lyx::support;
87 /// return the LyX mouse button state from Qt's
88 static mouse_button::state q_button_state(Qt::MouseButton button)
90 mouse_button::state b = mouse_button::none;
93 b = mouse_button::button1;
96 b = mouse_button::button2;
99 b = mouse_button::button3;
108 /// return the LyX mouse button state from Qt's
109 mouse_button::state q_motion_state(Qt::MouseButtons state)
111 mouse_button::state b = mouse_button::none;
112 if (state & Qt::LeftButton)
113 b |= mouse_button::button1;
114 if (state & Qt::MidButton)
115 b |= mouse_button::button2;
116 if (state & Qt::RightButton)
117 b |= mouse_button::button3;
130 void draw(QPainter & painter)
132 if (!show_ || !rect_.isValid())
136 int l = x_ - rect_.left();
137 int r = rect_.right() - x_;
138 int bot = rect_.bottom();
140 // draw vertical line
141 painter.fillRect(x_, y, cursor_width_, rect_.height(), color_);
143 // draw RTL/LTR indication
144 painter.setPen(color_);
147 painter.drawLine(x_, bot, x_ - l, bot);
149 painter.drawLine(x_, bot, x_ + cursor_width_ + r, bot);
152 // draw completion triangle
154 int m = y + rect_.height() / 2;
155 int d = TabIndicatorWidth - 1;
157 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
158 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
160 painter.drawLine(x_ + cursor_width_, m - d, x_ + cursor_width_ + d, m);
161 painter.drawLine(x_ + cursor_width_, m + d, x_ + cursor_width_ + d, m);
166 void update(int x, int y, int h, bool l_shape,
167 bool rtl, bool completable)
169 color_ = guiApp->colorCache().get(Color_cursor);
172 completable_ = completable;
175 // extension to left and right
179 // RTL/LTR indication
187 // completion triangle
190 l = max(l, TabIndicatorWidth);
192 r = max(r, TabIndicatorWidth);
195 // compute overall rectangle
196 rect_ = QRect(x - l, y, cursor_width_ + r + l, h);
199 void show(bool set_show = true) { show_ = set_show; }
200 void hide() { show_ = false; }
201 int cursorWidth() const { return cursor_width_; }
202 void recomputeWidth() {
203 cursor_width_ = lyxrc.cursor_width
205 : 1 + int((lyxrc.zoom + 50) / 200.0);
208 QRect const & rect() { return rect_; }
211 /// cursor is in RTL or LTR text
213 /// indication for RTL or LTR
215 /// triangle to show that a completion is available
221 /// rectangle, possibly with l_shape and completion triangle
223 /// x position (were the vertical line is drawn)
230 // This is a 'heartbeat' generating synthetic mouse move events when the
231 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
232 SyntheticMouseEvent::SyntheticMouseEvent()
233 : timeout(200), restart_timeout(true)
237 GuiWorkArea::GuiWorkArea(QWidget *)
238 : buffer_view_(0), lyx_view_(0),
239 cursor_visible_(false),
240 need_resize_(false), schedule_redraw_(false),
241 preedit_lines_(1), completer_(new GuiCompleter(this, this))
246 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
247 : buffer_view_(0), read_only_(buffer.isReadonly()), lyx_view_(0),
248 cursor_visible_(false),
249 need_resize_(false), schedule_redraw_(false),
250 preedit_lines_(1), completer_(new GuiCompleter(this, this))
258 void GuiWorkArea::init()
261 connect(&cursor_timeout_, SIGNAL(timeout()),
262 this, SLOT(toggleCursor()));
264 int const time = QApplication::cursorFlashTime() / 2;
266 cursor_timeout_.setInterval(time);
267 cursor_timeout_.start();
269 // let's initialize this just to be safe
270 cursor_timeout_.setInterval(500);
273 screen_ = QPixmap(viewport()->width(), viewport()->height());
274 // With Qt4.5 a mouse event will happen before the first paint event
275 // so make sure that the buffer view has an up to date metrics.
276 buffer_view_->resize(viewport()->width(), viewport()->height());
277 cursor_ = new frontend::CursorWidget();
280 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
281 setAcceptDrops(true);
282 setMouseTracking(true);
283 setMinimumSize(100, 70);
284 setFrameStyle(QFrame::NoFrame);
287 viewport()->setAutoFillBackground(false);
288 // We don't need double-buffering nor SystemBackground on
289 // the viewport because we have our own backing pixmap.
290 viewport()->setAttribute(Qt::WA_NoSystemBackground);
292 setFocusPolicy(Qt::StrongFocus);
294 setCursorShape(Qt::IBeamCursor);
296 synthetic_mouse_event_.timeout.timeout.connect(
297 bind(&GuiWorkArea::generateSyntheticMouseEvent,
300 // Initialize the vertical Scroll Bar
301 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
302 this, SLOT(scrollTo(int)));
304 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
305 << " viewport height: " << viewport()->height());
307 // Enables input methods for asian languages.
308 // Must be set when creating custom text editing widgets.
309 setAttribute(Qt::WA_InputMethodEnabled, true);
311 dialog_mode_ = false;
315 GuiWorkArea::~GuiWorkArea()
317 buffer_view_->buffer().workAreaManager().remove(this);
320 // Completer has a QObject parent and is thus automatically destroyed.
322 // delete completer_;
326 Qt::CursorShape GuiWorkArea::cursorShape() const
328 return viewport()->cursor().shape();
332 void GuiWorkArea::setCursorShape(Qt::CursorShape shape)
334 viewport()->setCursor(shape);
338 void GuiWorkArea::updateCursorShape()
340 setCursorShape(buffer_view_->clickableInset()
341 ? Qt::PointingHandCursor : Qt::IBeamCursor);
345 void GuiWorkArea::setGuiView(GuiView & gv)
351 void GuiWorkArea::setBuffer(Buffer & buffer)
354 buffer_view_ = new BufferView(buffer);
355 buffer.workAreaManager().add(this);
357 // HACK: Prevents an additional redraw when the scrollbar pops up
358 // which regularily happens on documents with more than one page.
359 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
360 // Since we have no geometry information yet, we assume that
361 // a document needs a scrollbar if there is more then four
362 // paragraph in the outermost text.
363 if (buffer.text().paragraphs().size() > 4)
364 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
365 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
369 void GuiWorkArea::fixVerticalScrollBar()
372 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
376 void GuiWorkArea::close()
378 lyx_view_->removeWorkArea(this);
382 void GuiWorkArea::setFullScreen(bool full_screen)
384 buffer_view_->setFullScreen(full_screen);
385 setFrameStyle(QFrame::NoFrame);
387 setFrameStyle(QFrame::NoFrame);
388 if (lyxrc.full_screen_scrollbar)
389 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
391 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
395 BufferView & GuiWorkArea::bufferView()
397 return *buffer_view_;
401 BufferView const & GuiWorkArea::bufferView() const
403 return *buffer_view_;
407 void GuiWorkArea::stopBlinkingCursor()
409 cursor_timeout_.stop();
414 void GuiWorkArea::startBlinkingCursor()
416 // do not show the cursor if the view is busy
422 buffer_view_->cursorPosAndHeight(p, h);
423 // Don't start blinking if the cursor isn't on screen.
424 if (!buffer_view_->cursorInView(p, h))
429 //we're not supposed to cache this value.
430 int const time = QApplication::cursorFlashTime() / 2;
433 cursor_timeout_.setInterval(time);
434 cursor_timeout_.start();
438 void GuiWorkArea::redraw(bool update_metrics)
441 // No need to redraw in this case.
444 // No need to do anything if this is the current view. The BufferView
445 // metrics are already up to date.
446 if (update_metrics || lyx_view_ != guiApp->currentView()
447 || lyx_view_->currentWorkArea() != this) {
448 // FIXME: it would be nice to optimize for the off-screen case.
449 buffer_view_->cursor().fixIfBroken();
450 buffer_view_->updateMetrics();
451 buffer_view_->cursor().fixIfBroken();
454 // update cursor position, because otherwise it has to wait until
455 // the blinking interval is over
456 if (cursor_visible_) {
461 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
463 update(0, 0, viewport()->width(), viewport()->height());
465 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
466 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
468 lyx_view_->updateStatusBar();
470 if (lyxerr.debugging(Debug::WORKAREA))
471 buffer_view_->coordCache().dump();
473 setReadOnly(buffer_view_->buffer().isReadonly());
479 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
481 if (lyx_view_->isFullScreen() && lyx_view_->menuBar()->isVisible()
482 && lyxrc.full_screen_menubar) {
483 // FIXME HACK: we should not have to do this here. See related comment
484 // in GuiView::event() (QEvent::ShortcutOverride)
485 lyx_view_->menuBar()->hide();
488 // In order to avoid bad surprise in the middle of an operation,
489 // we better stop the blinking cursor...
490 // the cursor gets restarted in GuiView::restartCursor()
491 stopBlinkingCursor();
492 guiApp->processKeySym(key, mod);
496 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
499 if (cmd0.action() == LFUN_FILE_OPEN) {
501 lyx_view_->dispatch(cmd0, dr);
507 if (cmd0.action() == LFUN_MOUSE_PRESS) {
508 if (mod == ShiftModifier)
509 cmd = FuncRequest(cmd0, "region-select");
510 else if (mod == ControlModifier)
511 cmd = FuncRequest(cmd0, "paragraph-select");
518 bool const notJustMovingTheMouse =
519 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
521 // In order to avoid bad surprise in the middle of an operation, we better stop
522 // the blinking cursor.
523 if (notJustMovingTheMouse)
524 stopBlinkingCursor();
526 buffer_view_->mouseEventDispatch(cmd);
528 // Skip these when selecting
529 if (cmd.action() != LFUN_MOUSE_MOTION) {
530 completer_->updateVisibility(false, false);
531 lyx_view_->updateDialogs();
532 lyx_view_->updateStatusBar();
535 // GUI tweaks except with mouse motion with no button pressed.
536 if (notJustMovingTheMouse) {
537 // Slight hack: this is only called currently when we
538 // clicked somewhere, so we force through the display
539 // of the new status here.
540 lyx_view_->clearMessage();
542 // Show the cursor immediately after any operation
543 startBlinkingCursor();
550 void GuiWorkArea::resizeBufferView()
552 // WARNING: Please don't put any code that will trigger a repaint here!
553 // We are already inside a paint event.
554 lyx_view_->setBusy(true);
557 buffer_view_->cursorPosAndHeight(p, h);
558 bool const cursor_in_view = buffer_view_->cursorInView(p, h);
559 buffer_view_->resize(viewport()->width(), viewport()->height());
561 buffer_view_->scrollToCursor();
564 // Update scrollbars which might have changed due different
565 // BufferView dimension. This is especially important when the
566 // BufferView goes from zero-size to the real-size for the first time,
567 // as the scrollbar paramters are then set for the first time.
570 lyx_view_->updateLayoutList();
571 lyx_view_->setBusy(false);
572 need_resize_ = false;
576 void GuiWorkArea::showCursor()
583 buffer_view_->cursorPosAndHeight(p, h);
584 if (!buffer_view_->cursorInView(p, h))
588 bool l_shape = false;
589 Font const & realfont = buffer_view_->cursor().real_current_font;
590 BufferParams const & bp = buffer_view_->buffer().params();
591 bool const samelang = realfont.language() == bp.language;
592 bool const isrtl = realfont.isVisibleRightToLeft();
594 if (!samelang || isrtl != bp.language->rightToLeft())
597 // The ERT language hack needs fixing up
598 if (realfont.language() == latex_language)
601 // show cursor on screen
602 Cursor & cur = buffer_view_->cursor();
603 bool completable = cur.inset().showCompletionCursor()
604 && completer_->completionAvailable()
605 && !completer_->popupVisible()
606 && !completer_->inlineVisible();
607 cursor_visible_ = true;
608 cursor_->recomputeWidth();
609 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
613 void GuiWorkArea::hideCursor()
615 if (!cursor_visible_)
618 cursor_visible_ = false;
623 void GuiWorkArea::toggleCursor()
632 void GuiWorkArea::updateScrollbar()
634 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
635 // WARNING: don't touch at the scrollbar value like this:
636 // verticalScrollBar()->setValue(scroll_.position);
637 // because this would cause a recursive signal/slot calling with
638 // GuiWorkArea::scrollTo
639 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
640 verticalScrollBar()->setPageStep(scroll_.page_step);
641 verticalScrollBar()->setSingleStep(scroll_.single_step);
642 verticalScrollBar()->setSliderPosition(scroll_.position);
646 void GuiWorkArea::scrollTo(int value)
648 stopBlinkingCursor();
649 buffer_view_->scrollDocView(value, true);
651 if (lyxrc.cursor_follows_scrollbar) {
652 buffer_view_->setCursorFromScrollbar();
653 lyx_view_->updateLayoutList();
655 // Show the cursor immediately after any operation.
656 startBlinkingCursor();
657 QApplication::syncX();
661 bool GuiWorkArea::event(QEvent * e)
664 case QEvent::ToolTip: {
665 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
666 if (lyxrc.use_tooltip) {
667 QPoint pos = helpEvent->pos();
668 if (pos.x() < viewport()->width()) {
669 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
670 QToolTip::showText(helpEvent->globalPos(), s);
673 QToolTip::hideText();
675 // Don't forget to accept the event!
680 case QEvent::ShortcutOverride: {
681 // We catch this event in order to catch the Tab or Shift+Tab key press
682 // which are otherwise reserved to focus switching between controls
684 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
685 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
686 || (ke->key() == Qt::Key_Backtab && (
687 ke->modifiers() == Qt::ShiftModifier
688 || ke->modifiers() == Qt::NoModifier))) {
692 return QAbstractScrollArea::event(e);
696 return QAbstractScrollArea::event(e);
702 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
705 if (e->reason() == QContextMenuEvent::Mouse)
706 // the menu name is set on mouse press
707 name = context_menu_name_;
709 QPoint pos = e->pos();
710 Cursor const & cur = buffer_view_->cursor();
711 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
712 // Do not access the context menu of math right in front of before
713 // the cursor. This does not work when the cursor is in text.
714 Inset * inset = cur.paragraph().getInset(cur.pos());
715 if (inset && inset->asInsetMath())
717 else if (cur.pos() > 0) {
718 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
723 name = buffer_view_->contextMenu(pos.x(), pos.y());
727 QAbstractScrollArea::contextMenuEvent(e);
730 // always show mnemonics when the keyboard is used to show the context menu
731 // FIXME: This should be fixed in Qt itself
732 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
733 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_, keyboard);
735 QAbstractScrollArea::contextMenuEvent(e);
738 // Position the menu to the right.
739 // FIXME: menu position should be different for RTL text.
740 menu->exec(e->globalPos());
745 void GuiWorkArea::focusInEvent(QFocusEvent * e)
747 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
748 if (lyx_view_->currentWorkArea() != this)
749 lyx_view_->setCurrentWorkArea(this);
751 startBlinkingCursor();
752 QAbstractScrollArea::focusInEvent(e);
756 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
758 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
759 stopBlinkingCursor();
760 QAbstractScrollArea::focusOutEvent(e);
764 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
766 if (dc_event_.active && dc_event_ == *e) {
767 dc_event_.active = false;
768 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
769 q_button_state(e->button()));
775 inputContext()->reset();
777 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
778 q_button_state(e->button()));
779 dispatch(cmd, q_key_state(e->modifiers()));
781 // Save the context menu on mouse press, because also the mouse
782 // cursor is set on mouse press. Afterwards, we can either release
783 // the mousebutton somewhere else, or the cursor might have moved
784 // due to the DEPM. We need to do this after the mouse has been
785 // set in dispatch(), because the selection state might change.
786 if (e->button() == Qt::RightButton)
787 context_menu_name_ = buffer_view_->contextMenu(e->x(), e->y());
793 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
795 if (synthetic_mouse_event_.timeout.running())
796 synthetic_mouse_event_.timeout.stop();
798 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
799 q_button_state(e->button()));
805 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
807 // we kill the triple click if we move
808 doubleClickTimeout();
809 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
810 q_motion_state(e->buttons()));
814 // If we're above or below the work area...
815 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
816 && e->buttons() == mouse_button::button1) {
817 // Make sure only a synthetic event can cause a page scroll,
818 // so they come at a steady rate:
820 // _Force_ a scroll up:
821 cmd.set_y(e->y() - 21);
823 cmd.set_y(e->y() + 21);
824 // Store the event, to be handled when the timeout expires.
825 synthetic_mouse_event_.cmd = cmd;
827 if (synthetic_mouse_event_.timeout.running()) {
828 // Discard the event. Note that it _may_ be handled
829 // when the timeout expires if
830 // synthetic_mouse_event_.cmd has not been overwritten.
831 // Ie, when the timeout expires, we handle the
832 // most recent event but discard all others that
833 // occurred after the one used to start the timeout
834 // in the first place.
838 synthetic_mouse_event_.restart_timeout = true;
839 synthetic_mouse_event_.timeout.start();
840 // Fall through to handle this event...
842 } else if (synthetic_mouse_event_.timeout.running()) {
843 // Store the event, to be possibly handled when the timeout
845 // Once the timeout has expired, normal control is returned
846 // to mouseMoveEvent (restart_timeout = false).
847 // This results in a much smoother 'feel' when moving the
848 // mouse back into the work area.
849 synthetic_mouse_event_.cmd = cmd;
850 synthetic_mouse_event_.restart_timeout = false;
857 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
859 // Wheel rotation by one notch results in a delta() of 120 (see
860 // documentation of QWheelEvent)
861 double const delta = ev->delta() / 120.0;
863 switch (lyxrc.scroll_wheel_zoom) {
864 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
865 zoom = ev->modifiers() & Qt::ControlModifier;
866 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
868 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
869 zoom = ev->modifiers() & Qt::ShiftModifier;
870 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
872 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
873 zoom = ev->modifiers() & Qt::AltModifier;
874 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
876 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
880 docstring arg = convert<docstring>(int(5 * delta));
881 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
885 // Take into account the desktop wide settings.
886 int const lines = qApp->wheelScrollLines();
887 int const page_step = verticalScrollBar()->pageStep();
888 // Test if the wheel mouse is set to one screen at a time.
889 int scroll_value = lines > page_step
890 ? page_step : lines * verticalScrollBar()->singleStep();
892 // Take into account the rotation and the user preferences.
893 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
894 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
895 << " delta = " << delta << " scroll_value = " << scroll_value
896 << " page_step = " << page_step);
898 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
904 void GuiWorkArea::generateSyntheticMouseEvent()
906 int const e_y = synthetic_mouse_event_.cmd.y();
907 int const wh = buffer_view_->workHeight();
908 bool const up = e_y < 0;
909 bool const down = e_y > wh;
911 // Set things off to generate the _next_ 'pseudo' event.
913 if (synthetic_mouse_event_.restart_timeout) {
914 // This is some magic formulae to determine the speed
915 // of scrolling related to the position of the mouse.
918 int dist = up ? -e_y : e_y - wh;
919 time = max(min(200, 250000 / (dist * dist)), 1) ;
922 step = 80000 / (time * time);
926 synthetic_mouse_event_.timeout.setTimeout(time);
927 synthetic_mouse_event_.timeout.start();
930 // Can we scroll further ?
931 int const value = verticalScrollBar()->value();
932 if (value == verticalScrollBar()->maximum()
933 || value == verticalScrollBar()->minimum()) {
934 synthetic_mouse_event_.timeout.stop();
939 if (step <= 2 * wh) {
940 buffer_view_->scroll(up ? -step : step);
941 buffer_view_->updateMetrics();
943 buffer_view_->scrollDocView(value + up ? -step : step, false);
946 // In which paragraph do we have to set the cursor ?
947 Cursor & cur = buffer_view_->cursor();
948 // FIXME: we don't know howto handle math.
949 Text * text = cur.text();
952 TextMetrics const & tm = buffer_view_->textMetrics(text);
954 pair<pit_type, const ParagraphMetrics *> p = up ? tm.first() : tm.last();
955 ParagraphMetrics const & pm = *p.second;
956 pit_type const pit = p.first;
958 if (pm.rows().empty())
961 // Find the row at which we set the cursor.
962 RowList::const_iterator rit = pm.rows().begin();
963 RowList::const_iterator rlast = pm.rows().end();
964 int yy = pm.position() - pm.ascent();
965 for (--rlast; rit != rlast; ++rit) {
966 int h = rit->height();
967 if ((up && yy + h > 0)
968 || (!up && yy + h > wh - defaultRowHeight()))
973 // Find the position of the cursor
975 int x = synthetic_mouse_event_.cmd.x();
976 pos_type const pos = rit->pos() + tm.getColumnNearX(pit, *rit, x, bound);
983 buffer_view_->buffer().changed(false);
988 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
990 // Do not process here some keys if dialog_mode_ is set
992 && (ev->modifiers() == Qt::NoModifier
993 || ev->modifiers() == Qt::ShiftModifier)
994 && (ev->key() == Qt::Key_Escape
995 || ev->key() == Qt::Key_Enter
996 || ev->key() == Qt::Key_Return)
1002 // intercept some keys if completion popup is visible
1003 if (completer_->popupVisible()) {
1004 switch (ev->key()) {
1006 case Qt::Key_Return:
1007 completer_->activate();
1013 // do nothing if there are other events
1014 // (the auto repeated events come too fast)
1015 // it looks like this is only needed on X11
1017 if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1018 switch (ev->key()) {
1019 case Qt::Key_PageDown:
1020 case Qt::Key_PageUp:
1025 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1032 KeyModifier m = q_key_state(ev->modifiers());
1035 if (m & ShiftModifier)
1037 if (m & ControlModifier)
1039 if (m & AltModifier)
1041 if (m & MetaModifier)
1044 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1045 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1046 << " keyState: " << str);
1049 setKeySymbol(&sym, ev);
1051 processKeySym(sym, q_key_state(ev->modifiers()));
1059 void GuiWorkArea::doubleClickTimeout()
1061 dc_event_.active = false;
1065 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1067 dc_event_ = DoubleClick(ev);
1068 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1069 SLOT(doubleClickTimeout()));
1070 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1072 q_button_state(ev->button()));
1078 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1080 QAbstractScrollArea::resizeEvent(ev);
1081 need_resize_ = true;
1086 void GuiWorkArea::update(int x, int y, int w, int h)
1088 viewport()->repaint(x, y, w, h);
1092 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1094 QRect const rc = ev->rect();
1095 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1096 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1099 screen_ = QPixmap(viewport()->width(), viewport()->height());
1101 if (cursor_visible_) {
1107 QPainter pain(viewport());
1108 pain.drawPixmap(rc, screen_, rc);
1109 cursor_->draw(pain);
1114 void GuiWorkArea::updateScreen()
1116 GuiPainter pain(&screen_);
1117 buffer_view_->draw(pain);
1121 void GuiWorkArea::showCursor(int x, int y, int h,
1122 bool l_shape, bool rtl, bool completable)
1124 if (schedule_redraw_) {
1125 // This happens when a graphic conversion is finished. As we don't know
1126 // the size of the new graphics, it's better the update everything.
1127 // We can't use redraw() here because this would trigger a infinite
1128 // recursive loop with showCursor().
1129 buffer_view_->resize(viewport()->width(), viewport()->height());
1132 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
1133 schedule_redraw_ = false;
1134 // Show the cursor immediately after the update.
1140 cursor_->update(x, y, h, l_shape, rtl, completable);
1142 viewport()->update(cursor_->rect());
1146 void GuiWorkArea::removeCursor()
1149 //if (!qApp->focusWidget())
1150 viewport()->update(cursor_->rect());
1154 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1156 QString const & commit_string = e->commitString();
1157 docstring const & preedit_string
1158 = qstring_to_ucs4(e->preeditString());
1160 if (!commit_string.isEmpty()) {
1162 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1163 << " commitString: " << e->commitString());
1167 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1168 for (int i = 0; i != commit_string.size(); ++i) {
1169 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1174 // Hide the cursor during the kana-kanji transformation.
1175 if (preedit_string.empty())
1176 startBlinkingCursor();
1178 stopBlinkingCursor();
1180 // last_width : for checking if last preedit string was/wasn't empty.
1181 static bool last_width = false;
1182 if (!last_width && preedit_string.empty()) {
1183 // if last_width is last length of preedit string.
1188 GuiPainter pain(&screen_);
1189 buffer_view_->updateMetrics();
1190 buffer_view_->draw(pain);
1191 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1192 FontMetrics const & fm = theFontMetrics(font);
1193 int height = fm.maxHeight();
1194 int cur_x = cursor_->rect().left();
1195 int cur_y = cursor_->rect().bottom();
1197 // redraw area of preedit string.
1198 update(0, cur_y - height, viewport()->width(),
1199 (height + 1) * preedit_lines_);
1201 if (preedit_string.empty()) {
1209 // att : stores an IM attribute.
1210 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1212 // get attributes of input method cursor.
1213 // cursor_pos : cursor position in preedit string.
1214 size_t cursor_pos = 0;
1215 bool cursor_is_visible = false;
1216 for (int i = 0; i != att.size(); ++i) {
1217 if (att.at(i).type == QInputMethodEvent::Cursor) {
1218 cursor_pos = att.at(i).start;
1219 cursor_is_visible = att.at(i).length != 0;
1224 size_t preedit_length = preedit_string.length();
1226 // get position of selection in input method.
1227 // FIXME: isn't there a way to do this simplier?
1228 // rStart : cursor position in selected string in IM.
1230 // rLength : selected string length in IM.
1232 if (cursor_pos < preedit_length) {
1233 for (int i = 0; i != att.size(); ++i) {
1234 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1235 if (att.at(i).start <= int(cursor_pos)
1236 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1237 rStart = att.at(i).start;
1238 rLength = att.at(i).length;
1239 if (!cursor_is_visible)
1240 cursor_pos += rLength;
1247 rStart = cursor_pos;
1251 int const right_margin = buffer_view_->rightMargin();
1252 Painter::preedit_style ps;
1253 // Most often there would be only one line:
1255 for (size_t pos = 0; pos != preedit_length; ++pos) {
1256 char_type const typed_char = preedit_string[pos];
1257 // reset preedit string style
1258 ps = Painter::preedit_default;
1260 // if we reached the right extremity of the screen, go to next line.
1261 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1262 cur_x = right_margin;
1263 cur_y += height + 1;
1266 // preedit strings are displayed with dashed underline
1267 // and partial strings are displayed white on black indicating
1268 // that we are in selecting mode in the input method.
1269 // FIXME: rLength == preedit_length is not a changing condition
1270 // FIXME: should be put out of the loop.
1272 && pos < rStart + rLength
1273 && !(cursor_pos < rLength && rLength == preedit_length))
1274 ps = Painter::preedit_selecting;
1276 if (pos == cursor_pos
1277 && (cursor_pos < rLength && rLength == preedit_length))
1278 ps = Painter::preedit_cursor;
1280 // draw one character and update cur_x.
1281 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1284 // update the preedit string screen area.
1285 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1286 (height + 1) * preedit_lines_);
1288 // Don't forget to accept the event!
1293 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1295 QRect cur_r(0, 0, 0, 0);
1297 // this is the CJK-specific composition window position and
1298 // the context menu position when the menu key is pressed.
1299 case Qt::ImMicroFocus:
1300 cur_r = cursor_->rect();
1301 if (preedit_lines_ != 1)
1303 cur_r.moveBottom(cur_r.bottom()
1304 + cur_r.height() * (preedit_lines_ - 1));
1305 // return lower right of cursor in LyX.
1308 return QWidget::inputMethodQuery(query);
1313 void GuiWorkArea::updateWindowTitle()
1315 docstring maximize_title;
1316 docstring minimize_title;
1318 Buffer const & buf = buffer_view_->buffer();
1319 FileName const file_name = buf.fileName();
1320 if (!file_name.empty()) {
1321 maximize_title = file_name.displayName(130);
1322 minimize_title = from_utf8(file_name.onlyFileName());
1323 if (buf.lyxvc().inUse()) {
1324 if (buf.lyxvc().locking())
1325 maximize_title += _(" (version control, locking)");
1327 maximize_title += _(" (version control)");
1329 if (!buf.isClean()) {
1330 maximize_title += _(" (changed)");
1331 minimize_title += char_type('*');
1333 if (buf.isReadonly())
1334 maximize_title += _(" (read only)");
1337 QString const new_title = toqstr(maximize_title);
1338 if (new_title != windowTitle()) {
1339 QWidget::setWindowTitle(new_title);
1340 QWidget::setWindowIconText(toqstr(minimize_title));
1346 void GuiWorkArea::setReadOnly(bool read_only)
1348 if (read_only_ == read_only)
1350 read_only_ = read_only;
1351 updateWindowTitle();
1352 if (this == lyx_view_->currentWorkArea())
1353 lyx_view_->updateDialogs();
1357 bool GuiWorkArea::isFullScreen()
1359 return lyx_view_ && lyx_view_->isFullScreen();
1363 ////////////////////////////////////////////////////////////////////
1367 ////////////////////////////////////////////////////////////////////
1370 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1372 buffer_ = theBufferList().newBuffer(
1373 support::FileName::tempName().absFileName() + "_embedded.internal");
1374 buffer_->setUnnamed(true);
1375 buffer_->setFullyLoaded(true);
1376 setBuffer(*buffer_);
1377 setDialogMode(true);
1381 EmbeddedWorkArea::~EmbeddedWorkArea()
1383 // No need to destroy buffer and bufferview here, because it is done
1384 // in theBufferList() destruction loop at application exit
1388 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1391 GuiWorkArea::closeEvent(ev);
1395 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1398 GuiWorkArea::hideEvent(ev);
1402 QSize EmbeddedWorkArea::sizeHint () const
1405 // GuiWorkArea sets the size to the screen's viewport
1406 // by returning a value this gets overridden
1407 // EmbeddedWorkArea is now sized to fit in the layout
1408 // of the parent, and has a minimum size set in GuiWorkArea
1409 // which is what we return here
1410 return QSize(100, 70);
1414 void EmbeddedWorkArea::disable()
1416 stopBlinkingCursor();
1417 if (view().currentWorkArea() != this)
1419 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1420 // tolerates it and shows the background logo), what happens if
1421 // an EmbeddedWorkArea is closed after closing all document WAs
1422 view().setCurrentWorkArea(view().currentMainWorkArea());
1425 ////////////////////////////////////////////////////////////////////
1429 ////////////////////////////////////////////////////////////////////
1432 class NoTabFrameMacStyle : public QMacStyle {
1435 QRect subElementRect(SubElement element, const QStyleOption * option,
1436 const QWidget * widget = 0) const
1438 QRect rect = QMacStyle::subElementRect(element, option, widget);
1439 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1441 // The Qt Mac style puts the contents into a 3 pixel wide box
1442 // which looks very ugly and not like other Mac applications.
1443 // Hence we remove this here, and moreover the 16 pixel round
1444 // frame above if the tab bar is hidden.
1445 if (element == QStyle::SE_TabWidgetTabContents) {
1446 rect.adjust(- rect.left(), 0, rect.left(), 0);
1455 NoTabFrameMacStyle noTabFrameMacStyle;
1459 TabWorkArea::TabWorkArea(QWidget * parent)
1460 : QTabWidget(parent), clicked_tab_(-1)
1463 setStyle(&noTabFrameMacStyle);
1465 #if QT_VERSION < 0x040500
1466 lyxrc.single_close_tab_button = true;
1469 QPalette pal = palette();
1470 pal.setColor(QPalette::Active, QPalette::Button,
1471 pal.color(QPalette::Active, QPalette::Window));
1472 pal.setColor(QPalette::Disabled, QPalette::Button,
1473 pal.color(QPalette::Disabled, QPalette::Window));
1474 pal.setColor(QPalette::Inactive, QPalette::Button,
1475 pal.color(QPalette::Inactive, QPalette::Window));
1477 QObject::connect(this, SIGNAL(currentChanged(int)),
1478 this, SLOT(on_currentTabChanged(int)));
1480 closeBufferButton = new QToolButton(this);
1481 closeBufferButton->setPalette(pal);
1482 // FIXME: rename the icon to closebuffer.png
1483 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1484 closeBufferButton->setText("Close File");
1485 closeBufferButton->setAutoRaise(true);
1486 closeBufferButton->setCursor(Qt::ArrowCursor);
1487 closeBufferButton->setToolTip(qt_("Close File"));
1488 closeBufferButton->setEnabled(true);
1489 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1490 this, SLOT(closeCurrentBuffer()));
1491 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1493 // setup drag'n'drop
1494 QTabBar* tb = new DragTabBar;
1495 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1496 this, SLOT(moveTab(int, int)));
1497 tb->setElideMode(Qt::ElideNone);
1500 // make us responsible for the context menu of the tabbar
1501 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1502 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1503 this, SLOT(showContextMenu(const QPoint &)));
1504 #if QT_VERSION >= 0x040500
1505 connect(tb, SIGNAL(tabCloseRequested(int)),
1506 this, SLOT(closeTab(int)));
1509 setUsesScrollButtons(true);
1513 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1515 if (event->button() != Qt::LeftButton)
1518 // return early if double click on existing tabs
1519 for (int i = 0; i < count(); ++i)
1520 if (tabBar()->tabRect(i).contains(event->pos()))
1523 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1527 void TabWorkArea::setFullScreen(bool full_screen)
1529 for (int i = 0; i != count(); ++i) {
1530 if (GuiWorkArea * wa = workArea(i))
1531 wa->setFullScreen(full_screen);
1534 if (lyxrc.full_screen_tabbar)
1535 showBar(!full_screen && count() > 1);
1539 void TabWorkArea::showBar(bool show)
1541 tabBar()->setEnabled(show);
1542 tabBar()->setVisible(show);
1543 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1544 #if QT_VERSION >= 0x040500
1545 setTabsClosable(!lyxrc.single_close_tab_button);
1550 GuiWorkArea * TabWorkArea::currentWorkArea()
1555 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1561 GuiWorkArea * TabWorkArea::workArea(int index)
1563 return dynamic_cast<GuiWorkArea *>(widget(index));
1567 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1569 // FIXME: this method doesn't work if we have more than work area
1570 // showing the same buffer.
1571 for (int i = 0; i != count(); ++i) {
1572 GuiWorkArea * wa = workArea(i);
1573 LASSERT(wa, return 0);
1574 if (&wa->bufferView().buffer() == &buffer)
1581 void TabWorkArea::closeAll()
1584 GuiWorkArea * wa = workArea(0);
1592 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1594 LASSERT(work_area, /**/);
1595 int index = indexOf(work_area);
1599 if (index == currentIndex())
1600 // Make sure the work area is up to date.
1601 on_currentTabChanged(index);
1603 // Switch to the work area.
1604 setCurrentIndex(index);
1605 work_area->setFocus();
1611 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1613 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1614 wa->setUpdatesEnabled(false);
1615 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1616 // when hiding it again below).
1617 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1618 showBar(count() > 0);
1619 addTab(wa, wa->windowTitle());
1620 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1621 this, SLOT(updateTabTexts()));
1622 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1623 setFullScreen(true);
1625 // Hide tabbar if there's only one tab.
1626 showBar(count() > 1);
1634 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1636 LASSERT(work_area, return false);
1637 int index = indexOf(work_area);
1641 work_area->setUpdatesEnabled(false);
1646 // make sure the next work area is enabled.
1647 currentWidget()->setUpdatesEnabled(true);
1648 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1649 setFullScreen(true);
1651 // Show tabbar only if there's more than one tab.
1652 showBar(count() > 1);
1654 lastWorkAreaRemoved();
1662 void TabWorkArea::on_currentTabChanged(int i)
1664 // returns e.g. on application destruction
1667 GuiWorkArea * wa = workArea(i);
1668 LASSERT(wa, return);
1669 wa->setUpdatesEnabled(true);
1673 currentWorkAreaChanged(wa);
1675 LYXERR(Debug::GUI, "currentTabChanged " << i
1676 << " File: " << wa->bufferView().buffer().absFileName());
1680 void TabWorkArea::closeCurrentBuffer()
1683 if (clicked_tab_ == -1)
1684 wa = currentWorkArea();
1686 wa = workArea(clicked_tab_);
1689 wa->view().closeWorkArea(wa);
1693 void TabWorkArea::hideCurrentTab()
1696 if (clicked_tab_ == -1)
1697 wa = currentWorkArea();
1699 wa = workArea(clicked_tab_);
1702 wa->view().hideWorkArea(wa);
1706 void TabWorkArea::closeTab(int index)
1708 on_currentTabChanged(index);
1711 wa = currentWorkArea();
1713 wa = workArea(index);
1716 wa->view().closeWorkArea(wa);
1723 /// make vector happy
1726 DisplayPath(int tab, FileName const & filename)
1729 filename_ = (filename.extension() == "lyx") ?
1730 toqstr(filename.onlyFileNameWithoutExt())
1731 : toqstr(filename.onlyFileName());
1732 postfix_ = toqstr(filename.absoluteFilePath()).
1733 split("/", QString::SkipEmptyParts);
1734 postfix_.pop_back();
1735 abs_ = toqstr(filename.absoluteFilePath());
1736 dottedPrefix_ = false;
1739 /// Absolute path for debugging.
1744 /// Add the first segment from the postfix or three dots to the prefix.
1745 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1746 /// when really needed.
1747 void shiftPathSegment(bool dotted)
1749 if (postfix_.count() <= 0)
1753 if (dottedPrefix_ && !prefix_.isEmpty())
1755 prefix_ += postfix_.front() + "/";
1757 dottedPrefix_ = dotted && !prefix_.isEmpty();
1758 postfix_.pop_front();
1761 QString displayString() const
1763 if (prefix_.isEmpty())
1766 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1767 return prefix_ + (dots ? ".../" : "") + filename_;
1770 QString forecastPathString() const
1772 if (postfix_.count() == 0)
1773 return displayString();
1776 + (dottedPrefix_ ? ".../" : "")
1777 + postfix_.front() + "/";
1780 bool final() const { return postfix_.empty(); }
1782 int tab() const { return tab_; }
1788 QStringList postfix_;
1801 bool operator<(DisplayPath const & a, DisplayPath const & b)
1803 return a.displayString() < b.displayString();
1807 bool operator==(DisplayPath const & a, DisplayPath const & b)
1809 return a.displayString() == b.displayString();
1813 void TabWorkArea::updateTabTexts()
1818 std::list<DisplayPath> paths;
1819 typedef std::list<DisplayPath>::iterator It;
1821 // collect full names first: path into postfix, empty prefix and
1822 // filename without extension
1823 for (size_t i = 0; i < n; ++i) {
1824 GuiWorkArea * i_wa = workArea(i);
1825 FileName const fn = i_wa->bufferView().buffer().fileName();
1826 paths.push_back(DisplayPath(i, fn));
1829 // go through path segments and see if it helps to make the path more unique
1830 bool somethingChanged = true;
1831 bool allFinal = false;
1832 while (somethingChanged && !allFinal) {
1833 // adding path segments changes order
1836 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1837 somethingChanged = false;
1840 // find segments which are not unique (i.e. non-atomic)
1841 It it = paths.begin();
1843 QString segString = it->displayString();
1844 for (; it != paths.end(); ++it) {
1845 // look to the next item
1850 allFinal = allFinal && it->final();
1852 LYXERR(Debug::GUI, "it = " << it->abs()
1853 << " => " << it->displayString());
1855 // still the same segment?
1857 if ((next != paths.end()
1858 && (nextString = next->displayString()) == segString))
1860 LYXERR(Debug::GUI, "segment ended");
1862 // only a trivial one with one element?
1863 if (it == segStart) {
1864 // start new segment
1866 segString = nextString;
1870 // we found a non-atomic segment segStart <= sit <= it < next.
1871 // Shift path segments and hope for the best
1872 // that it makes the path more unique.
1873 somethingChanged = true;
1875 QString dspString = sit->forecastPathString();
1876 LYXERR(Debug::GUI, "first forecast found for "
1877 << sit->abs() << " => " << dspString);
1879 bool moreUnique = false;
1880 for (; sit != next; ++sit) {
1881 if (sit->forecastPathString() != dspString) {
1882 LYXERR(Debug::GUI, "different forecast found for "
1883 << sit->abs() << " => " << sit->forecastPathString());
1887 LYXERR(Debug::GUI, "same forecast found for "
1888 << sit->abs() << " => " << dspString);
1891 // if the path segment helped, add it. Otherwise add dots
1892 bool dots = !moreUnique;
1893 LYXERR(Debug::GUI, "using dots = " << dots);
1894 for (sit = segStart; sit != next; ++sit) {
1895 sit->shiftPathSegment(dots);
1896 LYXERR(Debug::GUI, "shifting "
1897 << sit->abs() << " => " << sit->displayString());
1900 // start new segment
1902 segString = nextString;
1906 // set new tab titles
1907 for (It it = paths.begin(); it != paths.end(); ++it) {
1908 int const tab_index = it->tab();
1909 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
1910 QString tab_text = it->displayString();
1911 if (!buf.fileName().empty() && !buf.isClean())
1913 setTabText(tab_index, tab_text);
1914 setTabToolTip(tab_index, it->abs());
1919 void TabWorkArea::showContextMenu(const QPoint & pos)
1922 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1923 if (clicked_tab_ == -1)
1928 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
1929 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
1930 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
1931 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1932 popup.exec(tabBar()->mapToGlobal(pos));
1938 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1940 QWidget * w = widget(fromIndex);
1941 QIcon icon = tabIcon(fromIndex);
1942 QString text = tabText(fromIndex);
1944 setCurrentIndex(fromIndex);
1945 removeTab(fromIndex);
1946 insertTab(toIndex, w, icon, text);
1947 setCurrentIndex(toIndex);
1951 DragTabBar::DragTabBar(QWidget* parent)
1954 setAcceptDrops(true);
1955 #if QT_VERSION >= 0x040500
1956 setTabsClosable(!lyxrc.single_close_tab_button);
1961 #if QT_VERSION < 0x040300
1962 int DragTabBar::tabAt(QPoint const & position) const
1964 const int max = count();
1965 for (int i = 0; i < max; ++i) {
1966 if (tabRect(i).contains(position))
1974 void DragTabBar::mousePressEvent(QMouseEvent * event)
1976 if (event->button() == Qt::LeftButton)
1977 dragStartPos_ = event->pos();
1978 QTabBar::mousePressEvent(event);
1982 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1984 // If the left button isn't pressed anymore then return
1985 if (!(event->buttons() & Qt::LeftButton))
1988 // If the distance is too small then return
1989 if ((event->pos() - dragStartPos_).manhattanLength()
1990 < QApplication::startDragDistance())
1993 // did we hit something after all?
1994 int tab = tabAt(dragStartPos_);
1998 // simulate button release to remove highlight from button
1999 int i = currentIndex();
2000 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2001 event->button(), event->buttons(), 0);
2002 QTabBar::mouseReleaseEvent(&me);
2006 QDrag * drag = new QDrag(this);
2007 QMimeData * mimeData = new QMimeData;
2008 // a crude way to distinguish tab-reodering drops from other ones
2009 mimeData->setData("action", "tab-reordering") ;
2010 drag->setMimeData(mimeData);
2012 #if QT_VERSION >= 0x040300
2013 // get tab pixmap as cursor
2014 QRect r = tabRect(tab);
2015 QPixmap pixmap(r.size());
2016 render(&pixmap, - r.topLeft());
2017 drag->setPixmap(pixmap);
2020 drag->start(Qt::MoveAction);
2026 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2028 // Only accept if it's an tab-reordering request
2029 QMimeData const * m = event->mimeData();
2030 QStringList formats = m->formats();
2031 if (formats.contains("action")
2032 && m->data("action") == "tab-reordering")
2033 event->acceptProposedAction();
2037 void DragTabBar::dropEvent(QDropEvent * event)
2039 int fromIndex = tabAt(dragStartPos_);
2040 int toIndex = tabAt(event->pos());
2042 // Tell interested objects that
2043 if (fromIndex != toIndex)
2044 tabMoveRequested(fromIndex, toIndex);
2045 event->acceptProposedAction();
2049 } // namespace frontend
2052 #include "moc_GuiWorkArea.cpp"