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"
15 #include "GuiWorkArea_Private.h"
17 #include "ColorCache.h"
18 #include "FontLoader.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "CoordCache.h"
28 #include "FuncRequest.h"
29 #include "GuiApplication.h"
30 #include "GuiCompleter.h"
31 #include "GuiKeySymbol.h"
32 #include "GuiPainter.h"
34 #include "KeySymbol.h"
39 #include "qt_helpers.h"
41 #include "TextMetrics.h"
44 #include "graphics/GraphicsImage.h"
45 #include "graphics/GraphicsLoader.h"
47 #include "support/convert.h"
48 #include "support/debug.h"
49 #include "support/gettext.h"
50 #include "support/FileName.h"
51 #include "support/lassert.h"
52 #include "support/TempFile.h"
54 #include "frontends/Application.h"
55 #include "frontends/FontMetrics.h"
56 #include "frontends/WorkAreaManager.h"
58 #include <QContextMenuEvent>
59 #if (QT_VERSION < 0x050000)
60 #include <QInputContext>
65 #include <QProxyStyle>
67 #include <QMainWindow>
72 #include <QPixmapCache>
74 #include <QStyleOption>
75 #include <QStylePainter>
77 #include <QToolButton>
81 #include "support/bind.h"
85 int const TabIndicatorWidth = 3;
91 using namespace lyx::support;
96 /// return the LyX mouse button state from Qt's
97 static mouse_button::state q_button_state(Qt::MouseButton button)
99 mouse_button::state b = mouse_button::none;
102 b = mouse_button::button1;
105 b = mouse_button::button2;
107 case Qt::RightButton:
108 b = mouse_button::button3;
117 /// return the LyX mouse button state from Qt's
118 mouse_button::state q_motion_state(Qt::MouseButtons state)
120 mouse_button::state b = mouse_button::none;
121 if (state & Qt::LeftButton)
122 b |= mouse_button::button1;
123 if (state & Qt::MidButton)
124 b |= mouse_button::button2;
125 if (state & Qt::RightButton)
126 b |= mouse_button::button3;
135 CursorWidget() : rtl_(false), l_shape_(false), completable_(false),
136 show_(false), x_(0), cursor_width_(0)
141 void draw(QPainter & painter)
143 if (!show_ || !rect_.isValid())
147 int l = x_ - rect_.left();
148 int r = rect_.right() - x_;
149 int bot = rect_.bottom();
151 // draw vertical line
152 painter.fillRect(x_, y, cursor_width_, rect_.height(), color_);
154 // draw RTL/LTR indication
155 painter.setPen(color_);
158 painter.drawLine(x_, bot, x_ - l, bot);
160 painter.drawLine(x_, bot, x_ + cursor_width_ + r, bot);
163 // draw completion triangle
165 int m = y + rect_.height() / 2;
166 int d = TabIndicatorWidth - 1;
168 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
169 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
171 painter.drawLine(x_ + cursor_width_, m - d, x_ + cursor_width_ + d, m);
172 painter.drawLine(x_ + cursor_width_, m + d, x_ + cursor_width_ + d, m);
177 void update(int x, int y, int h, bool l_shape,
178 bool rtl, bool completable)
180 color_ = guiApp->colorCache().get(Color_cursor);
183 completable_ = completable;
186 // extension to left and right
190 // RTL/LTR indication
198 // completion triangle
201 l = max(l, TabIndicatorWidth);
203 r = max(r, TabIndicatorWidth);
206 // compute overall rectangle
207 rect_ = QRect(x - l, y, cursor_width_ + r + l, h);
210 void show(bool set_show = true) { show_ = set_show; }
211 void hide() { show_ = false; }
212 int cursorWidth() const { return cursor_width_; }
213 void recomputeWidth() {
214 cursor_width_ = lyxrc.cursor_width
216 : 1 + int((lyxrc.zoom + 50) / 200.0);
219 QRect const & rect() { return rect_; }
222 /// cursor is in RTL or LTR text
224 /// indication for RTL or LTR
226 /// triangle to show that a completion is available
232 /// rectangle, possibly with l_shape and completion triangle
234 /// x position (were the vertical line is drawn)
241 // This is a 'heartbeat' generating synthetic mouse move events when the
242 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
243 SyntheticMouseEvent::SyntheticMouseEvent()
244 : timeout(200), restart_timeout(true)
248 GuiWorkArea::Private::Private(GuiWorkArea * parent)
249 : p(parent), screen_(0), buffer_view_(0), read_only_(false), lyx_view_(0),
250 cursor_visible_(false), cursor_(0),
251 need_resize_(false), schedule_redraw_(false), preedit_lines_(1),
253 completer_(new GuiCompleter(p, p)), dialog_mode_(false)
258 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
259 : d(new Private(this))
264 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
265 : d(new Private(this))
268 buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
274 double GuiWorkArea::pixelRatio() const
276 #if QT_VERSION >= 0x050000
277 return devicePixelRatio();
284 void GuiWorkArea::init()
287 connect(&d->cursor_timeout_, SIGNAL(timeout()),
288 this, SLOT(toggleCursor()));
290 int const time = QApplication::cursorFlashTime() / 2;
292 d->cursor_timeout_.setInterval(time);
293 d->cursor_timeout_.start();
295 // let's initialize this just to be safe
296 d->cursor_timeout_.setInterval(500);
300 // With Qt4.5 a mouse event will happen before the first paint event
301 // so make sure that the buffer view has an up to date metrics.
302 d->buffer_view_->resize(viewport()->width(), viewport()->height());
303 d->cursor_ = new frontend::CursorWidget();
306 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
307 setAcceptDrops(true);
308 setMouseTracking(true);
309 setMinimumSize(100, 70);
310 setFrameStyle(QFrame::NoFrame);
313 viewport()->setAutoFillBackground(false);
314 // We don't need double-buffering nor SystemBackground on
315 // the viewport because we have our own backing pixmap.
316 viewport()->setAttribute(Qt::WA_NoSystemBackground);
318 setFocusPolicy(Qt::StrongFocus);
320 d->setCursorShape(Qt::IBeamCursor);
322 d->synthetic_mouse_event_.timeout.timeout.connect(
323 bind(&GuiWorkArea::generateSyntheticMouseEvent,
326 // Initialize the vertical Scroll Bar
327 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
328 this, SLOT(scrollTo(int)));
330 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
331 << " viewport height: " << viewport()->height());
333 // Enables input methods for asian languages.
334 // Must be set when creating custom text editing widgets.
335 setAttribute(Qt::WA_InputMethodEnabled, true);
337 d->dialog_mode_ = false;
341 GuiWorkArea::~GuiWorkArea()
343 d->buffer_view_->buffer().workAreaManager().remove(this);
345 delete d->buffer_view_;
347 // Completer has a QObject parent and is thus automatically destroyed.
349 // delete completer_;
354 Qt::CursorShape GuiWorkArea::cursorShape() const
356 return viewport()->cursor().shape();
360 void GuiWorkArea::Private::setCursorShape(Qt::CursorShape shape)
362 p->viewport()->setCursor(shape);
366 void GuiWorkArea::Private::updateCursorShape()
368 setCursorShape(buffer_view_->clickableInset()
369 ? Qt::PointingHandCursor : Qt::IBeamCursor);
373 void GuiWorkArea::setGuiView(GuiView & gv)
379 void GuiWorkArea::setBuffer(Buffer & buffer)
381 delete d->buffer_view_;
382 d->buffer_view_ = new BufferView(buffer);
383 buffer.workAreaManager().add(this);
385 // HACK: Prevents an additional redraw when the scrollbar pops up
386 // which regularily happens on documents with more than one page.
387 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
388 // Since we have no geometry information yet, we assume that
389 // a document needs a scrollbar if there is more then four
390 // paragraph in the outermost text.
391 if (buffer.text().paragraphs().size() > 4)
392 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
393 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
397 void GuiWorkArea::fixVerticalScrollBar()
400 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
404 void GuiWorkArea::close()
406 d->lyx_view_->removeWorkArea(this);
410 void GuiWorkArea::setFullScreen(bool full_screen)
412 d->buffer_view_->setFullScreen(full_screen);
413 setFrameStyle(QFrame::NoFrame);
415 setFrameStyle(QFrame::NoFrame);
416 if (lyxrc.full_screen_scrollbar)
417 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
419 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
423 BufferView & GuiWorkArea::bufferView()
425 return *d->buffer_view_;
429 BufferView const & GuiWorkArea::bufferView() const
431 return *d->buffer_view_;
435 void GuiWorkArea::stopBlinkingCursor()
437 d->cursor_timeout_.stop();
442 void GuiWorkArea::startBlinkingCursor()
444 // do not show the cursor if the view is busy
450 d->buffer_view_->cursorPosAndHeight(p, h);
451 // Don't start blinking if the cursor isn't on screen.
452 if (!d->buffer_view_->cursorInView(p, h))
457 //we're not supposed to cache this value.
458 int const time = QApplication::cursorFlashTime() / 2;
461 d->cursor_timeout_.setInterval(time);
462 d->cursor_timeout_.start();
466 void GuiWorkArea::redraw(bool update_metrics)
469 // No need to redraw in this case.
472 // No need to do anything if this is the current view. The BufferView
473 // metrics are already up to date.
474 if (update_metrics || d->lyx_view_ != guiApp->currentView()
475 || d->lyx_view_->currentWorkArea() != this) {
476 // FIXME: it would be nice to optimize for the off-screen case.
477 d->buffer_view_->cursor().fixIfBroken();
478 d->buffer_view_->updateMetrics();
479 d->buffer_view_->cursor().fixIfBroken();
482 // update cursor position, because otherwise it has to wait until
483 // the blinking interval is over
484 if (d->cursor_visible_) {
489 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
491 update(0, 0, viewport()->width(), viewport()->height());
493 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
494 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
495 d->updateScrollbar();
496 d->lyx_view_->updateStatusBar();
498 if (lyxerr.debugging(Debug::WORKAREA))
499 d->buffer_view_->coordCache().dump();
503 d->updateCursorShape();
507 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
509 if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
510 && lyxrc.full_screen_menubar) {
511 // FIXME HACK: we should not have to do this here. See related comment
512 // in GuiView::event() (QEvent::ShortcutOverride)
513 d->lyx_view_->menuBar()->hide();
516 // In order to avoid bad surprise in the middle of an operation,
517 // we better stop the blinking cursor...
518 // the cursor gets restarted in GuiView::restartCursor()
519 stopBlinkingCursor();
520 guiApp->processKeySym(key, mod);
524 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd0, KeyModifier mod)
527 if (cmd0.action() == LFUN_FILE_OPEN) {
529 lyx_view_->dispatch(cmd0, dr);
535 if (cmd0.action() == LFUN_MOUSE_PRESS) {
536 if (mod == ShiftModifier)
537 cmd = FuncRequest(cmd0, "region-select");
538 else if (mod == ControlModifier)
539 cmd = FuncRequest(cmd0, "paragraph-select");
546 bool const notJustMovingTheMouse =
547 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
549 // In order to avoid bad surprise in the middle of an operation, we better stop
550 // the blinking cursor.
551 if (notJustMovingTheMouse)
552 p->stopBlinkingCursor();
554 buffer_view_->mouseEventDispatch(cmd);
556 // Skip these when selecting
557 // FIXME: let GuiView take care of those.
558 if (cmd.action() != LFUN_MOUSE_MOTION) {
559 completer_->updateVisibility(false, false);
560 lyx_view_->updateDialogs();
561 lyx_view_->updateStatusBar();
564 // GUI tweaks except with mouse motion with no button pressed.
565 if (notJustMovingTheMouse) {
566 // Slight hack: this is only called currently when we
567 // clicked somewhere, so we force through the display
568 // of the new status here.
569 // FIXME: let GuiView take care of those.
570 lyx_view_->clearMessage();
572 // Show the cursor immediately after any operation
573 p->startBlinkingCursor();
580 void GuiWorkArea::Private::resizeBufferView()
582 // WARNING: Please don't put any code that will trigger a repaint here!
583 // We are already inside a paint event.
584 p->stopBlinkingCursor();
585 // Warn our container (GuiView).
590 buffer_view_->cursorPosAndHeight(point, h);
591 bool const cursor_in_view = buffer_view_->cursorInView(point, h);
592 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
594 buffer_view_->scrollToCursor();
597 // Update scrollbars which might have changed due different
598 // BufferView dimension. This is especially important when the
599 // BufferView goes from zero-size to the real-size for the first time,
600 // as the scrollbar paramters are then set for the first time.
603 need_resize_ = false;
605 // Eventually, restart the cursor after the resize event.
606 // We might be resizing even if the focus is on another widget so we only
607 // restart the cursor if we have the focus.
609 QTimer::singleShot(50, p, SLOT(startBlinkingCursor()));
613 void GuiWorkArea::Private::showCursor()
620 buffer_view_->cursorPosAndHeight(p, h);
621 if (!buffer_view_->cursorInView(p, h))
625 bool l_shape = false;
626 Font const & realfont = buffer_view_->cursor().real_current_font;
627 BufferParams const & bp = buffer_view_->buffer().params();
628 bool const samelang = realfont.language() == bp.language;
629 bool const isrtl = realfont.isVisibleRightToLeft();
631 if (!samelang || isrtl != bp.language->rightToLeft())
634 // The ERT language hack needs fixing up
635 if (realfont.language() == latex_language)
638 // show cursor on screen
639 Cursor & cur = buffer_view_->cursor();
640 bool completable = cur.inset().showCompletionCursor()
641 && completer_->completionAvailable()
642 && !completer_->popupVisible()
643 && !completer_->inlineVisible();
644 cursor_visible_ = true;
645 cursor_->recomputeWidth();
647 //int cur_x = buffer_view_->getPos(cur).x_;
648 // We may have decided to slide the cursor row so that cursor
650 p.x_ -= buffer_view_->horizScrollOffset();
652 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
656 void GuiWorkArea::Private::hideCursor()
658 if (!cursor_visible_)
661 cursor_visible_ = false;
666 void GuiWorkArea::toggleCursor()
668 if (d->cursor_visible_)
675 void GuiWorkArea::Private::updateScrollbar()
677 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
678 // WARNING: don't touch at the scrollbar value like this:
679 // verticalScrollBar()->setValue(scroll_.position);
680 // because this would cause a recursive signal/slot calling with
681 // GuiWorkArea::scrollTo
682 p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
683 p->verticalScrollBar()->setPageStep(scroll_.page_step);
684 p->verticalScrollBar()->setSingleStep(scroll_.single_step);
685 p->verticalScrollBar()->setSliderPosition(scroll_.position);
689 void GuiWorkArea::scrollTo(int value)
691 stopBlinkingCursor();
692 d->buffer_view_->scrollDocView(value, true);
694 if (lyxrc.cursor_follows_scrollbar) {
695 d->buffer_view_->setCursorFromScrollbar();
696 // FIXME: let GuiView take care of those.
697 d->lyx_view_->updateLayoutList();
699 // Show the cursor immediately after any operation.
700 startBlinkingCursor();
703 QApplication::syncX();
708 bool GuiWorkArea::event(QEvent * e)
711 case QEvent::ToolTip: {
712 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
713 if (lyxrc.use_tooltip) {
714 QPoint pos = helpEvent->pos();
715 if (pos.x() < viewport()->width()) {
716 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
717 QToolTip::showText(helpEvent->globalPos(), s);
720 QToolTip::hideText();
722 // Don't forget to accept the event!
727 case QEvent::ShortcutOverride: {
728 // We catch this event in order to catch the Tab or Shift+Tab key press
729 // which are otherwise reserved to focus switching between controls
731 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
732 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
733 || (ke->key() == Qt::Key_Backtab && (
734 ke->modifiers() == Qt::ShiftModifier
735 || ke->modifiers() == Qt::NoModifier))) {
739 return QAbstractScrollArea::event(e);
743 return QAbstractScrollArea::event(e);
749 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
752 if (e->reason() == QContextMenuEvent::Mouse)
753 // the menu name is set on mouse press
754 name = d->context_menu_name_;
756 QPoint pos = e->pos();
757 Cursor const & cur = d->buffer_view_->cursor();
758 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
759 // Do not access the context menu of math right in front of before
760 // the cursor. This does not work when the cursor is in text.
761 Inset * inset = cur.paragraph().getInset(cur.pos());
762 if (inset && inset->asInsetMath())
764 else if (cur.pos() > 0) {
765 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
770 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
774 QAbstractScrollArea::contextMenuEvent(e);
777 // always show mnemonics when the keyboard is used to show the context menu
778 // FIXME: This should be fixed in Qt itself
779 bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
780 QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
782 QAbstractScrollArea::contextMenuEvent(e);
785 // Position the menu to the right.
786 // FIXME: menu position should be different for RTL text.
787 menu->exec(e->globalPos());
792 void GuiWorkArea::focusInEvent(QFocusEvent * e)
794 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
795 if (d->lyx_view_->currentWorkArea() != this) {
796 d->lyx_view_->setCurrentWorkArea(this);
797 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
800 startBlinkingCursor();
801 QAbstractScrollArea::focusInEvent(e);
805 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
807 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
808 stopBlinkingCursor();
809 QAbstractScrollArea::focusOutEvent(e);
813 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
815 if (d->dc_event_.active && d->dc_event_ == *e) {
816 d->dc_event_.active = false;
817 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
818 q_button_state(e->button()));
824 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
825 inputContext()->reset();
828 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
829 q_button_state(e->button()));
830 d->dispatch(cmd, q_key_state(e->modifiers()));
832 // Save the context menu on mouse press, because also the mouse
833 // cursor is set on mouse press. Afterwards, we can either release
834 // the mousebutton somewhere else, or the cursor might have moved
835 // due to the DEPM. We need to do this after the mouse has been
836 // set in dispatch(), because the selection state might change.
837 if (e->button() == Qt::RightButton)
838 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
844 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
846 if (d->synthetic_mouse_event_.timeout.running())
847 d->synthetic_mouse_event_.timeout.stop();
849 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
850 q_button_state(e->button()));
856 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
858 // we kill the triple click if we move
859 doubleClickTimeout();
860 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
861 q_motion_state(e->buttons()));
865 // If we're above or below the work area...
866 if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
867 && e->buttons() == mouse_button::button1) {
868 // Make sure only a synthetic event can cause a page scroll,
869 // so they come at a steady rate:
871 // _Force_ a scroll up:
872 cmd.set_y(e->y() - 21);
874 cmd.set_y(e->y() + 21);
875 // Store the event, to be handled when the timeout expires.
876 d->synthetic_mouse_event_.cmd = cmd;
878 if (d->synthetic_mouse_event_.timeout.running()) {
879 // Discard the event. Note that it _may_ be handled
880 // when the timeout expires if
881 // synthetic_mouse_event_.cmd has not been overwritten.
882 // Ie, when the timeout expires, we handle the
883 // most recent event but discard all others that
884 // occurred after the one used to start the timeout
885 // in the first place.
889 d->synthetic_mouse_event_.restart_timeout = true;
890 d->synthetic_mouse_event_.timeout.start();
891 // Fall through to handle this event...
893 } else if (d->synthetic_mouse_event_.timeout.running()) {
894 // Store the event, to be possibly handled when the timeout
896 // Once the timeout has expired, normal control is returned
897 // to mouseMoveEvent (restart_timeout = false).
898 // This results in a much smoother 'feel' when moving the
899 // mouse back into the work area.
900 d->synthetic_mouse_event_.cmd = cmd;
901 d->synthetic_mouse_event_.restart_timeout = false;
908 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
910 // Wheel rotation by one notch results in a delta() of 120 (see
911 // documentation of QWheelEvent)
912 double const delta = ev->delta() / 120.0;
914 switch (lyxrc.scroll_wheel_zoom) {
915 case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
916 zoom = ev->modifiers() & Qt::ControlModifier;
917 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
919 case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
920 zoom = ev->modifiers() & Qt::ShiftModifier;
921 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
923 case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
924 zoom = ev->modifiers() & Qt::AltModifier;
925 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
927 case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
931 docstring arg = convert<docstring>(int(5 * delta));
932 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
936 // Take into account the desktop wide settings.
937 int const lines = qApp->wheelScrollLines();
938 int const page_step = verticalScrollBar()->pageStep();
939 // Test if the wheel mouse is set to one screen at a time.
940 int scroll_value = lines > page_step
941 ? page_step : lines * verticalScrollBar()->singleStep();
943 // Take into account the rotation and the user preferences.
944 scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
945 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
946 << " delta = " << delta << " scroll_value = " << scroll_value
947 << " page_step = " << page_step);
949 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
955 void GuiWorkArea::generateSyntheticMouseEvent()
957 int const e_y = d->synthetic_mouse_event_.cmd.y();
958 int const wh = d->buffer_view_->workHeight();
959 bool const up = e_y < 0;
960 bool const down = e_y > wh;
962 // Set things off to generate the _next_ 'pseudo' event.
964 if (d->synthetic_mouse_event_.restart_timeout) {
965 // This is some magic formulae to determine the speed
966 // of scrolling related to the position of the mouse.
969 int dist = up ? -e_y : e_y - wh;
970 time = max(min(200, 250000 / (dist * dist)), 1) ;
973 step = 80000 / (time * time);
977 d->synthetic_mouse_event_.timeout.setTimeout(time);
978 d->synthetic_mouse_event_.timeout.start();
981 // Can we scroll further ?
982 int const value = verticalScrollBar()->value();
983 if (value == verticalScrollBar()->maximum()
984 || value == verticalScrollBar()->minimum()) {
985 d->synthetic_mouse_event_.timeout.stop();
990 if (step <= 2 * wh) {
991 d->buffer_view_->scroll(up ? -step : step);
992 d->buffer_view_->updateMetrics();
994 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
997 // In which paragraph do we have to set the cursor ?
998 Cursor & cur = d->buffer_view_->cursor();
999 // FIXME: we don't know howto handle math.
1000 Text * text = cur.text();
1003 TextMetrics const & tm = d->buffer_view_->textMetrics(text);
1005 pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
1006 ParagraphMetrics const & pm = *pp.second;
1007 pit_type const pit = pp.first;
1009 if (pm.rows().empty())
1012 // Find the row at which we set the cursor.
1013 RowList::const_iterator rit = pm.rows().begin();
1014 RowList::const_iterator rlast = pm.rows().end();
1015 int yy = pm.position() - pm.ascent();
1016 for (--rlast; rit != rlast; ++rit) {
1017 int h = rit->height();
1018 if ((up && yy + h > 0)
1019 || (!up && yy + h > wh - defaultRowHeight()))
1024 // Find the position of the cursor
1026 int x = d->synthetic_mouse_event_.cmd.x();
1027 pos_type const pos = tm.getPosNearX(*rit, x, bound);
1032 cur.boundary(bound);
1034 d->buffer_view_->buffer().changed(false);
1039 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1041 // Do not process here some keys if dialog_mode_ is set
1043 && (ev->modifiers() == Qt::NoModifier
1044 || ev->modifiers() == Qt::ShiftModifier)
1045 && (ev->key() == Qt::Key_Escape
1046 || ev->key() == Qt::Key_Enter
1047 || ev->key() == Qt::Key_Return)
1053 // intercept some keys if completion popup is visible
1054 if (d->completer_->popupVisible()) {
1055 switch (ev->key()) {
1057 case Qt::Key_Return:
1058 d->completer_->activate();
1064 // do nothing if there are other events
1065 // (the auto repeated events come too fast)
1066 // it looks like this is only needed on X11
1067 #if defined(Q_WS_X11) || defined(QPA_XCB)
1068 if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1069 switch (ev->key()) {
1070 case Qt::Key_PageDown:
1071 case Qt::Key_PageUp:
1076 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1083 KeyModifier m = q_key_state(ev->modifiers());
1086 if (m & ShiftModifier)
1088 if (m & ControlModifier)
1090 if (m & AltModifier)
1092 if (m & MetaModifier)
1095 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1096 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1097 << " keyState: " << str);
1100 setKeySymbol(&sym, ev);
1102 processKeySym(sym, q_key_state(ev->modifiers()));
1110 void GuiWorkArea::doubleClickTimeout()
1112 d->dc_event_.active = false;
1116 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1118 d->dc_event_ = DoubleClick(ev);
1119 QTimer::singleShot(QApplication::doubleClickInterval(), this,
1120 SLOT(doubleClickTimeout()));
1121 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1123 q_button_state(ev->button()));
1129 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1131 QAbstractScrollArea::resizeEvent(ev);
1132 d->need_resize_ = true;
1137 void GuiWorkArea::Private::update(int x, int y, int w, int h)
1139 p->viewport()->update(x, y, w, h);
1143 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1145 QRectF const rc = ev->rect();
1146 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1147 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1149 if (d->needResize()) {
1151 d->resizeBufferView();
1152 if (d->cursor_visible_) {
1158 QPainter pain(viewport());
1159 double const pr = pixelRatio();
1160 QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr, rc.width() * pr, rc.height() * pr);
1162 if (lyxrc.use_qimage) {
1163 QImage const & image = static_cast<QImage const &>(*d->screen_);
1164 pain.drawImage(rc, image, rcs);
1166 QPixmap const & pixmap = static_cast<QPixmap const &>(*d->screen_);
1167 pain.drawPixmap(rc, pixmap, rcs);
1169 d->cursor_->draw(pain);
1174 void GuiWorkArea::Private::updateScreen()
1176 GuiPainter pain(screen_, p->pixelRatio());
1177 buffer_view_->draw(pain);
1181 void GuiWorkArea::Private::showCursor(int x, int y, int h,
1182 bool l_shape, bool rtl, bool completable)
1184 if (schedule_redraw_) {
1185 // This happens when a graphic conversion is finished. As we don't know
1186 // the size of the new graphics, it's better the update everything.
1187 // We can't use redraw() here because this would trigger a infinite
1188 // recursive loop with showCursor().
1189 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
1192 p->viewport()->update(QRect(0, 0, p->viewport()->width(), p->viewport()->height()));
1193 schedule_redraw_ = false;
1194 // Show the cursor immediately after the update.
1200 cursor_->update(x, y, h, l_shape, rtl, completable);
1202 p->viewport()->update(cursor_->rect());
1206 void GuiWorkArea::Private::removeCursor()
1209 //if (!qApp->focusWidget())
1210 p->viewport()->update(cursor_->rect());
1214 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1216 QString const & commit_string = e->commitString();
1217 docstring const & preedit_string
1218 = qstring_to_ucs4(e->preeditString());
1220 if (!commit_string.isEmpty()) {
1222 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1223 << " commitString: " << e->commitString());
1227 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1228 for (int i = 0; i != commit_string.size(); ++i) {
1229 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1234 // Hide the cursor during the kana-kanji transformation.
1235 if (preedit_string.empty())
1236 startBlinkingCursor();
1238 stopBlinkingCursor();
1240 // last_width : for checking if last preedit string was/wasn't empty.
1242 // We could have more than one work area, right?
1243 static bool last_width = false;
1244 if (!last_width && preedit_string.empty()) {
1245 // if last_width is last length of preedit string.
1250 GuiPainter pain(d->screen_, pixelRatio());
1251 d->buffer_view_->updateMetrics();
1252 d->buffer_view_->draw(pain);
1253 FontInfo font = d->buffer_view_->cursor().getFont().fontInfo();
1254 FontMetrics const & fm = theFontMetrics(font);
1255 int height = fm.maxHeight();
1256 int cur_x = d->cursor_->rect().left();
1257 int cur_y = d->cursor_->rect().bottom();
1259 // redraw area of preedit string.
1260 update(0, cur_y - height, viewport()->width(),
1261 (height + 1) * d->preedit_lines_);
1263 if (preedit_string.empty()) {
1265 d->preedit_lines_ = 1;
1271 // att : stores an IM attribute.
1272 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1274 // get attributes of input method cursor.
1275 // cursor_pos : cursor position in preedit string.
1276 size_t cursor_pos = 0;
1277 bool cursor_is_visible = false;
1278 for (int i = 0; i != att.size(); ++i) {
1279 if (att.at(i).type == QInputMethodEvent::Cursor) {
1280 cursor_pos = att.at(i).start;
1281 cursor_is_visible = att.at(i).length != 0;
1286 size_t preedit_length = preedit_string.length();
1288 // get position of selection in input method.
1289 // FIXME: isn't there a way to do this simplier?
1290 // rStart : cursor position in selected string in IM.
1292 // rLength : selected string length in IM.
1294 if (cursor_pos < preedit_length) {
1295 for (int i = 0; i != att.size(); ++i) {
1296 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1297 if (att.at(i).start <= int(cursor_pos)
1298 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1299 rStart = att.at(i).start;
1300 rLength = att.at(i).length;
1301 if (!cursor_is_visible)
1302 cursor_pos += rLength;
1309 rStart = cursor_pos;
1313 int const right_margin = d->buffer_view_->rightMargin();
1314 Painter::preedit_style ps;
1315 // Most often there would be only one line:
1316 d->preedit_lines_ = 1;
1317 for (size_t pos = 0; pos != preedit_length; ++pos) {
1318 char_type const typed_char = preedit_string[pos];
1319 // reset preedit string style
1320 ps = Painter::preedit_default;
1322 // if we reached the right extremity of the screen, go to next line.
1323 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1324 cur_x = right_margin;
1325 cur_y += height + 1;
1326 ++d->preedit_lines_;
1328 // preedit strings are displayed with dashed underline
1329 // and partial strings are displayed white on black indicating
1330 // that we are in selecting mode in the input method.
1331 // FIXME: rLength == preedit_length is not a changing condition
1332 // FIXME: should be put out of the loop.
1334 && pos < rStart + rLength
1335 && !(cursor_pos < rLength && rLength == preedit_length))
1336 ps = Painter::preedit_selecting;
1338 if (pos == cursor_pos
1339 && (cursor_pos < rLength && rLength == preedit_length))
1340 ps = Painter::preedit_cursor;
1342 // draw one character and update cur_x.
1343 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1346 // update the preedit string screen area.
1347 update(0, cur_y - d->preedit_lines_*height, viewport()->width(),
1348 (height + 1) * d->preedit_lines_);
1350 // Don't forget to accept the event!
1355 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1357 QRect cur_r(0, 0, 0, 0);
1359 // this is the CJK-specific composition window position and
1360 // the context menu position when the menu key is pressed.
1361 case Qt::ImMicroFocus:
1362 cur_r = d->cursor_->rect();
1363 if (d->preedit_lines_ != 1)
1365 cur_r.moveBottom(cur_r.bottom()
1366 + cur_r.height() * (d->preedit_lines_ - 1));
1367 // return lower right of cursor in LyX.
1370 return QWidget::inputMethodQuery(query);
1375 void GuiWorkArea::updateWindowTitle()
1377 docstring maximize_title;
1378 docstring minimize_title;
1380 Buffer const & buf = d->buffer_view_->buffer();
1381 FileName const file_name = buf.fileName();
1382 if (!file_name.empty()) {
1383 maximize_title = file_name.displayName(130);
1384 minimize_title = from_utf8(file_name.onlyFileName());
1385 if (buf.lyxvc().inUse()) {
1386 if (buf.lyxvc().locking())
1387 maximize_title += _(" (version control, locking)");
1389 maximize_title += _(" (version control)");
1391 if (!buf.isClean()) {
1392 maximize_title += _(" (changed)");
1393 minimize_title += char_type('*');
1395 if (buf.isReadonly())
1396 maximize_title += _(" (read only)");
1399 QString const new_title = toqstr(maximize_title);
1400 if (new_title != windowTitle()) {
1401 QWidget::setWindowTitle(new_title);
1402 QWidget::setWindowIconText(toqstr(minimize_title));
1408 bool GuiWorkArea::isFullScreen() const
1410 return d->lyx_view_ && d->lyx_view_->isFullScreen();
1414 void GuiWorkArea::scheduleRedraw()
1416 d->schedule_redraw_ = true;
1420 bool GuiWorkArea::inDialogMode() const
1422 return d->dialog_mode_;
1426 void GuiWorkArea::setDialogMode(bool mode)
1428 d->dialog_mode_ = mode;
1432 GuiCompleter & GuiWorkArea::completer()
1434 return *d->completer_;
1437 GuiView const & GuiWorkArea::view() const
1439 return *d->lyx_view_;
1443 GuiView & GuiWorkArea::view()
1445 return *d->lyx_view_;
1448 ////////////////////////////////////////////////////////////////////
1452 ////////////////////////////////////////////////////////////////////
1455 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1457 support::TempFile tempfile("embedded.internal");
1458 tempfile.setAutoRemove(false);
1459 buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1460 buffer_->setUnnamed(true);
1461 buffer_->setFullyLoaded(true);
1462 setBuffer(*buffer_);
1463 setDialogMode(true);
1467 EmbeddedWorkArea::~EmbeddedWorkArea()
1469 // No need to destroy buffer and bufferview here, because it is done
1470 // in theBufferList() destruction loop at application exit
1474 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1477 GuiWorkArea::closeEvent(ev);
1481 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1484 GuiWorkArea::hideEvent(ev);
1488 QSize EmbeddedWorkArea::sizeHint () const
1491 // GuiWorkArea sets the size to the screen's viewport
1492 // by returning a value this gets overridden
1493 // EmbeddedWorkArea is now sized to fit in the layout
1494 // of the parent, and has a minimum size set in GuiWorkArea
1495 // which is what we return here
1496 return QSize(100, 70);
1500 void EmbeddedWorkArea::disable()
1502 stopBlinkingCursor();
1503 if (view().currentWorkArea() != this)
1505 // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1506 // tolerates it and shows the background logo), what happens if
1507 // an EmbeddedWorkArea is closed after closing all document WAs
1508 view().setCurrentWorkArea(view().currentMainWorkArea());
1511 ////////////////////////////////////////////////////////////////////
1515 ////////////////////////////////////////////////////////////////////
1518 class NoTabFrameMacStyle : public QProxyStyle {
1521 QRect subElementRect(SubElement element, const QStyleOption * option,
1522 const QWidget * widget = 0) const
1524 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1525 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1527 // The Qt Mac style puts the contents into a 3 pixel wide box
1528 // which looks very ugly and not like other Mac applications.
1529 // Hence we remove this here, and moreover the 16 pixel round
1530 // frame above if the tab bar is hidden.
1531 if (element == QStyle::SE_TabWidgetTabContents) {
1532 rect.adjust(- rect.left(), 0, rect.left(), 0);
1541 NoTabFrameMacStyle noTabFrameMacStyle;
1545 TabWorkArea::TabWorkArea(QWidget * parent)
1546 : QTabWidget(parent), clicked_tab_(-1)
1549 setStyle(&noTabFrameMacStyle);
1552 QPalette pal = palette();
1553 pal.setColor(QPalette::Active, QPalette::Button,
1554 pal.color(QPalette::Active, QPalette::Window));
1555 pal.setColor(QPalette::Disabled, QPalette::Button,
1556 pal.color(QPalette::Disabled, QPalette::Window));
1557 pal.setColor(QPalette::Inactive, QPalette::Button,
1558 pal.color(QPalette::Inactive, QPalette::Window));
1560 QObject::connect(this, SIGNAL(currentChanged(int)),
1561 this, SLOT(on_currentTabChanged(int)));
1563 closeBufferButton = new QToolButton(this);
1564 closeBufferButton->setPalette(pal);
1565 // FIXME: rename the icon to closebuffer.png
1566 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1567 closeBufferButton->setText("Close File");
1568 closeBufferButton->setAutoRaise(true);
1569 closeBufferButton->setCursor(Qt::ArrowCursor);
1570 closeBufferButton->setToolTip(qt_("Close File"));
1571 closeBufferButton->setEnabled(true);
1572 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1573 this, SLOT(closeCurrentBuffer()));
1574 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1576 // setup drag'n'drop
1577 QTabBar* tb = new DragTabBar;
1578 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1579 this, SLOT(moveTab(int, int)));
1580 tb->setElideMode(Qt::ElideNone);
1583 // make us responsible for the context menu of the tabbar
1584 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1585 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1586 this, SLOT(showContextMenu(const QPoint &)));
1587 connect(tb, SIGNAL(tabCloseRequested(int)),
1588 this, SLOT(closeTab(int)));
1590 setUsesScrollButtons(true);
1594 void TabWorkArea::paintEvent(QPaintEvent * event)
1596 if (tabBar()->isVisible()) {
1597 QTabWidget::paintEvent(event);
1599 // Prevent the selected tab to influence the
1600 // painting of the frame of the tab widget.
1601 // This is needed for gtk style in Qt.
1602 QStylePainter p(this);
1603 #if QT_VERSION < 0x050000
1604 QStyleOptionTabWidgetFrameV2 opt;
1606 QStyleOptionTabWidgetFrame opt;
1608 initStyleOption(&opt);
1609 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1611 opt.selectedTabRect = QRect();
1612 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1617 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1619 if (event->button() != Qt::LeftButton)
1622 // return early if double click on existing tabs
1623 for (int i = 0; i < count(); ++i)
1624 if (tabBar()->tabRect(i).contains(event->pos()))
1627 dispatch(FuncRequest(LFUN_BUFFER_NEW));
1631 void TabWorkArea::setFullScreen(bool full_screen)
1633 for (int i = 0; i != count(); ++i) {
1634 if (GuiWorkArea * wa = workArea(i))
1635 wa->setFullScreen(full_screen);
1638 if (lyxrc.full_screen_tabbar)
1639 showBar(!full_screen && count() > 1);
1641 showBar(count() > 1);
1645 void TabWorkArea::showBar(bool show)
1647 tabBar()->setEnabled(show);
1648 tabBar()->setVisible(show);
1649 closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1650 setTabsClosable(!lyxrc.single_close_tab_button);
1654 GuiWorkArea * TabWorkArea::currentWorkArea()
1659 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1665 GuiWorkArea * TabWorkArea::workArea(int index)
1667 return dynamic_cast<GuiWorkArea *>(widget(index));
1671 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1673 // FIXME: this method doesn't work if we have more than work area
1674 // showing the same buffer.
1675 for (int i = 0; i != count(); ++i) {
1676 GuiWorkArea * wa = workArea(i);
1677 LASSERT(wa, return 0);
1678 if (&wa->bufferView().buffer() == &buffer)
1685 void TabWorkArea::closeAll()
1688 GuiWorkArea * wa = workArea(0);
1689 LASSERT(wa, return);
1696 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1698 LASSERT(work_area, return false);
1699 int index = indexOf(work_area);
1703 if (index == currentIndex())
1704 // Make sure the work area is up to date.
1705 on_currentTabChanged(index);
1707 // Switch to the work area.
1708 setCurrentIndex(index);
1709 work_area->setFocus();
1715 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1717 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1718 wa->setUpdatesEnabled(false);
1719 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1720 // when hiding it again below).
1721 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1722 showBar(count() > 0);
1723 addTab(wa, wa->windowTitle());
1724 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1725 this, SLOT(updateTabTexts()));
1726 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1727 setFullScreen(true);
1729 // Hide tabbar if there's only one tab.
1730 showBar(count() > 1);
1738 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1740 LASSERT(work_area, return false);
1741 int index = indexOf(work_area);
1745 work_area->setUpdatesEnabled(false);
1750 // make sure the next work area is enabled.
1751 currentWidget()->setUpdatesEnabled(true);
1752 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1753 setFullScreen(true);
1755 // Show tabbar only if there's more than one tab.
1756 showBar(count() > 1);
1758 lastWorkAreaRemoved();
1766 void TabWorkArea::on_currentTabChanged(int i)
1768 // returns e.g. on application destruction
1771 GuiWorkArea * wa = workArea(i);
1772 LASSERT(wa, return);
1773 wa->setUpdatesEnabled(true);
1777 currentWorkAreaChanged(wa);
1779 LYXERR(Debug::GUI, "currentTabChanged " << i
1780 << " File: " << wa->bufferView().buffer().absFileName());
1784 void TabWorkArea::closeCurrentBuffer()
1787 if (clicked_tab_ == -1)
1788 wa = currentWorkArea();
1790 wa = workArea(clicked_tab_);
1791 LASSERT(wa, return);
1793 wa->view().closeWorkArea(wa);
1797 void TabWorkArea::hideCurrentTab()
1800 if (clicked_tab_ == -1)
1801 wa = currentWorkArea();
1803 wa = workArea(clicked_tab_);
1804 LASSERT(wa, return);
1806 wa->view().hideWorkArea(wa);
1810 void TabWorkArea::closeTab(int index)
1812 on_currentTabChanged(index);
1815 wa = currentWorkArea();
1817 wa = workArea(index);
1818 LASSERT(wa, return);
1820 wa->view().closeWorkArea(wa);
1827 /// make vector happy
1830 DisplayPath(int tab, FileName const & filename)
1833 filename_ = (filename.extension() == "lyx") ?
1834 toqstr(filename.onlyFileNameWithoutExt())
1835 : toqstr(filename.onlyFileName());
1836 postfix_ = toqstr(filename.absoluteFilePath()).
1837 split("/", QString::SkipEmptyParts);
1838 postfix_.pop_back();
1839 abs_ = toqstr(filename.absoluteFilePath());
1840 dottedPrefix_ = false;
1843 /// Absolute path for debugging.
1848 /// Add the first segment from the postfix or three dots to the prefix.
1849 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1850 /// when really needed.
1851 void shiftPathSegment(bool dotted)
1853 if (postfix_.count() <= 0)
1857 if (dottedPrefix_ && !prefix_.isEmpty())
1858 prefix_ += ellipsisSlash_;
1859 prefix_ += postfix_.front() + "/";
1861 dottedPrefix_ = dotted && !prefix_.isEmpty();
1862 postfix_.pop_front();
1865 QString displayString() const
1867 if (prefix_.isEmpty())
1870 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1871 return prefix_ + (dots ? ellipsisSlash_ : "") + filename_;
1874 QString forecastPathString() const
1876 if (postfix_.count() == 0)
1877 return displayString();
1880 + (dottedPrefix_ ? ellipsisSlash_ : "")
1881 + postfix_.front() + "/";
1884 bool final() const { return postfix_.empty(); }
1886 int tab() const { return tab_; }
1890 static QString const ellipsisSlash_;
1894 QStringList postfix_;
1906 QString const DisplayPath::ellipsisSlash_ = QString(QChar(0x2026)) + "/";
1910 bool operator<(DisplayPath const & a, DisplayPath const & b)
1912 return a.displayString() < b.displayString();
1916 bool operator==(DisplayPath const & a, DisplayPath const & b)
1918 return a.displayString() == b.displayString();
1922 void TabWorkArea::updateTabTexts()
1927 std::list<DisplayPath> paths;
1928 typedef std::list<DisplayPath>::iterator It;
1930 // collect full names first: path into postfix, empty prefix and
1931 // filename without extension
1932 for (size_t i = 0; i < n; ++i) {
1933 GuiWorkArea * i_wa = workArea(i);
1934 FileName const fn = i_wa->bufferView().buffer().fileName();
1935 paths.push_back(DisplayPath(i, fn));
1938 // go through path segments and see if it helps to make the path more unique
1939 bool somethingChanged = true;
1940 bool allFinal = false;
1941 while (somethingChanged && !allFinal) {
1942 // adding path segments changes order
1945 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1946 somethingChanged = false;
1949 // find segments which are not unique (i.e. non-atomic)
1950 It it = paths.begin();
1952 QString segString = it->displayString();
1953 for (; it != paths.end(); ++it) {
1954 // look to the next item
1959 allFinal = allFinal && it->final();
1961 LYXERR(Debug::GUI, "it = " << it->abs()
1962 << " => " << it->displayString());
1964 // still the same segment?
1966 if ((next != paths.end()
1967 && (nextString = next->displayString()) == segString))
1969 LYXERR(Debug::GUI, "segment ended");
1971 // only a trivial one with one element?
1972 if (it == segStart) {
1973 // start new segment
1975 segString = nextString;
1979 // we found a non-atomic segment segStart <= sit <= it < next.
1980 // Shift path segments and hope for the best
1981 // that it makes the path more unique.
1982 somethingChanged = true;
1984 QString dspString = sit->forecastPathString();
1985 LYXERR(Debug::GUI, "first forecast found for "
1986 << sit->abs() << " => " << dspString);
1988 bool moreUnique = false;
1989 for (; sit != next; ++sit) {
1990 if (sit->forecastPathString() != dspString) {
1991 LYXERR(Debug::GUI, "different forecast found for "
1992 << sit->abs() << " => " << sit->forecastPathString());
1996 LYXERR(Debug::GUI, "same forecast found for "
1997 << sit->abs() << " => " << dspString);
2000 // if the path segment helped, add it. Otherwise add dots
2001 bool dots = !moreUnique;
2002 LYXERR(Debug::GUI, "using dots = " << dots);
2003 for (sit = segStart; sit != next; ++sit) {
2004 sit->shiftPathSegment(dots);
2005 LYXERR(Debug::GUI, "shifting "
2006 << sit->abs() << " => " << sit->displayString());
2009 // start new segment
2011 segString = nextString;
2015 // set new tab titles
2016 for (It it = paths.begin(); it != paths.end(); ++it) {
2017 int const tab_index = it->tab();
2018 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2019 QString tab_text = it->displayString().replace("&", "&&");
2020 if (!buf.fileName().empty() && !buf.isClean())
2022 QString tab_tooltip = it->abs();
2023 if (buf.isReadonly()) {
2024 setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2025 tab_tooltip = qt_("%1 (read only)").arg(it->abs());
2027 setTabIcon(tab_index, QIcon());
2028 setTabText(tab_index, tab_text);
2029 setTabToolTip(tab_index, tab_tooltip);
2034 void TabWorkArea::showContextMenu(const QPoint & pos)
2037 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
2038 if (clicked_tab_ == -1)
2043 popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2044 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2045 popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2046 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2047 popup.exec(tabBar()->mapToGlobal(pos));
2053 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2055 QWidget * w = widget(fromIndex);
2056 QIcon icon = tabIcon(fromIndex);
2057 QString text = tabText(fromIndex);
2059 setCurrentIndex(fromIndex);
2060 removeTab(fromIndex);
2061 insertTab(toIndex, w, icon, text);
2062 setCurrentIndex(toIndex);
2066 DragTabBar::DragTabBar(QWidget* parent)
2069 setAcceptDrops(true);
2070 setTabsClosable(!lyxrc.single_close_tab_button);
2074 void DragTabBar::mousePressEvent(QMouseEvent * event)
2076 if (event->button() == Qt::LeftButton)
2077 dragStartPos_ = event->pos();
2078 QTabBar::mousePressEvent(event);
2082 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2084 // If the left button isn't pressed anymore then return
2085 if (!(event->buttons() & Qt::LeftButton))
2088 // If the distance is too small then return
2089 if ((event->pos() - dragStartPos_).manhattanLength()
2090 < QApplication::startDragDistance())
2093 // did we hit something after all?
2094 int tab = tabAt(dragStartPos_);
2098 // simulate button release to remove highlight from button
2099 int i = currentIndex();
2100 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2101 event->button(), event->buttons(), 0);
2102 QTabBar::mouseReleaseEvent(&me);
2106 QDrag * drag = new QDrag(this);
2107 QMimeData * mimeData = new QMimeData;
2108 // a crude way to distinguish tab-reodering drops from other ones
2109 mimeData->setData("action", "tab-reordering") ;
2110 drag->setMimeData(mimeData);
2112 // get tab pixmap as cursor
2113 QRect r = tabRect(tab);
2114 QPixmap pixmap(r.size());
2115 render(&pixmap, - r.topLeft());
2116 drag->setPixmap(pixmap);
2121 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2123 // Only accept if it's an tab-reordering request
2124 QMimeData const * m = event->mimeData();
2125 QStringList formats = m->formats();
2126 if (formats.contains("action")
2127 && m->data("action") == "tab-reordering")
2128 event->acceptProposedAction();
2132 void DragTabBar::dropEvent(QDropEvent * event)
2134 int fromIndex = tabAt(dragStartPos_);
2135 int toIndex = tabAt(event->pos());
2137 // Tell interested objects that
2138 if (fromIndex != toIndex)
2139 tabMoveRequested(fromIndex, toIndex);
2140 event->acceptProposedAction();
2144 } // namespace frontend
2147 #include "moc_GuiWorkArea.cpp"