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"
42 #include "graphics/GraphicsImage.h"
43 #include "graphics/GraphicsLoader.h"
45 #include "support/convert.h"
46 #include "support/debug.h"
47 #include "support/gettext.h"
48 #include "support/FileName.h"
50 #include "frontends/Application.h"
51 #include "frontends/FontMetrics.h"
52 #include "frontends/WorkAreaManager.h"
54 #include <QContextMenuEvent>
55 #include <QInputContext>
60 #include <QMainWindow>
64 #include <QPixmapCache>
67 #include <QToolButton>
71 #include <boost/bind.hpp>
77 extern "C" int XEventsQueued(Display *display, int mode);
81 int const CursorWidth = 2;
83 int const CursorWidth = 1;
85 int const TabIndicatorWidth = 3;
91 using namespace lyx::support;
96 /// return the LyX mouse button state from Qt's
97 static mouse_button::state q_button_state(Qt::MouseButton button)
99 mouse_button::state b = mouse_button::none;
102 b = mouse_button::button1;
105 b = mouse_button::button2;
107 case Qt::RightButton:
108 b = mouse_button::button3;
117 /// return the LyX mouse button state from Qt's
118 mouse_button::state q_motion_state(Qt::MouseButtons state)
120 mouse_button::state b = mouse_button::none;
121 if (state & Qt::LeftButton)
122 b |= mouse_button::button1;
123 if (state & Qt::MidButton)
124 b |= mouse_button::button2;
125 if (state & Qt::RightButton)
126 b |= mouse_button::button3;
137 void draw(QPainter & painter)
139 if (!show_ || !rect_.isValid())
143 int l = x_ - rect_.left();
144 int r = rect_.right() - x_;
145 int bot = rect_.bottom();
147 // draw vertica linel
148 painter.fillRect(x_, y, CursorWidth, rect_.height(), color_);
150 // draw RTL/LTR indication
151 painter.setPen(color_);
154 painter.drawLine(x_, bot, x_ - l, bot);
156 painter.drawLine(x_, bot, x_ + CursorWidth + r, bot);
159 // draw completion triangle
161 int m = y + rect_.height() / 2;
162 int d = TabIndicatorWidth - 1;
164 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
165 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
167 painter.drawLine(x_ + CursorWidth, m - d, x_ + CursorWidth + d, m);
168 painter.drawLine(x_ + CursorWidth, m + d, x_ + CursorWidth + d, m);
173 void update(int x, int y, int h, bool l_shape,
174 bool rtl, bool completable)
176 color_ = guiApp->colorCache().get(Color_cursor);
179 completable_ = completable;
182 // extension to left and right
186 // RTL/LTR indication
194 // completion triangle
197 l = max(l, TabIndicatorWidth);
199 r = max(r, TabIndicatorWidth);
202 // compute overall rectangle
203 rect_ = QRect(x - l, y, CursorWidth + r + l, h);
206 void show(bool set_show = true) { show_ = set_show; }
207 void hide() { show_ = false; }
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)
229 // This is a 'heartbeat' generating synthetic mouse move events when the
230 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
231 SyntheticMouseEvent::SyntheticMouseEvent()
232 : timeout(200), restart_timeout(true),
233 x_old(-1), y_old(-1), min_scrollbar_old(-1), max_scrollbar_old(-1)
237 GuiWorkArea::GuiWorkArea(QWidget *)
238 : buffer_view_(0), lyx_view_(0),
239 cursor_visible_(false),
240 need_resize_(false), schedule_redraw_(false),
241 preedit_lines_(1), completer_(new GuiCompleter(this, this)),
242 context_target_pos_()
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)),
252 context_target_pos_()
260 void GuiWorkArea::init()
263 connect(&cursor_timeout_, SIGNAL(timeout()),
264 this, SLOT(toggleCursor()));
266 int const time = QApplication::cursorFlashTime() / 2;
268 cursor_timeout_.setInterval(time);
269 cursor_timeout_.start();
271 // let's initialize this just to be safe
272 cursor_timeout_.setInterval(500);
275 screen_ = QPixmap(viewport()->width(), viewport()->height());
276 // With Qt4.5 a mouse event will happen before the first paint event
277 // so make sure that the buffer view has an up to date metrics.
278 buffer_view_->resize(viewport()->width(), viewport()->height());
279 cursor_ = new frontend::CursorWidget();
282 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
283 setAcceptDrops(true);
284 setMouseTracking(true);
285 setMinimumSize(100, 70);
286 setFrameStyle(QFrame::NoFrame);
289 viewport()->setAutoFillBackground(false);
290 // We don't need double-buffering nor SystemBackground on
291 // the viewport because we have our own backing pixmap.
292 viewport()->setAttribute(Qt::WA_NoSystemBackground);
294 setFocusPolicy(Qt::StrongFocus);
296 viewport()->setCursor(Qt::IBeamCursor);
298 synthetic_mouse_event_.timeout.timeout.connect(
299 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
302 // Initialize the vertical Scroll Bar
303 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
304 this, SLOT(scrollTo(int)));
306 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
307 << " viewport height: " << viewport()->height());
309 // Enables input methods for asian languages.
310 // Must be set when creating custom text editing widgets.
311 setAttribute(Qt::WA_InputMethodEnabled, true);
313 dialog_mode_ = false;
317 GuiWorkArea::~GuiWorkArea()
319 buffer_view_->buffer().workAreaManager().remove(this);
322 // Completer has a QObject parent and is thus automatically destroyed.
324 // delete completer_;
328 void GuiWorkArea::setGuiView(GuiView & gv)
334 void GuiWorkArea::setBuffer(Buffer & buffer)
337 buffer_view_ = new BufferView(buffer);
338 buffer.workAreaManager().add(this);
340 // HACK: Prevents an additional redraw when the scrollbar pops up
341 // which regularily happens on documents with more than one page.
342 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
343 // Since we have no geometry information yet, we assume that
344 // a document needs a scrollbar if there is more then four
345 // paragraph in the outermost text.
346 if (buffer.text().paragraphs().size() > 4)
347 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
348 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
352 void GuiWorkArea::fixVerticalScrollBar()
355 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
359 void GuiWorkArea::close()
361 lyx_view_->removeWorkArea(this);
365 void GuiWorkArea::setFullScreen(bool full_screen)
367 buffer_view_->setFullScreen(full_screen);
368 setFrameStyle(QFrame::NoFrame);
370 setFrameStyle(QFrame::NoFrame);
371 if (lyxrc.full_screen_scrollbar)
372 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
374 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
378 BufferView & GuiWorkArea::bufferView()
380 return *buffer_view_;
384 BufferView const & GuiWorkArea::bufferView() const
386 return *buffer_view_;
390 void GuiWorkArea::stopBlinkingCursor()
392 cursor_timeout_.stop();
397 void GuiWorkArea::startBlinkingCursor()
401 buffer_view_->cursorPosAndHeight(p, h);
402 // Don't start blinking if the cursor isn't on screen.
403 if (!buffer_view_->cursorInView(p, h))
408 //we're not supposed to cache this value.
409 int const time = QApplication::cursorFlashTime() / 2;
412 cursor_timeout_.setInterval(time);
413 cursor_timeout_.start();
417 void GuiWorkArea::redraw(bool update_metrics)
420 // No need to redraw in this case.
423 // No need to do anything if this is the current view. The BufferView
424 // metrics are already up to date.
425 if (update_metrics || lyx_view_ != guiApp->currentView()
426 || lyx_view_->currentWorkArea() != this) {
427 // FIXME: it would be nice to optimize for the off-screen case.
428 buffer_view_->updateMetrics();
429 buffer_view_->cursor().fixIfBroken();
432 // update cursor position, because otherwise it has to wait until
433 // the blinking interval is over
434 if (cursor_visible_) {
439 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
441 update(0, 0, viewport()->width(), viewport()->height());
443 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
444 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
446 lyx_view_->updateStatusBar();
448 if (lyxerr.debugging(Debug::WORKAREA))
449 buffer_view_->coordCache().dump();
451 setReadOnly(buffer_view_->buffer().isReadonly());
455 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
457 if (lyx_view_->isFullScreen() && lyx_view_->menuBar()->isVisible()
458 && lyxrc.full_screen_menubar) {
459 // FIXME HACK: we should not have to do this here. See related comment
460 // in GuiView::event() (QEvent::ShortcutOverride)
461 lyx_view_->menuBar()->hide();
464 // In order to avoid bad surprise in the middle of an operation,
465 // we better stop the blinking cursor...
466 // the cursor gets restarted in GuiView::restartCursor()
467 stopBlinkingCursor();
468 guiApp->processKeySym(key, mod);
472 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
475 if (cmd0.action == LFUN_FILE_OPEN) {
477 lyx_view_->dispatch(cmd0, dr);
483 if (cmd0.action == LFUN_MOUSE_PRESS) {
484 if (mod == ShiftModifier)
485 cmd = FuncRequest(cmd0, "region-select");
486 else if (mod == ControlModifier)
487 cmd = FuncRequest(cmd0, "paragraph-select");
494 bool const notJustMovingTheMouse =
495 cmd.action != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
497 // In order to avoid bad surprise in the middle of an operation, we better stop
498 // the blinking cursor.
499 if (notJustMovingTheMouse)
500 stopBlinkingCursor();
502 buffer_view_->mouseEventDispatch(cmd);
504 // Skip these when selecting
505 if (cmd.action != LFUN_MOUSE_MOTION) {
506 completer_->updateVisibility(false, false);
507 lyx_view_->updateDialogs();
508 lyx_view_->updateStatusBar();
511 // GUI tweaks except with mouse motion with no button pressed.
512 if (notJustMovingTheMouse) {
513 // Slight hack: this is only called currently when we
514 // clicked somewhere, so we force through the display
515 // of the new status here.
516 lyx_view_->clearMessage();
518 // Show the cursor immediately after any operation
519 startBlinkingCursor();
524 void GuiWorkArea::resizeBufferView()
526 // WARNING: Please don't put any code that will trigger a repaint here!
527 // We are already inside a paint event.
528 lyx_view_->setBusy(true);
531 buffer_view_->cursorPosAndHeight(p, h);
532 bool const cursor_in_view = buffer_view_->cursorInView(p, h);
533 buffer_view_->resize(viewport()->width(), viewport()->height());
535 buffer_view_->scrollToCursor();
538 // Update scrollbars which might have changed due different
539 // BufferView dimension. This is especially important when the
540 // BufferView goes from zero-size to the real-size for the first time,
541 // as the scrollbar paramters are then set for the first time.
544 lyx_view_->updateLayoutList();
545 lyx_view_->setBusy(false);
546 need_resize_ = false;
550 void GuiWorkArea::showCursor()
557 buffer_view_->cursorPosAndHeight(p, h);
558 if (!buffer_view_->cursorInView(p, h))
562 bool l_shape = false;
563 Font const & realfont = buffer_view_->cursor().real_current_font;
564 BufferParams const & bp = buffer_view_->buffer().params();
565 bool const samelang = realfont.language() == bp.language;
566 bool const isrtl = realfont.isVisibleRightToLeft();
568 if (!samelang || isrtl != bp.language->rightToLeft())
571 // The ERT language hack needs fixing up
572 if (realfont.language() == latex_language)
575 // show cursor on screen
576 Cursor & cur = buffer_view_->cursor();
577 bool completable = cur.inset().showCompletionCursor()
578 && completer_->completionAvailable()
579 && !completer_->popupVisible()
580 && !completer_->inlineVisible();
581 cursor_visible_ = true;
582 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
586 void GuiWorkArea::hideCursor()
588 if (!cursor_visible_)
591 cursor_visible_ = false;
596 void GuiWorkArea::toggleCursor()
605 void GuiWorkArea::updateScrollbar()
607 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
608 // WARNING: don't touch at the scrollbar value like this:
609 // verticalScrollBar()->setValue(scroll_.position);
610 // because this would cause a recursive signal/slot calling with
611 // GuiWorkArea::scrollTo
612 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
613 verticalScrollBar()->setPageStep(scroll_.page_step);
614 verticalScrollBar()->setSingleStep(scroll_.single_step);
615 verticalScrollBar()->setSliderPosition(scroll_.position);
619 void GuiWorkArea::scrollTo(int value)
621 stopBlinkingCursor();
622 buffer_view_->scrollDocView(value);
624 if (lyxrc.cursor_follows_scrollbar) {
625 buffer_view_->setCursorFromScrollbar();
626 lyx_view_->updateLayoutList();
628 // Show the cursor immediately after any operation.
629 startBlinkingCursor();
630 QApplication::syncX();
634 bool GuiWorkArea::event(QEvent * e)
637 case QEvent::ToolTip: {
638 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
639 if (lyxrc.use_tooltip) {
640 QPoint pos = helpEvent->pos();
641 if (pos.x() < viewport()->width()) {
642 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
643 QToolTip::showText(helpEvent->globalPos(), s);
646 QToolTip::hideText();
648 // Don't forget to accept the event!
653 case QEvent::ShortcutOverride: {
654 // We catch this event in order to catch the Tab or Shift+Tab key press
655 // which are otherwise reserved to focus switching between controls
657 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
658 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
659 || ke->modifiers() & Qt::ControlModifier)
660 return QAbstractScrollArea::event(e);
666 return QAbstractScrollArea::event(e);
672 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
675 if (e->reason() == QContextMenuEvent::Mouse)
676 // the position is set on mouse press
677 pos = context_target_pos_;
680 Cursor const & cur = buffer_view_->cursor();
681 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
682 // Do not access the context menu of math right in front of before
683 // the cursor. This does not work when the cursor is in text.
684 Inset * inset = cur.paragraph().getInset(cur.pos());
685 if (inset && inset->asInsetMath())
687 else if (cur.pos() > 0) {
688 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
693 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
695 QAbstractScrollArea::contextMenuEvent(e);
698 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
700 QAbstractScrollArea::contextMenuEvent(e);
703 // Position the menu to the right.
704 // FIXME: menu position should be different for RTL text.
705 menu->exec(e->globalPos());
710 void GuiWorkArea::focusInEvent(QFocusEvent * e)
712 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
713 if (lyx_view_->currentWorkArea() != this)
714 lyx_view_->setCurrentWorkArea(this);
716 startBlinkingCursor();
717 QAbstractScrollArea::focusInEvent(e);
721 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
723 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
724 stopBlinkingCursor();
725 QAbstractScrollArea::focusOutEvent(e);
729 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
731 if (dc_event_.active && dc_event_ == *e) {
732 dc_event_.active = false;
733 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
734 q_button_state(e->button()));
740 if (e->button() == Qt::RightButton)
741 context_target_pos_ = e->pos();
743 inputContext()->reset();
745 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
746 q_button_state(e->button()));
747 dispatch(cmd, q_key_state(e->modifiers()));
752 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
754 if (synthetic_mouse_event_.timeout.running())
755 synthetic_mouse_event_.timeout.stop();
757 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
758 q_button_state(e->button()));
764 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
766 // we kill the triple click if we move
767 doubleClickTimeout();
768 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
769 q_motion_state(e->buttons()));
773 // If we're above or below the work area...
774 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
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:
781 cmd.y = viewport()->height();
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.
795 synthetic_mouse_event_.restart_timeout = true;
796 synthetic_mouse_event_.timeout.start();
797 // Fall through to handle this event...
799 } else if (synthetic_mouse_event_.timeout.running()) {
800 // Store the event, to be possibly handled when the timeout
802 // Once the timeout has expired, normal control is returned
803 // to mouseMoveEvent (restart_timeout = false).
804 // This results in a much smoother 'feel' when moving the
805 // mouse back into the work area.
806 synthetic_mouse_event_.cmd = cmd;
807 synthetic_mouse_event_.restart_timeout = false;
811 // Has anything changed on-screen since the last QMouseEvent
813 if (e->x() == synthetic_mouse_event_.x_old
814 && e->y() == synthetic_mouse_event_.y_old
815 && synthetic_mouse_event_.min_scrollbar_old == verticalScrollBar()->minimum()
816 && synthetic_mouse_event_.max_scrollbar_old == verticalScrollBar()->maximum()) {
817 // Nothing changed on-screen since the last QMouseEvent.
821 // Yes something has changed. Store the params used to check this.
822 synthetic_mouse_event_.x_old = e->x();
823 synthetic_mouse_event_.y_old = e->y();
824 synthetic_mouse_event_.min_scrollbar_old = verticalScrollBar()->minimum();
825 synthetic_mouse_event_.max_scrollbar_old = verticalScrollBar()->maximum();
827 // ... and dispatch the event to the LyX core.
832 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
834 // Wheel rotation by one notch results in a delta() of 120 (see
835 // documentation of QWheelEvent)
836 int const delta = ev->delta() / 120;
837 if (ev->modifiers() & Qt::ControlModifier) {
838 docstring arg = convert<docstring>(5 * delta);
839 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
843 // Take into account the desktop wide settings.
844 int const lines = qApp->wheelScrollLines();
845 int const page_step = verticalScrollBar()->pageStep();
846 // Test if the wheel mouse is set to one screen at a time.
847 int scroll_value = lines > page_step
848 ? page_step : lines * verticalScrollBar()->singleStep();
850 // Take into account the rotation.
851 scroll_value *= delta;
853 // Take into account user preference.
854 scroll_value = int(scroll_value * lyxrc.mouse_wheel_speed);
855 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
856 << " delta = " << delta << " scroll_value = " << scroll_value
857 << " page_step = " << page_step);
859 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
865 void GuiWorkArea::generateSyntheticMouseEvent()
867 // Set things off to generate the _next_ 'pseudo' event.
868 if (synthetic_mouse_event_.restart_timeout)
869 synthetic_mouse_event_.timeout.start();
871 // Has anything changed on-screen since the last timeout signal
873 int const min_scrollbar = verticalScrollBar()->minimum();
874 int const max_scrollbar = verticalScrollBar()->maximum();
875 if (min_scrollbar == synthetic_mouse_event_.min_scrollbar_old
876 && max_scrollbar == synthetic_mouse_event_.max_scrollbar_old) {
879 // Yes it has. Store the params used to check this.
880 synthetic_mouse_event_.min_scrollbar_old = min_scrollbar;
881 synthetic_mouse_event_.max_scrollbar_old = max_scrollbar;
882 // ... and dispatch the event to the LyX core.
883 dispatch(synthetic_mouse_event_.cmd);
887 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
889 // Do not process here some keys if dialog_mode_ is set
891 && (ev->modifiers() == Qt::NoModifier
892 || ev->modifiers() == Qt::ShiftModifier)
893 && (ev->key() == Qt::Key_Escape
894 || ev->key() == Qt::Key_Enter
895 || ev->key() == Qt::Key_Return)
901 // intercept some keys if completion popup is visible
902 if (completer_->popupVisible()) {
906 completer_->activate();
912 // do nothing if there are other events
913 // (the auto repeated events come too fast)
914 // \todo FIXME: remove hard coded Qt keys, process the key binding
916 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
917 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
918 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
924 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
925 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
928 setKeySymbol(&sym, ev);
930 processKeySym(sym, q_key_state(ev->modifiers()));
938 void GuiWorkArea::doubleClickTimeout()
940 dc_event_.active = false;
944 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
946 dc_event_ = DoubleClick(ev);
947 QTimer::singleShot(QApplication::doubleClickInterval(), this,
948 SLOT(doubleClickTimeout()));
949 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
951 q_button_state(ev->button()));
957 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
959 QAbstractScrollArea::resizeEvent(ev);
965 void GuiWorkArea::update(int x, int y, int w, int h)
967 viewport()->repaint(x, y, w, h);
971 void GuiWorkArea::paintEvent(QPaintEvent * ev)
973 QRect const rc = ev->rect();
974 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
975 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
978 screen_ = QPixmap(viewport()->width(), viewport()->height());
980 if (cursor_visible_) {
986 QPainter pain(viewport());
987 pain.drawPixmap(rc, screen_, rc);
993 void GuiWorkArea::updateScreen()
995 GuiPainter pain(&screen_);
996 buffer_view_->draw(pain);
1000 void GuiWorkArea::showCursor(int x, int y, int h,
1001 bool l_shape, bool rtl, bool completable)
1003 if (schedule_redraw_) {
1004 // This happens when a graphic conversion is finished. As we don't know
1005 // the size of the new graphics, it's better the update everything.
1006 // We can't use redraw() here because this would trigger a infinite
1007 // recursive loop with showCursor().
1008 buffer_view_->resize(viewport()->width(), viewport()->height());
1011 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
1012 schedule_redraw_ = false;
1013 // Show the cursor immediately after the update.
1019 cursor_->update(x, y, h, l_shape, rtl, completable);
1021 viewport()->update(cursor_->rect());
1025 void GuiWorkArea::removeCursor()
1028 //if (!qApp->focusWidget())
1029 viewport()->update(cursor_->rect());
1033 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1035 QString const & commit_string = e->commitString();
1036 docstring const & preedit_string
1037 = qstring_to_ucs4(e->preeditString());
1039 if (!commit_string.isEmpty()) {
1041 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1042 << " commitString: " << e->commitString());
1046 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1047 for (int i = 0; i != commit_string.size(); ++i) {
1048 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1053 // Hide the cursor during the kana-kanji transformation.
1054 if (preedit_string.empty())
1055 startBlinkingCursor();
1057 stopBlinkingCursor();
1059 // last_width : for checking if last preedit string was/wasn't empty.
1060 static bool last_width = false;
1061 if (!last_width && preedit_string.empty()) {
1062 // if last_width is last length of preedit string.
1067 GuiPainter pain(&screen_);
1068 buffer_view_->updateMetrics();
1069 buffer_view_->draw(pain);
1070 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1071 FontMetrics const & fm = theFontMetrics(font);
1072 int height = fm.maxHeight();
1073 int cur_x = cursor_->rect().left();
1074 int cur_y = cursor_->rect().bottom();
1076 // redraw area of preedit string.
1077 update(0, cur_y - height, viewport()->width(),
1078 (height + 1) * preedit_lines_);
1080 if (preedit_string.empty()) {
1088 // att : stores an IM attribute.
1089 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1091 // get attributes of input method cursor.
1092 // cursor_pos : cursor position in preedit string.
1093 size_t cursor_pos = 0;
1094 bool cursor_is_visible = false;
1095 for (int i = 0; i != att.size(); ++i) {
1096 if (att.at(i).type == QInputMethodEvent::Cursor) {
1097 cursor_pos = att.at(i).start;
1098 cursor_is_visible = att.at(i).length != 0;
1103 size_t preedit_length = preedit_string.length();
1105 // get position of selection in input method.
1106 // FIXME: isn't there a way to do this simplier?
1107 // rStart : cursor position in selected string in IM.
1109 // rLength : selected string length in IM.
1111 if (cursor_pos < preedit_length) {
1112 for (int i = 0; i != att.size(); ++i) {
1113 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1114 if (att.at(i).start <= int(cursor_pos)
1115 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1116 rStart = att.at(i).start;
1117 rLength = att.at(i).length;
1118 if (!cursor_is_visible)
1119 cursor_pos += rLength;
1126 rStart = cursor_pos;
1130 int const right_margin = buffer_view_->rightMargin();
1131 Painter::preedit_style ps;
1132 // Most often there would be only one line:
1134 for (size_t pos = 0; pos != preedit_length; ++pos) {
1135 char_type const typed_char = preedit_string[pos];
1136 // reset preedit string style
1137 ps = Painter::preedit_default;
1139 // if we reached the right extremity of the screen, go to next line.
1140 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1141 cur_x = right_margin;
1142 cur_y += height + 1;
1145 // preedit strings are displayed with dashed underline
1146 // and partial strings are displayed white on black indicating
1147 // that we are in selecting mode in the input method.
1148 // FIXME: rLength == preedit_length is not a changing condition
1149 // FIXME: should be put out of the loop.
1151 && pos < rStart + rLength
1152 && !(cursor_pos < rLength && rLength == preedit_length))
1153 ps = Painter::preedit_selecting;
1155 if (pos == cursor_pos
1156 && (cursor_pos < rLength && rLength == preedit_length))
1157 ps = Painter::preedit_cursor;
1159 // draw one character and update cur_x.
1160 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1163 // update the preedit string screen area.
1164 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1165 (height + 1) * preedit_lines_);
1167 // Don't forget to accept the event!
1172 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1174 QRect cur_r(0, 0, 0, 0);
1176 // this is the CJK-specific composition window position and
1177 // the context menu position when the menu key is pressed.
1178 case Qt::ImMicroFocus:
1179 cur_r = cursor_->rect();
1180 if (preedit_lines_ != 1)
1182 cur_r.moveBottom(cur_r.bottom()
1183 + cur_r.height() * (preedit_lines_ - 1));
1184 // return lower right of cursor in LyX.
1187 return QWidget::inputMethodQuery(query);
1192 void GuiWorkArea::updateWindowTitle()
1194 docstring maximize_title;
1195 docstring minimize_title;
1197 Buffer & buf = buffer_view_->buffer();
1198 FileName const fileName = buf.fileName();
1199 if (!fileName.empty()) {
1200 maximize_title = fileName.displayName(30);
1201 minimize_title = from_utf8(fileName.onlyFileName());
1202 if (buf.lyxvc().inUse()) {
1203 if (buf.lyxvc().locking())
1204 maximize_title += _(" (version control, locking)");
1206 maximize_title += _(" (version control)");
1208 if (!buf.isClean()) {
1209 maximize_title += _(" (changed)");
1210 minimize_title += char_type('*');
1212 if (buf.isReadonly())
1213 maximize_title += _(" (read only)");
1216 QString title = windowTitle();
1217 QString new_title = toqstr(maximize_title);
1218 if (title == new_title)
1221 QWidget::setWindowTitle(new_title);
1222 QWidget::setWindowIconText(toqstr(minimize_title));
1227 void GuiWorkArea::setReadOnly(bool read_only)
1229 if (read_only_ == read_only)
1231 read_only_ = read_only;
1232 updateWindowTitle();
1233 if (this == lyx_view_->currentWorkArea())
1234 lyx_view_->updateDialogs();
1238 bool GuiWorkArea::isFullScreen()
1240 return lyx_view_ && lyx_view_->isFullScreen();
1244 ////////////////////////////////////////////////////////////////////
1248 ////////////////////////////////////////////////////////////////////
1251 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1253 buffer_ = theBufferList().newBuffer(
1254 support::FileName::tempName().absFilename() + "_embedded.internal");
1255 buffer_->setUnnamed(true);
1256 buffer_->setFullyLoaded(true);
1257 setBuffer(*buffer_);
1258 setDialogMode(true);
1262 EmbeddedWorkArea::~EmbeddedWorkArea()
1264 // No need to destroy buffer and bufferview here, because it is done
1265 // in theBuffeerList() destruction loop at application exit
1269 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1272 GuiWorkArea::closeEvent(ev);
1276 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1279 GuiWorkArea::hideEvent(ev);
1283 QSize EmbeddedWorkArea::sizeHint () const
1286 // GuiWorkArea sets the size to the screen's viewport
1287 // by returning a value this gets overridden
1288 // EmbeddedWorkArea is now sized to fit in the layout
1289 // of the parent, and has a minimum size set in GuiWorkArea
1290 // which is what we return here
1291 return QSize(100, 70);
1295 void EmbeddedWorkArea::disable()
1297 stopBlinkingCursor();
1298 if (view().currentWorkArea() != this)
1300 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1301 // tolerates it and shows the background logo), what happens if
1302 // an EmbeddedWorkArea is closed after closing all document WAs
1303 view().setCurrentWorkArea(view().currentMainWorkArea());
1306 ////////////////////////////////////////////////////////////////////
1310 ////////////////////////////////////////////////////////////////////
1313 class NoTabFrameMacStyle : public QMacStyle {
1316 QRect subElementRect(SubElement element, const QStyleOption * option,
1317 const QWidget * widget = 0) const
1319 QRect rect = QMacStyle::subElementRect(element, option, widget);
1320 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1322 // The Qt Mac style puts the contents into a 3 pixel wide box
1323 // which looks very ugly and not like other Mac applications.
1324 // Hence we remove this here, and moreover the 16 pixel round
1325 // frame above if the tab bar is hidden.
1326 if (element == QStyle::SE_TabWidgetTabContents) {
1327 rect.adjust(- rect.left(), 0, rect.left(), 0);
1336 NoTabFrameMacStyle noTabFrameMacStyle;
1340 TabWorkArea::TabWorkArea(QWidget * parent)
1341 : QTabWidget(parent), clicked_tab_(-1)
1344 setStyle(&noTabFrameMacStyle);
1346 #if QT_VERSION < 0x040500
1347 lyxrc.single_close_tab_button = true;
1350 QPalette pal = palette();
1351 pal.setColor(QPalette::Active, QPalette::Button,
1352 pal.color(QPalette::Active, QPalette::Window));
1353 pal.setColor(QPalette::Disabled, QPalette::Button,
1354 pal.color(QPalette::Disabled, QPalette::Window));
1355 pal.setColor(QPalette::Inactive, QPalette::Button,
1356 pal.color(QPalette::Inactive, QPalette::Window));
1358 QObject::connect(this, SIGNAL(currentChanged(int)),
1359 this, SLOT(on_currentTabChanged(int)));
1361 closeBufferButton = new QToolButton(this);
1362 closeBufferButton->setPalette(pal);
1363 // FIXME: rename the icon to closebuffer.png
1364 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1365 closeBufferButton->setText("Close File");
1366 closeBufferButton->setAutoRaise(true);
1367 closeBufferButton->setCursor(Qt::ArrowCursor);
1368 closeBufferButton->setToolTip(qt_("Close File"));
1369 closeBufferButton->setEnabled(true);
1370 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1371 this, SLOT(closeCurrentBuffer()));
1372 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1374 // setup drag'n'drop
1375 QTabBar* tb = new DragTabBar;
1376 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1377 this, SLOT(moveTab(int, int)));
1378 tb->setElideMode(Qt::ElideNone);
1381 // make us responsible for the context menu of the tabbar
1382 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1383 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1384 this, SLOT(showContextMenu(const QPoint &)));
1385 #if QT_VERSION >= 0x040500
1386 connect(tb, SIGNAL(tabCloseRequested(int)),
1387 this, SLOT(closeTab(int)));
1390 setUsesScrollButtons(true);
1394 void TabWorkArea::setFullScreen(bool full_screen)
1396 for (int i = 0; i != count(); ++i) {
1397 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1398 wa->setFullScreen(full_screen);
1401 if (lyxrc.full_screen_tabbar)
1402 showBar(!full_screen && count() > 1);
1406 void TabWorkArea::showBar(bool show)
1408 tabBar()->setEnabled(show);
1409 tabBar()->setVisible(show);
1410 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1411 #if QT_VERSION >= 0x040500
1412 setTabsClosable(!lyxrc.single_close_tab_button);
1417 GuiWorkArea * TabWorkArea::currentWorkArea()
1422 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1428 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1430 for (int i = 0; i != count(); ++i) {
1431 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1432 LASSERT(wa, return 0);
1433 if (&wa->bufferView().buffer() == &buffer)
1440 void TabWorkArea::closeAll()
1443 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1451 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1453 LASSERT(work_area, /**/);
1454 int index = indexOf(work_area);
1458 if (index == currentIndex())
1459 // Make sure the work area is up to date.
1460 on_currentTabChanged(index);
1462 // Switch to the work area.
1463 setCurrentIndex(index);
1464 work_area->setFocus();
1470 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1472 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1473 wa->setUpdatesEnabled(false);
1474 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1475 // when hiding it again below).
1476 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1477 showBar(count() > 0);
1478 addTab(wa, wa->windowTitle());
1479 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1480 this, SLOT(updateTabTexts()));
1481 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1482 setFullScreen(true);
1484 // Hide tabbar if there's only one tab.
1485 showBar(count() > 1);
1493 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1495 LASSERT(work_area, return false);
1496 int index = indexOf(work_area);
1500 work_area->setUpdatesEnabled(false);
1505 // make sure the next work area is enabled.
1506 currentWidget()->setUpdatesEnabled(true);
1507 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1508 setFullScreen(true);
1510 // Show tabbar only if there's more than one tab.
1511 showBar(count() > 1);
1513 lastWorkAreaRemoved();
1521 void TabWorkArea::on_currentTabChanged(int i)
1523 // returns e.g. on application destruction
1526 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1527 LASSERT(wa, return);
1528 wa->setUpdatesEnabled(true);
1532 currentWorkAreaChanged(wa);
1534 LYXERR(Debug::GUI, "currentTabChanged " << i
1535 << " File: " << wa->bufferView().buffer().absFileName());
1539 void TabWorkArea::closeCurrentBuffer()
1542 if (clicked_tab_ == -1)
1543 wa = currentWorkArea();
1545 wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1548 wa->view().closeWorkArea(wa);
1552 void TabWorkArea::hideCurrentTab()
1555 if (clicked_tab_ == -1)
1556 wa = currentWorkArea();
1558 wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1561 wa->view().hideWorkArea(wa);
1565 void TabWorkArea::closeTab(int index)
1567 on_currentTabChanged(index);
1570 wa = currentWorkArea();
1572 wa = dynamic_cast<GuiWorkArea *>(widget(index));
1575 wa->view().closeWorkArea(wa);
1582 /// make vector happy
1585 DisplayPath(int tab, FileName const & filename)
1588 filename_ = (filename.extension() == "lyx") ?
1589 toqstr(filename.onlyFileNameWithoutExt())
1590 : toqstr(filename.onlyFileName());
1591 postfix_ = toqstr(filename.absoluteFilePath()).
1592 split("/", QString::SkipEmptyParts);
1593 postfix_.pop_back();
1594 abs_ = toqstr(filename.absoluteFilePath());
1595 dottedPrefix_ = false;
1598 /// Absolute path for debugging.
1603 /// Add the first segment from the postfix or three dots to the prefix.
1604 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1605 /// when really needed.
1606 void shiftPathSegment(bool dotted)
1608 if (postfix_.count() <= 0)
1612 if (dottedPrefix_ && !prefix_.isEmpty())
1614 prefix_ += postfix_.front() + "/";
1616 dottedPrefix_ = dotted && !prefix_.isEmpty();
1617 postfix_.pop_front();
1620 QString displayString() const
1622 if (prefix_.isEmpty())
1625 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1626 return prefix_ + (dots ? ".../" : "") + filename_;
1629 QString forecastPathString() const
1631 if (postfix_.count() == 0)
1632 return displayString();
1635 + (dottedPrefix_ ? ".../" : "")
1636 + postfix_.front() + "/";
1639 bool final() const { return postfix_.empty(); }
1641 int tab() const { return tab_; }
1647 QStringList postfix_;
1660 bool operator<(DisplayPath const & a, DisplayPath const & b)
1662 return a.displayString() < b.displayString();
1666 bool operator==(DisplayPath const & a, DisplayPath const & b)
1668 return a.displayString() == b.displayString();
1672 void TabWorkArea::updateTabTexts()
1677 std::list<DisplayPath> paths;
1678 typedef std::list<DisplayPath>::iterator It;
1680 // collect full names first: path into postfix, empty prefix and
1681 // filename without extension
1682 for (size_t i = 0; i < n; ++i) {
1683 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(i));
1684 FileName const fn = i_wa->bufferView().buffer().fileName();
1685 paths.push_back(DisplayPath(i, fn));
1688 // go through path segments and see if it helps to make the path more unique
1689 bool somethingChanged = true;
1690 bool allFinal = false;
1691 while (somethingChanged && !allFinal) {
1692 // adding path segments changes order
1695 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1696 somethingChanged = false;
1699 // find segments which are not unique (i.e. non-atomic)
1700 It it = paths.begin();
1702 QString segString = it->displayString();
1703 for (; it != paths.end(); ++it) {
1704 // look to the next item
1709 allFinal = allFinal && it->final();
1711 LYXERR(Debug::GUI, "it = " << it->abs()
1712 << " => " << it->displayString());
1714 // still the same segment?
1716 if ((next != paths.end()
1717 && (nextString = next->displayString()) == segString))
1719 LYXERR(Debug::GUI, "segment ended");
1721 // only a trivial one with one element?
1722 if (it == segStart) {
1723 // start new segment
1725 segString = nextString;
1729 // we found a non-atomic segment segStart <= sit <= it < next.
1730 // Shift path segments and hope for the best
1731 // that it makes the path more unique.
1732 somethingChanged = true;
1734 QString dspString = sit->forecastPathString();
1735 LYXERR(Debug::GUI, "first forecast found for "
1736 << sit->abs() << " => " << dspString);
1738 bool moreUnique = false;
1739 for (; sit != next; ++sit) {
1740 if (sit->forecastPathString() != dspString) {
1741 LYXERR(Debug::GUI, "different forecast found for "
1742 << sit->abs() << " => " << sit->forecastPathString());
1746 LYXERR(Debug::GUI, "same forecast found for "
1747 << sit->abs() << " => " << dspString);
1750 // if the path segment helped, add it. Otherwise add dots
1751 bool dots = !moreUnique;
1752 LYXERR(Debug::GUI, "using dots = " << dots);
1753 for (sit = segStart; sit != next; ++sit) {
1754 sit->shiftPathSegment(dots);
1755 LYXERR(Debug::GUI, "shifting "
1756 << sit->abs() << " => " << sit->displayString());
1759 // start new segment
1761 segString = nextString;
1765 // set new tab titles
1766 for (It it = paths.begin(); it != paths.end(); ++it) {
1767 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(it->tab()));
1768 Buffer & buf = i_wa->bufferView().buffer();
1769 if (!buf.fileName().empty() && !buf.isClean())
1770 setTabText(it->tab(), it->displayString() + "*");
1772 setTabText(it->tab(), it->displayString());
1777 void TabWorkArea::showContextMenu(const QPoint & pos)
1780 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1781 if (clicked_tab_ == -1)
1786 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
1787 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
1788 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
1789 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1790 popup.exec(tabBar()->mapToGlobal(pos));
1796 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1798 QWidget * w = widget(fromIndex);
1799 QIcon icon = tabIcon(fromIndex);
1800 QString text = tabText(fromIndex);
1802 setCurrentIndex(fromIndex);
1803 removeTab(fromIndex);
1804 insertTab(toIndex, w, icon, text);
1805 setCurrentIndex(toIndex);
1809 DragTabBar::DragTabBar(QWidget* parent)
1812 setAcceptDrops(true);
1813 #if QT_VERSION >= 0x040500
1814 setTabsClosable(!lyxrc.single_close_tab_button);
1819 #if QT_VERSION < 0x040300
1820 int DragTabBar::tabAt(QPoint const & position) const
1822 const int max = count();
1823 for (int i = 0; i < max; ++i) {
1824 if (tabRect(i).contains(position))
1832 void DragTabBar::mousePressEvent(QMouseEvent * event)
1834 if (event->button() == Qt::LeftButton)
1835 dragStartPos_ = event->pos();
1836 QTabBar::mousePressEvent(event);
1840 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1842 // If the left button isn't pressed anymore then return
1843 if (!(event->buttons() & Qt::LeftButton))
1846 // If the distance is too small then return
1847 if ((event->pos() - dragStartPos_).manhattanLength()
1848 < QApplication::startDragDistance())
1851 // did we hit something after all?
1852 int tab = tabAt(dragStartPos_);
1856 // simulate button release to remove highlight from button
1857 int i = currentIndex();
1858 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1859 event->button(), event->buttons(), 0);
1860 QTabBar::mouseReleaseEvent(&me);
1864 QDrag * drag = new QDrag(this);
1865 QMimeData * mimeData = new QMimeData;
1866 // a crude way to distinguish tab-reodering drops from other ones
1867 mimeData->setData("action", "tab-reordering") ;
1868 drag->setMimeData(mimeData);
1870 #if QT_VERSION >= 0x040300
1871 // get tab pixmap as cursor
1872 QRect r = tabRect(tab);
1873 QPixmap pixmap(r.size());
1874 render(&pixmap, - r.topLeft());
1875 drag->setPixmap(pixmap);
1878 drag->start(Qt::MoveAction);
1884 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1886 // Only accept if it's an tab-reordering request
1887 QMimeData const * m = event->mimeData();
1888 QStringList formats = m->formats();
1889 if (formats.contains("action")
1890 && m->data("action") == "tab-reordering")
1891 event->acceptProposedAction();
1895 void DragTabBar::dropEvent(QDropEvent * event)
1897 int fromIndex = tabAt(dragStartPos_);
1898 int toIndex = tabAt(event->pos());
1900 // Tell interested objects that
1901 if (fromIndex != toIndex)
1902 tabMoveRequested(fromIndex, toIndex);
1903 event->acceptProposedAction();
1907 } // namespace frontend
1910 #include "moc_GuiWorkArea.cpp"