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();
539 // Update scrollbars which might have changed due different
540 // BufferView dimension. This is especially important when the
541 // BufferView goes from zero-size to the real-size for the first time,
542 // as the scrollbar paramters are then set for the first time.
545 lyx_view_->updateLayoutList();
546 lyx_view_->setBusy(false);
547 need_resize_ = false;
551 void GuiWorkArea::showCursor()
558 buffer_view_->cursorPosAndHeight(p, h);
559 if (!buffer_view_->cursorInView(p, h))
563 bool l_shape = false;
564 Font const & realfont = buffer_view_->cursor().real_current_font;
565 BufferParams const & bp = buffer_view_->buffer().params();
566 bool const samelang = realfont.language() == bp.language;
567 bool const isrtl = realfont.isVisibleRightToLeft();
569 if (!samelang || isrtl != bp.language->rightToLeft())
572 // The ERT language hack needs fixing up
573 if (realfont.language() == latex_language)
576 // show cursor on screen
577 Cursor & cur = buffer_view_->cursor();
578 bool completable = cur.inset().showCompletionCursor()
579 && completer_->completionAvailable()
580 && !completer_->popupVisible()
581 && !completer_->inlineVisible();
582 cursor_visible_ = true;
583 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
587 void GuiWorkArea::hideCursor()
589 if (!cursor_visible_)
592 cursor_visible_ = false;
597 void GuiWorkArea::toggleCursor()
606 void GuiWorkArea::updateScrollbar()
608 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
609 // WARNING: don't touch at the scrollbar value like this:
610 // verticalScrollBar()->setValue(scroll_.position);
611 // because this would cause a recursive signal/slot calling with
612 // GuiWorkArea::scrollTo
613 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
614 verticalScrollBar()->setPageStep(scroll_.page_step);
615 verticalScrollBar()->setSingleStep(scroll_.single_step);
616 verticalScrollBar()->setSliderPosition(scroll_.position);
620 void GuiWorkArea::scrollTo(int value)
622 stopBlinkingCursor();
623 buffer_view_->scrollDocView(value);
625 if (lyxrc.cursor_follows_scrollbar) {
626 buffer_view_->setCursorFromScrollbar();
627 lyx_view_->updateLayoutList();
629 // Show the cursor immediately after any operation.
630 startBlinkingCursor();
631 QApplication::syncX();
635 bool GuiWorkArea::event(QEvent * e)
638 case QEvent::ToolTip: {
639 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
640 if (lyxrc.use_tooltip) {
641 QPoint pos = helpEvent->pos();
642 if (pos.x() < viewport()->width()) {
643 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
644 QToolTip::showText(helpEvent->globalPos(), s);
647 QToolTip::hideText();
649 // Don't forget to accept the event!
654 case QEvent::ShortcutOverride: {
655 // We catch this event in order to catch the Tab or Shift+Tab key press
656 // which are otherwise reserved to focus switching between controls
658 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
659 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
660 || ke->modifiers() & Qt::ControlModifier)
661 return QAbstractScrollArea::event(e);
667 return QAbstractScrollArea::event(e);
673 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
676 if (e->reason() == QContextMenuEvent::Mouse)
677 // the position is set on mouse press
678 pos = context_target_pos_;
681 Cursor const & cur = buffer_view_->cursor();
682 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
683 // Do not access the context menu of math right in front of before
684 // the cursor. This does not work when the cursor is in text.
685 Inset * inset = cur.paragraph().getInset(cur.pos());
686 if (inset && inset->asInsetMath())
688 else if (cur.pos() > 0) {
689 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
694 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
696 QAbstractScrollArea::contextMenuEvent(e);
699 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
701 QAbstractScrollArea::contextMenuEvent(e);
704 // Position the menu to the right.
705 // FIXME: menu position should be different for RTL text.
706 menu->exec(e->globalPos());
711 void GuiWorkArea::focusInEvent(QFocusEvent * e)
713 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
714 if (lyx_view_->currentWorkArea() != this)
715 lyx_view_->setCurrentWorkArea(this);
717 startBlinkingCursor();
718 QAbstractScrollArea::focusInEvent(e);
722 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
724 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
725 stopBlinkingCursor();
726 QAbstractScrollArea::focusOutEvent(e);
730 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
732 if (dc_event_.active && dc_event_ == *e) {
733 dc_event_.active = false;
734 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
735 q_button_state(e->button()));
741 if (e->button() == Qt::RightButton)
742 context_target_pos_ = e->pos();
744 inputContext()->reset();
746 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
747 q_button_state(e->button()));
748 dispatch(cmd, q_key_state(e->modifiers()));
753 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
755 if (synthetic_mouse_event_.timeout.running())
756 synthetic_mouse_event_.timeout.stop();
758 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
759 q_button_state(e->button()));
765 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
767 // we kill the triple click if we move
768 doubleClickTimeout();
769 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
770 q_motion_state(e->buttons()));
774 // If we're above or below the work area...
775 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
776 // Make sure only a synthetic event can cause a page scroll,
777 // so they come at a steady rate:
779 // _Force_ a scroll up:
782 cmd.y = viewport()->height();
783 // Store the event, to be handled when the timeout expires.
784 synthetic_mouse_event_.cmd = cmd;
786 if (synthetic_mouse_event_.timeout.running())
787 // Discard the event. Note that it _may_ be handled
788 // when the timeout expires if
789 // synthetic_mouse_event_.cmd has not been overwritten.
790 // Ie, when the timeout expires, we handle the
791 // most recent event but discard all others that
792 // occurred after the one used to start the timeout
793 // 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;
812 // Has anything changed on-screen since the last QMouseEvent
814 if (e->x() == synthetic_mouse_event_.x_old
815 && e->y() == synthetic_mouse_event_.y_old
816 && synthetic_mouse_event_.min_scrollbar_old == verticalScrollBar()->minimum()
817 && synthetic_mouse_event_.max_scrollbar_old == verticalScrollBar()->maximum()) {
818 // Nothing changed on-screen since the last QMouseEvent.
822 // Yes something has changed. Store the params used to check this.
823 synthetic_mouse_event_.x_old = e->x();
824 synthetic_mouse_event_.y_old = e->y();
825 synthetic_mouse_event_.min_scrollbar_old = verticalScrollBar()->minimum();
826 synthetic_mouse_event_.max_scrollbar_old = verticalScrollBar()->maximum();
828 // ... and dispatch the event to the LyX core.
833 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
835 // Wheel rotation by one notch results in a delta() of 120 (see
836 // documentation of QWheelEvent)
837 int const delta = ev->delta() / 120;
838 if (ev->modifiers() & Qt::ControlModifier) {
839 docstring arg = convert<docstring>(5 * delta);
840 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
844 // Take into account the desktop wide settings.
845 int const lines = qApp->wheelScrollLines();
846 int const page_step = verticalScrollBar()->pageStep();
847 // Test if the wheel mouse is set to one screen at a time.
848 int scroll_value = lines > page_step
849 ? page_step : lines * verticalScrollBar()->singleStep();
851 // Take into account the rotation.
852 scroll_value *= delta;
854 // Take into account user preference.
855 scroll_value = int(scroll_value * lyxrc.mouse_wheel_speed);
856 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
857 << " delta = " << delta << " scroll_value = " << scroll_value
858 << " page_step = " << page_step);
860 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
866 void GuiWorkArea::generateSyntheticMouseEvent()
868 // Set things off to generate the _next_ 'pseudo' event.
869 if (synthetic_mouse_event_.restart_timeout)
870 synthetic_mouse_event_.timeout.start();
872 // Has anything changed on-screen since the last timeout signal
874 int const min_scrollbar = verticalScrollBar()->minimum();
875 int const max_scrollbar = verticalScrollBar()->maximum();
876 if (min_scrollbar == synthetic_mouse_event_.min_scrollbar_old
877 && max_scrollbar == synthetic_mouse_event_.max_scrollbar_old) {
880 // Yes it has. Store the params used to check this.
881 synthetic_mouse_event_.min_scrollbar_old = min_scrollbar;
882 synthetic_mouse_event_.max_scrollbar_old = max_scrollbar;
883 // ... and dispatch the event to the LyX core.
884 dispatch(synthetic_mouse_event_.cmd);
888 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
890 // Do not process here some keys if dialog_mode_ is set
892 && (ev->modifiers() == Qt::NoModifier
893 || ev->modifiers() == Qt::ShiftModifier)
894 && (ev->key() == Qt::Key_Escape
895 || ev->key() == Qt::Key_Enter
896 || ev->key() == Qt::Key_Return)
902 // intercept some keys if completion popup is visible
903 if (completer_->popupVisible()) {
907 completer_->activate();
913 // do nothing if there are other events
914 // (the auto repeated events come too fast)
915 // \todo FIXME: remove hard coded Qt keys, process the key binding
917 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
918 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
919 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
925 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
926 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
929 setKeySymbol(&sym, ev);
931 processKeySym(sym, q_key_state(ev->modifiers()));
939 void GuiWorkArea::doubleClickTimeout()
941 dc_event_.active = false;
945 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
947 dc_event_ = DoubleClick(ev);
948 QTimer::singleShot(QApplication::doubleClickInterval(), this,
949 SLOT(doubleClickTimeout()));
950 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
952 q_button_state(ev->button()));
958 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
960 QAbstractScrollArea::resizeEvent(ev);
966 void GuiWorkArea::update(int x, int y, int w, int h)
968 viewport()->repaint(x, y, w, h);
972 void GuiWorkArea::paintEvent(QPaintEvent * ev)
974 QRect const rc = ev->rect();
975 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
976 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
979 screen_ = QPixmap(viewport()->width(), viewport()->height());
981 if (cursor_visible_) {
987 QPainter pain(viewport());
988 pain.drawPixmap(rc, screen_, rc);
994 void GuiWorkArea::updateScreen()
996 GuiPainter pain(&screen_);
997 buffer_view_->draw(pain);
1001 void GuiWorkArea::showCursor(int x, int y, int h,
1002 bool l_shape, bool rtl, bool completable)
1004 if (schedule_redraw_) {
1005 // This happens when a graphic conversion is finished. As we don't know
1006 // the size of the new graphics, it's better the update everything.
1007 // We can't use redraw() here because this would trigger a infinite
1008 // recursive loop with showCursor().
1009 buffer_view_->resize(viewport()->width(), viewport()->height());
1012 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
1013 schedule_redraw_ = false;
1014 // Show the cursor immediately after the update.
1020 cursor_->update(x, y, h, l_shape, rtl, completable);
1022 viewport()->update(cursor_->rect());
1026 void GuiWorkArea::removeCursor()
1029 //if (!qApp->focusWidget())
1030 viewport()->update(cursor_->rect());
1034 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1036 QString const & commit_string = e->commitString();
1037 docstring const & preedit_string
1038 = qstring_to_ucs4(e->preeditString());
1040 if (!commit_string.isEmpty()) {
1042 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1043 << " commitString: " << e->commitString());
1047 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1048 for (int i = 0; i != commit_string.size(); ++i) {
1049 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1054 // Hide the cursor during the kana-kanji transformation.
1055 if (preedit_string.empty())
1056 startBlinkingCursor();
1058 stopBlinkingCursor();
1060 // last_width : for checking if last preedit string was/wasn't empty.
1061 static bool last_width = false;
1062 if (!last_width && preedit_string.empty()) {
1063 // if last_width is last length of preedit string.
1068 GuiPainter pain(&screen_);
1069 buffer_view_->updateMetrics();
1070 buffer_view_->draw(pain);
1071 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1072 FontMetrics const & fm = theFontMetrics(font);
1073 int height = fm.maxHeight();
1074 int cur_x = cursor_->rect().left();
1075 int cur_y = cursor_->rect().bottom();
1077 // redraw area of preedit string.
1078 update(0, cur_y - height, viewport()->width(),
1079 (height + 1) * preedit_lines_);
1081 if (preedit_string.empty()) {
1089 // att : stores an IM attribute.
1090 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1092 // get attributes of input method cursor.
1093 // cursor_pos : cursor position in preedit string.
1094 size_t cursor_pos = 0;
1095 bool cursor_is_visible = false;
1096 for (int i = 0; i != att.size(); ++i) {
1097 if (att.at(i).type == QInputMethodEvent::Cursor) {
1098 cursor_pos = att.at(i).start;
1099 cursor_is_visible = att.at(i).length != 0;
1104 size_t preedit_length = preedit_string.length();
1106 // get position of selection in input method.
1107 // FIXME: isn't there a way to do this simplier?
1108 // rStart : cursor position in selected string in IM.
1110 // rLength : selected string length in IM.
1112 if (cursor_pos < preedit_length) {
1113 for (int i = 0; i != att.size(); ++i) {
1114 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1115 if (att.at(i).start <= int(cursor_pos)
1116 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1117 rStart = att.at(i).start;
1118 rLength = att.at(i).length;
1119 if (!cursor_is_visible)
1120 cursor_pos += rLength;
1127 rStart = cursor_pos;
1131 int const right_margin = buffer_view_->rightMargin();
1132 Painter::preedit_style ps;
1133 // Most often there would be only one line:
1135 for (size_t pos = 0; pos != preedit_length; ++pos) {
1136 char_type const typed_char = preedit_string[pos];
1137 // reset preedit string style
1138 ps = Painter::preedit_default;
1140 // if we reached the right extremity of the screen, go to next line.
1141 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1142 cur_x = right_margin;
1143 cur_y += height + 1;
1146 // preedit strings are displayed with dashed underline
1147 // and partial strings are displayed white on black indicating
1148 // that we are in selecting mode in the input method.
1149 // FIXME: rLength == preedit_length is not a changing condition
1150 // FIXME: should be put out of the loop.
1152 && pos < rStart + rLength
1153 && !(cursor_pos < rLength && rLength == preedit_length))
1154 ps = Painter::preedit_selecting;
1156 if (pos == cursor_pos
1157 && (cursor_pos < rLength && rLength == preedit_length))
1158 ps = Painter::preedit_cursor;
1160 // draw one character and update cur_x.
1161 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1164 // update the preedit string screen area.
1165 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1166 (height + 1) * preedit_lines_);
1168 // Don't forget to accept the event!
1173 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1175 QRect cur_r(0, 0, 0, 0);
1177 // this is the CJK-specific composition window position and
1178 // the context menu position when the menu key is pressed.
1179 case Qt::ImMicroFocus:
1180 cur_r = cursor_->rect();
1181 if (preedit_lines_ != 1)
1183 cur_r.moveBottom(cur_r.bottom()
1184 + cur_r.height() * (preedit_lines_ - 1));
1185 // return lower right of cursor in LyX.
1188 return QWidget::inputMethodQuery(query);
1193 void GuiWorkArea::updateWindowTitle()
1195 docstring maximize_title;
1196 docstring minimize_title;
1198 Buffer & buf = buffer_view_->buffer();
1199 FileName const fileName = buf.fileName();
1200 if (!fileName.empty()) {
1201 maximize_title = fileName.displayName(30);
1202 minimize_title = from_utf8(fileName.onlyFileName());
1203 if (buf.lyxvc().inUse()) {
1204 if (buf.lyxvc().locking())
1205 maximize_title += _(" (version control, locking)");
1207 maximize_title += _(" (version control)");
1209 if (!buf.isClean()) {
1210 maximize_title += _(" (changed)");
1211 minimize_title += char_type('*');
1213 if (buf.isReadonly())
1214 maximize_title += _(" (read only)");
1217 QString title = windowTitle();
1218 QString new_title = toqstr(maximize_title);
1219 if (title == new_title)
1222 QWidget::setWindowTitle(new_title);
1223 QWidget::setWindowIconText(toqstr(minimize_title));
1228 void GuiWorkArea::setReadOnly(bool read_only)
1230 if (read_only_ == read_only)
1232 read_only_ = read_only;
1233 updateWindowTitle();
1234 if (this == lyx_view_->currentWorkArea())
1235 lyx_view_->updateDialogs();
1239 bool GuiWorkArea::isFullScreen()
1241 return lyx_view_ && lyx_view_->isFullScreen();
1245 ////////////////////////////////////////////////////////////////////
1249 ////////////////////////////////////////////////////////////////////
1252 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1254 buffer_ = theBufferList().newBuffer(
1255 support::FileName::tempName().absFilename() + "_embedded.internal");
1256 buffer_->setUnnamed(true);
1257 buffer_->setFullyLoaded(true);
1258 setBuffer(*buffer_);
1259 setDialogMode(true);
1263 EmbeddedWorkArea::~EmbeddedWorkArea()
1265 // No need to destroy buffer and bufferview here, because it is done
1266 // in theBuffeerList() destruction loop at application exit
1270 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1273 GuiWorkArea::closeEvent(ev);
1277 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1280 GuiWorkArea::hideEvent(ev);
1284 QSize EmbeddedWorkArea::sizeHint () const
1287 // GuiWorkArea sets the size to the screen's viewport
1288 // by returning a value this gets overridden
1289 // EmbeddedWorkArea is now sized to fit in the layout
1290 // of the parent, and has a minimum size set in GuiWorkArea
1291 // which is what we return here
1292 return QSize(100, 70);
1296 void EmbeddedWorkArea::disable()
1298 stopBlinkingCursor();
1299 if (view().currentWorkArea() != this)
1301 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1302 // tolerates it and shows the background logo), what happens if
1303 // an EmbeddedWorkArea is closed after closing all document WAs
1304 view().setCurrentWorkArea(view().currentMainWorkArea());
1307 ////////////////////////////////////////////////////////////////////
1311 ////////////////////////////////////////////////////////////////////
1314 class NoTabFrameMacStyle : public QMacStyle {
1317 QRect subElementRect(SubElement element, const QStyleOption * option,
1318 const QWidget * widget = 0) const
1320 QRect rect = QMacStyle::subElementRect(element, option, widget);
1321 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1323 // The Qt Mac style puts the contents into a 3 pixel wide box
1324 // which looks very ugly and not like other Mac applications.
1325 // Hence we remove this here, and moreover the 16 pixel round
1326 // frame above if the tab bar is hidden.
1327 if (element == QStyle::SE_TabWidgetTabContents) {
1328 rect.adjust(- rect.left(), 0, rect.left(), 0);
1337 NoTabFrameMacStyle noTabFrameMacStyle;
1341 TabWorkArea::TabWorkArea(QWidget * parent)
1342 : QTabWidget(parent), clicked_tab_(-1)
1345 setStyle(&noTabFrameMacStyle);
1347 #if QT_VERSION < 0x040500
1348 lyxrc.single_close_tab_button = true;
1351 QPalette pal = palette();
1352 pal.setColor(QPalette::Active, QPalette::Button,
1353 pal.color(QPalette::Active, QPalette::Window));
1354 pal.setColor(QPalette::Disabled, QPalette::Button,
1355 pal.color(QPalette::Disabled, QPalette::Window));
1356 pal.setColor(QPalette::Inactive, QPalette::Button,
1357 pal.color(QPalette::Inactive, QPalette::Window));
1359 QObject::connect(this, SIGNAL(currentChanged(int)),
1360 this, SLOT(on_currentTabChanged(int)));
1362 closeBufferButton = new QToolButton(this);
1363 closeBufferButton->setPalette(pal);
1364 // FIXME: rename the icon to closebuffer.png
1365 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1366 closeBufferButton->setText("Close File");
1367 closeBufferButton->setAutoRaise(true);
1368 closeBufferButton->setCursor(Qt::ArrowCursor);
1369 closeBufferButton->setToolTip(qt_("Close File"));
1370 closeBufferButton->setEnabled(true);
1371 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1372 this, SLOT(closeCurrentBuffer()));
1373 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1375 // setup drag'n'drop
1376 QTabBar* tb = new DragTabBar;
1377 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1378 this, SLOT(moveTab(int, int)));
1379 tb->setElideMode(Qt::ElideNone);
1382 // make us responsible for the context menu of the tabbar
1383 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1384 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1385 this, SLOT(showContextMenu(const QPoint &)));
1386 #if QT_VERSION >= 0x040500
1387 connect(tb, SIGNAL(tabCloseRequested(int)),
1388 this, SLOT(closeTab(int)));
1391 setUsesScrollButtons(true);
1395 void TabWorkArea::setFullScreen(bool full_screen)
1397 for (int i = 0; i != count(); ++i) {
1398 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1399 wa->setFullScreen(full_screen);
1402 if (lyxrc.full_screen_tabbar)
1403 showBar(!full_screen && count() > 1);
1407 void TabWorkArea::showBar(bool show)
1409 tabBar()->setEnabled(show);
1410 tabBar()->setVisible(show);
1411 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1412 #if QT_VERSION >= 0x040500
1413 setTabsClosable(!lyxrc.single_close_tab_button);
1418 GuiWorkArea * TabWorkArea::currentWorkArea()
1423 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1429 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1431 for (int i = 0; i != count(); ++i) {
1432 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1433 LASSERT(wa, return 0);
1434 if (&wa->bufferView().buffer() == &buffer)
1441 void TabWorkArea::closeAll()
1444 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1452 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1454 LASSERT(work_area, /**/);
1455 int index = indexOf(work_area);
1459 if (index == currentIndex())
1460 // Make sure the work area is up to date.
1461 on_currentTabChanged(index);
1463 // Switch to the work area.
1464 setCurrentIndex(index);
1465 work_area->setFocus();
1471 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1473 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1474 wa->setUpdatesEnabled(false);
1475 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1476 // when hiding it again below).
1477 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1478 showBar(count() > 0);
1479 addTab(wa, wa->windowTitle());
1480 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1481 this, SLOT(updateTabTexts()));
1482 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1483 setFullScreen(true);
1485 // Hide tabbar if there's only one tab.
1486 showBar(count() > 1);
1494 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1496 LASSERT(work_area, return false);
1497 int index = indexOf(work_area);
1501 work_area->setUpdatesEnabled(false);
1506 // make sure the next work area is enabled.
1507 currentWidget()->setUpdatesEnabled(true);
1508 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1509 setFullScreen(true);
1511 // Show tabbar only if there's more than one tab.
1512 showBar(count() > 1);
1514 lastWorkAreaRemoved();
1522 void TabWorkArea::on_currentTabChanged(int i)
1524 // returns e.g. on application destruction
1527 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1528 LASSERT(wa, return);
1529 wa->setUpdatesEnabled(true);
1533 currentWorkAreaChanged(wa);
1535 LYXERR(Debug::GUI, "currentTabChanged " << i
1536 << " File: " << wa->bufferView().buffer().absFileName());
1540 void TabWorkArea::closeCurrentBuffer()
1543 if (clicked_tab_ == -1)
1544 wa = currentWorkArea();
1546 wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1549 wa->view().closeWorkArea(wa);
1553 void TabWorkArea::hideCurrentTab()
1556 if (clicked_tab_ == -1)
1557 wa = currentWorkArea();
1559 wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1562 wa->view().hideWorkArea(wa);
1566 void TabWorkArea::closeTab(int index)
1568 on_currentTabChanged(index);
1571 wa = currentWorkArea();
1573 wa = dynamic_cast<GuiWorkArea *>(widget(index));
1576 wa->view().closeWorkArea(wa);
1583 /// make vector happy
1586 DisplayPath(int tab, FileName const & filename)
1589 filename_ = (filename.extension() == "lyx") ?
1590 toqstr(filename.onlyFileNameWithoutExt())
1591 : toqstr(filename.onlyFileName());
1592 postfix_ = toqstr(filename.absoluteFilePath()).
1593 split("/", QString::SkipEmptyParts);
1594 postfix_.pop_back();
1595 abs_ = toqstr(filename.absoluteFilePath());
1596 dottedPrefix_ = false;
1599 /// Absolute path for debugging.
1604 /// Add the first segment from the postfix or three dots to the prefix.
1605 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1606 /// when really needed.
1607 void shiftPathSegment(bool dotted)
1609 if (postfix_.count() <= 0)
1613 if (dottedPrefix_ && !prefix_.isEmpty())
1615 prefix_ += postfix_.front() + "/";
1617 dottedPrefix_ = dotted && !prefix_.isEmpty();
1618 postfix_.pop_front();
1621 QString displayString() const
1623 if (prefix_.isEmpty())
1626 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1627 return prefix_ + (dots ? ".../" : "") + filename_;
1630 QString forecastPathString() const
1632 if (postfix_.count() == 0)
1633 return displayString();
1636 + (dottedPrefix_ ? ".../" : "")
1637 + postfix_.front() + "/";
1640 bool final() const { return postfix_.empty(); }
1642 int tab() const { return tab_; }
1648 QStringList postfix_;
1661 bool operator<(DisplayPath const & a, DisplayPath const & b)
1663 return a.displayString() < b.displayString();
1667 bool operator==(DisplayPath const & a, DisplayPath const & b)
1669 return a.displayString() == b.displayString();
1673 void TabWorkArea::updateTabTexts()
1678 std::list<DisplayPath> paths;
1679 typedef std::list<DisplayPath>::iterator It;
1681 // collect full names first: path into postfix, empty prefix and
1682 // filename without extension
1683 for (size_t i = 0; i < n; ++i) {
1684 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(i));
1685 FileName const fn = i_wa->bufferView().buffer().fileName();
1686 paths.push_back(DisplayPath(i, fn));
1689 // go through path segments and see if it helps to make the path more unique
1690 bool somethingChanged = true;
1691 bool allFinal = false;
1692 while (somethingChanged && !allFinal) {
1693 // adding path segments changes order
1696 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1697 somethingChanged = false;
1700 // find segments which are not unique (i.e. non-atomic)
1701 It it = paths.begin();
1703 QString segString = it->displayString();
1704 for (; it != paths.end(); ++it) {
1705 // look to the next item
1710 allFinal = allFinal && it->final();
1712 LYXERR(Debug::GUI, "it = " << it->abs()
1713 << " => " << it->displayString());
1715 // still the same segment?
1717 if ((next != paths.end()
1718 && (nextString = next->displayString()) == segString))
1720 LYXERR(Debug::GUI, "segment ended");
1722 // only a trivial one with one element?
1723 if (it == segStart) {
1724 // start new segment
1726 segString = nextString;
1730 // we found a non-atomic segment segStart <= sit <= it < next.
1731 // Shift path segments and hope for the best
1732 // that it makes the path more unique.
1733 somethingChanged = true;
1735 QString dspString = sit->forecastPathString();
1736 LYXERR(Debug::GUI, "first forecast found for "
1737 << sit->abs() << " => " << dspString);
1739 bool moreUnique = false;
1740 for (; sit != next; ++sit) {
1741 if (sit->forecastPathString() != dspString) {
1742 LYXERR(Debug::GUI, "different forecast found for "
1743 << sit->abs() << " => " << sit->forecastPathString());
1747 LYXERR(Debug::GUI, "same forecast found for "
1748 << sit->abs() << " => " << dspString);
1751 // if the path segment helped, add it. Otherwise add dots
1752 bool dots = !moreUnique;
1753 LYXERR(Debug::GUI, "using dots = " << dots);
1754 for (sit = segStart; sit != next; ++sit) {
1755 sit->shiftPathSegment(dots);
1756 LYXERR(Debug::GUI, "shifting "
1757 << sit->abs() << " => " << sit->displayString());
1760 // start new segment
1762 segString = nextString;
1766 // set new tab titles
1767 for (It it = paths.begin(); it != paths.end(); ++it) {
1768 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(it->tab()));
1769 Buffer & buf = i_wa->bufferView().buffer();
1770 if (!buf.fileName().empty() && !buf.isClean())
1771 setTabText(it->tab(), it->displayString() + "*");
1773 setTabText(it->tab(), it->displayString());
1778 void TabWorkArea::showContextMenu(const QPoint & pos)
1781 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1782 if (clicked_tab_ == -1)
1787 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
1788 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
1789 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
1790 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1791 popup.exec(tabBar()->mapToGlobal(pos));
1797 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1799 QWidget * w = widget(fromIndex);
1800 QIcon icon = tabIcon(fromIndex);
1801 QString text = tabText(fromIndex);
1803 setCurrentIndex(fromIndex);
1804 removeTab(fromIndex);
1805 insertTab(toIndex, w, icon, text);
1806 setCurrentIndex(toIndex);
1810 DragTabBar::DragTabBar(QWidget* parent)
1813 setAcceptDrops(true);
1814 #if QT_VERSION >= 0x040500
1815 setTabsClosable(!lyxrc.single_close_tab_button);
1820 #if QT_VERSION < 0x040300
1821 int DragTabBar::tabAt(QPoint const & position) const
1823 const int max = count();
1824 for (int i = 0; i < max; ++i) {
1825 if (tabRect(i).contains(position))
1833 void DragTabBar::mousePressEvent(QMouseEvent * event)
1835 if (event->button() == Qt::LeftButton)
1836 dragStartPos_ = event->pos();
1837 QTabBar::mousePressEvent(event);
1841 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1843 // If the left button isn't pressed anymore then return
1844 if (!(event->buttons() & Qt::LeftButton))
1847 // If the distance is too small then return
1848 if ((event->pos() - dragStartPos_).manhattanLength()
1849 < QApplication::startDragDistance())
1852 // did we hit something after all?
1853 int tab = tabAt(dragStartPos_);
1857 // simulate button release to remove highlight from button
1858 int i = currentIndex();
1859 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1860 event->button(), event->buttons(), 0);
1861 QTabBar::mouseReleaseEvent(&me);
1865 QDrag * drag = new QDrag(this);
1866 QMimeData * mimeData = new QMimeData;
1867 // a crude way to distinguish tab-reodering drops from other ones
1868 mimeData->setData("action", "tab-reordering") ;
1869 drag->setMimeData(mimeData);
1871 #if QT_VERSION >= 0x040300
1872 // get tab pixmap as cursor
1873 QRect r = tabRect(tab);
1874 QPixmap pixmap(r.size());
1875 render(&pixmap, - r.topLeft());
1876 drag->setPixmap(pixmap);
1879 drag->start(Qt::MoveAction);
1885 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1887 // Only accept if it's an tab-reordering request
1888 QMimeData const * m = event->mimeData();
1889 QStringList formats = m->formats();
1890 if (formats.contains("action")
1891 && m->data("action") == "tab-reordering")
1892 event->acceptProposedAction();
1896 void DragTabBar::dropEvent(QDropEvent * event)
1898 int fromIndex = tabAt(dragStartPos_);
1899 int toIndex = tabAt(event->pos());
1901 // Tell interested objects that
1902 if (fromIndex != toIndex)
1903 tabMoveRequested(fromIndex, toIndex);
1904 event->acceptProposedAction();
1908 } // namespace frontend
1911 #include "moc_GuiWorkArea.cpp"