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 vertical line
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))
241 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
242 : buffer_view_(0), read_only_(buffer.isReadonly()), lyx_view_(0),
243 cursor_visible_(false),
244 need_resize_(false), schedule_redraw_(false),
245 preedit_lines_(1), completer_(new GuiCompleter(this, this))
253 void GuiWorkArea::init()
256 connect(&cursor_timeout_, SIGNAL(timeout()),
257 this, SLOT(toggleCursor()));
259 int const time = QApplication::cursorFlashTime() / 2;
261 cursor_timeout_.setInterval(time);
262 cursor_timeout_.start();
264 // let's initialize this just to be safe
265 cursor_timeout_.setInterval(500);
268 screen_ = QPixmap(viewport()->width(), viewport()->height());
269 // With Qt4.5 a mouse event will happen before the first paint event
270 // so make sure that the buffer view has an up to date metrics.
271 buffer_view_->resize(viewport()->width(), viewport()->height());
272 cursor_ = new frontend::CursorWidget();
275 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
276 setAcceptDrops(true);
277 setMouseTracking(true);
278 setMinimumSize(100, 70);
279 setFrameStyle(QFrame::NoFrame);
282 viewport()->setAutoFillBackground(false);
283 // We don't need double-buffering nor SystemBackground on
284 // the viewport because we have our own backing pixmap.
285 viewport()->setAttribute(Qt::WA_NoSystemBackground);
287 setFocusPolicy(Qt::StrongFocus);
289 setCursorShape(Qt::IBeamCursor);
291 synthetic_mouse_event_.timeout.timeout.connect(
292 bind(&GuiWorkArea::generateSyntheticMouseEvent,
295 // Initialize the vertical Scroll Bar
296 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
297 this, SLOT(scrollTo(int)));
299 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
300 << " viewport height: " << viewport()->height());
302 // Enables input methods for asian languages.
303 // Must be set when creating custom text editing widgets.
304 setAttribute(Qt::WA_InputMethodEnabled, true);
306 dialog_mode_ = false;
310 GuiWorkArea::~GuiWorkArea()
312 buffer_view_->buffer().workAreaManager().remove(this);
315 // Completer has a QObject parent and is thus automatically destroyed.
317 // delete completer_;
321 Qt::CursorShape GuiWorkArea::cursorShape() const
323 return viewport()->cursor().shape();
327 void GuiWorkArea::setCursorShape(Qt::CursorShape shape)
329 viewport()->setCursor(shape);
333 void GuiWorkArea::updateCursorShape()
335 setCursorShape(buffer_view_->clickableInset()
336 ? Qt::PointingHandCursor : Qt::IBeamCursor);
340 void GuiWorkArea::setGuiView(GuiView & gv)
346 void GuiWorkArea::setBuffer(Buffer & buffer)
349 buffer_view_ = new BufferView(buffer);
350 buffer.workAreaManager().add(this);
352 // HACK: Prevents an additional redraw when the scrollbar pops up
353 // which regularily happens on documents with more than one page.
354 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
355 // Since we have no geometry information yet, we assume that
356 // a document needs a scrollbar if there is more then four
357 // paragraph in the outermost text.
358 if (buffer.text().paragraphs().size() > 4)
359 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
360 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
364 void GuiWorkArea::fixVerticalScrollBar()
367 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
371 void GuiWorkArea::close()
373 lyx_view_->removeWorkArea(this);
377 void GuiWorkArea::setFullScreen(bool full_screen)
379 buffer_view_->setFullScreen(full_screen);
380 setFrameStyle(QFrame::NoFrame);
382 setFrameStyle(QFrame::NoFrame);
383 if (lyxrc.full_screen_scrollbar)
384 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
386 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
390 BufferView & GuiWorkArea::bufferView()
392 return *buffer_view_;
396 BufferView const & GuiWorkArea::bufferView() const
398 return *buffer_view_;
402 void GuiWorkArea::stopBlinkingCursor()
404 cursor_timeout_.stop();
409 void GuiWorkArea::startBlinkingCursor()
411 // do not show the cursor if the view is busy
417 buffer_view_->cursorPosAndHeight(p, h);
418 // Don't start blinking if the cursor isn't on screen.
419 if (!buffer_view_->cursorInView(p, h))
424 //we're not supposed to cache this value.
425 int const time = QApplication::cursorFlashTime() / 2;
428 cursor_timeout_.setInterval(time);
429 cursor_timeout_.start();
433 void GuiWorkArea::redraw(bool update_metrics)
436 // No need to redraw in this case.
439 // No need to do anything if this is the current view. The BufferView
440 // metrics are already up to date.
441 if (update_metrics || lyx_view_ != guiApp->currentView()
442 || lyx_view_->currentWorkArea() != this) {
443 // FIXME: it would be nice to optimize for the off-screen case.
444 buffer_view_->cursor().fixIfBroken();
445 buffer_view_->updateMetrics();
446 buffer_view_->cursor().fixIfBroken();
449 // update cursor position, because otherwise it has to wait until
450 // the blinking interval is over
451 if (cursor_visible_) {
456 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
458 update(0, 0, viewport()->width(), viewport()->height());
460 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
461 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
463 lyx_view_->updateStatusBar();
465 if (lyxerr.debugging(Debug::WORKAREA))
466 buffer_view_->coordCache().dump();
468 setReadOnly(buffer_view_->buffer().isReadonly());
474 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
476 if (lyx_view_->isFullScreen() && lyx_view_->menuBar()->isVisible()
477 && lyxrc.full_screen_menubar) {
478 // FIXME HACK: we should not have to do this here. See related comment
479 // in GuiView::event() (QEvent::ShortcutOverride)
480 lyx_view_->menuBar()->hide();
483 // In order to avoid bad surprise in the middle of an operation,
484 // we better stop the blinking cursor...
485 // the cursor gets restarted in GuiView::restartCursor()
486 stopBlinkingCursor();
487 guiApp->processKeySym(key, mod);
491 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
494 if (cmd0.action() == LFUN_FILE_OPEN) {
496 lyx_view_->dispatch(cmd0, dr);
502 if (cmd0.action() == LFUN_MOUSE_PRESS) {
503 if (mod == ShiftModifier)
504 cmd = FuncRequest(cmd0, "region-select");
505 else if (mod == ControlModifier)
506 cmd = FuncRequest(cmd0, "paragraph-select");
513 bool const notJustMovingTheMouse =
514 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
516 // In order to avoid bad surprise in the middle of an operation, we better stop
517 // the blinking cursor.
518 if (notJustMovingTheMouse)
519 stopBlinkingCursor();
521 buffer_view_->mouseEventDispatch(cmd);
523 // Skip these when selecting
524 if (cmd.action() != LFUN_MOUSE_MOTION) {
525 completer_->updateVisibility(false, false);
526 lyx_view_->updateDialogs();
527 lyx_view_->updateStatusBar();
530 // GUI tweaks except with mouse motion with no button pressed.
531 if (notJustMovingTheMouse) {
532 // Slight hack: this is only called currently when we
533 // clicked somewhere, so we force through the display
534 // of the new status here.
535 lyx_view_->clearMessage();
537 // Show the cursor immediately after any operation
538 startBlinkingCursor();
545 void GuiWorkArea::resizeBufferView()
547 // WARNING: Please don't put any code that will trigger a repaint here!
548 // We are already inside a paint event.
549 lyx_view_->setBusy(true);
552 buffer_view_->cursorPosAndHeight(p, h);
553 bool const cursor_in_view = buffer_view_->cursorInView(p, h);
554 buffer_view_->resize(viewport()->width(), viewport()->height());
556 buffer_view_->scrollToCursor();
559 // Update scrollbars which might have changed due different
560 // BufferView dimension. This is especially important when the
561 // BufferView goes from zero-size to the real-size for the first time,
562 // as the scrollbar paramters are then set for the first time.
565 lyx_view_->updateLayoutList();
566 lyx_view_->setBusy(false);
567 need_resize_ = false;
571 void GuiWorkArea::showCursor()
578 buffer_view_->cursorPosAndHeight(p, h);
579 if (!buffer_view_->cursorInView(p, h))
583 bool l_shape = false;
584 Font const & realfont = buffer_view_->cursor().real_current_font;
585 BufferParams const & bp = buffer_view_->buffer().params();
586 bool const samelang = realfont.language() == bp.language;
587 bool const isrtl = realfont.isVisibleRightToLeft();
589 if (!samelang || isrtl != bp.language->rightToLeft())
592 // The ERT language hack needs fixing up
593 if (realfont.language() == latex_language)
596 // show cursor on screen
597 Cursor & cur = buffer_view_->cursor();
598 bool completable = cur.inset().showCompletionCursor()
599 && completer_->completionAvailable()
600 && !completer_->popupVisible()
601 && !completer_->inlineVisible();
602 cursor_visible_ = true;
603 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
607 void GuiWorkArea::hideCursor()
609 if (!cursor_visible_)
612 cursor_visible_ = false;
617 void GuiWorkArea::toggleCursor()
626 void GuiWorkArea::updateScrollbar()
628 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
629 // WARNING: don't touch at the scrollbar value like this:
630 // verticalScrollBar()->setValue(scroll_.position);
631 // because this would cause a recursive signal/slot calling with
632 // GuiWorkArea::scrollTo
633 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
634 verticalScrollBar()->setPageStep(scroll_.page_step);
635 verticalScrollBar()->setSingleStep(scroll_.single_step);
636 verticalScrollBar()->setSliderPosition(scroll_.position);
640 void GuiWorkArea::scrollTo(int value)
642 stopBlinkingCursor();
643 buffer_view_->scrollDocView(value, true);
645 if (lyxrc.cursor_follows_scrollbar) {
646 buffer_view_->setCursorFromScrollbar();
647 lyx_view_->updateLayoutList();
649 // Show the cursor immediately after any operation.
650 startBlinkingCursor();
651 QApplication::syncX();
655 bool GuiWorkArea::event(QEvent * e)
658 case QEvent::ToolTip: {
659 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
660 if (lyxrc.use_tooltip) {
661 QPoint pos = helpEvent->pos();
662 if (pos.x() < viewport()->width()) {
663 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
664 QToolTip::showText(helpEvent->globalPos(), s);
667 QToolTip::hideText();
669 // Don't forget to accept the event!
674 case QEvent::ShortcutOverride: {
675 // We catch this event in order to catch the Tab or Shift+Tab key press
676 // which are otherwise reserved to focus switching between controls
678 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
679 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
680 || (ke->key() == Qt::Key_Backtab && (
681 ke->modifiers() == Qt::ShiftModifier
682 || ke->modifiers() == Qt::NoModifier))) {
686 return QAbstractScrollArea::event(e);
690 return QAbstractScrollArea::event(e);
696 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
699 if (e->reason() == QContextMenuEvent::Mouse)
700 // the menu name is set on mouse press
701 name = context_menu_name_;
703 QPoint pos = e->pos();
704 Cursor const & cur = buffer_view_->cursor();
705 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
706 // Do not access the context menu of math right in front of before
707 // the cursor. This does not work when the cursor is in text.
708 Inset * inset = cur.paragraph().getInset(cur.pos());
709 if (inset && inset->asInsetMath())
711 else if (cur.pos() > 0) {
712 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
717 name = buffer_view_->contextMenu(pos.x(), pos.y());
721 QAbstractScrollArea::contextMenuEvent(e);
724 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
726 QAbstractScrollArea::contextMenuEvent(e);
729 // Position the menu to the right.
730 // FIXME: menu position should be different for RTL text.
731 menu->exec(e->globalPos());
736 void GuiWorkArea::focusInEvent(QFocusEvent * e)
738 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
739 if (lyx_view_->currentWorkArea() != this)
740 lyx_view_->setCurrentWorkArea(this);
742 startBlinkingCursor();
743 QAbstractScrollArea::focusInEvent(e);
747 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
749 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
750 stopBlinkingCursor();
751 QAbstractScrollArea::focusOutEvent(e);
755 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
757 if (dc_event_.active && dc_event_ == *e) {
758 dc_event_.active = false;
759 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
760 q_button_state(e->button()));
766 // Save the context menu on mouse press, because also the mouse
767 // cursor is set on mouse press. Afterwards, we can either release
768 // the mousebutton somewhere else, or the cursor might have moved
770 if (e->button() == Qt::RightButton)
771 context_menu_name_ = buffer_view_->contextMenu(e->x(), e->y());
773 inputContext()->reset();
775 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
776 q_button_state(e->button()));
777 dispatch(cmd, q_key_state(e->modifiers()));
782 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
784 if (synthetic_mouse_event_.timeout.running())
785 synthetic_mouse_event_.timeout.stop();
787 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
788 q_button_state(e->button()));
794 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
796 // we kill the triple click if we move
797 doubleClickTimeout();
798 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
799 q_motion_state(e->buttons()));
803 // If we're above or below the work area...
804 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
805 && e->buttons() == mouse_button::button1) {
806 // Make sure only a synthetic event can cause a page scroll,
807 // so they come at a steady rate:
809 // _Force_ a scroll up:
810 cmd.set_y(e->y() - 21);
812 cmd.set_y(e->y() + 21);
813 // Store the event, to be handled when the timeout expires.
814 synthetic_mouse_event_.cmd = cmd;
816 if (synthetic_mouse_event_.timeout.running()) {
817 // Discard the event. Note that it _may_ be handled
818 // when the timeout expires if
819 // synthetic_mouse_event_.cmd has not been overwritten.
820 // Ie, when the timeout expires, we handle the
821 // most recent event but discard all others that
822 // occurred after the one used to start the timeout
823 // in the first place.
827 synthetic_mouse_event_.restart_timeout = true;
828 synthetic_mouse_event_.timeout.start();
829 // Fall through to handle this event...
831 } else if (synthetic_mouse_event_.timeout.running()) {
832 // Store the event, to be possibly handled when the timeout
834 // Once the timeout has expired, normal control is returned
835 // to mouseMoveEvent (restart_timeout = false).
836 // This results in a much smoother 'feel' when moving the
837 // mouse back into the work area.
838 synthetic_mouse_event_.cmd = cmd;
839 synthetic_mouse_event_.restart_timeout = false;
846 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
848 // Wheel rotation by one notch results in a delta() of 120 (see
849 // documentation of QWheelEvent)
850 double const delta = ev->delta() / 120.0;
852 switch (lyxrc.scroll_wheel_zoom) {
853 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
854 zoom = ev->modifiers() & Qt::ControlModifier;
855 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
857 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
858 zoom = ev->modifiers() & Qt::ShiftModifier;
859 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
861 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
862 zoom = ev->modifiers() & Qt::AltModifier;
863 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
865 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
869 docstring arg = convert<docstring>(int(5 * delta));
870 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
874 // Take into account the desktop wide settings.
875 int const lines = qApp->wheelScrollLines();
876 int const page_step = verticalScrollBar()->pageStep();
877 // Test if the wheel mouse is set to one screen at a time.
878 int scroll_value = lines > page_step
879 ? page_step : lines * verticalScrollBar()->singleStep();
881 // Take into account the rotation and the user preferences.
882 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
883 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
884 << " delta = " << delta << " scroll_value = " << scroll_value
885 << " page_step = " << page_step);
887 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
893 void GuiWorkArea::generateSyntheticMouseEvent()
895 int const e_y = synthetic_mouse_event_.cmd.y();
896 int const wh = buffer_view_->workHeight();
897 bool const up = e_y < 0;
898 bool const down = e_y > wh;
900 // Set things off to generate the _next_ 'pseudo' event.
902 if (synthetic_mouse_event_.restart_timeout) {
903 // This is some magic formulae to determine the speed
904 // of scrolling related to the position of the mouse.
907 int dist = up ? -e_y : e_y - wh;
908 time = max(min(200, 250000 / (dist * dist)), 1) ;
911 step = 80000 / (time * time);
915 synthetic_mouse_event_.timeout.setTimeout(time);
916 synthetic_mouse_event_.timeout.start();
919 // Can we scroll further ?
920 int const value = verticalScrollBar()->value();
921 if (value == verticalScrollBar()->maximum()
922 || value == verticalScrollBar()->minimum()) {
923 synthetic_mouse_event_.timeout.stop();
928 if (step <= 2 * wh) {
929 buffer_view_->scroll(up ? -step : step);
930 buffer_view_->updateMetrics();
932 buffer_view_->scrollDocView(value + up ? -step : step, false);
935 // In which paragraph do we have to set the cursor ?
936 Cursor & cur = buffer_view_->cursor();
937 TextMetrics const & tm = buffer_view_->textMetrics(cur.text());
939 pair<pit_type, const ParagraphMetrics *> p = up ? tm.first() : tm.last();
940 ParagraphMetrics const & pm = *p.second;
941 pit_type const pit = p.first;
943 if (pm.rows().empty())
946 // Find the row at which we set the cursor.
947 RowList::const_iterator rit = pm.rows().begin();
948 RowList::const_iterator rlast = pm.rows().end();
949 int yy = pm.position() - pm.ascent();
950 for (--rlast; rit != rlast; ++rit) {
951 int h = rit->height();
952 if ((up && yy + h > 0)
953 || (!up && yy + h > wh - defaultRowHeight()))
958 // Find the position of the cursor
960 int x = synthetic_mouse_event_.cmd.x();
961 pos_type const pos = rit->pos() + tm.getColumnNearX(pit, *rit, x, bound);
968 buffer_view_->buffer().changed(false);
973 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
975 // Do not process here some keys if dialog_mode_ is set
977 && (ev->modifiers() == Qt::NoModifier
978 || ev->modifiers() == Qt::ShiftModifier)
979 && (ev->key() == Qt::Key_Escape
980 || ev->key() == Qt::Key_Enter
981 || ev->key() == Qt::Key_Return)
987 // intercept some keys if completion popup is visible
988 if (completer_->popupVisible()) {
992 completer_->activate();
998 // do nothing if there are other events
999 // (the auto repeated events come too fast)
1000 // it looks like this is only needed on X11
1002 if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1003 LYXERR(Debug::KEY, "system is busy: keyPress event ignored");
1009 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1010 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
1013 setKeySymbol(&sym, ev);
1015 processKeySym(sym, q_key_state(ev->modifiers()));
1023 void GuiWorkArea::doubleClickTimeout()
1025 dc_event_.active = false;
1029 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1031 dc_event_ = DoubleClick(ev);
1032 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1033 SLOT(doubleClickTimeout()));
1034 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1036 q_button_state(ev->button()));
1042 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1044 QAbstractScrollArea::resizeEvent(ev);
1045 need_resize_ = true;
1050 void GuiWorkArea::update(int x, int y, int w, int h)
1052 viewport()->repaint(x, y, w, h);
1056 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1058 QRect const rc = ev->rect();
1059 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1060 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1063 screen_ = QPixmap(viewport()->width(), viewport()->height());
1065 if (cursor_visible_) {
1071 QPainter pain(viewport());
1072 pain.drawPixmap(rc, screen_, rc);
1073 cursor_->draw(pain);
1078 void GuiWorkArea::updateScreen()
1080 GuiPainter pain(&screen_);
1081 buffer_view_->draw(pain);
1085 void GuiWorkArea::showCursor(int x, int y, int h,
1086 bool l_shape, bool rtl, bool completable)
1088 if (schedule_redraw_) {
1089 // This happens when a graphic conversion is finished. As we don't know
1090 // the size of the new graphics, it's better the update everything.
1091 // We can't use redraw() here because this would trigger a infinite
1092 // recursive loop with showCursor().
1093 buffer_view_->resize(viewport()->width(), viewport()->height());
1096 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
1097 schedule_redraw_ = false;
1098 // Show the cursor immediately after the update.
1104 cursor_->update(x, y, h, l_shape, rtl, completable);
1106 viewport()->update(cursor_->rect());
1110 void GuiWorkArea::removeCursor()
1113 //if (!qApp->focusWidget())
1114 viewport()->update(cursor_->rect());
1118 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1120 QString const & commit_string = e->commitString();
1121 docstring const & preedit_string
1122 = qstring_to_ucs4(e->preeditString());
1124 if (!commit_string.isEmpty()) {
1126 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1127 << " commitString: " << e->commitString());
1131 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1132 for (int i = 0; i != commit_string.size(); ++i) {
1133 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1138 // Hide the cursor during the kana-kanji transformation.
1139 if (preedit_string.empty())
1140 startBlinkingCursor();
1142 stopBlinkingCursor();
1144 // last_width : for checking if last preedit string was/wasn't empty.
1145 static bool last_width = false;
1146 if (!last_width && preedit_string.empty()) {
1147 // if last_width is last length of preedit string.
1152 GuiPainter pain(&screen_);
1153 buffer_view_->updateMetrics();
1154 buffer_view_->draw(pain);
1155 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1156 FontMetrics const & fm = theFontMetrics(font);
1157 int height = fm.maxHeight();
1158 int cur_x = cursor_->rect().left();
1159 int cur_y = cursor_->rect().bottom();
1161 // redraw area of preedit string.
1162 update(0, cur_y - height, viewport()->width(),
1163 (height + 1) * preedit_lines_);
1165 if (preedit_string.empty()) {
1173 // att : stores an IM attribute.
1174 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1176 // get attributes of input method cursor.
1177 // cursor_pos : cursor position in preedit string.
1178 size_t cursor_pos = 0;
1179 bool cursor_is_visible = false;
1180 for (int i = 0; i != att.size(); ++i) {
1181 if (att.at(i).type == QInputMethodEvent::Cursor) {
1182 cursor_pos = att.at(i).start;
1183 cursor_is_visible = att.at(i).length != 0;
1188 size_t preedit_length = preedit_string.length();
1190 // get position of selection in input method.
1191 // FIXME: isn't there a way to do this simplier?
1192 // rStart : cursor position in selected string in IM.
1194 // rLength : selected string length in IM.
1196 if (cursor_pos < preedit_length) {
1197 for (int i = 0; i != att.size(); ++i) {
1198 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1199 if (att.at(i).start <= int(cursor_pos)
1200 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1201 rStart = att.at(i).start;
1202 rLength = att.at(i).length;
1203 if (!cursor_is_visible)
1204 cursor_pos += rLength;
1211 rStart = cursor_pos;
1215 int const right_margin = buffer_view_->rightMargin();
1216 Painter::preedit_style ps;
1217 // Most often there would be only one line:
1219 for (size_t pos = 0; pos != preedit_length; ++pos) {
1220 char_type const typed_char = preedit_string[pos];
1221 // reset preedit string style
1222 ps = Painter::preedit_default;
1224 // if we reached the right extremity of the screen, go to next line.
1225 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1226 cur_x = right_margin;
1227 cur_y += height + 1;
1230 // preedit strings are displayed with dashed underline
1231 // and partial strings are displayed white on black indicating
1232 // that we are in selecting mode in the input method.
1233 // FIXME: rLength == preedit_length is not a changing condition
1234 // FIXME: should be put out of the loop.
1236 && pos < rStart + rLength
1237 && !(cursor_pos < rLength && rLength == preedit_length))
1238 ps = Painter::preedit_selecting;
1240 if (pos == cursor_pos
1241 && (cursor_pos < rLength && rLength == preedit_length))
1242 ps = Painter::preedit_cursor;
1244 // draw one character and update cur_x.
1245 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1248 // update the preedit string screen area.
1249 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1250 (height + 1) * preedit_lines_);
1252 // Don't forget to accept the event!
1257 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1259 QRect cur_r(0, 0, 0, 0);
1261 // this is the CJK-specific composition window position and
1262 // the context menu position when the menu key is pressed.
1263 case Qt::ImMicroFocus:
1264 cur_r = cursor_->rect();
1265 if (preedit_lines_ != 1)
1267 cur_r.moveBottom(cur_r.bottom()
1268 + cur_r.height() * (preedit_lines_ - 1));
1269 // return lower right of cursor in LyX.
1272 return QWidget::inputMethodQuery(query);
1277 void GuiWorkArea::updateWindowTitle()
1279 docstring maximize_title;
1280 docstring minimize_title;
1282 Buffer const & buf = buffer_view_->buffer();
1283 FileName const file_name = buf.fileName();
1284 if (!file_name.empty()) {
1285 maximize_title = file_name.displayName(130);
1286 minimize_title = from_utf8(file_name.onlyFileName());
1287 if (buf.lyxvc().inUse()) {
1288 if (buf.lyxvc().locking())
1289 maximize_title += _(" (version control, locking)");
1291 maximize_title += _(" (version control)");
1293 if (!buf.isClean()) {
1294 maximize_title += _(" (changed)");
1295 minimize_title += char_type('*');
1297 if (buf.isReadonly())
1298 maximize_title += _(" (read only)");
1301 QString const new_title = toqstr(maximize_title);
1302 if (new_title != windowTitle()) {
1303 QWidget::setWindowTitle(new_title);
1304 QWidget::setWindowIconText(toqstr(minimize_title));
1310 void GuiWorkArea::setReadOnly(bool read_only)
1312 if (read_only_ == read_only)
1314 read_only_ = read_only;
1315 updateWindowTitle();
1316 if (this == lyx_view_->currentWorkArea())
1317 lyx_view_->updateDialogs();
1321 bool GuiWorkArea::isFullScreen()
1323 return lyx_view_ && lyx_view_->isFullScreen();
1327 ////////////////////////////////////////////////////////////////////
1331 ////////////////////////////////////////////////////////////////////
1334 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1336 buffer_ = theBufferList().newBuffer(
1337 support::FileName::tempName().absFileName() + "_embedded.internal");
1338 buffer_->setUnnamed(true);
1339 buffer_->setFullyLoaded(true);
1340 setBuffer(*buffer_);
1341 setDialogMode(true);
1345 EmbeddedWorkArea::~EmbeddedWorkArea()
1347 // No need to destroy buffer and bufferview here, because it is done
1348 // in theBufferList() destruction loop at application exit
1352 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1355 GuiWorkArea::closeEvent(ev);
1359 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1362 GuiWorkArea::hideEvent(ev);
1366 QSize EmbeddedWorkArea::sizeHint () const
1369 // GuiWorkArea sets the size to the screen's viewport
1370 // by returning a value this gets overridden
1371 // EmbeddedWorkArea is now sized to fit in the layout
1372 // of the parent, and has a minimum size set in GuiWorkArea
1373 // which is what we return here
1374 return QSize(100, 70);
1378 void EmbeddedWorkArea::disable()
1380 stopBlinkingCursor();
1381 if (view().currentWorkArea() != this)
1383 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1384 // tolerates it and shows the background logo), what happens if
1385 // an EmbeddedWorkArea is closed after closing all document WAs
1386 view().setCurrentWorkArea(view().currentMainWorkArea());
1389 ////////////////////////////////////////////////////////////////////
1393 ////////////////////////////////////////////////////////////////////
1396 class NoTabFrameMacStyle : public QMacStyle {
1399 QRect subElementRect(SubElement element, const QStyleOption * option,
1400 const QWidget * widget = 0) const
1402 QRect rect = QMacStyle::subElementRect(element, option, widget);
1403 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1405 // The Qt Mac style puts the contents into a 3 pixel wide box
1406 // which looks very ugly and not like other Mac applications.
1407 // Hence we remove this here, and moreover the 16 pixel round
1408 // frame above if the tab bar is hidden.
1409 if (element == QStyle::SE_TabWidgetTabContents) {
1410 rect.adjust(- rect.left(), 0, rect.left(), 0);
1419 NoTabFrameMacStyle noTabFrameMacStyle;
1423 TabWorkArea::TabWorkArea(QWidget * parent)
1424 : QTabWidget(parent), clicked_tab_(-1)
1427 setStyle(&noTabFrameMacStyle);
1429 #if QT_VERSION < 0x040500
1430 lyxrc.single_close_tab_button = true;
1433 QPalette pal = palette();
1434 pal.setColor(QPalette::Active, QPalette::Button,
1435 pal.color(QPalette::Active, QPalette::Window));
1436 pal.setColor(QPalette::Disabled, QPalette::Button,
1437 pal.color(QPalette::Disabled, QPalette::Window));
1438 pal.setColor(QPalette::Inactive, QPalette::Button,
1439 pal.color(QPalette::Inactive, QPalette::Window));
1441 QObject::connect(this, SIGNAL(currentChanged(int)),
1442 this, SLOT(on_currentTabChanged(int)));
1444 closeBufferButton = new QToolButton(this);
1445 closeBufferButton->setPalette(pal);
1446 // FIXME: rename the icon to closebuffer.png
1447 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1448 closeBufferButton->setText("Close File");
1449 closeBufferButton->setAutoRaise(true);
1450 closeBufferButton->setCursor(Qt::ArrowCursor);
1451 closeBufferButton->setToolTip(qt_("Close File"));
1452 closeBufferButton->setEnabled(true);
1453 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1454 this, SLOT(closeCurrentBuffer()));
1455 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1457 // setup drag'n'drop
1458 QTabBar* tb = new DragTabBar;
1459 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1460 this, SLOT(moveTab(int, int)));
1461 tb->setElideMode(Qt::ElideNone);
1464 // make us responsible for the context menu of the tabbar
1465 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1466 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1467 this, SLOT(showContextMenu(const QPoint &)));
1468 #if QT_VERSION >= 0x040500
1469 connect(tb, SIGNAL(tabCloseRequested(int)),
1470 this, SLOT(closeTab(int)));
1473 setUsesScrollButtons(true);
1477 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1479 if (event->button() != Qt::LeftButton)
1482 // return early if double click on existing tabs
1483 for (int i = 0; i < count(); ++i)
1484 if (tabBar()->tabRect(i).contains(event->pos()))
1487 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1491 void TabWorkArea::setFullScreen(bool full_screen)
1493 for (int i = 0; i != count(); ++i) {
1494 if (GuiWorkArea * wa = workArea(i))
1495 wa->setFullScreen(full_screen);
1498 if (lyxrc.full_screen_tabbar)
1499 showBar(!full_screen && count() > 1);
1503 void TabWorkArea::showBar(bool show)
1505 tabBar()->setEnabled(show);
1506 tabBar()->setVisible(show);
1507 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1508 #if QT_VERSION >= 0x040500
1509 setTabsClosable(!lyxrc.single_close_tab_button);
1514 GuiWorkArea * TabWorkArea::currentWorkArea()
1519 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1525 GuiWorkArea * TabWorkArea::workArea(int index)
1527 return dynamic_cast<GuiWorkArea *>(widget(index));
1531 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1533 // FIXME: this method doesn't work if we have more than work area
1534 // showing the same buffer.
1535 for (int i = 0; i != count(); ++i) {
1536 GuiWorkArea * wa = workArea(i);
1537 LASSERT(wa, return 0);
1538 if (&wa->bufferView().buffer() == &buffer)
1545 void TabWorkArea::closeAll()
1548 GuiWorkArea * wa = workArea(0);
1556 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1558 LASSERT(work_area, /**/);
1559 int index = indexOf(work_area);
1563 if (index == currentIndex())
1564 // Make sure the work area is up to date.
1565 on_currentTabChanged(index);
1567 // Switch to the work area.
1568 setCurrentIndex(index);
1569 work_area->setFocus();
1575 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1577 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1578 wa->setUpdatesEnabled(false);
1579 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1580 // when hiding it again below).
1581 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1582 showBar(count() > 0);
1583 addTab(wa, wa->windowTitle());
1584 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1585 this, SLOT(updateTabTexts()));
1586 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1587 setFullScreen(true);
1589 // Hide tabbar if there's only one tab.
1590 showBar(count() > 1);
1598 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1600 LASSERT(work_area, return false);
1601 int index = indexOf(work_area);
1605 work_area->setUpdatesEnabled(false);
1610 // make sure the next work area is enabled.
1611 currentWidget()->setUpdatesEnabled(true);
1612 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1613 setFullScreen(true);
1615 // Show tabbar only if there's more than one tab.
1616 showBar(count() > 1);
1618 lastWorkAreaRemoved();
1626 void TabWorkArea::on_currentTabChanged(int i)
1628 // returns e.g. on application destruction
1631 GuiWorkArea * wa = workArea(i);
1632 LASSERT(wa, return);
1633 wa->setUpdatesEnabled(true);
1637 currentWorkAreaChanged(wa);
1639 LYXERR(Debug::GUI, "currentTabChanged " << i
1640 << " File: " << wa->bufferView().buffer().absFileName());
1644 void TabWorkArea::closeCurrentBuffer()
1647 if (clicked_tab_ == -1)
1648 wa = currentWorkArea();
1650 wa = workArea(clicked_tab_);
1653 wa->view().closeWorkArea(wa);
1657 void TabWorkArea::hideCurrentTab()
1660 if (clicked_tab_ == -1)
1661 wa = currentWorkArea();
1663 wa = workArea(clicked_tab_);
1666 wa->view().hideWorkArea(wa);
1670 void TabWorkArea::closeTab(int index)
1672 on_currentTabChanged(index);
1675 wa = currentWorkArea();
1677 wa = workArea(index);
1680 wa->view().closeWorkArea(wa);
1687 /// make vector happy
1690 DisplayPath(int tab, FileName const & filename)
1693 filename_ = (filename.extension() == "lyx") ?
1694 toqstr(filename.onlyFileNameWithoutExt())
1695 : toqstr(filename.onlyFileName());
1696 postfix_ = toqstr(filename.absoluteFilePath()).
1697 split("/", QString::SkipEmptyParts);
1698 postfix_.pop_back();
1699 abs_ = toqstr(filename.absoluteFilePath());
1700 dottedPrefix_ = false;
1703 /// Absolute path for debugging.
1708 /// Add the first segment from the postfix or three dots to the prefix.
1709 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1710 /// when really needed.
1711 void shiftPathSegment(bool dotted)
1713 if (postfix_.count() <= 0)
1717 if (dottedPrefix_ && !prefix_.isEmpty())
1719 prefix_ += postfix_.front() + "/";
1721 dottedPrefix_ = dotted && !prefix_.isEmpty();
1722 postfix_.pop_front();
1725 QString displayString() const
1727 if (prefix_.isEmpty())
1730 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1731 return prefix_ + (dots ? ".../" : "") + filename_;
1734 QString forecastPathString() const
1736 if (postfix_.count() == 0)
1737 return displayString();
1740 + (dottedPrefix_ ? ".../" : "")
1741 + postfix_.front() + "/";
1744 bool final() const { return postfix_.empty(); }
1746 int tab() const { return tab_; }
1752 QStringList postfix_;
1765 bool operator<(DisplayPath const & a, DisplayPath const & b)
1767 return a.displayString() < b.displayString();
1771 bool operator==(DisplayPath const & a, DisplayPath const & b)
1773 return a.displayString() == b.displayString();
1777 void TabWorkArea::updateTabTexts()
1782 std::list<DisplayPath> paths;
1783 typedef std::list<DisplayPath>::iterator It;
1785 // collect full names first: path into postfix, empty prefix and
1786 // filename without extension
1787 for (size_t i = 0; i < n; ++i) {
1788 GuiWorkArea * i_wa = workArea(i);
1789 FileName const fn = i_wa->bufferView().buffer().fileName();
1790 paths.push_back(DisplayPath(i, fn));
1793 // go through path segments and see if it helps to make the path more unique
1794 bool somethingChanged = true;
1795 bool allFinal = false;
1796 while (somethingChanged && !allFinal) {
1797 // adding path segments changes order
1800 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1801 somethingChanged = false;
1804 // find segments which are not unique (i.e. non-atomic)
1805 It it = paths.begin();
1807 QString segString = it->displayString();
1808 for (; it != paths.end(); ++it) {
1809 // look to the next item
1814 allFinal = allFinal && it->final();
1816 LYXERR(Debug::GUI, "it = " << it->abs()
1817 << " => " << it->displayString());
1819 // still the same segment?
1821 if ((next != paths.end()
1822 && (nextString = next->displayString()) == segString))
1824 LYXERR(Debug::GUI, "segment ended");
1826 // only a trivial one with one element?
1827 if (it == segStart) {
1828 // start new segment
1830 segString = nextString;
1834 // we found a non-atomic segment segStart <= sit <= it < next.
1835 // Shift path segments and hope for the best
1836 // that it makes the path more unique.
1837 somethingChanged = true;
1839 QString dspString = sit->forecastPathString();
1840 LYXERR(Debug::GUI, "first forecast found for "
1841 << sit->abs() << " => " << dspString);
1843 bool moreUnique = false;
1844 for (; sit != next; ++sit) {
1845 if (sit->forecastPathString() != dspString) {
1846 LYXERR(Debug::GUI, "different forecast found for "
1847 << sit->abs() << " => " << sit->forecastPathString());
1851 LYXERR(Debug::GUI, "same forecast found for "
1852 << sit->abs() << " => " << dspString);
1855 // if the path segment helped, add it. Otherwise add dots
1856 bool dots = !moreUnique;
1857 LYXERR(Debug::GUI, "using dots = " << dots);
1858 for (sit = segStart; sit != next; ++sit) {
1859 sit->shiftPathSegment(dots);
1860 LYXERR(Debug::GUI, "shifting "
1861 << sit->abs() << " => " << sit->displayString());
1864 // start new segment
1866 segString = nextString;
1870 // set new tab titles
1871 for (It it = paths.begin(); it != paths.end(); ++it) {
1872 int const tab_index = it->tab();
1873 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
1874 QString tab_text = it->displayString();
1875 if (!buf.fileName().empty() && !buf.isClean())
1877 setTabText(tab_index, tab_text);
1878 setTabToolTip(tab_index, it->abs());
1883 void TabWorkArea::showContextMenu(const QPoint & pos)
1886 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1887 if (clicked_tab_ == -1)
1892 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
1893 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
1894 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
1895 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1896 popup.exec(tabBar()->mapToGlobal(pos));
1902 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1904 QWidget * w = widget(fromIndex);
1905 QIcon icon = tabIcon(fromIndex);
1906 QString text = tabText(fromIndex);
1908 setCurrentIndex(fromIndex);
1909 removeTab(fromIndex);
1910 insertTab(toIndex, w, icon, text);
1911 setCurrentIndex(toIndex);
1915 DragTabBar::DragTabBar(QWidget* parent)
1918 setAcceptDrops(true);
1919 #if QT_VERSION >= 0x040500
1920 setTabsClosable(!lyxrc.single_close_tab_button);
1925 #if QT_VERSION < 0x040300
1926 int DragTabBar::tabAt(QPoint const & position) const
1928 const int max = count();
1929 for (int i = 0; i < max; ++i) {
1930 if (tabRect(i).contains(position))
1938 void DragTabBar::mousePressEvent(QMouseEvent * event)
1940 if (event->button() == Qt::LeftButton)
1941 dragStartPos_ = event->pos();
1942 QTabBar::mousePressEvent(event);
1946 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1948 // If the left button isn't pressed anymore then return
1949 if (!(event->buttons() & Qt::LeftButton))
1952 // If the distance is too small then return
1953 if ((event->pos() - dragStartPos_).manhattanLength()
1954 < QApplication::startDragDistance())
1957 // did we hit something after all?
1958 int tab = tabAt(dragStartPos_);
1962 // simulate button release to remove highlight from button
1963 int i = currentIndex();
1964 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1965 event->button(), event->buttons(), 0);
1966 QTabBar::mouseReleaseEvent(&me);
1970 QDrag * drag = new QDrag(this);
1971 QMimeData * mimeData = new QMimeData;
1972 // a crude way to distinguish tab-reodering drops from other ones
1973 mimeData->setData("action", "tab-reordering") ;
1974 drag->setMimeData(mimeData);
1976 #if QT_VERSION >= 0x040300
1977 // get tab pixmap as cursor
1978 QRect r = tabRect(tab);
1979 QPixmap pixmap(r.size());
1980 render(&pixmap, - r.topLeft());
1981 drag->setPixmap(pixmap);
1984 drag->start(Qt::MoveAction);
1990 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1992 // Only accept if it's an tab-reordering request
1993 QMimeData const * m = event->mimeData();
1994 QStringList formats = m->formats();
1995 if (formats.contains("action")
1996 && m->data("action") == "tab-reordering")
1997 event->acceptProposedAction();
2001 void DragTabBar::dropEvent(QDropEvent * event)
2003 int fromIndex = tabAt(dragStartPos_);
2004 int toIndex = tabAt(event->pos());
2006 // Tell interested objects that
2007 if (fromIndex != toIndex)
2008 tabMoveRequested(fromIndex, toIndex);
2009 event->acceptProposedAction();
2013 } // namespace frontend
2016 #include "moc_GuiWorkArea.cpp"