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"
77 int const CursorWidth = 2;
79 int const CursorWidth = 1;
81 int const TabIndicatorWidth = 3;
87 using namespace lyx::support;
92 /// return the LyX mouse button state from Qt's
93 static mouse_button::state q_button_state(Qt::MouseButton button)
95 mouse_button::state b = mouse_button::none;
98 b = mouse_button::button1;
101 b = mouse_button::button2;
103 case Qt::RightButton:
104 b = mouse_button::button3;
113 /// return the LyX mouse button state from Qt's
114 mouse_button::state q_motion_state(Qt::MouseButtons state)
116 mouse_button::state b = mouse_button::none;
117 if (state & Qt::LeftButton)
118 b |= mouse_button::button1;
119 if (state & Qt::MidButton)
120 b |= mouse_button::button2;
121 if (state & Qt::RightButton)
122 b |= mouse_button::button3;
133 void draw(QPainter & painter)
135 if (!show_ || !rect_.isValid())
139 int l = x_ - rect_.left();
140 int r = rect_.right() - x_;
141 int bot = rect_.bottom();
143 // draw vertica linel
144 painter.fillRect(x_, y, CursorWidth, rect_.height(), color_);
146 // draw RTL/LTR indication
147 painter.setPen(color_);
150 painter.drawLine(x_, bot, x_ - l, bot);
152 painter.drawLine(x_, bot, x_ + CursorWidth + r, bot);
155 // draw completion triangle
157 int m = y + rect_.height() / 2;
158 int d = TabIndicatorWidth - 1;
160 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
161 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
163 painter.drawLine(x_ + CursorWidth, m - d, x_ + CursorWidth + d, m);
164 painter.drawLine(x_ + CursorWidth, m + d, x_ + CursorWidth + d, m);
169 void update(int x, int y, int h, bool l_shape,
170 bool rtl, bool completable)
172 color_ = guiApp->colorCache().get(Color_cursor);
175 completable_ = completable;
178 // extension to left and right
182 // RTL/LTR indication
190 // completion triangle
193 l = max(l, TabIndicatorWidth);
195 r = max(r, TabIndicatorWidth);
198 // compute overall rectangle
199 rect_ = QRect(x - l, y, CursorWidth + r + l, h);
202 void show(bool set_show = true) { show_ = set_show; }
203 void hide() { show_ = false; }
205 QRect const & rect() { return rect_; }
208 /// cursor is in RTL or LTR text
210 /// indication for RTL or LTR
212 /// triangle to show that a completion is available
218 /// rectangle, possibly with l_shape and completion triangle
220 /// x position (were the vertical line is drawn)
225 // This is a 'heartbeat' generating synthetic mouse move events when the
226 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
227 SyntheticMouseEvent::SyntheticMouseEvent()
228 : timeout(200), restart_timeout(true)
232 GuiWorkArea::GuiWorkArea(QWidget *)
233 : buffer_view_(0), lyx_view_(0),
234 cursor_visible_(false),
235 need_resize_(false), schedule_redraw_(false),
236 preedit_lines_(1), completer_(new GuiCompleter(this, this)),
237 context_target_pos_()
242 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
243 : buffer_view_(0), read_only_(buffer.isReadonly()), lyx_view_(0),
244 cursor_visible_(false),
245 need_resize_(false), schedule_redraw_(false),
246 preedit_lines_(1), completer_(new GuiCompleter(this, this)),
247 context_target_pos_()
255 void GuiWorkArea::init()
258 connect(&cursor_timeout_, SIGNAL(timeout()),
259 this, SLOT(toggleCursor()));
261 int const time = QApplication::cursorFlashTime() / 2;
263 cursor_timeout_.setInterval(time);
264 cursor_timeout_.start();
266 // let's initialize this just to be safe
267 cursor_timeout_.setInterval(500);
270 screen_ = QPixmap(viewport()->width(), viewport()->height());
271 // With Qt4.5 a mouse event will happen before the first paint event
272 // so make sure that the buffer view has an up to date metrics.
273 buffer_view_->resize(viewport()->width(), viewport()->height());
274 cursor_ = new frontend::CursorWidget();
277 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
278 setAcceptDrops(true);
279 setMouseTracking(true);
280 setMinimumSize(100, 70);
281 setFrameStyle(QFrame::NoFrame);
284 viewport()->setAutoFillBackground(false);
285 // We don't need double-buffering nor SystemBackground on
286 // the viewport because we have our own backing pixmap.
287 viewport()->setAttribute(Qt::WA_NoSystemBackground);
289 setFocusPolicy(Qt::StrongFocus);
291 viewport()->setCursor(Qt::IBeamCursor);
293 synthetic_mouse_event_.timeout.timeout.connect(
294 bind(&GuiWorkArea::generateSyntheticMouseEvent,
297 // Initialize the vertical Scroll Bar
298 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
299 this, SLOT(scrollTo(int)));
301 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
302 << " viewport height: " << viewport()->height());
304 // Enables input methods for asian languages.
305 // Must be set when creating custom text editing widgets.
306 setAttribute(Qt::WA_InputMethodEnabled, true);
308 dialog_mode_ = false;
312 GuiWorkArea::~GuiWorkArea()
314 buffer_view_->buffer().workAreaManager().remove(this);
317 // Completer has a QObject parent and is thus automatically destroyed.
319 // delete completer_;
323 void GuiWorkArea::setGuiView(GuiView & gv)
329 void GuiWorkArea::setBuffer(Buffer & buffer)
332 buffer_view_ = new BufferView(buffer);
333 buffer.workAreaManager().add(this);
335 // HACK: Prevents an additional redraw when the scrollbar pops up
336 // which regularily happens on documents with more than one page.
337 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
338 // Since we have no geometry information yet, we assume that
339 // a document needs a scrollbar if there is more then four
340 // paragraph in the outermost text.
341 if (buffer.text().paragraphs().size() > 4)
342 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
343 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
347 void GuiWorkArea::fixVerticalScrollBar()
350 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
354 void GuiWorkArea::close()
356 lyx_view_->removeWorkArea(this);
360 void GuiWorkArea::setFullScreen(bool full_screen)
362 buffer_view_->setFullScreen(full_screen);
363 setFrameStyle(QFrame::NoFrame);
365 setFrameStyle(QFrame::NoFrame);
366 if (lyxrc.full_screen_scrollbar)
367 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
369 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
373 BufferView & GuiWorkArea::bufferView()
375 return *buffer_view_;
379 BufferView const & GuiWorkArea::bufferView() const
381 return *buffer_view_;
385 void GuiWorkArea::stopBlinkingCursor()
387 cursor_timeout_.stop();
392 void GuiWorkArea::startBlinkingCursor()
394 // do not show the cursor if the view is busy
400 buffer_view_->cursorPosAndHeight(p, h);
401 // Don't start blinking if the cursor isn't on screen.
402 if (!buffer_view_->cursorInView(p, h))
407 //we're not supposed to cache this value.
408 int const time = QApplication::cursorFlashTime() / 2;
411 cursor_timeout_.setInterval(time);
412 cursor_timeout_.start();
416 void GuiWorkArea::redraw(bool update_metrics)
419 // No need to redraw in this case.
422 // No need to do anything if this is the current view. The BufferView
423 // metrics are already up to date.
424 if (update_metrics || lyx_view_ != guiApp->currentView()
425 || lyx_view_->currentWorkArea() != this) {
426 // FIXME: it would be nice to optimize for the off-screen case.
427 buffer_view_->updateMetrics();
428 buffer_view_->cursor().fixIfBroken();
431 // update cursor position, because otherwise it has to wait until
432 // the blinking interval is over
433 if (cursor_visible_) {
438 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
440 update(0, 0, viewport()->width(), viewport()->height());
442 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
443 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
445 lyx_view_->updateStatusBar();
447 if (lyxerr.debugging(Debug::WORKAREA))
448 buffer_view_->coordCache().dump();
450 setReadOnly(buffer_view_->buffer().isReadonly());
454 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
456 if (lyx_view_->isFullScreen() && lyx_view_->menuBar()->isVisible()
457 && lyxrc.full_screen_menubar) {
458 // FIXME HACK: we should not have to do this here. See related comment
459 // in GuiView::event() (QEvent::ShortcutOverride)
460 lyx_view_->menuBar()->hide();
463 // In order to avoid bad surprise in the middle of an operation,
464 // we better stop the blinking cursor...
465 // the cursor gets restarted in GuiView::restartCursor()
466 stopBlinkingCursor();
467 guiApp->processKeySym(key, mod);
471 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
474 if (cmd0.action() == LFUN_FILE_OPEN) {
476 lyx_view_->dispatch(cmd0, dr);
482 if (cmd0.action() == LFUN_MOUSE_PRESS) {
483 if (mod == ShiftModifier)
484 cmd = FuncRequest(cmd0, "region-select");
485 else if (mod == ControlModifier)
486 cmd = FuncRequest(cmd0, "paragraph-select");
493 bool const notJustMovingTheMouse =
494 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
496 // In order to avoid bad surprise in the middle of an operation, we better stop
497 // the blinking cursor.
498 if (notJustMovingTheMouse)
499 stopBlinkingCursor();
501 buffer_view_->mouseEventDispatch(cmd);
503 // Skip these when selecting
504 if (cmd.action() != LFUN_MOUSE_MOTION) {
505 completer_->updateVisibility(false, false);
506 lyx_view_->updateDialogs();
507 lyx_view_->updateStatusBar();
510 // GUI tweaks except with mouse motion with no button pressed.
511 if (notJustMovingTheMouse) {
512 // Slight hack: this is only called currently when we
513 // clicked somewhere, so we force through the display
514 // of the new status here.
515 lyx_view_->clearMessage();
517 // Show the cursor immediately after any operation
518 startBlinkingCursor();
523 void GuiWorkArea::resizeBufferView()
525 // WARNING: Please don't put any code that will trigger a repaint here!
526 // We are already inside a paint event.
527 lyx_view_->setBusy(true);
530 buffer_view_->cursorPosAndHeight(p, h);
531 bool const cursor_in_view = buffer_view_->cursorInView(p, h);
532 buffer_view_->resize(viewport()->width(), viewport()->height());
534 buffer_view_->scrollToCursor();
537 // Update scrollbars which might have changed due different
538 // BufferView dimension. This is especially important when the
539 // BufferView goes from zero-size to the real-size for the first time,
540 // as the scrollbar paramters are then set for the first time.
543 lyx_view_->updateLayoutList();
544 lyx_view_->setBusy(false);
545 need_resize_ = false;
549 void GuiWorkArea::showCursor()
556 buffer_view_->cursorPosAndHeight(p, h);
557 if (!buffer_view_->cursorInView(p, h))
561 bool l_shape = false;
562 Font const & realfont = buffer_view_->cursor().real_current_font;
563 BufferParams const & bp = buffer_view_->buffer().params();
564 bool const samelang = realfont.language() == bp.language;
565 bool const isrtl = realfont.isVisibleRightToLeft();
567 if (!samelang || isrtl != bp.language->rightToLeft())
570 // The ERT language hack needs fixing up
571 if (realfont.language() == latex_language)
574 // show cursor on screen
575 Cursor & cur = buffer_view_->cursor();
576 bool completable = cur.inset().showCompletionCursor()
577 && completer_->completionAvailable()
578 && !completer_->popupVisible()
579 && !completer_->inlineVisible();
580 cursor_visible_ = true;
581 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
585 void GuiWorkArea::hideCursor()
587 if (!cursor_visible_)
590 cursor_visible_ = false;
595 void GuiWorkArea::toggleCursor()
604 void GuiWorkArea::updateScrollbar()
606 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
607 // WARNING: don't touch at the scrollbar value like this:
608 // verticalScrollBar()->setValue(scroll_.position);
609 // because this would cause a recursive signal/slot calling with
610 // GuiWorkArea::scrollTo
611 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
612 verticalScrollBar()->setPageStep(scroll_.page_step);
613 verticalScrollBar()->setSingleStep(scroll_.single_step);
614 verticalScrollBar()->setSliderPosition(scroll_.position);
618 void GuiWorkArea::scrollTo(int value)
620 stopBlinkingCursor();
621 buffer_view_->scrollDocView(value, true);
623 if (lyxrc.cursor_follows_scrollbar) {
624 buffer_view_->setCursorFromScrollbar();
625 lyx_view_->updateLayoutList();
627 // Show the cursor immediately after any operation.
628 startBlinkingCursor();
629 QApplication::syncX();
633 bool GuiWorkArea::event(QEvent * e)
636 case QEvent::ToolTip: {
637 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
638 if (lyxrc.use_tooltip) {
639 QPoint pos = helpEvent->pos();
640 if (pos.x() < viewport()->width()) {
641 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
642 QToolTip::showText(helpEvent->globalPos(), s);
645 QToolTip::hideText();
647 // Don't forget to accept the event!
652 case QEvent::ShortcutOverride: {
653 // We catch this event in order to catch the Tab or Shift+Tab key press
654 // which are otherwise reserved to focus switching between controls
656 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
657 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
658 || ke->modifiers() & Qt::ControlModifier)
659 return QAbstractScrollArea::event(e);
665 return QAbstractScrollArea::event(e);
671 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
674 if (e->reason() == QContextMenuEvent::Mouse)
675 // the position is set on mouse press
676 pos = context_target_pos_;
679 Cursor const & cur = buffer_view_->cursor();
680 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
681 // Do not access the context menu of math right in front of before
682 // the cursor. This does not work when the cursor is in text.
683 Inset * inset = cur.paragraph().getInset(cur.pos());
684 if (inset && inset->asInsetMath())
686 else if (cur.pos() > 0) {
687 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
692 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
694 QAbstractScrollArea::contextMenuEvent(e);
697 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
699 QAbstractScrollArea::contextMenuEvent(e);
702 // Position the menu to the right.
703 // FIXME: menu position should be different for RTL text.
704 menu->exec(e->globalPos());
709 void GuiWorkArea::focusInEvent(QFocusEvent * e)
711 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
712 if (lyx_view_->currentWorkArea() != this)
713 lyx_view_->setCurrentWorkArea(this);
715 startBlinkingCursor();
716 QAbstractScrollArea::focusInEvent(e);
720 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
722 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
723 stopBlinkingCursor();
724 QAbstractScrollArea::focusOutEvent(e);
728 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
730 if (dc_event_.active && dc_event_ == *e) {
731 dc_event_.active = false;
732 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
733 q_button_state(e->button()));
739 if (e->button() == Qt::RightButton)
740 context_target_pos_ = e->pos();
742 inputContext()->reset();
744 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
745 q_button_state(e->button()));
746 dispatch(cmd, q_key_state(e->modifiers()));
751 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
753 if (synthetic_mouse_event_.timeout.running())
754 synthetic_mouse_event_.timeout.stop();
756 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
757 q_button_state(e->button()));
763 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
765 // we kill the triple click if we move
766 doubleClickTimeout();
767 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
768 q_motion_state(e->buttons()));
772 // If we're above or below the work area...
773 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
774 && e->buttons() == mouse_button::button1) {
775 // Make sure only a synthetic event can cause a page scroll,
776 // so they come at a steady rate:
778 // _Force_ a scroll up:
779 cmd.set_y(e->y() - 21);
781 cmd.set_y(e->y() + 21);
782 // Store the event, to be handled when the timeout expires.
783 synthetic_mouse_event_.cmd = cmd;
785 if (synthetic_mouse_event_.timeout.running()) {
786 // Discard the event. Note that it _may_ be handled
787 // when the timeout expires if
788 // synthetic_mouse_event_.cmd has not been overwritten.
789 // Ie, when the timeout expires, we handle the
790 // most recent event but discard all others that
791 // occurred after the one used to start the timeout
792 // in the first place.
796 synthetic_mouse_event_.restart_timeout = true;
797 synthetic_mouse_event_.timeout.start();
798 // Fall through to handle this event...
800 } else if (synthetic_mouse_event_.timeout.running()) {
801 // Store the event, to be possibly handled when the timeout
803 // Once the timeout has expired, normal control is returned
804 // to mouseMoveEvent (restart_timeout = false).
805 // This results in a much smoother 'feel' when moving the
806 // mouse back into the work area.
807 synthetic_mouse_event_.cmd = cmd;
808 synthetic_mouse_event_.restart_timeout = false;
815 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
817 // Wheel rotation by one notch results in a delta() of 120 (see
818 // documentation of QWheelEvent)
819 int const delta = ev->delta() / 120;
820 if (ev->modifiers() & Qt::ControlModifier) {
821 docstring arg = convert<docstring>(5 * delta);
822 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
826 // Take into account the desktop wide settings.
827 int const lines = qApp->wheelScrollLines();
828 int const page_step = verticalScrollBar()->pageStep();
829 // Test if the wheel mouse is set to one screen at a time.
830 int scroll_value = lines > page_step
831 ? page_step : lines * verticalScrollBar()->singleStep();
833 // Take into account the rotation.
834 scroll_value *= delta;
836 // Take into account user preference.
837 scroll_value = int(scroll_value * lyxrc.mouse_wheel_speed);
838 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
839 << " delta = " << delta << " scroll_value = " << scroll_value
840 << " page_step = " << page_step);
842 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
848 void GuiWorkArea::generateSyntheticMouseEvent()
850 int const e_y = synthetic_mouse_event_.cmd.y();
851 int const wh = buffer_view_->workHeight();
852 bool const up = e_y < 0;
853 bool const down = e_y > wh;
855 // Set things off to generate the _next_ 'pseudo' event.
857 if (synthetic_mouse_event_.restart_timeout) {
858 // This is some magic formulae to determine the speed
859 // of scrolling related to the position of the mouse.
862 int dist = up ? -e_y : e_y - wh;
863 time = max(min(200, 250000 / (dist * dist)), 1) ;
866 step = 80000 / (time * time);
870 synthetic_mouse_event_.timeout.setTimeout(time);
871 synthetic_mouse_event_.timeout.start();
874 // Can we scroll further ?
875 int const value = verticalScrollBar()->value();
876 if (value == verticalScrollBar()->maximum()
877 || value == verticalScrollBar()->minimum()) {
878 synthetic_mouse_event_.timeout.stop();
883 if (step <= 2 * wh) {
884 buffer_view_->scroll(up ? -step : step);
885 buffer_view_->updateMetrics();
887 buffer_view_->scrollDocView(value + up ? -step : step, false);
890 // In which paragraph do we have to set the cursor ?
891 Cursor & cur = buffer_view_->cursor();
892 TextMetrics const & tm = buffer_view_->textMetrics(cur.text());
894 pair<pit_type, const ParagraphMetrics *> p = up ? tm.first() : tm.last();
895 ParagraphMetrics const & pm = *p.second;
896 pit_type const pit = p.first;
898 if (pm.rows().empty())
901 // Find the row at which we set the cursor.
902 RowList::const_iterator rit = pm.rows().begin();
903 RowList::const_iterator rlast = pm.rows().end();
904 int yy = pm.position() - pm.ascent();
905 for (--rlast; rit != rlast; ++rit) {
906 int h = rit->height();
907 if ((up && yy + h > 0)
908 || (!up && yy + h > wh - defaultRowHeight()))
913 // Find the position of the cursor
915 int x = synthetic_mouse_event_.cmd.x();
916 pos_type const pos = rit->pos() + tm.getColumnNearX(pit, *rit, x, bound);
923 buffer_view_->buffer().changed(false);
928 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
930 // Do not process here some keys if dialog_mode_ is set
932 && (ev->modifiers() == Qt::NoModifier
933 || ev->modifiers() == Qt::ShiftModifier)
934 && (ev->key() == Qt::Key_Escape
935 || ev->key() == Qt::Key_Enter
936 || ev->key() == Qt::Key_Return)
942 // intercept some keys if completion popup is visible
943 if (completer_->popupVisible()) {
947 completer_->activate();
953 // do nothing if there are other events
954 // (the auto repeated events come too fast)
955 // it looks like this is only needed on X11
957 if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
958 LYXERR(Debug::KEY, "system is busy: keyPress event ignored");
964 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
965 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
968 setKeySymbol(&sym, ev);
970 processKeySym(sym, q_key_state(ev->modifiers()));
978 void GuiWorkArea::doubleClickTimeout()
980 dc_event_.active = false;
984 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
986 dc_event_ = DoubleClick(ev);
987 QTimer::singleShot(QApplication::doubleClickInterval(), this,
988 SLOT(doubleClickTimeout()));
989 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
991 q_button_state(ev->button()));
997 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
999 QAbstractScrollArea::resizeEvent(ev);
1000 need_resize_ = true;
1005 void GuiWorkArea::update(int x, int y, int w, int h)
1007 viewport()->repaint(x, y, w, h);
1011 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1013 QRect const rc = ev->rect();
1014 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1015 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1018 screen_ = QPixmap(viewport()->width(), viewport()->height());
1020 if (cursor_visible_) {
1026 QPainter pain(viewport());
1027 pain.drawPixmap(rc, screen_, rc);
1028 cursor_->draw(pain);
1033 void GuiWorkArea::updateScreen()
1035 GuiPainter pain(&screen_);
1036 buffer_view_->draw(pain);
1040 void GuiWorkArea::showCursor(int x, int y, int h,
1041 bool l_shape, bool rtl, bool completable)
1043 if (schedule_redraw_) {
1044 // This happens when a graphic conversion is finished. As we don't know
1045 // the size of the new graphics, it's better the update everything.
1046 // We can't use redraw() here because this would trigger a infinite
1047 // recursive loop with showCursor().
1048 buffer_view_->resize(viewport()->width(), viewport()->height());
1051 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
1052 schedule_redraw_ = false;
1053 // Show the cursor immediately after the update.
1059 cursor_->update(x, y, h, l_shape, rtl, completable);
1061 viewport()->update(cursor_->rect());
1065 void GuiWorkArea::removeCursor()
1068 //if (!qApp->focusWidget())
1069 viewport()->update(cursor_->rect());
1073 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1075 QString const & commit_string = e->commitString();
1076 docstring const & preedit_string
1077 = qstring_to_ucs4(e->preeditString());
1079 if (!commit_string.isEmpty()) {
1081 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1082 << " commitString: " << e->commitString());
1086 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1087 for (int i = 0; i != commit_string.size(); ++i) {
1088 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1093 // Hide the cursor during the kana-kanji transformation.
1094 if (preedit_string.empty())
1095 startBlinkingCursor();
1097 stopBlinkingCursor();
1099 // last_width : for checking if last preedit string was/wasn't empty.
1100 static bool last_width = false;
1101 if (!last_width && preedit_string.empty()) {
1102 // if last_width is last length of preedit string.
1107 GuiPainter pain(&screen_);
1108 buffer_view_->updateMetrics();
1109 buffer_view_->draw(pain);
1110 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1111 FontMetrics const & fm = theFontMetrics(font);
1112 int height = fm.maxHeight();
1113 int cur_x = cursor_->rect().left();
1114 int cur_y = cursor_->rect().bottom();
1116 // redraw area of preedit string.
1117 update(0, cur_y - height, viewport()->width(),
1118 (height + 1) * preedit_lines_);
1120 if (preedit_string.empty()) {
1128 // att : stores an IM attribute.
1129 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1131 // get attributes of input method cursor.
1132 // cursor_pos : cursor position in preedit string.
1133 size_t cursor_pos = 0;
1134 bool cursor_is_visible = false;
1135 for (int i = 0; i != att.size(); ++i) {
1136 if (att.at(i).type == QInputMethodEvent::Cursor) {
1137 cursor_pos = att.at(i).start;
1138 cursor_is_visible = att.at(i).length != 0;
1143 size_t preedit_length = preedit_string.length();
1145 // get position of selection in input method.
1146 // FIXME: isn't there a way to do this simplier?
1147 // rStart : cursor position in selected string in IM.
1149 // rLength : selected string length in IM.
1151 if (cursor_pos < preedit_length) {
1152 for (int i = 0; i != att.size(); ++i) {
1153 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1154 if (att.at(i).start <= int(cursor_pos)
1155 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1156 rStart = att.at(i).start;
1157 rLength = att.at(i).length;
1158 if (!cursor_is_visible)
1159 cursor_pos += rLength;
1166 rStart = cursor_pos;
1170 int const right_margin = buffer_view_->rightMargin();
1171 Painter::preedit_style ps;
1172 // Most often there would be only one line:
1174 for (size_t pos = 0; pos != preedit_length; ++pos) {
1175 char_type const typed_char = preedit_string[pos];
1176 // reset preedit string style
1177 ps = Painter::preedit_default;
1179 // if we reached the right extremity of the screen, go to next line.
1180 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1181 cur_x = right_margin;
1182 cur_y += height + 1;
1185 // preedit strings are displayed with dashed underline
1186 // and partial strings are displayed white on black indicating
1187 // that we are in selecting mode in the input method.
1188 // FIXME: rLength == preedit_length is not a changing condition
1189 // FIXME: should be put out of the loop.
1191 && pos < rStart + rLength
1192 && !(cursor_pos < rLength && rLength == preedit_length))
1193 ps = Painter::preedit_selecting;
1195 if (pos == cursor_pos
1196 && (cursor_pos < rLength && rLength == preedit_length))
1197 ps = Painter::preedit_cursor;
1199 // draw one character and update cur_x.
1200 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1203 // update the preedit string screen area.
1204 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1205 (height + 1) * preedit_lines_);
1207 // Don't forget to accept the event!
1212 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1214 QRect cur_r(0, 0, 0, 0);
1216 // this is the CJK-specific composition window position and
1217 // the context menu position when the menu key is pressed.
1218 case Qt::ImMicroFocus:
1219 cur_r = cursor_->rect();
1220 if (preedit_lines_ != 1)
1222 cur_r.moveBottom(cur_r.bottom()
1223 + cur_r.height() * (preedit_lines_ - 1));
1224 // return lower right of cursor in LyX.
1227 return QWidget::inputMethodQuery(query);
1232 void GuiWorkArea::updateWindowTitle()
1234 docstring maximize_title;
1235 docstring minimize_title;
1237 Buffer & buf = buffer_view_->buffer();
1238 FileName const fileName = buf.fileName();
1239 if (!fileName.empty()) {
1240 maximize_title = fileName.displayName(30);
1241 minimize_title = from_utf8(fileName.onlyFileName());
1242 if (buf.lyxvc().inUse()) {
1243 if (buf.lyxvc().locking())
1244 maximize_title += _(" (version control, locking)");
1246 maximize_title += _(" (version control)");
1248 if (!buf.isClean()) {
1249 maximize_title += _(" (changed)");
1250 minimize_title += char_type('*');
1252 if (buf.isReadonly())
1253 maximize_title += _(" (read only)");
1256 QString title = windowTitle();
1257 QString new_title = toqstr(maximize_title);
1258 if (title == new_title)
1261 QWidget::setWindowTitle(new_title);
1262 QWidget::setWindowIconText(toqstr(minimize_title));
1267 void GuiWorkArea::setReadOnly(bool read_only)
1269 if (read_only_ == read_only)
1271 read_only_ = read_only;
1272 updateWindowTitle();
1273 if (this == lyx_view_->currentWorkArea())
1274 lyx_view_->updateDialogs();
1278 bool GuiWorkArea::isFullScreen()
1280 return lyx_view_ && lyx_view_->isFullScreen();
1284 ////////////////////////////////////////////////////////////////////
1288 ////////////////////////////////////////////////////////////////////
1291 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1293 buffer_ = theBufferList().newBuffer(
1294 support::FileName::tempName().absFileName() + "_embedded.internal");
1295 buffer_->setUnnamed(true);
1296 buffer_->setFullyLoaded(true);
1297 setBuffer(*buffer_);
1298 setDialogMode(true);
1302 EmbeddedWorkArea::~EmbeddedWorkArea()
1304 // No need to destroy buffer and bufferview here, because it is done
1305 // in theBuffeerList() destruction loop at application exit
1309 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1312 GuiWorkArea::closeEvent(ev);
1316 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1319 GuiWorkArea::hideEvent(ev);
1323 QSize EmbeddedWorkArea::sizeHint () const
1326 // GuiWorkArea sets the size to the screen's viewport
1327 // by returning a value this gets overridden
1328 // EmbeddedWorkArea is now sized to fit in the layout
1329 // of the parent, and has a minimum size set in GuiWorkArea
1330 // which is what we return here
1331 return QSize(100, 70);
1335 void EmbeddedWorkArea::disable()
1337 stopBlinkingCursor();
1338 if (view().currentWorkArea() != this)
1340 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1341 // tolerates it and shows the background logo), what happens if
1342 // an EmbeddedWorkArea is closed after closing all document WAs
1343 view().setCurrentWorkArea(view().currentMainWorkArea());
1346 ////////////////////////////////////////////////////////////////////
1350 ////////////////////////////////////////////////////////////////////
1353 class NoTabFrameMacStyle : public QMacStyle {
1356 QRect subElementRect(SubElement element, const QStyleOption * option,
1357 const QWidget * widget = 0) const
1359 QRect rect = QMacStyle::subElementRect(element, option, widget);
1360 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1362 // The Qt Mac style puts the contents into a 3 pixel wide box
1363 // which looks very ugly and not like other Mac applications.
1364 // Hence we remove this here, and moreover the 16 pixel round
1365 // frame above if the tab bar is hidden.
1366 if (element == QStyle::SE_TabWidgetTabContents) {
1367 rect.adjust(- rect.left(), 0, rect.left(), 0);
1376 NoTabFrameMacStyle noTabFrameMacStyle;
1380 TabWorkArea::TabWorkArea(QWidget * parent)
1381 : QTabWidget(parent), clicked_tab_(-1)
1384 setStyle(&noTabFrameMacStyle);
1386 #if QT_VERSION < 0x040500
1387 lyxrc.single_close_tab_button = true;
1390 QPalette pal = palette();
1391 pal.setColor(QPalette::Active, QPalette::Button,
1392 pal.color(QPalette::Active, QPalette::Window));
1393 pal.setColor(QPalette::Disabled, QPalette::Button,
1394 pal.color(QPalette::Disabled, QPalette::Window));
1395 pal.setColor(QPalette::Inactive, QPalette::Button,
1396 pal.color(QPalette::Inactive, QPalette::Window));
1398 QObject::connect(this, SIGNAL(currentChanged(int)),
1399 this, SLOT(on_currentTabChanged(int)));
1401 closeBufferButton = new QToolButton(this);
1402 closeBufferButton->setPalette(pal);
1403 // FIXME: rename the icon to closebuffer.png
1404 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1405 closeBufferButton->setText("Close File");
1406 closeBufferButton->setAutoRaise(true);
1407 closeBufferButton->setCursor(Qt::ArrowCursor);
1408 closeBufferButton->setToolTip(qt_("Close File"));
1409 closeBufferButton->setEnabled(true);
1410 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1411 this, SLOT(closeCurrentBuffer()));
1412 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1414 // setup drag'n'drop
1415 QTabBar* tb = new DragTabBar;
1416 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1417 this, SLOT(moveTab(int, int)));
1418 tb->setElideMode(Qt::ElideNone);
1421 // make us responsible for the context menu of the tabbar
1422 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1423 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1424 this, SLOT(showContextMenu(const QPoint &)));
1425 #if QT_VERSION >= 0x040500
1426 connect(tb, SIGNAL(tabCloseRequested(int)),
1427 this, SLOT(closeTab(int)));
1430 setUsesScrollButtons(true);
1434 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1436 if (event->button() != Qt::LeftButton)
1439 // return early if double click on existing tabs
1440 for (int i = 0; i < count(); ++i)
1441 if (tabBar()->tabRect(i).contains(event->pos()))
1444 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1448 void TabWorkArea::setFullScreen(bool full_screen)
1450 for (int i = 0; i != count(); ++i) {
1451 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1452 wa->setFullScreen(full_screen);
1455 if (lyxrc.full_screen_tabbar)
1456 showBar(!full_screen && count() > 1);
1460 void TabWorkArea::showBar(bool show)
1462 tabBar()->setEnabled(show);
1463 tabBar()->setVisible(show);
1464 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1465 #if QT_VERSION >= 0x040500
1466 setTabsClosable(!lyxrc.single_close_tab_button);
1471 GuiWorkArea * TabWorkArea::currentWorkArea()
1476 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1482 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1484 // FIXME: this method doesn't work if we have more than work area
1485 // showing the same buffer.
1486 for (int i = 0; i != count(); ++i) {
1487 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1488 LASSERT(wa, return 0);
1489 if (&wa->bufferView().buffer() == &buffer)
1496 void TabWorkArea::closeAll()
1499 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1507 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1509 LASSERT(work_area, /**/);
1510 int index = indexOf(work_area);
1514 if (index == currentIndex())
1515 // Make sure the work area is up to date.
1516 on_currentTabChanged(index);
1518 // Switch to the work area.
1519 setCurrentIndex(index);
1520 work_area->setFocus();
1526 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1528 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1529 wa->setUpdatesEnabled(false);
1530 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1531 // when hiding it again below).
1532 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1533 showBar(count() > 0);
1534 addTab(wa, wa->windowTitle());
1535 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1536 this, SLOT(updateTabTexts()));
1537 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1538 setFullScreen(true);
1540 // Hide tabbar if there's only one tab.
1541 showBar(count() > 1);
1549 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1551 LASSERT(work_area, return false);
1552 int index = indexOf(work_area);
1556 work_area->setUpdatesEnabled(false);
1561 // make sure the next work area is enabled.
1562 currentWidget()->setUpdatesEnabled(true);
1563 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1564 setFullScreen(true);
1566 // Show tabbar only if there's more than one tab.
1567 showBar(count() > 1);
1569 lastWorkAreaRemoved();
1577 void TabWorkArea::on_currentTabChanged(int i)
1579 // returns e.g. on application destruction
1582 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1583 LASSERT(wa, return);
1584 wa->setUpdatesEnabled(true);
1588 currentWorkAreaChanged(wa);
1590 LYXERR(Debug::GUI, "currentTabChanged " << i
1591 << " File: " << wa->bufferView().buffer().absFileName());
1595 void TabWorkArea::closeCurrentBuffer()
1598 if (clicked_tab_ == -1)
1599 wa = currentWorkArea();
1601 wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1604 wa->view().closeWorkArea(wa);
1608 void TabWorkArea::hideCurrentTab()
1611 if (clicked_tab_ == -1)
1612 wa = currentWorkArea();
1614 wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1617 wa->view().hideWorkArea(wa);
1621 void TabWorkArea::closeTab(int index)
1623 on_currentTabChanged(index);
1626 wa = currentWorkArea();
1628 wa = dynamic_cast<GuiWorkArea *>(widget(index));
1631 wa->view().closeWorkArea(wa);
1638 /// make vector happy
1641 DisplayPath(int tab, FileName const & filename)
1644 filename_ = (filename.extension() == "lyx") ?
1645 toqstr(filename.onlyFileNameWithoutExt())
1646 : toqstr(filename.onlyFileName());
1647 postfix_ = toqstr(filename.absoluteFilePath()).
1648 split("/", QString::SkipEmptyParts);
1649 postfix_.pop_back();
1650 abs_ = toqstr(filename.absoluteFilePath());
1651 dottedPrefix_ = false;
1654 /// Absolute path for debugging.
1659 /// Add the first segment from the postfix or three dots to the prefix.
1660 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1661 /// when really needed.
1662 void shiftPathSegment(bool dotted)
1664 if (postfix_.count() <= 0)
1668 if (dottedPrefix_ && !prefix_.isEmpty())
1670 prefix_ += postfix_.front() + "/";
1672 dottedPrefix_ = dotted && !prefix_.isEmpty();
1673 postfix_.pop_front();
1676 QString displayString() const
1678 if (prefix_.isEmpty())
1681 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1682 return prefix_ + (dots ? ".../" : "") + filename_;
1685 QString forecastPathString() const
1687 if (postfix_.count() == 0)
1688 return displayString();
1691 + (dottedPrefix_ ? ".../" : "")
1692 + postfix_.front() + "/";
1695 bool final() const { return postfix_.empty(); }
1697 int tab() const { return tab_; }
1703 QStringList postfix_;
1716 bool operator<(DisplayPath const & a, DisplayPath const & b)
1718 return a.displayString() < b.displayString();
1722 bool operator==(DisplayPath const & a, DisplayPath const & b)
1724 return a.displayString() == b.displayString();
1728 void TabWorkArea::updateTabTexts()
1733 std::list<DisplayPath> paths;
1734 typedef std::list<DisplayPath>::iterator It;
1736 // collect full names first: path into postfix, empty prefix and
1737 // filename without extension
1738 for (size_t i = 0; i < n; ++i) {
1739 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(i));
1740 FileName const fn = i_wa->bufferView().buffer().fileName();
1741 paths.push_back(DisplayPath(i, fn));
1744 // go through path segments and see if it helps to make the path more unique
1745 bool somethingChanged = true;
1746 bool allFinal = false;
1747 while (somethingChanged && !allFinal) {
1748 // adding path segments changes order
1751 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1752 somethingChanged = false;
1755 // find segments which are not unique (i.e. non-atomic)
1756 It it = paths.begin();
1758 QString segString = it->displayString();
1759 for (; it != paths.end(); ++it) {
1760 // look to the next item
1765 allFinal = allFinal && it->final();
1767 LYXERR(Debug::GUI, "it = " << it->abs()
1768 << " => " << it->displayString());
1770 // still the same segment?
1772 if ((next != paths.end()
1773 && (nextString = next->displayString()) == segString))
1775 LYXERR(Debug::GUI, "segment ended");
1777 // only a trivial one with one element?
1778 if (it == segStart) {
1779 // start new segment
1781 segString = nextString;
1785 // we found a non-atomic segment segStart <= sit <= it < next.
1786 // Shift path segments and hope for the best
1787 // that it makes the path more unique.
1788 somethingChanged = true;
1790 QString dspString = sit->forecastPathString();
1791 LYXERR(Debug::GUI, "first forecast found for "
1792 << sit->abs() << " => " << dspString);
1794 bool moreUnique = false;
1795 for (; sit != next; ++sit) {
1796 if (sit->forecastPathString() != dspString) {
1797 LYXERR(Debug::GUI, "different forecast found for "
1798 << sit->abs() << " => " << sit->forecastPathString());
1802 LYXERR(Debug::GUI, "same forecast found for "
1803 << sit->abs() << " => " << dspString);
1806 // if the path segment helped, add it. Otherwise add dots
1807 bool dots = !moreUnique;
1808 LYXERR(Debug::GUI, "using dots = " << dots);
1809 for (sit = segStart; sit != next; ++sit) {
1810 sit->shiftPathSegment(dots);
1811 LYXERR(Debug::GUI, "shifting "
1812 << sit->abs() << " => " << sit->displayString());
1815 // start new segment
1817 segString = nextString;
1821 // set new tab titles
1822 for (It it = paths.begin(); it != paths.end(); ++it) {
1823 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(it->tab()));
1824 Buffer & buf = i_wa->bufferView().buffer();
1825 if (!buf.fileName().empty() && !buf.isClean())
1826 setTabText(it->tab(), it->displayString() + "*");
1828 setTabText(it->tab(), it->displayString());
1833 void TabWorkArea::showContextMenu(const QPoint & pos)
1836 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1837 if (clicked_tab_ == -1)
1842 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
1843 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
1844 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
1845 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1846 popup.exec(tabBar()->mapToGlobal(pos));
1852 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1854 QWidget * w = widget(fromIndex);
1855 QIcon icon = tabIcon(fromIndex);
1856 QString text = tabText(fromIndex);
1858 setCurrentIndex(fromIndex);
1859 removeTab(fromIndex);
1860 insertTab(toIndex, w, icon, text);
1861 setCurrentIndex(toIndex);
1865 DragTabBar::DragTabBar(QWidget* parent)
1868 setAcceptDrops(true);
1869 #if QT_VERSION >= 0x040500
1870 setTabsClosable(!lyxrc.single_close_tab_button);
1875 #if QT_VERSION < 0x040300
1876 int DragTabBar::tabAt(QPoint const & position) const
1878 const int max = count();
1879 for (int i = 0; i < max; ++i) {
1880 if (tabRect(i).contains(position))
1888 void DragTabBar::mousePressEvent(QMouseEvent * event)
1890 if (event->button() == Qt::LeftButton)
1891 dragStartPos_ = event->pos();
1892 QTabBar::mousePressEvent(event);
1896 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1898 // If the left button isn't pressed anymore then return
1899 if (!(event->buttons() & Qt::LeftButton))
1902 // If the distance is too small then return
1903 if ((event->pos() - dragStartPos_).manhattanLength()
1904 < QApplication::startDragDistance())
1907 // did we hit something after all?
1908 int tab = tabAt(dragStartPos_);
1912 // simulate button release to remove highlight from button
1913 int i = currentIndex();
1914 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1915 event->button(), event->buttons(), 0);
1916 QTabBar::mouseReleaseEvent(&me);
1920 QDrag * drag = new QDrag(this);
1921 QMimeData * mimeData = new QMimeData;
1922 // a crude way to distinguish tab-reodering drops from other ones
1923 mimeData->setData("action", "tab-reordering") ;
1924 drag->setMimeData(mimeData);
1926 #if QT_VERSION >= 0x040300
1927 // get tab pixmap as cursor
1928 QRect r = tabRect(tab);
1929 QPixmap pixmap(r.size());
1930 render(&pixmap, - r.topLeft());
1931 drag->setPixmap(pixmap);
1934 drag->start(Qt::MoveAction);
1940 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1942 // Only accept if it's an tab-reordering request
1943 QMimeData const * m = event->mimeData();
1944 QStringList formats = m->formats();
1945 if (formats.contains("action")
1946 && m->data("action") == "tab-reordering")
1947 event->acceptProposedAction();
1951 void DragTabBar::dropEvent(QDropEvent * event)
1953 int fromIndex = tabAt(dragStartPos_);
1954 int toIndex = tabAt(event->pos());
1956 // Tell interested objects that
1957 if (fromIndex != toIndex)
1958 tabMoveRequested(fromIndex, toIndex);
1959 event->acceptProposedAction();
1963 } // namespace frontend
1966 #include "moc_GuiWorkArea.cpp"