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"
50 #include "support/lassert.h"
52 #include "frontends/Application.h"
53 #include "frontends/FontMetrics.h"
54 #include "frontends/WorkAreaManager.h"
56 #include <QContextMenuEvent>
57 #include <QInputContext>
62 #include <QMainWindow>
66 #include <QPixmapCache>
69 #include <QToolButton>
73 #include "support/bind.h"
77 int const TabIndicatorWidth = 3;
83 using namespace lyx::support;
88 /// return the LyX mouse button state from Qt's
89 static mouse_button::state q_button_state(Qt::MouseButton button)
91 mouse_button::state b = mouse_button::none;
94 b = mouse_button::button1;
97 b = mouse_button::button2;
100 b = mouse_button::button3;
109 /// return the LyX mouse button state from Qt's
110 mouse_button::state q_motion_state(Qt::MouseButtons state)
112 mouse_button::state b = mouse_button::none;
113 if (state & Qt::LeftButton)
114 b |= mouse_button::button1;
115 if (state & Qt::MidButton)
116 b |= mouse_button::button2;
117 if (state & Qt::RightButton)
118 b |= mouse_button::button3;
131 void draw(QPainter & painter)
133 if (!show_ || !rect_.isValid())
137 int l = x_ - rect_.left();
138 int r = rect_.right() - x_;
139 int bot = rect_.bottom();
141 // draw vertical line
142 painter.fillRect(x_, y, cursor_width_, rect_.height(), color_);
144 // draw RTL/LTR indication
145 painter.setPen(color_);
148 painter.drawLine(x_, bot, x_ - l, bot);
150 painter.drawLine(x_, bot, x_ + cursor_width_ + r, bot);
153 // draw completion triangle
155 int m = y + rect_.height() / 2;
156 int d = TabIndicatorWidth - 1;
158 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
159 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
161 painter.drawLine(x_ + cursor_width_, m - d, x_ + cursor_width_ + d, m);
162 painter.drawLine(x_ + cursor_width_, m + d, x_ + cursor_width_ + d, m);
167 void update(int x, int y, int h, bool l_shape,
168 bool rtl, bool completable)
170 color_ = guiApp->colorCache().get(Color_cursor);
173 completable_ = completable;
176 // extension to left and right
180 // RTL/LTR indication
188 // completion triangle
191 l = max(l, TabIndicatorWidth);
193 r = max(r, TabIndicatorWidth);
196 // compute overall rectangle
197 rect_ = QRect(x - l, y, cursor_width_ + r + l, h);
200 void show(bool set_show = true) { show_ = set_show; }
201 void hide() { show_ = false; }
202 int cursorWidth() const { return cursor_width_; }
203 void recomputeWidth() {
204 cursor_width_ = lyxrc.cursor_width
206 : 1 + int((lyxrc.zoom + 50) / 200.0);
209 QRect const & rect() { return rect_; }
212 /// cursor is in RTL or LTR text
214 /// indication for RTL or LTR
216 /// triangle to show that a completion is available
222 /// rectangle, possibly with l_shape and completion triangle
224 /// x position (were the vertical line is drawn)
231 // This is a 'heartbeat' generating synthetic mouse move events when the
232 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
233 SyntheticMouseEvent::SyntheticMouseEvent()
234 : timeout(200), restart_timeout(true)
238 GuiWorkArea::GuiWorkArea(QWidget *)
239 : buffer_view_(0), lyx_view_(0),
240 cursor_visible_(false),
241 need_resize_(false), schedule_redraw_(false),
242 preedit_lines_(1), completer_(new GuiCompleter(this, this))
247 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
248 : buffer_view_(0), read_only_(buffer.isReadonly()), lyx_view_(0),
249 cursor_visible_(false),
250 need_resize_(false), schedule_redraw_(false),
251 preedit_lines_(1), completer_(new GuiCompleter(this, this))
259 void GuiWorkArea::init()
262 connect(&cursor_timeout_, SIGNAL(timeout()),
263 this, SLOT(toggleCursor()));
265 int const time = QApplication::cursorFlashTime() / 2;
267 cursor_timeout_.setInterval(time);
268 cursor_timeout_.start();
270 // let's initialize this just to be safe
271 cursor_timeout_.setInterval(500);
274 screen_ = QPixmap(viewport()->width(), viewport()->height());
275 // With Qt4.5 a mouse event will happen before the first paint event
276 // so make sure that the buffer view has an up to date metrics.
277 buffer_view_->resize(viewport()->width(), viewport()->height());
278 cursor_ = new frontend::CursorWidget();
281 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
282 setAcceptDrops(true);
283 setMouseTracking(true);
284 setMinimumSize(100, 70);
285 setFrameStyle(QFrame::NoFrame);
288 viewport()->setAutoFillBackground(false);
289 // We don't need double-buffering nor SystemBackground on
290 // the viewport because we have our own backing pixmap.
291 viewport()->setAttribute(Qt::WA_NoSystemBackground);
293 setFocusPolicy(Qt::StrongFocus);
295 setCursorShape(Qt::IBeamCursor);
297 synthetic_mouse_event_.timeout.timeout.connect(
298 bind(&GuiWorkArea::generateSyntheticMouseEvent,
301 // Initialize the vertical Scroll Bar
302 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
303 this, SLOT(scrollTo(int)));
305 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
306 << " viewport height: " << viewport()->height());
308 // Enables input methods for asian languages.
309 // Must be set when creating custom text editing widgets.
310 setAttribute(Qt::WA_InputMethodEnabled, true);
312 dialog_mode_ = false;
316 GuiWorkArea::~GuiWorkArea()
318 buffer_view_->buffer().workAreaManager().remove(this);
321 // Completer has a QObject parent and is thus automatically destroyed.
323 // delete completer_;
327 Qt::CursorShape GuiWorkArea::cursorShape() const
329 return viewport()->cursor().shape();
333 void GuiWorkArea::setCursorShape(Qt::CursorShape shape)
335 viewport()->setCursor(shape);
339 void GuiWorkArea::updateCursorShape()
341 setCursorShape(buffer_view_->clickableInset()
342 ? Qt::PointingHandCursor : Qt::IBeamCursor);
346 void GuiWorkArea::setGuiView(GuiView & gv)
352 void GuiWorkArea::setBuffer(Buffer & buffer)
355 buffer_view_ = new BufferView(buffer);
356 buffer.workAreaManager().add(this);
358 // HACK: Prevents an additional redraw when the scrollbar pops up
359 // which regularily happens on documents with more than one page.
360 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
361 // Since we have no geometry information yet, we assume that
362 // a document needs a scrollbar if there is more then four
363 // paragraph in the outermost text.
364 if (buffer.text().paragraphs().size() > 4)
365 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
366 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
370 void GuiWorkArea::fixVerticalScrollBar()
373 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
377 void GuiWorkArea::close()
379 lyx_view_->removeWorkArea(this);
383 void GuiWorkArea::setFullScreen(bool full_screen)
385 buffer_view_->setFullScreen(full_screen);
386 setFrameStyle(QFrame::NoFrame);
388 setFrameStyle(QFrame::NoFrame);
389 if (lyxrc.full_screen_scrollbar)
390 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
392 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
396 BufferView & GuiWorkArea::bufferView()
398 return *buffer_view_;
402 BufferView const & GuiWorkArea::bufferView() const
404 return *buffer_view_;
408 void GuiWorkArea::stopBlinkingCursor()
410 cursor_timeout_.stop();
415 void GuiWorkArea::startBlinkingCursor()
417 // do not show the cursor if the view is busy
423 buffer_view_->cursorPosAndHeight(p, h);
424 // Don't start blinking if the cursor isn't on screen.
425 if (!buffer_view_->cursorInView(p, h))
430 //we're not supposed to cache this value.
431 int const time = QApplication::cursorFlashTime() / 2;
434 cursor_timeout_.setInterval(time);
435 cursor_timeout_.start();
439 void GuiWorkArea::redraw(bool update_metrics)
442 // No need to redraw in this case.
445 // No need to do anything if this is the current view. The BufferView
446 // metrics are already up to date.
447 if (update_metrics || lyx_view_ != guiApp->currentView()
448 || lyx_view_->currentWorkArea() != this) {
449 // FIXME: it would be nice to optimize for the off-screen case.
450 buffer_view_->cursor().fixIfBroken();
451 buffer_view_->updateMetrics();
452 buffer_view_->cursor().fixIfBroken();
455 // update cursor position, because otherwise it has to wait until
456 // the blinking interval is over
457 if (cursor_visible_) {
462 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
464 update(0, 0, viewport()->width(), viewport()->height());
466 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
467 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
469 lyx_view_->updateStatusBar();
471 if (lyxerr.debugging(Debug::WORKAREA))
472 buffer_view_->coordCache().dump();
474 setReadOnly(buffer_view_->buffer().isReadonly());
480 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
482 if (lyx_view_->isFullScreen() && lyx_view_->menuBar()->isVisible()
483 && lyxrc.full_screen_menubar) {
484 // FIXME HACK: we should not have to do this here. See related comment
485 // in GuiView::event() (QEvent::ShortcutOverride)
486 lyx_view_->menuBar()->hide();
489 // In order to avoid bad surprise in the middle of an operation,
490 // we better stop the blinking cursor...
491 // the cursor gets restarted in GuiView::restartCursor()
492 stopBlinkingCursor();
493 guiApp->processKeySym(key, mod);
497 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
500 if (cmd0.action() == LFUN_FILE_OPEN) {
502 lyx_view_->dispatch(cmd0, dr);
508 if (cmd0.action() == LFUN_MOUSE_PRESS) {
509 if (mod == ShiftModifier)
510 cmd = FuncRequest(cmd0, "region-select");
511 else if (mod == ControlModifier)
512 cmd = FuncRequest(cmd0, "paragraph-select");
519 bool const notJustMovingTheMouse =
520 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
522 // In order to avoid bad surprise in the middle of an operation, we better stop
523 // the blinking cursor.
524 if (notJustMovingTheMouse)
525 stopBlinkingCursor();
527 buffer_view_->mouseEventDispatch(cmd);
529 // Skip these when selecting
530 if (cmd.action() != LFUN_MOUSE_MOTION) {
531 completer_->updateVisibility(false, false);
532 lyx_view_->updateDialogs();
533 lyx_view_->updateStatusBar();
536 // GUI tweaks except with mouse motion with no button pressed.
537 if (notJustMovingTheMouse) {
538 // Slight hack: this is only called currently when we
539 // clicked somewhere, so we force through the display
540 // of the new status here.
541 lyx_view_->clearMessage();
543 // Show the cursor immediately after any operation
544 startBlinkingCursor();
551 void GuiWorkArea::resizeBufferView()
553 // WARNING: Please don't put any code that will trigger a repaint here!
554 // We are already inside a paint event.
555 lyx_view_->setBusy(true);
558 buffer_view_->cursorPosAndHeight(p, h);
559 bool const cursor_in_view = buffer_view_->cursorInView(p, h);
560 buffer_view_->resize(viewport()->width(), viewport()->height());
562 buffer_view_->scrollToCursor();
565 // Update scrollbars which might have changed due different
566 // BufferView dimension. This is especially important when the
567 // BufferView goes from zero-size to the real-size for the first time,
568 // as the scrollbar paramters are then set for the first time.
571 lyx_view_->updateLayoutList();
572 lyx_view_->setBusy(false);
573 need_resize_ = false;
577 void GuiWorkArea::showCursor()
584 buffer_view_->cursorPosAndHeight(p, h);
585 if (!buffer_view_->cursorInView(p, h))
589 bool l_shape = false;
590 Font const & realfont = buffer_view_->cursor().real_current_font;
591 BufferParams const & bp = buffer_view_->buffer().params();
592 bool const samelang = realfont.language() == bp.language;
593 bool const isrtl = realfont.isVisibleRightToLeft();
595 if (!samelang || isrtl != bp.language->rightToLeft())
598 // The ERT language hack needs fixing up
599 if (realfont.language() == latex_language)
602 // show cursor on screen
603 Cursor & cur = buffer_view_->cursor();
604 bool completable = cur.inset().showCompletionCursor()
605 && completer_->completionAvailable()
606 && !completer_->popupVisible()
607 && !completer_->inlineVisible();
608 cursor_visible_ = true;
609 cursor_->recomputeWidth();
610 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
614 void GuiWorkArea::hideCursor()
616 if (!cursor_visible_)
619 cursor_visible_ = false;
624 void GuiWorkArea::toggleCursor()
633 void GuiWorkArea::updateScrollbar()
635 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
636 // WARNING: don't touch at the scrollbar value like this:
637 // verticalScrollBar()->setValue(scroll_.position);
638 // because this would cause a recursive signal/slot calling with
639 // GuiWorkArea::scrollTo
640 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
641 verticalScrollBar()->setPageStep(scroll_.page_step);
642 verticalScrollBar()->setSingleStep(scroll_.single_step);
643 verticalScrollBar()->setSliderPosition(scroll_.position);
647 void GuiWorkArea::scrollTo(int value)
649 stopBlinkingCursor();
650 buffer_view_->scrollDocView(value, true);
652 if (lyxrc.cursor_follows_scrollbar) {
653 buffer_view_->setCursorFromScrollbar();
654 lyx_view_->updateLayoutList();
656 // Show the cursor immediately after any operation.
657 startBlinkingCursor();
658 QApplication::syncX();
662 bool GuiWorkArea::event(QEvent * e)
665 case QEvent::ToolTip: {
666 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
667 if (lyxrc.use_tooltip) {
668 QPoint pos = helpEvent->pos();
669 if (pos.x() < viewport()->width()) {
670 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
671 QToolTip::showText(helpEvent->globalPos(), s);
674 QToolTip::hideText();
676 // Don't forget to accept the event!
681 case QEvent::ShortcutOverride: {
682 // We catch this event in order to catch the Tab or Shift+Tab key press
683 // which are otherwise reserved to focus switching between controls
685 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
686 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
687 || (ke->key() == Qt::Key_Backtab && (
688 ke->modifiers() == Qt::ShiftModifier
689 || ke->modifiers() == Qt::NoModifier))) {
693 return QAbstractScrollArea::event(e);
697 return QAbstractScrollArea::event(e);
703 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
706 if (e->reason() == QContextMenuEvent::Mouse)
707 // the menu name is set on mouse press
708 name = context_menu_name_;
710 QPoint pos = e->pos();
711 Cursor const & cur = buffer_view_->cursor();
712 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
713 // Do not access the context menu of math right in front of before
714 // the cursor. This does not work when the cursor is in text.
715 Inset * inset = cur.paragraph().getInset(cur.pos());
716 if (inset && inset->asInsetMath())
718 else if (cur.pos() > 0) {
719 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
724 name = buffer_view_->contextMenu(pos.x(), pos.y());
728 QAbstractScrollArea::contextMenuEvent(e);
731 // always show mnemonics when the keyboard is used to show the context menu
732 // FIXME: This should be fixed in Qt itself
733 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
734 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_, keyboard);
736 QAbstractScrollArea::contextMenuEvent(e);
739 // Position the menu to the right.
740 // FIXME: menu position should be different for RTL text.
741 menu->exec(e->globalPos());
746 void GuiWorkArea::focusInEvent(QFocusEvent * e)
748 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
749 if (lyx_view_->currentWorkArea() != this)
750 lyx_view_->setCurrentWorkArea(this);
752 startBlinkingCursor();
753 QAbstractScrollArea::focusInEvent(e);
757 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
759 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
760 stopBlinkingCursor();
761 QAbstractScrollArea::focusOutEvent(e);
765 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
767 if (dc_event_.active && dc_event_ == *e) {
768 dc_event_.active = false;
769 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
770 q_button_state(e->button()));
776 inputContext()->reset();
778 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
779 q_button_state(e->button()));
780 dispatch(cmd, q_key_state(e->modifiers()));
782 // Save the context menu on mouse press, because also the mouse
783 // cursor is set on mouse press. Afterwards, we can either release
784 // the mousebutton somewhere else, or the cursor might have moved
785 // due to the DEPM. We need to do this after the mouse has been
786 // set in dispatch(), because the selection state might change.
787 if (e->button() == Qt::RightButton)
788 context_menu_name_ = buffer_view_->contextMenu(e->x(), e->y());
794 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
796 if (synthetic_mouse_event_.timeout.running())
797 synthetic_mouse_event_.timeout.stop();
799 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
800 q_button_state(e->button()));
806 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
808 // we kill the triple click if we move
809 doubleClickTimeout();
810 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
811 q_motion_state(e->buttons()));
815 // If we're above or below the work area...
816 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
817 && e->buttons() == mouse_button::button1) {
818 // Make sure only a synthetic event can cause a page scroll,
819 // so they come at a steady rate:
821 // _Force_ a scroll up:
822 cmd.set_y(e->y() - 21);
824 cmd.set_y(e->y() + 21);
825 // Store the event, to be handled when the timeout expires.
826 synthetic_mouse_event_.cmd = cmd;
828 if (synthetic_mouse_event_.timeout.running()) {
829 // Discard the event. Note that it _may_ be handled
830 // when the timeout expires if
831 // synthetic_mouse_event_.cmd has not been overwritten.
832 // Ie, when the timeout expires, we handle the
833 // most recent event but discard all others that
834 // occurred after the one used to start the timeout
835 // in the first place.
839 synthetic_mouse_event_.restart_timeout = true;
840 synthetic_mouse_event_.timeout.start();
841 // Fall through to handle this event...
843 } else if (synthetic_mouse_event_.timeout.running()) {
844 // Store the event, to be possibly handled when the timeout
846 // Once the timeout has expired, normal control is returned
847 // to mouseMoveEvent (restart_timeout = false).
848 // This results in a much smoother 'feel' when moving the
849 // mouse back into the work area.
850 synthetic_mouse_event_.cmd = cmd;
851 synthetic_mouse_event_.restart_timeout = false;
858 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
860 // Wheel rotation by one notch results in a delta() of 120 (see
861 // documentation of QWheelEvent)
862 double const delta = ev->delta() / 120.0;
864 switch (lyxrc.scroll_wheel_zoom) {
865 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
866 zoom = ev->modifiers() & Qt::ControlModifier;
867 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
869 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
870 zoom = ev->modifiers() & Qt::ShiftModifier;
871 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
873 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
874 zoom = ev->modifiers() & Qt::AltModifier;
875 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
877 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
881 docstring arg = convert<docstring>(int(5 * delta));
882 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
886 // Take into account the desktop wide settings.
887 int const lines = qApp->wheelScrollLines();
888 int const page_step = verticalScrollBar()->pageStep();
889 // Test if the wheel mouse is set to one screen at a time.
890 int scroll_value = lines > page_step
891 ? page_step : lines * verticalScrollBar()->singleStep();
893 // Take into account the rotation and the user preferences.
894 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
895 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
896 << " delta = " << delta << " scroll_value = " << scroll_value
897 << " page_step = " << page_step);
899 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
905 void GuiWorkArea::generateSyntheticMouseEvent()
907 int const e_y = synthetic_mouse_event_.cmd.y();
908 int const wh = buffer_view_->workHeight();
909 bool const up = e_y < 0;
910 bool const down = e_y > wh;
912 // Set things off to generate the _next_ 'pseudo' event.
914 if (synthetic_mouse_event_.restart_timeout) {
915 // This is some magic formulae to determine the speed
916 // of scrolling related to the position of the mouse.
919 int dist = up ? -e_y : e_y - wh;
920 time = max(min(200, 250000 / (dist * dist)), 1) ;
923 step = 80000 / (time * time);
927 synthetic_mouse_event_.timeout.setTimeout(time);
928 synthetic_mouse_event_.timeout.start();
931 // Can we scroll further ?
932 int const value = verticalScrollBar()->value();
933 if (value == verticalScrollBar()->maximum()
934 || value == verticalScrollBar()->minimum()) {
935 synthetic_mouse_event_.timeout.stop();
940 if (step <= 2 * wh) {
941 buffer_view_->scroll(up ? -step : step);
942 buffer_view_->updateMetrics();
944 buffer_view_->scrollDocView(value + up ? -step : step, false);
947 // In which paragraph do we have to set the cursor ?
948 Cursor & cur = buffer_view_->cursor();
949 // FIXME: we don't know howto handle math.
950 Text * text = cur.text();
953 TextMetrics const & tm = buffer_view_->textMetrics(text);
955 pair<pit_type, const ParagraphMetrics *> p = up ? tm.first() : tm.last();
956 ParagraphMetrics const & pm = *p.second;
957 pit_type const pit = p.first;
959 if (pm.rows().empty())
962 // Find the row at which we set the cursor.
963 RowList::const_iterator rit = pm.rows().begin();
964 RowList::const_iterator rlast = pm.rows().end();
965 int yy = pm.position() - pm.ascent();
966 for (--rlast; rit != rlast; ++rit) {
967 int h = rit->height();
968 if ((up && yy + h > 0)
969 || (!up && yy + h > wh - defaultRowHeight()))
974 // Find the position of the cursor
976 int x = synthetic_mouse_event_.cmd.x();
977 pos_type const pos = rit->pos() + tm.getColumnNearX(pit, *rit, x, bound);
984 buffer_view_->buffer().changed(false);
989 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
991 // Do not process here some keys if dialog_mode_ is set
993 && (ev->modifiers() == Qt::NoModifier
994 || ev->modifiers() == Qt::ShiftModifier)
995 && (ev->key() == Qt::Key_Escape
996 || ev->key() == Qt::Key_Enter
997 || ev->key() == Qt::Key_Return)
1003 // intercept some keys if completion popup is visible
1004 if (completer_->popupVisible()) {
1005 switch (ev->key()) {
1007 case Qt::Key_Return:
1008 completer_->activate();
1014 // do nothing if there are other events
1015 // (the auto repeated events come too fast)
1016 // it looks like this is only needed on X11
1018 if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1019 switch (ev->key()) {
1020 case Qt::Key_PageDown:
1021 case Qt::Key_PageUp:
1026 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1033 KeyModifier m = q_key_state(ev->modifiers());
1036 if (m & ShiftModifier)
1038 if (m & ControlModifier)
1040 if (m & AltModifier)
1042 if (m & MetaModifier)
1045 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1046 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1047 << " keyState: " << str);
1050 setKeySymbol(&sym, ev);
1052 processKeySym(sym, q_key_state(ev->modifiers()));
1060 void GuiWorkArea::doubleClickTimeout()
1062 dc_event_.active = false;
1066 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1068 dc_event_ = DoubleClick(ev);
1069 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1070 SLOT(doubleClickTimeout()));
1071 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1073 q_button_state(ev->button()));
1079 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1081 QAbstractScrollArea::resizeEvent(ev);
1082 need_resize_ = true;
1087 void GuiWorkArea::update(int x, int y, int w, int h)
1089 viewport()->update(x, y, w, h);
1093 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1095 QRect const rc = ev->rect();
1096 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1097 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1100 screen_ = QPixmap(viewport()->width(), viewport()->height());
1102 if (cursor_visible_) {
1108 QPainter pain(viewport());
1109 pain.drawPixmap(rc, screen_, rc);
1110 cursor_->draw(pain);
1115 void GuiWorkArea::updateScreen()
1117 GuiPainter pain(&screen_);
1118 buffer_view_->draw(pain);
1122 void GuiWorkArea::showCursor(int x, int y, int h,
1123 bool l_shape, bool rtl, bool completable)
1125 if (schedule_redraw_) {
1126 // This happens when a graphic conversion is finished. As we don't know
1127 // the size of the new graphics, it's better the update everything.
1128 // We can't use redraw() here because this would trigger a infinite
1129 // recursive loop with showCursor().
1130 buffer_view_->resize(viewport()->width(), viewport()->height());
1133 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
1134 schedule_redraw_ = false;
1135 // Show the cursor immediately after the update.
1141 cursor_->update(x, y, h, l_shape, rtl, completable);
1143 viewport()->update(cursor_->rect());
1147 void GuiWorkArea::removeCursor()
1150 //if (!qApp->focusWidget())
1151 viewport()->update(cursor_->rect());
1155 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1157 QString const & commit_string = e->commitString();
1158 docstring const & preedit_string
1159 = qstring_to_ucs4(e->preeditString());
1161 if (!commit_string.isEmpty()) {
1163 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1164 << " commitString: " << e->commitString());
1168 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1169 for (int i = 0; i != commit_string.size(); ++i) {
1170 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1175 // Hide the cursor during the kana-kanji transformation.
1176 if (preedit_string.empty())
1177 startBlinkingCursor();
1179 stopBlinkingCursor();
1181 // last_width : for checking if last preedit string was/wasn't empty.
1182 static bool last_width = false;
1183 if (!last_width && preedit_string.empty()) {
1184 // if last_width is last length of preedit string.
1189 GuiPainter pain(&screen_);
1190 buffer_view_->updateMetrics();
1191 buffer_view_->draw(pain);
1192 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1193 FontMetrics const & fm = theFontMetrics(font);
1194 int height = fm.maxHeight();
1195 int cur_x = cursor_->rect().left();
1196 int cur_y = cursor_->rect().bottom();
1198 // redraw area of preedit string.
1199 update(0, cur_y - height, viewport()->width(),
1200 (height + 1) * preedit_lines_);
1202 if (preedit_string.empty()) {
1210 // att : stores an IM attribute.
1211 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1213 // get attributes of input method cursor.
1214 // cursor_pos : cursor position in preedit string.
1215 size_t cursor_pos = 0;
1216 bool cursor_is_visible = false;
1217 for (int i = 0; i != att.size(); ++i) {
1218 if (att.at(i).type == QInputMethodEvent::Cursor) {
1219 cursor_pos = att.at(i).start;
1220 cursor_is_visible = att.at(i).length != 0;
1225 size_t preedit_length = preedit_string.length();
1227 // get position of selection in input method.
1228 // FIXME: isn't there a way to do this simplier?
1229 // rStart : cursor position in selected string in IM.
1231 // rLength : selected string length in IM.
1233 if (cursor_pos < preedit_length) {
1234 for (int i = 0; i != att.size(); ++i) {
1235 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1236 if (att.at(i).start <= int(cursor_pos)
1237 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1238 rStart = att.at(i).start;
1239 rLength = att.at(i).length;
1240 if (!cursor_is_visible)
1241 cursor_pos += rLength;
1248 rStart = cursor_pos;
1252 int const right_margin = buffer_view_->rightMargin();
1253 Painter::preedit_style ps;
1254 // Most often there would be only one line:
1256 for (size_t pos = 0; pos != preedit_length; ++pos) {
1257 char_type const typed_char = preedit_string[pos];
1258 // reset preedit string style
1259 ps = Painter::preedit_default;
1261 // if we reached the right extremity of the screen, go to next line.
1262 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1263 cur_x = right_margin;
1264 cur_y += height + 1;
1267 // preedit strings are displayed with dashed underline
1268 // and partial strings are displayed white on black indicating
1269 // that we are in selecting mode in the input method.
1270 // FIXME: rLength == preedit_length is not a changing condition
1271 // FIXME: should be put out of the loop.
1273 && pos < rStart + rLength
1274 && !(cursor_pos < rLength && rLength == preedit_length))
1275 ps = Painter::preedit_selecting;
1277 if (pos == cursor_pos
1278 && (cursor_pos < rLength && rLength == preedit_length))
1279 ps = Painter::preedit_cursor;
1281 // draw one character and update cur_x.
1282 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1285 // update the preedit string screen area.
1286 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1287 (height + 1) * preedit_lines_);
1289 // Don't forget to accept the event!
1294 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1296 QRect cur_r(0, 0, 0, 0);
1298 // this is the CJK-specific composition window position and
1299 // the context menu position when the menu key is pressed.
1300 case Qt::ImMicroFocus:
1301 cur_r = cursor_->rect();
1302 if (preedit_lines_ != 1)
1304 cur_r.moveBottom(cur_r.bottom()
1305 + cur_r.height() * (preedit_lines_ - 1));
1306 // return lower right of cursor in LyX.
1309 return QWidget::inputMethodQuery(query);
1314 void GuiWorkArea::updateWindowTitle()
1316 docstring maximize_title;
1317 docstring minimize_title;
1319 Buffer const & buf = buffer_view_->buffer();
1320 FileName const file_name = buf.fileName();
1321 if (!file_name.empty()) {
1322 maximize_title = file_name.displayName(130);
1323 minimize_title = from_utf8(file_name.onlyFileName());
1324 if (buf.lyxvc().inUse()) {
1325 if (buf.lyxvc().locking())
1326 maximize_title += _(" (version control, locking)");
1328 maximize_title += _(" (version control)");
1330 if (!buf.isClean()) {
1331 maximize_title += _(" (changed)");
1332 minimize_title += char_type('*');
1334 if (buf.isReadonly())
1335 maximize_title += _(" (read only)");
1338 QString const new_title = toqstr(maximize_title);
1339 if (new_title != windowTitle()) {
1340 QWidget::setWindowTitle(new_title);
1341 QWidget::setWindowIconText(toqstr(minimize_title));
1347 void GuiWorkArea::setReadOnly(bool read_only)
1349 if (read_only_ == read_only)
1351 read_only_ = read_only;
1352 updateWindowTitle();
1353 if (this == lyx_view_->currentWorkArea())
1354 lyx_view_->updateDialogs();
1358 bool GuiWorkArea::isFullScreen()
1360 return lyx_view_ && lyx_view_->isFullScreen();
1364 ////////////////////////////////////////////////////////////////////
1368 ////////////////////////////////////////////////////////////////////
1371 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1373 buffer_ = theBufferList().newBuffer(
1374 support::FileName::tempName().absFileName() + "_embedded.internal");
1375 buffer_->setUnnamed(true);
1376 buffer_->setFullyLoaded(true);
1377 setBuffer(*buffer_);
1378 setDialogMode(true);
1382 EmbeddedWorkArea::~EmbeddedWorkArea()
1384 // No need to destroy buffer and bufferview here, because it is done
1385 // in theBufferList() destruction loop at application exit
1389 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1392 GuiWorkArea::closeEvent(ev);
1396 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1399 GuiWorkArea::hideEvent(ev);
1403 QSize EmbeddedWorkArea::sizeHint () const
1406 // GuiWorkArea sets the size to the screen's viewport
1407 // by returning a value this gets overridden
1408 // EmbeddedWorkArea is now sized to fit in the layout
1409 // of the parent, and has a minimum size set in GuiWorkArea
1410 // which is what we return here
1411 return QSize(100, 70);
1415 void EmbeddedWorkArea::disable()
1417 stopBlinkingCursor();
1418 if (view().currentWorkArea() != this)
1420 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1421 // tolerates it and shows the background logo), what happens if
1422 // an EmbeddedWorkArea is closed after closing all document WAs
1423 view().setCurrentWorkArea(view().currentMainWorkArea());
1426 ////////////////////////////////////////////////////////////////////
1430 ////////////////////////////////////////////////////////////////////
1433 class NoTabFrameMacStyle : public QMacStyle {
1436 QRect subElementRect(SubElement element, const QStyleOption * option,
1437 const QWidget * widget = 0) const
1439 QRect rect = QMacStyle::subElementRect(element, option, widget);
1440 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1442 // The Qt Mac style puts the contents into a 3 pixel wide box
1443 // which looks very ugly and not like other Mac applications.
1444 // Hence we remove this here, and moreover the 16 pixel round
1445 // frame above if the tab bar is hidden.
1446 if (element == QStyle::SE_TabWidgetTabContents) {
1447 rect.adjust(- rect.left(), 0, rect.left(), 0);
1456 NoTabFrameMacStyle noTabFrameMacStyle;
1460 TabWorkArea::TabWorkArea(QWidget * parent)
1461 : QTabWidget(parent), clicked_tab_(-1)
1464 setStyle(&noTabFrameMacStyle);
1466 #if QT_VERSION < 0x040500
1467 lyxrc.single_close_tab_button = true;
1470 QPalette pal = palette();
1471 pal.setColor(QPalette::Active, QPalette::Button,
1472 pal.color(QPalette::Active, QPalette::Window));
1473 pal.setColor(QPalette::Disabled, QPalette::Button,
1474 pal.color(QPalette::Disabled, QPalette::Window));
1475 pal.setColor(QPalette::Inactive, QPalette::Button,
1476 pal.color(QPalette::Inactive, QPalette::Window));
1478 QObject::connect(this, SIGNAL(currentChanged(int)),
1479 this, SLOT(on_currentTabChanged(int)));
1481 closeBufferButton = new QToolButton(this);
1482 closeBufferButton->setPalette(pal);
1483 // FIXME: rename the icon to closebuffer.png
1484 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1485 closeBufferButton->setText("Close File");
1486 closeBufferButton->setAutoRaise(true);
1487 closeBufferButton->setCursor(Qt::ArrowCursor);
1488 closeBufferButton->setToolTip(qt_("Close File"));
1489 closeBufferButton->setEnabled(true);
1490 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1491 this, SLOT(closeCurrentBuffer()));
1492 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1494 // setup drag'n'drop
1495 QTabBar* tb = new DragTabBar;
1496 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1497 this, SLOT(moveTab(int, int)));
1498 tb->setElideMode(Qt::ElideNone);
1501 // make us responsible for the context menu of the tabbar
1502 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1503 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1504 this, SLOT(showContextMenu(const QPoint &)));
1505 #if QT_VERSION >= 0x040500
1506 connect(tb, SIGNAL(tabCloseRequested(int)),
1507 this, SLOT(closeTab(int)));
1510 setUsesScrollButtons(true);
1514 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1516 if (event->button() != Qt::LeftButton)
1519 // return early if double click on existing tabs
1520 for (int i = 0; i < count(); ++i)
1521 if (tabBar()->tabRect(i).contains(event->pos()))
1524 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1528 void TabWorkArea::setFullScreen(bool full_screen)
1530 for (int i = 0; i != count(); ++i) {
1531 if (GuiWorkArea * wa = workArea(i))
1532 wa->setFullScreen(full_screen);
1535 if (lyxrc.full_screen_tabbar)
1536 showBar(!full_screen && count() > 1);
1540 void TabWorkArea::showBar(bool show)
1542 tabBar()->setEnabled(show);
1543 tabBar()->setVisible(show);
1544 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1545 #if QT_VERSION >= 0x040500
1546 setTabsClosable(!lyxrc.single_close_tab_button);
1551 GuiWorkArea * TabWorkArea::currentWorkArea()
1556 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1562 GuiWorkArea * TabWorkArea::workArea(int index)
1564 return dynamic_cast<GuiWorkArea *>(widget(index));
1568 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1570 // FIXME: this method doesn't work if we have more than work area
1571 // showing the same buffer.
1572 for (int i = 0; i != count(); ++i) {
1573 GuiWorkArea * wa = workArea(i);
1574 LASSERT(wa, return 0);
1575 if (&wa->bufferView().buffer() == &buffer)
1582 void TabWorkArea::closeAll()
1585 GuiWorkArea * wa = workArea(0);
1593 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1595 LASSERT(work_area, /**/);
1596 int index = indexOf(work_area);
1600 if (index == currentIndex())
1601 // Make sure the work area is up to date.
1602 on_currentTabChanged(index);
1604 // Switch to the work area.
1605 setCurrentIndex(index);
1606 work_area->setFocus();
1612 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1614 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1615 wa->setUpdatesEnabled(false);
1616 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1617 // when hiding it again below).
1618 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1619 showBar(count() > 0);
1620 addTab(wa, wa->windowTitle());
1621 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1622 this, SLOT(updateTabTexts()));
1623 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1624 setFullScreen(true);
1626 // Hide tabbar if there's only one tab.
1627 showBar(count() > 1);
1635 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1637 LASSERT(work_area, return false);
1638 int index = indexOf(work_area);
1642 work_area->setUpdatesEnabled(false);
1647 // make sure the next work area is enabled.
1648 currentWidget()->setUpdatesEnabled(true);
1649 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1650 setFullScreen(true);
1652 // Show tabbar only if there's more than one tab.
1653 showBar(count() > 1);
1655 lastWorkAreaRemoved();
1663 void TabWorkArea::on_currentTabChanged(int i)
1665 // returns e.g. on application destruction
1668 GuiWorkArea * wa = workArea(i);
1669 LASSERT(wa, return);
1670 wa->setUpdatesEnabled(true);
1674 currentWorkAreaChanged(wa);
1676 LYXERR(Debug::GUI, "currentTabChanged " << i
1677 << " File: " << wa->bufferView().buffer().absFileName());
1681 void TabWorkArea::closeCurrentBuffer()
1684 if (clicked_tab_ == -1)
1685 wa = currentWorkArea();
1687 wa = workArea(clicked_tab_);
1690 wa->view().closeWorkArea(wa);
1694 void TabWorkArea::hideCurrentTab()
1697 if (clicked_tab_ == -1)
1698 wa = currentWorkArea();
1700 wa = workArea(clicked_tab_);
1703 wa->view().hideWorkArea(wa);
1707 void TabWorkArea::closeTab(int index)
1709 on_currentTabChanged(index);
1712 wa = currentWorkArea();
1714 wa = workArea(index);
1717 wa->view().closeWorkArea(wa);
1724 /// make vector happy
1727 DisplayPath(int tab, FileName const & filename)
1730 filename_ = (filename.extension() == "lyx") ?
1731 toqstr(filename.onlyFileNameWithoutExt())
1732 : toqstr(filename.onlyFileName());
1733 postfix_ = toqstr(filename.absoluteFilePath()).
1734 split("/", QString::SkipEmptyParts);
1735 postfix_.pop_back();
1736 abs_ = toqstr(filename.absoluteFilePath());
1737 dottedPrefix_ = false;
1740 /// Absolute path for debugging.
1745 /// Add the first segment from the postfix or three dots to the prefix.
1746 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1747 /// when really needed.
1748 void shiftPathSegment(bool dotted)
1750 if (postfix_.count() <= 0)
1754 if (dottedPrefix_ && !prefix_.isEmpty())
1756 prefix_ += postfix_.front() + "/";
1758 dottedPrefix_ = dotted && !prefix_.isEmpty();
1759 postfix_.pop_front();
1762 QString displayString() const
1764 if (prefix_.isEmpty())
1767 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1768 return prefix_ + (dots ? ".../" : "") + filename_;
1771 QString forecastPathString() const
1773 if (postfix_.count() == 0)
1774 return displayString();
1777 + (dottedPrefix_ ? ".../" : "")
1778 + postfix_.front() + "/";
1781 bool final() const { return postfix_.empty(); }
1783 int tab() const { return tab_; }
1789 QStringList postfix_;
1802 bool operator<(DisplayPath const & a, DisplayPath const & b)
1804 return a.displayString() < b.displayString();
1808 bool operator==(DisplayPath const & a, DisplayPath const & b)
1810 return a.displayString() == b.displayString();
1814 void TabWorkArea::updateTabTexts()
1819 std::list<DisplayPath> paths;
1820 typedef std::list<DisplayPath>::iterator It;
1822 // collect full names first: path into postfix, empty prefix and
1823 // filename without extension
1824 for (size_t i = 0; i < n; ++i) {
1825 GuiWorkArea * i_wa = workArea(i);
1826 FileName const fn = i_wa->bufferView().buffer().fileName();
1827 paths.push_back(DisplayPath(i, fn));
1830 // go through path segments and see if it helps to make the path more unique
1831 bool somethingChanged = true;
1832 bool allFinal = false;
1833 while (somethingChanged && !allFinal) {
1834 // adding path segments changes order
1837 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1838 somethingChanged = false;
1841 // find segments which are not unique (i.e. non-atomic)
1842 It it = paths.begin();
1844 QString segString = it->displayString();
1845 for (; it != paths.end(); ++it) {
1846 // look to the next item
1851 allFinal = allFinal && it->final();
1853 LYXERR(Debug::GUI, "it = " << it->abs()
1854 << " => " << it->displayString());
1856 // still the same segment?
1858 if ((next != paths.end()
1859 && (nextString = next->displayString()) == segString))
1861 LYXERR(Debug::GUI, "segment ended");
1863 // only a trivial one with one element?
1864 if (it == segStart) {
1865 // start new segment
1867 segString = nextString;
1871 // we found a non-atomic segment segStart <= sit <= it < next.
1872 // Shift path segments and hope for the best
1873 // that it makes the path more unique.
1874 somethingChanged = true;
1876 QString dspString = sit->forecastPathString();
1877 LYXERR(Debug::GUI, "first forecast found for "
1878 << sit->abs() << " => " << dspString);
1880 bool moreUnique = false;
1881 for (; sit != next; ++sit) {
1882 if (sit->forecastPathString() != dspString) {
1883 LYXERR(Debug::GUI, "different forecast found for "
1884 << sit->abs() << " => " << sit->forecastPathString());
1888 LYXERR(Debug::GUI, "same forecast found for "
1889 << sit->abs() << " => " << dspString);
1892 // if the path segment helped, add it. Otherwise add dots
1893 bool dots = !moreUnique;
1894 LYXERR(Debug::GUI, "using dots = " << dots);
1895 for (sit = segStart; sit != next; ++sit) {
1896 sit->shiftPathSegment(dots);
1897 LYXERR(Debug::GUI, "shifting "
1898 << sit->abs() << " => " << sit->displayString());
1901 // start new segment
1903 segString = nextString;
1907 // set new tab titles
1908 for (It it = paths.begin(); it != paths.end(); ++it) {
1909 int const tab_index = it->tab();
1910 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
1911 QString tab_text = it->displayString();
1912 if (!buf.fileName().empty() && !buf.isClean())
1914 setTabText(tab_index, tab_text);
1915 setTabToolTip(tab_index, it->abs());
1920 void TabWorkArea::showContextMenu(const QPoint & pos)
1923 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1924 if (clicked_tab_ == -1)
1929 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
1930 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
1931 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
1932 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1933 popup.exec(tabBar()->mapToGlobal(pos));
1939 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1941 QWidget * w = widget(fromIndex);
1942 QIcon icon = tabIcon(fromIndex);
1943 QString text = tabText(fromIndex);
1945 setCurrentIndex(fromIndex);
1946 removeTab(fromIndex);
1947 insertTab(toIndex, w, icon, text);
1948 setCurrentIndex(toIndex);
1952 DragTabBar::DragTabBar(QWidget* parent)
1955 setAcceptDrops(true);
1956 #if QT_VERSION >= 0x040500
1957 setTabsClosable(!lyxrc.single_close_tab_button);
1962 #if QT_VERSION < 0x040300
1963 int DragTabBar::tabAt(QPoint const & position) const
1965 const int max = count();
1966 for (int i = 0; i < max; ++i) {
1967 if (tabRect(i).contains(position))
1975 void DragTabBar::mousePressEvent(QMouseEvent * event)
1977 if (event->button() == Qt::LeftButton)
1978 dragStartPos_ = event->pos();
1979 QTabBar::mousePressEvent(event);
1983 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1985 // If the left button isn't pressed anymore then return
1986 if (!(event->buttons() & Qt::LeftButton))
1989 // If the distance is too small then return
1990 if ((event->pos() - dragStartPos_).manhattanLength()
1991 < QApplication::startDragDistance())
1994 // did we hit something after all?
1995 int tab = tabAt(dragStartPos_);
1999 // simulate button release to remove highlight from button
2000 int i = currentIndex();
2001 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2002 event->button(), event->buttons(), 0);
2003 QTabBar::mouseReleaseEvent(&me);
2007 QDrag * drag = new QDrag(this);
2008 QMimeData * mimeData = new QMimeData;
2009 // a crude way to distinguish tab-reodering drops from other ones
2010 mimeData->setData("action", "tab-reordering") ;
2011 drag->setMimeData(mimeData);
2013 #if QT_VERSION >= 0x040300
2014 // get tab pixmap as cursor
2015 QRect r = tabRect(tab);
2016 QPixmap pixmap(r.size());
2017 render(&pixmap, - r.topLeft());
2018 drag->setPixmap(pixmap);
2021 drag->start(Qt::MoveAction);
2027 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2029 // Only accept if it's an tab-reordering request
2030 QMimeData const * m = event->mimeData();
2031 QStringList formats = m->formats();
2032 if (formats.contains("action")
2033 && m->data("action") == "tab-reordering")
2034 event->acceptProposedAction();
2038 void DragTabBar::dropEvent(QDropEvent * event)
2040 int fromIndex = tabAt(dragStartPos_);
2041 int toIndex = tabAt(event->pos());
2043 // Tell interested objects that
2044 if (fromIndex != toIndex)
2045 tabMoveRequested(fromIndex, toIndex);
2046 event->acceptProposedAction();
2050 } // namespace frontend
2053 #include "moc_GuiWorkArea.cpp"