2 * \file GuiWorkArea.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Abdelrazak Younes
9 * Full author contact details are available in file CREDITS.
14 #include "GuiWorkArea.h"
16 #include "ColorCache.h"
17 #include "FontLoader.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
24 #include "CoordCache.h"
27 #include "FuncRequest.h"
28 #include "GuiApplication.h"
29 #include "GuiCompleter.h"
30 #include "GuiKeySymbol.h"
31 #include "GuiPainter.h"
33 #include "KeySymbol.h"
38 #include "qt_helpers.h"
40 #include "TextMetrics.h"
43 #include "graphics/GraphicsImage.h"
44 #include "graphics/GraphicsLoader.h"
46 #include "support/convert.h"
47 #include "support/debug.h"
48 #include "support/gettext.h"
49 #include "support/FileName.h"
51 #include "frontends/Application.h"
52 #include "frontends/FontMetrics.h"
53 #include "frontends/WorkAreaManager.h"
55 #include <QContextMenuEvent>
56 #include <QInputContext>
61 #include <QMainWindow>
65 #include <QPixmapCache>
68 #include <QToolButton>
72 #include "support/bind.h"
77 int const CursorWidth = 2;
79 int const CursorWidth = 1;
81 int const TabIndicatorWidth = 3;
87 using namespace lyx::support;
92 /// return the LyX mouse button state from Qt's
93 static mouse_button::state q_button_state(Qt::MouseButton button)
95 mouse_button::state b = mouse_button::none;
98 b = mouse_button::button1;
101 b = mouse_button::button2;
103 case Qt::RightButton:
104 b = mouse_button::button3;
113 /// return the LyX mouse button state from Qt's
114 mouse_button::state q_motion_state(Qt::MouseButtons state)
116 mouse_button::state b = mouse_button::none;
117 if (state & Qt::LeftButton)
118 b |= mouse_button::button1;
119 if (state & Qt::MidButton)
120 b |= mouse_button::button2;
121 if (state & Qt::RightButton)
122 b |= mouse_button::button3;
133 void draw(QPainter & painter)
135 if (!show_ || !rect_.isValid())
139 int l = x_ - rect_.left();
140 int r = rect_.right() - x_;
141 int bot = rect_.bottom();
143 // draw vertica linel
144 painter.fillRect(x_, y, CursorWidth, rect_.height(), color_);
146 // draw RTL/LTR indication
147 painter.setPen(color_);
150 painter.drawLine(x_, bot, x_ - l, bot);
152 painter.drawLine(x_, bot, x_ + CursorWidth + r, bot);
155 // draw completion triangle
157 int m = y + rect_.height() / 2;
158 int d = TabIndicatorWidth - 1;
160 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
161 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
163 painter.drawLine(x_ + CursorWidth, m - d, x_ + CursorWidth + d, m);
164 painter.drawLine(x_ + CursorWidth, m + d, x_ + CursorWidth + d, m);
169 void update(int x, int y, int h, bool l_shape,
170 bool rtl, bool completable)
172 color_ = guiApp->colorCache().get(Color_cursor);
175 completable_ = completable;
178 // extension to left and right
182 // RTL/LTR indication
190 // completion triangle
193 l = max(l, TabIndicatorWidth);
195 r = max(r, TabIndicatorWidth);
198 // compute overall rectangle
199 rect_ = QRect(x - l, y, CursorWidth + r + l, h);
202 void show(bool set_show = true) { show_ = set_show; }
203 void hide() { show_ = false; }
205 QRect const & rect() { return rect_; }
208 /// cursor is in RTL or LTR text
210 /// indication for RTL or LTR
212 /// triangle to show that a completion is available
218 /// rectangle, possibly with l_shape and completion triangle
220 /// x position (were the vertical line is drawn)
225 // This is a 'heartbeat' generating synthetic mouse move events when the
226 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
227 SyntheticMouseEvent::SyntheticMouseEvent()
228 : timeout(200), restart_timeout(true)
232 GuiWorkArea::GuiWorkArea(QWidget *)
233 : buffer_view_(0), lyx_view_(0),
234 cursor_visible_(false),
235 need_resize_(false), schedule_redraw_(false),
236 preedit_lines_(1), completer_(new GuiCompleter(this, this)),
237 context_target_pos_()
242 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
243 : buffer_view_(0), read_only_(buffer.isReadonly()), lyx_view_(0),
244 cursor_visible_(false),
245 need_resize_(false), schedule_redraw_(false),
246 preedit_lines_(1), completer_(new GuiCompleter(this, this)),
247 context_target_pos_()
255 void GuiWorkArea::init()
258 connect(&cursor_timeout_, SIGNAL(timeout()),
259 this, SLOT(toggleCursor()));
261 int const time = QApplication::cursorFlashTime() / 2;
263 cursor_timeout_.setInterval(time);
264 cursor_timeout_.start();
266 // let's initialize this just to be safe
267 cursor_timeout_.setInterval(500);
270 screen_ = QPixmap(viewport()->width(), viewport()->height());
271 // With Qt4.5 a mouse event will happen before the first paint event
272 // so make sure that the buffer view has an up to date metrics.
273 buffer_view_->resize(viewport()->width(), viewport()->height());
274 cursor_ = new frontend::CursorWidget();
277 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
278 setAcceptDrops(true);
279 setMouseTracking(true);
280 setMinimumSize(100, 70);
281 setFrameStyle(QFrame::NoFrame);
284 viewport()->setAutoFillBackground(false);
285 // We don't need double-buffering nor SystemBackground on
286 // the viewport because we have our own backing pixmap.
287 viewport()->setAttribute(Qt::WA_NoSystemBackground);
289 setFocusPolicy(Qt::StrongFocus);
291 setCursorShape(Qt::IBeamCursor);
293 synthetic_mouse_event_.timeout.timeout.connect(
294 bind(&GuiWorkArea::generateSyntheticMouseEvent,
297 // Initialize the vertical Scroll Bar
298 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
299 this, SLOT(scrollTo(int)));
301 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
302 << " viewport height: " << viewport()->height());
304 // Enables input methods for asian languages.
305 // Must be set when creating custom text editing widgets.
306 setAttribute(Qt::WA_InputMethodEnabled, true);
308 dialog_mode_ = false;
312 GuiWorkArea::~GuiWorkArea()
314 buffer_view_->buffer().workAreaManager().remove(this);
317 // Completer has a QObject parent and is thus automatically destroyed.
319 // delete completer_;
323 Qt::CursorShape GuiWorkArea::cursorShape() const
325 return viewport()->cursor().shape();
329 void GuiWorkArea::setCursorShape(Qt::CursorShape shape)
331 viewport()->setCursor(shape);
335 void GuiWorkArea::updateCursorShape()
337 setCursorShape(buffer_view_->clickableInset()
338 ? Qt::PointingHandCursor : Qt::IBeamCursor);
342 void GuiWorkArea::setGuiView(GuiView & gv)
348 void GuiWorkArea::setBuffer(Buffer & buffer)
351 buffer_view_ = new BufferView(buffer);
352 buffer.workAreaManager().add(this);
354 // HACK: Prevents an additional redraw when the scrollbar pops up
355 // which regularily happens on documents with more than one page.
356 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
357 // Since we have no geometry information yet, we assume that
358 // a document needs a scrollbar if there is more then four
359 // paragraph in the outermost text.
360 if (buffer.text().paragraphs().size() > 4)
361 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
362 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
366 void GuiWorkArea::fixVerticalScrollBar()
369 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
373 void GuiWorkArea::close()
375 lyx_view_->removeWorkArea(this);
379 void GuiWorkArea::setFullScreen(bool full_screen)
381 buffer_view_->setFullScreen(full_screen);
382 setFrameStyle(QFrame::NoFrame);
384 setFrameStyle(QFrame::NoFrame);
385 if (lyxrc.full_screen_scrollbar)
386 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
388 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
392 BufferView & GuiWorkArea::bufferView()
394 return *buffer_view_;
398 BufferView const & GuiWorkArea::bufferView() const
400 return *buffer_view_;
404 void GuiWorkArea::stopBlinkingCursor()
406 cursor_timeout_.stop();
411 void GuiWorkArea::startBlinkingCursor()
413 // do not show the cursor if the view is busy
419 buffer_view_->cursorPosAndHeight(p, h);
420 // Don't start blinking if the cursor isn't on screen.
421 if (!buffer_view_->cursorInView(p, h))
426 //we're not supposed to cache this value.
427 int const time = QApplication::cursorFlashTime() / 2;
430 cursor_timeout_.setInterval(time);
431 cursor_timeout_.start();
435 void GuiWorkArea::redraw(bool update_metrics)
438 // No need to redraw in this case.
441 // No need to do anything if this is the current view. The BufferView
442 // metrics are already up to date.
443 if (update_metrics || lyx_view_ != guiApp->currentView()
444 || lyx_view_->currentWorkArea() != this) {
445 // FIXME: it would be nice to optimize for the off-screen case.
446 buffer_view_->updateMetrics();
447 buffer_view_->cursor().fixIfBroken();
450 // update cursor position, because otherwise it has to wait until
451 // the blinking interval is over
452 if (cursor_visible_) {
457 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
459 update(0, 0, viewport()->width(), viewport()->height());
461 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
462 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
464 lyx_view_->updateStatusBar();
466 if (lyxerr.debugging(Debug::WORKAREA))
467 buffer_view_->coordCache().dump();
469 setReadOnly(buffer_view_->buffer().isReadonly());
475 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
477 if (lyx_view_->isFullScreen() && lyx_view_->menuBar()->isVisible()
478 && lyxrc.full_screen_menubar) {
479 // FIXME HACK: we should not have to do this here. See related comment
480 // in GuiView::event() (QEvent::ShortcutOverride)
481 lyx_view_->menuBar()->hide();
484 // In order to avoid bad surprise in the middle of an operation,
485 // we better stop the blinking cursor...
486 // the cursor gets restarted in GuiView::restartCursor()
487 stopBlinkingCursor();
488 guiApp->processKeySym(key, mod);
492 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
495 if (cmd0.action() == LFUN_FILE_OPEN) {
497 lyx_view_->dispatch(cmd0, dr);
503 if (cmd0.action() == LFUN_MOUSE_PRESS) {
504 if (mod == ShiftModifier)
505 cmd = FuncRequest(cmd0, "region-select");
506 else if (mod == ControlModifier)
507 cmd = FuncRequest(cmd0, "paragraph-select");
514 bool const notJustMovingTheMouse =
515 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
517 // In order to avoid bad surprise in the middle of an operation, we better stop
518 // the blinking cursor.
519 if (notJustMovingTheMouse)
520 stopBlinkingCursor();
522 buffer_view_->mouseEventDispatch(cmd);
524 // Skip these when selecting
525 if (cmd.action() != LFUN_MOUSE_MOTION) {
526 completer_->updateVisibility(false, false);
527 lyx_view_->updateDialogs();
528 lyx_view_->updateStatusBar();
531 // GUI tweaks except with mouse motion with no button pressed.
532 if (notJustMovingTheMouse) {
533 // Slight hack: this is only called currently when we
534 // clicked somewhere, so we force through the display
535 // of the new status here.
536 lyx_view_->clearMessage();
538 // Show the cursor immediately after any operation
539 startBlinkingCursor();
546 void GuiWorkArea::resizeBufferView()
548 // WARNING: Please don't put any code that will trigger a repaint here!
549 // We are already inside a paint event.
550 lyx_view_->setBusy(true);
553 buffer_view_->cursorPosAndHeight(p, h);
554 bool const cursor_in_view = buffer_view_->cursorInView(p, h);
555 buffer_view_->resize(viewport()->width(), viewport()->height());
557 buffer_view_->scrollToCursor();
560 // Update scrollbars which might have changed due different
561 // BufferView dimension. This is especially important when the
562 // BufferView goes from zero-size to the real-size for the first time,
563 // as the scrollbar paramters are then set for the first time.
566 lyx_view_->updateLayoutList();
567 lyx_view_->setBusy(false);
568 need_resize_ = false;
572 void GuiWorkArea::showCursor()
579 buffer_view_->cursorPosAndHeight(p, h);
580 if (!buffer_view_->cursorInView(p, h))
584 bool l_shape = false;
585 Font const & realfont = buffer_view_->cursor().real_current_font;
586 BufferParams const & bp = buffer_view_->buffer().params();
587 bool const samelang = realfont.language() == bp.language;
588 bool const isrtl = realfont.isVisibleRightToLeft();
590 if (!samelang || isrtl != bp.language->rightToLeft())
593 // The ERT language hack needs fixing up
594 if (realfont.language() == latex_language)
597 // show cursor on screen
598 Cursor & cur = buffer_view_->cursor();
599 bool completable = cur.inset().showCompletionCursor()
600 && completer_->completionAvailable()
601 && !completer_->popupVisible()
602 && !completer_->inlineVisible();
603 cursor_visible_ = true;
604 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
608 void GuiWorkArea::hideCursor()
610 if (!cursor_visible_)
613 cursor_visible_ = false;
618 void GuiWorkArea::toggleCursor()
627 void GuiWorkArea::updateScrollbar()
629 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
630 // WARNING: don't touch at the scrollbar value like this:
631 // verticalScrollBar()->setValue(scroll_.position);
632 // because this would cause a recursive signal/slot calling with
633 // GuiWorkArea::scrollTo
634 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
635 verticalScrollBar()->setPageStep(scroll_.page_step);
636 verticalScrollBar()->setSingleStep(scroll_.single_step);
637 verticalScrollBar()->setSliderPosition(scroll_.position);
641 void GuiWorkArea::scrollTo(int value)
643 stopBlinkingCursor();
644 buffer_view_->scrollDocView(value, true);
646 if (lyxrc.cursor_follows_scrollbar) {
647 buffer_view_->setCursorFromScrollbar();
648 lyx_view_->updateLayoutList();
650 // Show the cursor immediately after any operation.
651 startBlinkingCursor();
652 QApplication::syncX();
656 bool GuiWorkArea::event(QEvent * e)
659 case QEvent::ToolTip: {
660 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
661 if (lyxrc.use_tooltip) {
662 QPoint pos = helpEvent->pos();
663 if (pos.x() < viewport()->width()) {
664 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
665 QToolTip::showText(helpEvent->globalPos(), s);
668 QToolTip::hideText();
670 // Don't forget to accept the event!
675 case QEvent::ShortcutOverride: {
676 // We catch this event in order to catch the Tab or Shift+Tab key press
677 // which are otherwise reserved to focus switching between controls
679 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
680 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
681 || (ke->key() == Qt::Key_Backtab && (
682 ke->modifiers() == Qt::ShiftModifier
683 || ke->modifiers() == Qt::NoModifier))) {
687 return QAbstractScrollArea::event(e);
691 return QAbstractScrollArea::event(e);
697 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
700 if (e->reason() == QContextMenuEvent::Mouse)
701 // the position is set on mouse press
702 pos = context_target_pos_;
705 Cursor const & cur = buffer_view_->cursor();
706 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
707 // Do not access the context menu of math right in front of before
708 // the cursor. This does not work when the cursor is in text.
709 Inset * inset = cur.paragraph().getInset(cur.pos());
710 if (inset && inset->asInsetMath())
712 else if (cur.pos() > 0) {
713 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
718 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
720 QAbstractScrollArea::contextMenuEvent(e);
723 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
725 QAbstractScrollArea::contextMenuEvent(e);
728 // Position the menu to the right.
729 // FIXME: menu position should be different for RTL text.
730 menu->exec(e->globalPos());
735 void GuiWorkArea::focusInEvent(QFocusEvent * e)
737 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
738 if (lyx_view_->currentWorkArea() != this)
739 lyx_view_->setCurrentWorkArea(this);
741 startBlinkingCursor();
742 QAbstractScrollArea::focusInEvent(e);
746 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
748 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
749 stopBlinkingCursor();
750 QAbstractScrollArea::focusOutEvent(e);
754 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
756 if (dc_event_.active && dc_event_ == *e) {
757 dc_event_.active = false;
758 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
759 q_button_state(e->button()));
765 if (e->button() == Qt::RightButton)
766 context_target_pos_ = e->pos();
768 inputContext()->reset();
770 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
771 q_button_state(e->button()));
772 dispatch(cmd, q_key_state(e->modifiers()));
777 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
779 if (synthetic_mouse_event_.timeout.running())
780 synthetic_mouse_event_.timeout.stop();
782 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
783 q_button_state(e->button()));
789 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
791 // we kill the triple click if we move
792 doubleClickTimeout();
793 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
794 q_motion_state(e->buttons()));
798 // If we're above or below the work area...
799 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
800 && e->buttons() == mouse_button::button1) {
801 // Make sure only a synthetic event can cause a page scroll,
802 // so they come at a steady rate:
804 // _Force_ a scroll up:
805 cmd.set_y(e->y() - 21);
807 cmd.set_y(e->y() + 21);
808 // Store the event, to be handled when the timeout expires.
809 synthetic_mouse_event_.cmd = cmd;
811 if (synthetic_mouse_event_.timeout.running()) {
812 // Discard the event. Note that it _may_ be handled
813 // when the timeout expires if
814 // synthetic_mouse_event_.cmd has not been overwritten.
815 // Ie, when the timeout expires, we handle the
816 // most recent event but discard all others that
817 // occurred after the one used to start the timeout
818 // in the first place.
822 synthetic_mouse_event_.restart_timeout = true;
823 synthetic_mouse_event_.timeout.start();
824 // Fall through to handle this event...
826 } else if (synthetic_mouse_event_.timeout.running()) {
827 // Store the event, to be possibly handled when the timeout
829 // Once the timeout has expired, normal control is returned
830 // to mouseMoveEvent (restart_timeout = false).
831 // This results in a much smoother 'feel' when moving the
832 // mouse back into the work area.
833 synthetic_mouse_event_.cmd = cmd;
834 synthetic_mouse_event_.restart_timeout = false;
841 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
843 // Wheel rotation by one notch results in a delta() of 120 (see
844 // documentation of QWheelEvent)
845 double const delta = ev->delta() / 120.0;
847 switch (lyxrc.scroll_wheel_zoom) {
848 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
849 zoom = ev->modifiers() & Qt::ControlModifier;
850 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
852 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
853 zoom = ev->modifiers() & Qt::ShiftModifier;
854 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
856 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
857 zoom = ev->modifiers() & Qt::AltModifier;
858 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
860 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
864 docstring arg = convert<docstring>(int(5 * delta));
865 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
869 // Take into account the desktop wide settings.
870 int const lines = qApp->wheelScrollLines();
871 int const page_step = verticalScrollBar()->pageStep();
872 // Test if the wheel mouse is set to one screen at a time.
873 int scroll_value = lines > page_step
874 ? page_step : lines * verticalScrollBar()->singleStep();
876 // Take into account the rotation and the user preferences.
877 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
878 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
879 << " delta = " << delta << " scroll_value = " << scroll_value
880 << " page_step = " << page_step);
882 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
888 void GuiWorkArea::generateSyntheticMouseEvent()
890 int const e_y = synthetic_mouse_event_.cmd.y();
891 int const wh = buffer_view_->workHeight();
892 bool const up = e_y < 0;
893 bool const down = e_y > wh;
895 // Set things off to generate the _next_ 'pseudo' event.
897 if (synthetic_mouse_event_.restart_timeout) {
898 // This is some magic formulae to determine the speed
899 // of scrolling related to the position of the mouse.
902 int dist = up ? -e_y : e_y - wh;
903 time = max(min(200, 250000 / (dist * dist)), 1) ;
906 step = 80000 / (time * time);
910 synthetic_mouse_event_.timeout.setTimeout(time);
911 synthetic_mouse_event_.timeout.start();
914 // Can we scroll further ?
915 int const value = verticalScrollBar()->value();
916 if (value == verticalScrollBar()->maximum()
917 || value == verticalScrollBar()->minimum()) {
918 synthetic_mouse_event_.timeout.stop();
923 if (step <= 2 * wh) {
924 buffer_view_->scroll(up ? -step : step);
925 buffer_view_->updateMetrics();
927 buffer_view_->scrollDocView(value + up ? -step : step, false);
930 // In which paragraph do we have to set the cursor ?
931 Cursor & cur = buffer_view_->cursor();
932 TextMetrics const & tm = buffer_view_->textMetrics(cur.text());
934 pair<pit_type, const ParagraphMetrics *> p = up ? tm.first() : tm.last();
935 ParagraphMetrics const & pm = *p.second;
936 pit_type const pit = p.first;
938 if (pm.rows().empty())
941 // Find the row at which we set the cursor.
942 RowList::const_iterator rit = pm.rows().begin();
943 RowList::const_iterator rlast = pm.rows().end();
944 int yy = pm.position() - pm.ascent();
945 for (--rlast; rit != rlast; ++rit) {
946 int h = rit->height();
947 if ((up && yy + h > 0)
948 || (!up && yy + h > wh - defaultRowHeight()))
953 // Find the position of the cursor
955 int x = synthetic_mouse_event_.cmd.x();
956 pos_type const pos = rit->pos() + tm.getColumnNearX(pit, *rit, x, bound);
963 buffer_view_->buffer().changed(false);
968 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
970 // Do not process here some keys if dialog_mode_ is set
972 && (ev->modifiers() == Qt::NoModifier
973 || ev->modifiers() == Qt::ShiftModifier)
974 && (ev->key() == Qt::Key_Escape
975 || ev->key() == Qt::Key_Enter
976 || ev->key() == Qt::Key_Return)
982 // intercept some keys if completion popup is visible
983 if (completer_->popupVisible()) {
987 completer_->activate();
993 // do nothing if there are other events
994 // (the auto repeated events come too fast)
995 // it looks like this is only needed on X11
997 if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
998 LYXERR(Debug::KEY, "system is busy: keyPress event ignored");
1004 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1005 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
1008 setKeySymbol(&sym, ev);
1010 processKeySym(sym, q_key_state(ev->modifiers()));
1018 void GuiWorkArea::doubleClickTimeout()
1020 dc_event_.active = false;
1024 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1026 dc_event_ = DoubleClick(ev);
1027 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1028 SLOT(doubleClickTimeout()));
1029 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1031 q_button_state(ev->button()));
1037 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1039 QAbstractScrollArea::resizeEvent(ev);
1040 need_resize_ = true;
1045 void GuiWorkArea::update(int x, int y, int w, int h)
1047 viewport()->repaint(x, y, w, h);
1051 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1053 QRect const rc = ev->rect();
1054 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1055 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1058 screen_ = QPixmap(viewport()->width(), viewport()->height());
1060 if (cursor_visible_) {
1066 QPainter pain(viewport());
1067 pain.drawPixmap(rc, screen_, rc);
1068 cursor_->draw(pain);
1073 void GuiWorkArea::updateScreen()
1075 GuiPainter pain(&screen_);
1076 buffer_view_->draw(pain);
1080 void GuiWorkArea::showCursor(int x, int y, int h,
1081 bool l_shape, bool rtl, bool completable)
1083 if (schedule_redraw_) {
1084 // This happens when a graphic conversion is finished. As we don't know
1085 // the size of the new graphics, it's better the update everything.
1086 // We can't use redraw() here because this would trigger a infinite
1087 // recursive loop with showCursor().
1088 buffer_view_->resize(viewport()->width(), viewport()->height());
1091 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
1092 schedule_redraw_ = false;
1093 // Show the cursor immediately after the update.
1099 cursor_->update(x, y, h, l_shape, rtl, completable);
1101 viewport()->update(cursor_->rect());
1105 void GuiWorkArea::removeCursor()
1108 //if (!qApp->focusWidget())
1109 viewport()->update(cursor_->rect());
1113 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1115 QString const & commit_string = e->commitString();
1116 docstring const & preedit_string
1117 = qstring_to_ucs4(e->preeditString());
1119 if (!commit_string.isEmpty()) {
1121 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1122 << " commitString: " << e->commitString());
1126 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1127 for (int i = 0; i != commit_string.size(); ++i) {
1128 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1133 // Hide the cursor during the kana-kanji transformation.
1134 if (preedit_string.empty())
1135 startBlinkingCursor();
1137 stopBlinkingCursor();
1139 // last_width : for checking if last preedit string was/wasn't empty.
1140 static bool last_width = false;
1141 if (!last_width && preedit_string.empty()) {
1142 // if last_width is last length of preedit string.
1147 GuiPainter pain(&screen_);
1148 buffer_view_->updateMetrics();
1149 buffer_view_->draw(pain);
1150 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1151 FontMetrics const & fm = theFontMetrics(font);
1152 int height = fm.maxHeight();
1153 int cur_x = cursor_->rect().left();
1154 int cur_y = cursor_->rect().bottom();
1156 // redraw area of preedit string.
1157 update(0, cur_y - height, viewport()->width(),
1158 (height + 1) * preedit_lines_);
1160 if (preedit_string.empty()) {
1168 // att : stores an IM attribute.
1169 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1171 // get attributes of input method cursor.
1172 // cursor_pos : cursor position in preedit string.
1173 size_t cursor_pos = 0;
1174 bool cursor_is_visible = false;
1175 for (int i = 0; i != att.size(); ++i) {
1176 if (att.at(i).type == QInputMethodEvent::Cursor) {
1177 cursor_pos = att.at(i).start;
1178 cursor_is_visible = att.at(i).length != 0;
1183 size_t preedit_length = preedit_string.length();
1185 // get position of selection in input method.
1186 // FIXME: isn't there a way to do this simplier?
1187 // rStart : cursor position in selected string in IM.
1189 // rLength : selected string length in IM.
1191 if (cursor_pos < preedit_length) {
1192 for (int i = 0; i != att.size(); ++i) {
1193 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1194 if (att.at(i).start <= int(cursor_pos)
1195 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1196 rStart = att.at(i).start;
1197 rLength = att.at(i).length;
1198 if (!cursor_is_visible)
1199 cursor_pos += rLength;
1206 rStart = cursor_pos;
1210 int const right_margin = buffer_view_->rightMargin();
1211 Painter::preedit_style ps;
1212 // Most often there would be only one line:
1214 for (size_t pos = 0; pos != preedit_length; ++pos) {
1215 char_type const typed_char = preedit_string[pos];
1216 // reset preedit string style
1217 ps = Painter::preedit_default;
1219 // if we reached the right extremity of the screen, go to next line.
1220 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1221 cur_x = right_margin;
1222 cur_y += height + 1;
1225 // preedit strings are displayed with dashed underline
1226 // and partial strings are displayed white on black indicating
1227 // that we are in selecting mode in the input method.
1228 // FIXME: rLength == preedit_length is not a changing condition
1229 // FIXME: should be put out of the loop.
1231 && pos < rStart + rLength
1232 && !(cursor_pos < rLength && rLength == preedit_length))
1233 ps = Painter::preedit_selecting;
1235 if (pos == cursor_pos
1236 && (cursor_pos < rLength && rLength == preedit_length))
1237 ps = Painter::preedit_cursor;
1239 // draw one character and update cur_x.
1240 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1243 // update the preedit string screen area.
1244 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1245 (height + 1) * preedit_lines_);
1247 // Don't forget to accept the event!
1252 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1254 QRect cur_r(0, 0, 0, 0);
1256 // this is the CJK-specific composition window position and
1257 // the context menu position when the menu key is pressed.
1258 case Qt::ImMicroFocus:
1259 cur_r = cursor_->rect();
1260 if (preedit_lines_ != 1)
1262 cur_r.moveBottom(cur_r.bottom()
1263 + cur_r.height() * (preedit_lines_ - 1));
1264 // return lower right of cursor in LyX.
1267 return QWidget::inputMethodQuery(query);
1272 void GuiWorkArea::updateWindowTitle()
1274 docstring maximize_title;
1275 docstring minimize_title;
1277 Buffer & buf = buffer_view_->buffer();
1278 FileName const fileName = buf.fileName();
1279 if (!fileName.empty()) {
1280 maximize_title = fileName.displayName(30);
1281 minimize_title = from_utf8(fileName.onlyFileName());
1282 if (buf.lyxvc().inUse()) {
1283 if (buf.lyxvc().locking())
1284 maximize_title += _(" (version control, locking)");
1286 maximize_title += _(" (version control)");
1288 if (!buf.isClean()) {
1289 maximize_title += _(" (changed)");
1290 minimize_title += char_type('*');
1292 if (buf.isReadonly())
1293 maximize_title += _(" (read only)");
1296 QString title = windowTitle();
1297 QString new_title = toqstr(maximize_title);
1298 if (title == new_title)
1301 QWidget::setWindowTitle(new_title);
1302 QWidget::setWindowIconText(toqstr(minimize_title));
1307 void GuiWorkArea::setReadOnly(bool read_only)
1309 if (read_only_ == read_only)
1311 read_only_ = read_only;
1312 updateWindowTitle();
1313 if (this == lyx_view_->currentWorkArea())
1314 lyx_view_->updateDialogs();
1318 bool GuiWorkArea::isFullScreen()
1320 return lyx_view_ && lyx_view_->isFullScreen();
1324 ////////////////////////////////////////////////////////////////////
1328 ////////////////////////////////////////////////////////////////////
1331 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1333 buffer_ = theBufferList().newBuffer(
1334 support::FileName::tempName().absFileName() + "_embedded.internal");
1335 buffer_->setUnnamed(true);
1336 buffer_->setFullyLoaded(true);
1337 setBuffer(*buffer_);
1338 setDialogMode(true);
1342 EmbeddedWorkArea::~EmbeddedWorkArea()
1344 // No need to destroy buffer and bufferview here, because it is done
1345 // in theBufferList() destruction loop at application exit
1349 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1352 GuiWorkArea::closeEvent(ev);
1356 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1359 GuiWorkArea::hideEvent(ev);
1363 QSize EmbeddedWorkArea::sizeHint () const
1366 // GuiWorkArea sets the size to the screen's viewport
1367 // by returning a value this gets overridden
1368 // EmbeddedWorkArea is now sized to fit in the layout
1369 // of the parent, and has a minimum size set in GuiWorkArea
1370 // which is what we return here
1371 return QSize(100, 70);
1375 void EmbeddedWorkArea::disable()
1377 stopBlinkingCursor();
1378 if (view().currentWorkArea() != this)
1380 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1381 // tolerates it and shows the background logo), what happens if
1382 // an EmbeddedWorkArea is closed after closing all document WAs
1383 view().setCurrentWorkArea(view().currentMainWorkArea());
1386 ////////////////////////////////////////////////////////////////////
1390 ////////////////////////////////////////////////////////////////////
1393 class NoTabFrameMacStyle : public QMacStyle {
1396 QRect subElementRect(SubElement element, const QStyleOption * option,
1397 const QWidget * widget = 0) const
1399 QRect rect = QMacStyle::subElementRect(element, option, widget);
1400 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1402 // The Qt Mac style puts the contents into a 3 pixel wide box
1403 // which looks very ugly and not like other Mac applications.
1404 // Hence we remove this here, and moreover the 16 pixel round
1405 // frame above if the tab bar is hidden.
1406 if (element == QStyle::SE_TabWidgetTabContents) {
1407 rect.adjust(- rect.left(), 0, rect.left(), 0);
1416 NoTabFrameMacStyle noTabFrameMacStyle;
1420 TabWorkArea::TabWorkArea(QWidget * parent)
1421 : QTabWidget(parent), clicked_tab_(-1)
1424 setStyle(&noTabFrameMacStyle);
1426 #if QT_VERSION < 0x040500
1427 lyxrc.single_close_tab_button = true;
1430 QPalette pal = palette();
1431 pal.setColor(QPalette::Active, QPalette::Button,
1432 pal.color(QPalette::Active, QPalette::Window));
1433 pal.setColor(QPalette::Disabled, QPalette::Button,
1434 pal.color(QPalette::Disabled, QPalette::Window));
1435 pal.setColor(QPalette::Inactive, QPalette::Button,
1436 pal.color(QPalette::Inactive, QPalette::Window));
1438 QObject::connect(this, SIGNAL(currentChanged(int)),
1439 this, SLOT(on_currentTabChanged(int)));
1441 closeBufferButton = new QToolButton(this);
1442 closeBufferButton->setPalette(pal);
1443 // FIXME: rename the icon to closebuffer.png
1444 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1445 closeBufferButton->setText("Close File");
1446 closeBufferButton->setAutoRaise(true);
1447 closeBufferButton->setCursor(Qt::ArrowCursor);
1448 closeBufferButton->setToolTip(qt_("Close File"));
1449 closeBufferButton->setEnabled(true);
1450 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1451 this, SLOT(closeCurrentBuffer()));
1452 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1454 // setup drag'n'drop
1455 QTabBar* tb = new DragTabBar;
1456 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1457 this, SLOT(moveTab(int, int)));
1458 tb->setElideMode(Qt::ElideNone);
1461 // make us responsible for the context menu of the tabbar
1462 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1463 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1464 this, SLOT(showContextMenu(const QPoint &)));
1465 #if QT_VERSION >= 0x040500
1466 connect(tb, SIGNAL(tabCloseRequested(int)),
1467 this, SLOT(closeTab(int)));
1470 setUsesScrollButtons(true);
1474 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1476 if (event->button() != Qt::LeftButton)
1479 // return early if double click on existing tabs
1480 for (int i = 0; i < count(); ++i)
1481 if (tabBar()->tabRect(i).contains(event->pos()))
1484 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1488 void TabWorkArea::setFullScreen(bool full_screen)
1490 for (int i = 0; i != count(); ++i) {
1491 if (GuiWorkArea * wa = workArea(i))
1492 wa->setFullScreen(full_screen);
1495 if (lyxrc.full_screen_tabbar)
1496 showBar(!full_screen && count() > 1);
1500 void TabWorkArea::showBar(bool show)
1502 tabBar()->setEnabled(show);
1503 tabBar()->setVisible(show);
1504 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1505 #if QT_VERSION >= 0x040500
1506 setTabsClosable(!lyxrc.single_close_tab_button);
1511 GuiWorkArea * TabWorkArea::currentWorkArea()
1516 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1522 GuiWorkArea * TabWorkArea::workArea(int index)
1524 return dynamic_cast<GuiWorkArea *>(widget(index));
1528 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1530 // FIXME: this method doesn't work if we have more than work area
1531 // showing the same buffer.
1532 for (int i = 0; i != count(); ++i) {
1533 GuiWorkArea * wa = workArea(i);
1534 LASSERT(wa, return 0);
1535 if (&wa->bufferView().buffer() == &buffer)
1542 void TabWorkArea::closeAll()
1545 GuiWorkArea * wa = workArea(0);
1553 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1555 LASSERT(work_area, /**/);
1556 int index = indexOf(work_area);
1560 if (index == currentIndex())
1561 // Make sure the work area is up to date.
1562 on_currentTabChanged(index);
1564 // Switch to the work area.
1565 setCurrentIndex(index);
1566 work_area->setFocus();
1572 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1574 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1575 wa->setUpdatesEnabled(false);
1576 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1577 // when hiding it again below).
1578 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1579 showBar(count() > 0);
1580 addTab(wa, wa->windowTitle());
1581 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1582 this, SLOT(updateTabTexts()));
1583 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1584 setFullScreen(true);
1586 // Hide tabbar if there's only one tab.
1587 showBar(count() > 1);
1595 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1597 LASSERT(work_area, return false);
1598 int index = indexOf(work_area);
1602 work_area->setUpdatesEnabled(false);
1607 // make sure the next work area is enabled.
1608 currentWidget()->setUpdatesEnabled(true);
1609 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1610 setFullScreen(true);
1612 // Show tabbar only if there's more than one tab.
1613 showBar(count() > 1);
1615 lastWorkAreaRemoved();
1623 void TabWorkArea::on_currentTabChanged(int i)
1625 // returns e.g. on application destruction
1628 GuiWorkArea * wa = workArea(i);
1629 LASSERT(wa, return);
1630 wa->setUpdatesEnabled(true);
1634 currentWorkAreaChanged(wa);
1636 LYXERR(Debug::GUI, "currentTabChanged " << i
1637 << " File: " << wa->bufferView().buffer().absFileName());
1641 void TabWorkArea::closeCurrentBuffer()
1644 if (clicked_tab_ == -1)
1645 wa = currentWorkArea();
1647 wa = workArea(clicked_tab_);
1650 wa->view().closeWorkArea(wa);
1654 void TabWorkArea::hideCurrentTab()
1657 if (clicked_tab_ == -1)
1658 wa = currentWorkArea();
1660 wa = workArea(clicked_tab_);
1663 wa->view().hideWorkArea(wa);
1667 void TabWorkArea::closeTab(int index)
1669 on_currentTabChanged(index);
1672 wa = currentWorkArea();
1674 wa = workArea(index);
1677 wa->view().closeWorkArea(wa);
1684 /// make vector happy
1687 DisplayPath(int tab, FileName const & filename)
1690 filename_ = (filename.extension() == "lyx") ?
1691 toqstr(filename.onlyFileNameWithoutExt())
1692 : toqstr(filename.onlyFileName());
1693 postfix_ = toqstr(filename.absoluteFilePath()).
1694 split("/", QString::SkipEmptyParts);
1695 postfix_.pop_back();
1696 abs_ = toqstr(filename.absoluteFilePath());
1697 dottedPrefix_ = false;
1700 /// Absolute path for debugging.
1705 /// Add the first segment from the postfix or three dots to the prefix.
1706 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1707 /// when really needed.
1708 void shiftPathSegment(bool dotted)
1710 if (postfix_.count() <= 0)
1714 if (dottedPrefix_ && !prefix_.isEmpty())
1716 prefix_ += postfix_.front() + "/";
1718 dottedPrefix_ = dotted && !prefix_.isEmpty();
1719 postfix_.pop_front();
1722 QString displayString() const
1724 if (prefix_.isEmpty())
1727 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1728 return prefix_ + (dots ? ".../" : "") + filename_;
1731 QString forecastPathString() const
1733 if (postfix_.count() == 0)
1734 return displayString();
1737 + (dottedPrefix_ ? ".../" : "")
1738 + postfix_.front() + "/";
1741 bool final() const { return postfix_.empty(); }
1743 int tab() const { return tab_; }
1749 QStringList postfix_;
1762 bool operator<(DisplayPath const & a, DisplayPath const & b)
1764 return a.displayString() < b.displayString();
1768 bool operator==(DisplayPath const & a, DisplayPath const & b)
1770 return a.displayString() == b.displayString();
1774 void TabWorkArea::updateTabTexts()
1779 std::list<DisplayPath> paths;
1780 typedef std::list<DisplayPath>::iterator It;
1782 // collect full names first: path into postfix, empty prefix and
1783 // filename without extension
1784 for (size_t i = 0; i < n; ++i) {
1785 GuiWorkArea * i_wa = workArea(i);
1786 FileName const fn = i_wa->bufferView().buffer().fileName();
1787 paths.push_back(DisplayPath(i, fn));
1790 // go through path segments and see if it helps to make the path more unique
1791 bool somethingChanged = true;
1792 bool allFinal = false;
1793 while (somethingChanged && !allFinal) {
1794 // adding path segments changes order
1797 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1798 somethingChanged = false;
1801 // find segments which are not unique (i.e. non-atomic)
1802 It it = paths.begin();
1804 QString segString = it->displayString();
1805 for (; it != paths.end(); ++it) {
1806 // look to the next item
1811 allFinal = allFinal && it->final();
1813 LYXERR(Debug::GUI, "it = " << it->abs()
1814 << " => " << it->displayString());
1816 // still the same segment?
1818 if ((next != paths.end()
1819 && (nextString = next->displayString()) == segString))
1821 LYXERR(Debug::GUI, "segment ended");
1823 // only a trivial one with one element?
1824 if (it == segStart) {
1825 // start new segment
1827 segString = nextString;
1831 // we found a non-atomic segment segStart <= sit <= it < next.
1832 // Shift path segments and hope for the best
1833 // that it makes the path more unique.
1834 somethingChanged = true;
1836 QString dspString = sit->forecastPathString();
1837 LYXERR(Debug::GUI, "first forecast found for "
1838 << sit->abs() << " => " << dspString);
1840 bool moreUnique = false;
1841 for (; sit != next; ++sit) {
1842 if (sit->forecastPathString() != dspString) {
1843 LYXERR(Debug::GUI, "different forecast found for "
1844 << sit->abs() << " => " << sit->forecastPathString());
1848 LYXERR(Debug::GUI, "same forecast found for "
1849 << sit->abs() << " => " << dspString);
1852 // if the path segment helped, add it. Otherwise add dots
1853 bool dots = !moreUnique;
1854 LYXERR(Debug::GUI, "using dots = " << dots);
1855 for (sit = segStart; sit != next; ++sit) {
1856 sit->shiftPathSegment(dots);
1857 LYXERR(Debug::GUI, "shifting "
1858 << sit->abs() << " => " << sit->displayString());
1861 // start new segment
1863 segString = nextString;
1867 // set new tab titles
1868 for (It it = paths.begin(); it != paths.end(); ++it) {
1869 GuiWorkArea * i_wa = workArea(it->tab());
1870 Buffer & buf = i_wa->bufferView().buffer();
1871 if (!buf.fileName().empty() && !buf.isClean())
1872 setTabText(it->tab(), it->displayString() + "*");
1874 setTabText(it->tab(), it->displayString());
1879 void TabWorkArea::showContextMenu(const QPoint & pos)
1882 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1883 if (clicked_tab_ == -1)
1888 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
1889 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
1890 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
1891 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1892 popup.exec(tabBar()->mapToGlobal(pos));
1898 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1900 QWidget * w = widget(fromIndex);
1901 QIcon icon = tabIcon(fromIndex);
1902 QString text = tabText(fromIndex);
1904 setCurrentIndex(fromIndex);
1905 removeTab(fromIndex);
1906 insertTab(toIndex, w, icon, text);
1907 setCurrentIndex(toIndex);
1911 DragTabBar::DragTabBar(QWidget* parent)
1914 setAcceptDrops(true);
1915 #if QT_VERSION >= 0x040500
1916 setTabsClosable(!lyxrc.single_close_tab_button);
1921 #if QT_VERSION < 0x040300
1922 int DragTabBar::tabAt(QPoint const & position) const
1924 const int max = count();
1925 for (int i = 0; i < max; ++i) {
1926 if (tabRect(i).contains(position))
1934 void DragTabBar::mousePressEvent(QMouseEvent * event)
1936 if (event->button() == Qt::LeftButton)
1937 dragStartPos_ = event->pos();
1938 QTabBar::mousePressEvent(event);
1942 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1944 // If the left button isn't pressed anymore then return
1945 if (!(event->buttons() & Qt::LeftButton))
1948 // If the distance is too small then return
1949 if ((event->pos() - dragStartPos_).manhattanLength()
1950 < QApplication::startDragDistance())
1953 // did we hit something after all?
1954 int tab = tabAt(dragStartPos_);
1958 // simulate button release to remove highlight from button
1959 int i = currentIndex();
1960 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1961 event->button(), event->buttons(), 0);
1962 QTabBar::mouseReleaseEvent(&me);
1966 QDrag * drag = new QDrag(this);
1967 QMimeData * mimeData = new QMimeData;
1968 // a crude way to distinguish tab-reodering drops from other ones
1969 mimeData->setData("action", "tab-reordering") ;
1970 drag->setMimeData(mimeData);
1972 #if QT_VERSION >= 0x040300
1973 // get tab pixmap as cursor
1974 QRect r = tabRect(tab);
1975 QPixmap pixmap(r.size());
1976 render(&pixmap, - r.topLeft());
1977 drag->setPixmap(pixmap);
1980 drag->start(Qt::MoveAction);
1986 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1988 // Only accept if it's an tab-reordering request
1989 QMimeData const * m = event->mimeData();
1990 QStringList formats = m->formats();
1991 if (formats.contains("action")
1992 && m->data("action") == "tab-reordering")
1993 event->acceptProposedAction();
1997 void DragTabBar::dropEvent(QDropEvent * event)
1999 int fromIndex = tabAt(dragStartPos_);
2000 int toIndex = tabAt(event->pos());
2002 // Tell interested objects that
2003 if (fromIndex != toIndex)
2004 tabMoveRequested(fromIndex, toIndex);
2005 event->acceptProposedAction();
2009 } // namespace frontend
2012 #include "moc_GuiWorkArea.cpp"