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 // always show mnemonics when the keyboard is used to show the context menu
725 // FIXME: This should be fixed in Qt itself
726 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
727 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_, keyboard);
729 QAbstractScrollArea::contextMenuEvent(e);
732 // Position the menu to the right.
733 // FIXME: menu position should be different for RTL text.
734 menu->exec(e->globalPos());
739 void GuiWorkArea::focusInEvent(QFocusEvent * e)
741 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
742 if (lyx_view_->currentWorkArea() != this)
743 lyx_view_->setCurrentWorkArea(this);
745 startBlinkingCursor();
746 QAbstractScrollArea::focusInEvent(e);
750 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
752 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
753 stopBlinkingCursor();
754 QAbstractScrollArea::focusOutEvent(e);
758 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
760 if (dc_event_.active && dc_event_ == *e) {
761 dc_event_.active = false;
762 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
763 q_button_state(e->button()));
769 // Save the context menu on mouse press, because also the mouse
770 // cursor is set on mouse press. Afterwards, we can either release
771 // the mousebutton somewhere else, or the cursor might have moved
773 if (e->button() == Qt::RightButton)
774 context_menu_name_ = buffer_view_->contextMenu(e->x(), e->y());
776 inputContext()->reset();
778 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
779 q_button_state(e->button()));
780 dispatch(cmd, q_key_state(e->modifiers()));
785 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
787 if (synthetic_mouse_event_.timeout.running())
788 synthetic_mouse_event_.timeout.stop();
790 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
791 q_button_state(e->button()));
797 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
799 // we kill the triple click if we move
800 doubleClickTimeout();
801 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
802 q_motion_state(e->buttons()));
806 // If we're above or below the work area...
807 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
808 && e->buttons() == mouse_button::button1) {
809 // Make sure only a synthetic event can cause a page scroll,
810 // so they come at a steady rate:
812 // _Force_ a scroll up:
813 cmd.set_y(e->y() - 21);
815 cmd.set_y(e->y() + 21);
816 // Store the event, to be handled when the timeout expires.
817 synthetic_mouse_event_.cmd = cmd;
819 if (synthetic_mouse_event_.timeout.running()) {
820 // Discard the event. Note that it _may_ be handled
821 // when the timeout expires if
822 // synthetic_mouse_event_.cmd has not been overwritten.
823 // Ie, when the timeout expires, we handle the
824 // most recent event but discard all others that
825 // occurred after the one used to start the timeout
826 // in the first place.
830 synthetic_mouse_event_.restart_timeout = true;
831 synthetic_mouse_event_.timeout.start();
832 // Fall through to handle this event...
834 } else if (synthetic_mouse_event_.timeout.running()) {
835 // Store the event, to be possibly handled when the timeout
837 // Once the timeout has expired, normal control is returned
838 // to mouseMoveEvent (restart_timeout = false).
839 // This results in a much smoother 'feel' when moving the
840 // mouse back into the work area.
841 synthetic_mouse_event_.cmd = cmd;
842 synthetic_mouse_event_.restart_timeout = false;
849 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
851 // Wheel rotation by one notch results in a delta() of 120 (see
852 // documentation of QWheelEvent)
853 double const delta = ev->delta() / 120.0;
855 switch (lyxrc.scroll_wheel_zoom) {
856 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
857 zoom = ev->modifiers() & Qt::ControlModifier;
858 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
860 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
861 zoom = ev->modifiers() & Qt::ShiftModifier;
862 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
864 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
865 zoom = ev->modifiers() & Qt::AltModifier;
866 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
868 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
872 docstring arg = convert<docstring>(int(5 * delta));
873 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
877 // Take into account the desktop wide settings.
878 int const lines = qApp->wheelScrollLines();
879 int const page_step = verticalScrollBar()->pageStep();
880 // Test if the wheel mouse is set to one screen at a time.
881 int scroll_value = lines > page_step
882 ? page_step : lines * verticalScrollBar()->singleStep();
884 // Take into account the rotation and the user preferences.
885 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
886 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
887 << " delta = " << delta << " scroll_value = " << scroll_value
888 << " page_step = " << page_step);
890 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
896 void GuiWorkArea::generateSyntheticMouseEvent()
898 int const e_y = synthetic_mouse_event_.cmd.y();
899 int const wh = buffer_view_->workHeight();
900 bool const up = e_y < 0;
901 bool const down = e_y > wh;
903 // Set things off to generate the _next_ 'pseudo' event.
905 if (synthetic_mouse_event_.restart_timeout) {
906 // This is some magic formulae to determine the speed
907 // of scrolling related to the position of the mouse.
910 int dist = up ? -e_y : e_y - wh;
911 time = max(min(200, 250000 / (dist * dist)), 1) ;
914 step = 80000 / (time * time);
918 synthetic_mouse_event_.timeout.setTimeout(time);
919 synthetic_mouse_event_.timeout.start();
922 // Can we scroll further ?
923 int const value = verticalScrollBar()->value();
924 if (value == verticalScrollBar()->maximum()
925 || value == verticalScrollBar()->minimum()) {
926 synthetic_mouse_event_.timeout.stop();
931 if (step <= 2 * wh) {
932 buffer_view_->scroll(up ? -step : step);
933 buffer_view_->updateMetrics();
935 buffer_view_->scrollDocView(value + up ? -step : step, false);
938 // In which paragraph do we have to set the cursor ?
939 Cursor & cur = buffer_view_->cursor();
940 TextMetrics const & tm = buffer_view_->textMetrics(cur.text());
942 pair<pit_type, const ParagraphMetrics *> p = up ? tm.first() : tm.last();
943 ParagraphMetrics const & pm = *p.second;
944 pit_type const pit = p.first;
946 if (pm.rows().empty())
949 // Find the row at which we set the cursor.
950 RowList::const_iterator rit = pm.rows().begin();
951 RowList::const_iterator rlast = pm.rows().end();
952 int yy = pm.position() - pm.ascent();
953 for (--rlast; rit != rlast; ++rit) {
954 int h = rit->height();
955 if ((up && yy + h > 0)
956 || (!up && yy + h > wh - defaultRowHeight()))
961 // Find the position of the cursor
963 int x = synthetic_mouse_event_.cmd.x();
964 pos_type const pos = rit->pos() + tm.getColumnNearX(pit, *rit, x, bound);
971 buffer_view_->buffer().changed(false);
976 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
978 // Do not process here some keys if dialog_mode_ is set
980 && (ev->modifiers() == Qt::NoModifier
981 || ev->modifiers() == Qt::ShiftModifier)
982 && (ev->key() == Qt::Key_Escape
983 || ev->key() == Qt::Key_Enter
984 || ev->key() == Qt::Key_Return)
990 // intercept some keys if completion popup is visible
991 if (completer_->popupVisible()) {
995 completer_->activate();
1001 // do nothing if there are other events
1002 // (the auto repeated events come too fast)
1003 // it looks like this is only needed on X11
1005 if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1006 LYXERR(Debug::KEY, "system is busy: keyPress event ignored");
1012 KeyModifier m = q_key_state(ev->modifiers());
1015 if (m & ShiftModifier)
1017 if (m & ControlModifier)
1019 if (m & AltModifier)
1021 if (m & MetaModifier)
1024 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1025 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1026 << " keyState: " << str);
1029 setKeySymbol(&sym, ev);
1031 processKeySym(sym, q_key_state(ev->modifiers()));
1039 void GuiWorkArea::doubleClickTimeout()
1041 dc_event_.active = false;
1045 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1047 dc_event_ = DoubleClick(ev);
1048 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1049 SLOT(doubleClickTimeout()));
1050 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1052 q_button_state(ev->button()));
1058 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1060 QAbstractScrollArea::resizeEvent(ev);
1061 need_resize_ = true;
1066 void GuiWorkArea::update(int x, int y, int w, int h)
1068 viewport()->repaint(x, y, w, h);
1072 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1074 QRect const rc = ev->rect();
1075 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1076 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1079 screen_ = QPixmap(viewport()->width(), viewport()->height());
1081 if (cursor_visible_) {
1087 QPainter pain(viewport());
1088 pain.drawPixmap(rc, screen_, rc);
1089 cursor_->draw(pain);
1094 void GuiWorkArea::updateScreen()
1096 GuiPainter pain(&screen_);
1097 buffer_view_->draw(pain);
1101 void GuiWorkArea::showCursor(int x, int y, int h,
1102 bool l_shape, bool rtl, bool completable)
1104 if (schedule_redraw_) {
1105 // This happens when a graphic conversion is finished. As we don't know
1106 // the size of the new graphics, it's better the update everything.
1107 // We can't use redraw() here because this would trigger a infinite
1108 // recursive loop with showCursor().
1109 buffer_view_->resize(viewport()->width(), viewport()->height());
1112 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
1113 schedule_redraw_ = false;
1114 // Show the cursor immediately after the update.
1120 cursor_->update(x, y, h, l_shape, rtl, completable);
1122 viewport()->update(cursor_->rect());
1126 void GuiWorkArea::removeCursor()
1129 //if (!qApp->focusWidget())
1130 viewport()->update(cursor_->rect());
1134 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1136 QString const & commit_string = e->commitString();
1137 docstring const & preedit_string
1138 = qstring_to_ucs4(e->preeditString());
1140 if (!commit_string.isEmpty()) {
1142 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1143 << " commitString: " << e->commitString());
1147 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1148 for (int i = 0; i != commit_string.size(); ++i) {
1149 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1154 // Hide the cursor during the kana-kanji transformation.
1155 if (preedit_string.empty())
1156 startBlinkingCursor();
1158 stopBlinkingCursor();
1160 // last_width : for checking if last preedit string was/wasn't empty.
1161 static bool last_width = false;
1162 if (!last_width && preedit_string.empty()) {
1163 // if last_width is last length of preedit string.
1168 GuiPainter pain(&screen_);
1169 buffer_view_->updateMetrics();
1170 buffer_view_->draw(pain);
1171 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1172 FontMetrics const & fm = theFontMetrics(font);
1173 int height = fm.maxHeight();
1174 int cur_x = cursor_->rect().left();
1175 int cur_y = cursor_->rect().bottom();
1177 // redraw area of preedit string.
1178 update(0, cur_y - height, viewport()->width(),
1179 (height + 1) * preedit_lines_);
1181 if (preedit_string.empty()) {
1189 // att : stores an IM attribute.
1190 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1192 // get attributes of input method cursor.
1193 // cursor_pos : cursor position in preedit string.
1194 size_t cursor_pos = 0;
1195 bool cursor_is_visible = false;
1196 for (int i = 0; i != att.size(); ++i) {
1197 if (att.at(i).type == QInputMethodEvent::Cursor) {
1198 cursor_pos = att.at(i).start;
1199 cursor_is_visible = att.at(i).length != 0;
1204 size_t preedit_length = preedit_string.length();
1206 // get position of selection in input method.
1207 // FIXME: isn't there a way to do this simplier?
1208 // rStart : cursor position in selected string in IM.
1210 // rLength : selected string length in IM.
1212 if (cursor_pos < preedit_length) {
1213 for (int i = 0; i != att.size(); ++i) {
1214 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1215 if (att.at(i).start <= int(cursor_pos)
1216 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1217 rStart = att.at(i).start;
1218 rLength = att.at(i).length;
1219 if (!cursor_is_visible)
1220 cursor_pos += rLength;
1227 rStart = cursor_pos;
1231 int const right_margin = buffer_view_->rightMargin();
1232 Painter::preedit_style ps;
1233 // Most often there would be only one line:
1235 for (size_t pos = 0; pos != preedit_length; ++pos) {
1236 char_type const typed_char = preedit_string[pos];
1237 // reset preedit string style
1238 ps = Painter::preedit_default;
1240 // if we reached the right extremity of the screen, go to next line.
1241 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1242 cur_x = right_margin;
1243 cur_y += height + 1;
1246 // preedit strings are displayed with dashed underline
1247 // and partial strings are displayed white on black indicating
1248 // that we are in selecting mode in the input method.
1249 // FIXME: rLength == preedit_length is not a changing condition
1250 // FIXME: should be put out of the loop.
1252 && pos < rStart + rLength
1253 && !(cursor_pos < rLength && rLength == preedit_length))
1254 ps = Painter::preedit_selecting;
1256 if (pos == cursor_pos
1257 && (cursor_pos < rLength && rLength == preedit_length))
1258 ps = Painter::preedit_cursor;
1260 // draw one character and update cur_x.
1261 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1264 // update the preedit string screen area.
1265 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1266 (height + 1) * preedit_lines_);
1268 // Don't forget to accept the event!
1273 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1275 QRect cur_r(0, 0, 0, 0);
1277 // this is the CJK-specific composition window position and
1278 // the context menu position when the menu key is pressed.
1279 case Qt::ImMicroFocus:
1280 cur_r = cursor_->rect();
1281 if (preedit_lines_ != 1)
1283 cur_r.moveBottom(cur_r.bottom()
1284 + cur_r.height() * (preedit_lines_ - 1));
1285 // return lower right of cursor in LyX.
1288 return QWidget::inputMethodQuery(query);
1293 void GuiWorkArea::updateWindowTitle()
1295 docstring maximize_title;
1296 docstring minimize_title;
1298 Buffer const & buf = buffer_view_->buffer();
1299 FileName const file_name = buf.fileName();
1300 if (!file_name.empty()) {
1301 maximize_title = file_name.displayName(130);
1302 minimize_title = from_utf8(file_name.onlyFileName());
1303 if (buf.lyxvc().inUse()) {
1304 if (buf.lyxvc().locking())
1305 maximize_title += _(" (version control, locking)");
1307 maximize_title += _(" (version control)");
1309 if (!buf.isClean()) {
1310 maximize_title += _(" (changed)");
1311 minimize_title += char_type('*');
1313 if (buf.isReadonly())
1314 maximize_title += _(" (read only)");
1317 QString const new_title = toqstr(maximize_title);
1318 if (new_title != windowTitle()) {
1319 QWidget::setWindowTitle(new_title);
1320 QWidget::setWindowIconText(toqstr(minimize_title));
1326 void GuiWorkArea::setReadOnly(bool read_only)
1328 if (read_only_ == read_only)
1330 read_only_ = read_only;
1331 updateWindowTitle();
1332 if (this == lyx_view_->currentWorkArea())
1333 lyx_view_->updateDialogs();
1337 bool GuiWorkArea::isFullScreen()
1339 return lyx_view_ && lyx_view_->isFullScreen();
1343 ////////////////////////////////////////////////////////////////////
1347 ////////////////////////////////////////////////////////////////////
1350 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1352 buffer_ = theBufferList().newBuffer(
1353 support::FileName::tempName().absFileName() + "_embedded.internal");
1354 buffer_->setUnnamed(true);
1355 buffer_->setFullyLoaded(true);
1356 setBuffer(*buffer_);
1357 setDialogMode(true);
1361 EmbeddedWorkArea::~EmbeddedWorkArea()
1363 // No need to destroy buffer and bufferview here, because it is done
1364 // in theBufferList() destruction loop at application exit
1368 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1371 GuiWorkArea::closeEvent(ev);
1375 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1378 GuiWorkArea::hideEvent(ev);
1382 QSize EmbeddedWorkArea::sizeHint () const
1385 // GuiWorkArea sets the size to the screen's viewport
1386 // by returning a value this gets overridden
1387 // EmbeddedWorkArea is now sized to fit in the layout
1388 // of the parent, and has a minimum size set in GuiWorkArea
1389 // which is what we return here
1390 return QSize(100, 70);
1394 void EmbeddedWorkArea::disable()
1396 stopBlinkingCursor();
1397 if (view().currentWorkArea() != this)
1399 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1400 // tolerates it and shows the background logo), what happens if
1401 // an EmbeddedWorkArea is closed after closing all document WAs
1402 view().setCurrentWorkArea(view().currentMainWorkArea());
1405 ////////////////////////////////////////////////////////////////////
1409 ////////////////////////////////////////////////////////////////////
1412 class NoTabFrameMacStyle : public QMacStyle {
1415 QRect subElementRect(SubElement element, const QStyleOption * option,
1416 const QWidget * widget = 0) const
1418 QRect rect = QMacStyle::subElementRect(element, option, widget);
1419 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1421 // The Qt Mac style puts the contents into a 3 pixel wide box
1422 // which looks very ugly and not like other Mac applications.
1423 // Hence we remove this here, and moreover the 16 pixel round
1424 // frame above if the tab bar is hidden.
1425 if (element == QStyle::SE_TabWidgetTabContents) {
1426 rect.adjust(- rect.left(), 0, rect.left(), 0);
1435 NoTabFrameMacStyle noTabFrameMacStyle;
1439 TabWorkArea::TabWorkArea(QWidget * parent)
1440 : QTabWidget(parent), clicked_tab_(-1)
1443 setStyle(&noTabFrameMacStyle);
1445 #if QT_VERSION < 0x040500
1446 lyxrc.single_close_tab_button = true;
1449 QPalette pal = palette();
1450 pal.setColor(QPalette::Active, QPalette::Button,
1451 pal.color(QPalette::Active, QPalette::Window));
1452 pal.setColor(QPalette::Disabled, QPalette::Button,
1453 pal.color(QPalette::Disabled, QPalette::Window));
1454 pal.setColor(QPalette::Inactive, QPalette::Button,
1455 pal.color(QPalette::Inactive, QPalette::Window));
1457 QObject::connect(this, SIGNAL(currentChanged(int)),
1458 this, SLOT(on_currentTabChanged(int)));
1460 closeBufferButton = new QToolButton(this);
1461 closeBufferButton->setPalette(pal);
1462 // FIXME: rename the icon to closebuffer.png
1463 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1464 closeBufferButton->setText("Close File");
1465 closeBufferButton->setAutoRaise(true);
1466 closeBufferButton->setCursor(Qt::ArrowCursor);
1467 closeBufferButton->setToolTip(qt_("Close File"));
1468 closeBufferButton->setEnabled(true);
1469 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1470 this, SLOT(closeCurrentBuffer()));
1471 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1473 // setup drag'n'drop
1474 QTabBar* tb = new DragTabBar;
1475 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1476 this, SLOT(moveTab(int, int)));
1477 tb->setElideMode(Qt::ElideNone);
1480 // make us responsible for the context menu of the tabbar
1481 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1482 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1483 this, SLOT(showContextMenu(const QPoint &)));
1484 #if QT_VERSION >= 0x040500
1485 connect(tb, SIGNAL(tabCloseRequested(int)),
1486 this, SLOT(closeTab(int)));
1489 setUsesScrollButtons(true);
1493 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1495 if (event->button() != Qt::LeftButton)
1498 // return early if double click on existing tabs
1499 for (int i = 0; i < count(); ++i)
1500 if (tabBar()->tabRect(i).contains(event->pos()))
1503 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1507 void TabWorkArea::setFullScreen(bool full_screen)
1509 for (int i = 0; i != count(); ++i) {
1510 if (GuiWorkArea * wa = workArea(i))
1511 wa->setFullScreen(full_screen);
1514 if (lyxrc.full_screen_tabbar)
1515 showBar(!full_screen && count() > 1);
1519 void TabWorkArea::showBar(bool show)
1521 tabBar()->setEnabled(show);
1522 tabBar()->setVisible(show);
1523 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1524 #if QT_VERSION >= 0x040500
1525 setTabsClosable(!lyxrc.single_close_tab_button);
1530 GuiWorkArea * TabWorkArea::currentWorkArea()
1535 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1541 GuiWorkArea * TabWorkArea::workArea(int index)
1543 return dynamic_cast<GuiWorkArea *>(widget(index));
1547 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1549 // FIXME: this method doesn't work if we have more than work area
1550 // showing the same buffer.
1551 for (int i = 0; i != count(); ++i) {
1552 GuiWorkArea * wa = workArea(i);
1553 LASSERT(wa, return 0);
1554 if (&wa->bufferView().buffer() == &buffer)
1561 void TabWorkArea::closeAll()
1564 GuiWorkArea * wa = workArea(0);
1572 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1574 LASSERT(work_area, /**/);
1575 int index = indexOf(work_area);
1579 if (index == currentIndex())
1580 // Make sure the work area is up to date.
1581 on_currentTabChanged(index);
1583 // Switch to the work area.
1584 setCurrentIndex(index);
1585 work_area->setFocus();
1591 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1593 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1594 wa->setUpdatesEnabled(false);
1595 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1596 // when hiding it again below).
1597 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1598 showBar(count() > 0);
1599 addTab(wa, wa->windowTitle());
1600 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1601 this, SLOT(updateTabTexts()));
1602 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1603 setFullScreen(true);
1605 // Hide tabbar if there's only one tab.
1606 showBar(count() > 1);
1614 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1616 LASSERT(work_area, return false);
1617 int index = indexOf(work_area);
1621 work_area->setUpdatesEnabled(false);
1626 // make sure the next work area is enabled.
1627 currentWidget()->setUpdatesEnabled(true);
1628 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1629 setFullScreen(true);
1631 // Show tabbar only if there's more than one tab.
1632 showBar(count() > 1);
1634 lastWorkAreaRemoved();
1642 void TabWorkArea::on_currentTabChanged(int i)
1644 // returns e.g. on application destruction
1647 GuiWorkArea * wa = workArea(i);
1648 LASSERT(wa, return);
1649 wa->setUpdatesEnabled(true);
1653 currentWorkAreaChanged(wa);
1655 LYXERR(Debug::GUI, "currentTabChanged " << i
1656 << " File: " << wa->bufferView().buffer().absFileName());
1660 void TabWorkArea::closeCurrentBuffer()
1663 if (clicked_tab_ == -1)
1664 wa = currentWorkArea();
1666 wa = workArea(clicked_tab_);
1669 wa->view().closeWorkArea(wa);
1673 void TabWorkArea::hideCurrentTab()
1676 if (clicked_tab_ == -1)
1677 wa = currentWorkArea();
1679 wa = workArea(clicked_tab_);
1682 wa->view().hideWorkArea(wa);
1686 void TabWorkArea::closeTab(int index)
1688 on_currentTabChanged(index);
1691 wa = currentWorkArea();
1693 wa = workArea(index);
1696 wa->view().closeWorkArea(wa);
1703 /// make vector happy
1706 DisplayPath(int tab, FileName const & filename)
1709 filename_ = (filename.extension() == "lyx") ?
1710 toqstr(filename.onlyFileNameWithoutExt())
1711 : toqstr(filename.onlyFileName());
1712 postfix_ = toqstr(filename.absoluteFilePath()).
1713 split("/", QString::SkipEmptyParts);
1714 postfix_.pop_back();
1715 abs_ = toqstr(filename.absoluteFilePath());
1716 dottedPrefix_ = false;
1719 /// Absolute path for debugging.
1724 /// Add the first segment from the postfix or three dots to the prefix.
1725 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1726 /// when really needed.
1727 void shiftPathSegment(bool dotted)
1729 if (postfix_.count() <= 0)
1733 if (dottedPrefix_ && !prefix_.isEmpty())
1735 prefix_ += postfix_.front() + "/";
1737 dottedPrefix_ = dotted && !prefix_.isEmpty();
1738 postfix_.pop_front();
1741 QString displayString() const
1743 if (prefix_.isEmpty())
1746 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1747 return prefix_ + (dots ? ".../" : "") + filename_;
1750 QString forecastPathString() const
1752 if (postfix_.count() == 0)
1753 return displayString();
1756 + (dottedPrefix_ ? ".../" : "")
1757 + postfix_.front() + "/";
1760 bool final() const { return postfix_.empty(); }
1762 int tab() const { return tab_; }
1768 QStringList postfix_;
1781 bool operator<(DisplayPath const & a, DisplayPath const & b)
1783 return a.displayString() < b.displayString();
1787 bool operator==(DisplayPath const & a, DisplayPath const & b)
1789 return a.displayString() == b.displayString();
1793 void TabWorkArea::updateTabTexts()
1798 std::list<DisplayPath> paths;
1799 typedef std::list<DisplayPath>::iterator It;
1801 // collect full names first: path into postfix, empty prefix and
1802 // filename without extension
1803 for (size_t i = 0; i < n; ++i) {
1804 GuiWorkArea * i_wa = workArea(i);
1805 FileName const fn = i_wa->bufferView().buffer().fileName();
1806 paths.push_back(DisplayPath(i, fn));
1809 // go through path segments and see if it helps to make the path more unique
1810 bool somethingChanged = true;
1811 bool allFinal = false;
1812 while (somethingChanged && !allFinal) {
1813 // adding path segments changes order
1816 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1817 somethingChanged = false;
1820 // find segments which are not unique (i.e. non-atomic)
1821 It it = paths.begin();
1823 QString segString = it->displayString();
1824 for (; it != paths.end(); ++it) {
1825 // look to the next item
1830 allFinal = allFinal && it->final();
1832 LYXERR(Debug::GUI, "it = " << it->abs()
1833 << " => " << it->displayString());
1835 // still the same segment?
1837 if ((next != paths.end()
1838 && (nextString = next->displayString()) == segString))
1840 LYXERR(Debug::GUI, "segment ended");
1842 // only a trivial one with one element?
1843 if (it == segStart) {
1844 // start new segment
1846 segString = nextString;
1850 // we found a non-atomic segment segStart <= sit <= it < next.
1851 // Shift path segments and hope for the best
1852 // that it makes the path more unique.
1853 somethingChanged = true;
1855 QString dspString = sit->forecastPathString();
1856 LYXERR(Debug::GUI, "first forecast found for "
1857 << sit->abs() << " => " << dspString);
1859 bool moreUnique = false;
1860 for (; sit != next; ++sit) {
1861 if (sit->forecastPathString() != dspString) {
1862 LYXERR(Debug::GUI, "different forecast found for "
1863 << sit->abs() << " => " << sit->forecastPathString());
1867 LYXERR(Debug::GUI, "same forecast found for "
1868 << sit->abs() << " => " << dspString);
1871 // if the path segment helped, add it. Otherwise add dots
1872 bool dots = !moreUnique;
1873 LYXERR(Debug::GUI, "using dots = " << dots);
1874 for (sit = segStart; sit != next; ++sit) {
1875 sit->shiftPathSegment(dots);
1876 LYXERR(Debug::GUI, "shifting "
1877 << sit->abs() << " => " << sit->displayString());
1880 // start new segment
1882 segString = nextString;
1886 // set new tab titles
1887 for (It it = paths.begin(); it != paths.end(); ++it) {
1888 int const tab_index = it->tab();
1889 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
1890 QString tab_text = it->displayString();
1891 if (!buf.fileName().empty() && !buf.isClean())
1893 setTabText(tab_index, tab_text);
1894 setTabToolTip(tab_index, it->abs());
1899 void TabWorkArea::showContextMenu(const QPoint & pos)
1902 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1903 if (clicked_tab_ == -1)
1908 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
1909 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
1910 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
1911 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1912 popup.exec(tabBar()->mapToGlobal(pos));
1918 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1920 QWidget * w = widget(fromIndex);
1921 QIcon icon = tabIcon(fromIndex);
1922 QString text = tabText(fromIndex);
1924 setCurrentIndex(fromIndex);
1925 removeTab(fromIndex);
1926 insertTab(toIndex, w, icon, text);
1927 setCurrentIndex(toIndex);
1931 DragTabBar::DragTabBar(QWidget* parent)
1934 setAcceptDrops(true);
1935 #if QT_VERSION >= 0x040500
1936 setTabsClosable(!lyxrc.single_close_tab_button);
1941 #if QT_VERSION < 0x040300
1942 int DragTabBar::tabAt(QPoint const & position) const
1944 const int max = count();
1945 for (int i = 0; i < max; ++i) {
1946 if (tabRect(i).contains(position))
1954 void DragTabBar::mousePressEvent(QMouseEvent * event)
1956 if (event->button() == Qt::LeftButton)
1957 dragStartPos_ = event->pos();
1958 QTabBar::mousePressEvent(event);
1962 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1964 // If the left button isn't pressed anymore then return
1965 if (!(event->buttons() & Qt::LeftButton))
1968 // If the distance is too small then return
1969 if ((event->pos() - dragStartPos_).manhattanLength()
1970 < QApplication::startDragDistance())
1973 // did we hit something after all?
1974 int tab = tabAt(dragStartPos_);
1978 // simulate button release to remove highlight from button
1979 int i = currentIndex();
1980 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1981 event->button(), event->buttons(), 0);
1982 QTabBar::mouseReleaseEvent(&me);
1986 QDrag * drag = new QDrag(this);
1987 QMimeData * mimeData = new QMimeData;
1988 // a crude way to distinguish tab-reodering drops from other ones
1989 mimeData->setData("action", "tab-reordering") ;
1990 drag->setMimeData(mimeData);
1992 #if QT_VERSION >= 0x040300
1993 // get tab pixmap as cursor
1994 QRect r = tabRect(tab);
1995 QPixmap pixmap(r.size());
1996 render(&pixmap, - r.topLeft());
1997 drag->setPixmap(pixmap);
2000 drag->start(Qt::MoveAction);
2006 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2008 // Only accept if it's an tab-reordering request
2009 QMimeData const * m = event->mimeData();
2010 QStringList formats = m->formats();
2011 if (formats.contains("action")
2012 && m->data("action") == "tab-reordering")
2013 event->acceptProposedAction();
2017 void DragTabBar::dropEvent(QDropEvent * event)
2019 int fromIndex = tabAt(dragStartPos_);
2020 int toIndex = tabAt(event->pos());
2022 // Tell interested objects that
2023 if (fromIndex != toIndex)
2024 tabMoveRequested(fromIndex, toIndex);
2025 event->acceptProposedAction();
2029 } // namespace frontend
2032 #include "moc_GuiWorkArea.cpp"