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 "MetricsInfo.h"
39 #include "qt_helpers.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 <boost/bind.hpp>
78 extern "C" int XEventsQueued(Display *display, int mode);
82 int const CursorWidth = 2;
84 int const CursorWidth = 1;
86 int const TabIndicatorWidth = 3;
92 using namespace lyx::support;
97 /// return the LyX mouse button state from Qt's
98 static mouse_button::state q_button_state(Qt::MouseButton button)
100 mouse_button::state b = mouse_button::none;
103 b = mouse_button::button1;
106 b = mouse_button::button2;
108 case Qt::RightButton:
109 b = mouse_button::button3;
118 /// return the LyX mouse button state from Qt's
119 mouse_button::state q_motion_state(Qt::MouseButtons state)
121 mouse_button::state b = mouse_button::none;
122 if (state & Qt::LeftButton)
123 b |= mouse_button::button1;
124 if (state & Qt::MidButton)
125 b |= mouse_button::button2;
126 if (state & Qt::RightButton)
127 b |= mouse_button::button3;
138 void draw(QPainter & painter)
140 if (!show_ || !rect_.isValid())
144 int l = x_ - rect_.left();
145 int r = rect_.right() - x_;
146 int bot = rect_.bottom();
148 // draw vertica linel
149 painter.fillRect(x_, y, CursorWidth, rect_.height(), color_);
151 // draw RTL/LTR indication
152 painter.setPen(color_);
155 painter.drawLine(x_, bot, x_ - l, bot);
157 painter.drawLine(x_, bot, x_ + CursorWidth + r, bot);
160 // draw completion triangle
162 int m = y + rect_.height() / 2;
163 int d = TabIndicatorWidth - 1;
165 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
166 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
168 painter.drawLine(x_ + CursorWidth, m - d, x_ + CursorWidth + d, m);
169 painter.drawLine(x_ + CursorWidth, m + d, x_ + CursorWidth + d, m);
174 void update(int x, int y, int h, bool l_shape,
175 bool rtl, bool completable)
177 color_ = guiApp->colorCache().get(Color_cursor);
180 completable_ = completable;
183 // extension to left and right
187 // RTL/LTR indication
195 // completion triangle
198 l = max(l, TabIndicatorWidth);
200 r = max(r, TabIndicatorWidth);
203 // compute overall rectangle
204 rect_ = QRect(x - l, y, CursorWidth + r + l, h);
207 void show(bool set_show = true) { show_ = set_show; }
208 void hide() { show_ = false; }
210 QRect const & rect() { return rect_; }
213 /// cursor is in RTL or LTR text
215 /// indication for RTL or LTR
217 /// triangle to show that a completion is available
223 /// rectangle, possibly with l_shape and completion triangle
225 /// x position (were the vertical line is drawn)
230 // This is a 'heartbeat' generating synthetic mouse move events when the
231 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
232 SyntheticMouseEvent::SyntheticMouseEvent()
233 : timeout(200), restart_timeout(true),
234 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
238 GuiWorkArea::GuiWorkArea(QWidget *)
239 : buffer_view_(0), lyx_view_(0),
240 cursor_visible_(false),
241 need_resize_(false), schedule_redraw_(false),
242 preedit_lines_(1), completer_(new GuiCompleter(this))
247 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
248 : buffer_view_(0), lyx_view_(0),
249 cursor_visible_(false),
250 need_resize_(false), schedule_redraw_(false),
251 preedit_lines_(1), completer_(new GuiCompleter(this))
259 void GuiWorkArea::init()
262 connect(&cursor_timeout_, SIGNAL(timeout()),
263 this, SLOT(toggleCursor()));
265 int const time = QApplication::cursorFlashTime() / 2;
267 cursor_timeout_.setInterval(time);
268 cursor_timeout_.start();
270 // let's initialize this just to be safe
271 cursor_timeout_.setInterval(500);
274 screen_ = QPixmap(viewport()->width(), viewport()->height());
275 cursor_ = new frontend::CursorWidget();
278 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
279 setAcceptDrops(true);
280 setMouseTracking(true);
281 setMinimumSize(100, 70);
282 setFrameStyle(QFrame::NoFrame);
285 viewport()->setAutoFillBackground(false);
286 // We don't need double-buffering nor SystemBackground on
287 // the viewport because we have our own backing pixmap.
288 viewport()->setAttribute(Qt::WA_NoSystemBackground);
290 setFocusPolicy(Qt::StrongFocus);
292 viewport()->setCursor(Qt::IBeamCursor);
294 synthetic_mouse_event_.timeout.timeout.connect(
295 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
298 // Initialize the vertical Scroll Bar
299 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
300 this, SLOT(scrollTo(int)));
302 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
303 << " viewport height: " << viewport()->height());
305 // Enables input methods for asian languages.
306 // Must be set when creating custom text editing widgets.
307 setAttribute(Qt::WA_InputMethodEnabled, true);
309 dialog_mode_ = false;
313 GuiWorkArea::~GuiWorkArea()
315 buffer_view_->buffer().workAreaManager().remove(this);
318 // Completer has a QObject parent and is thus automatically destroyed.
319 // delete completer_;
323 void GuiWorkArea::setGuiView(GuiView & gv)
329 void GuiWorkArea::setBuffer(Buffer & buffer)
332 buffer_view_ = new BufferView(buffer),
333 buffer.workAreaManager().add(this);
335 // HACK: Prevents an additional redraw when the scrollbar pops up
336 // which regularily happens on documents with more than one page.
337 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
338 // Since we have no geometry information yet, we assume that
339 // a document needs a scrollbar if there is more then four
340 // paragraph in the outermost text.
341 if (buffer.text().paragraphs().size() > 4)
342 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
343 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
347 void GuiWorkArea::fixVerticalScrollBar()
350 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
354 void GuiWorkArea::close()
356 lyx_view_->removeWorkArea(this);
360 void GuiWorkArea::setFullScreen(bool full_screen)
362 buffer_view_->setFullScreen(full_screen);
364 setFrameStyle(QFrame::NoFrame);
365 if (lyxrc.full_screen_scrollbar)
366 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
369 setFrameStyle(QFrame::NoFrame);
371 setFrameStyle(QFrame::Box);
373 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
378 BufferView & GuiWorkArea::bufferView()
380 return *buffer_view_;
384 BufferView const & GuiWorkArea::bufferView() const
386 return *buffer_view_;
390 void GuiWorkArea::stopBlinkingCursor()
392 cursor_timeout_.stop();
397 void GuiWorkArea::startBlinkingCursor()
400 //we're not supposed to cache this value.
401 int const time = QApplication::cursorFlashTime() / 2;
404 cursor_timeout_.setInterval(time);
405 cursor_timeout_.start();
409 void GuiWorkArea::redraw()
412 // No need to redraw in this case.
415 // No need to do anything if this is the current view. The BufferView
416 // metrics are already up to date.
417 if (lyx_view_ != guiApp->currentView()
418 || lyx_view_->currentWorkArea() != this) {
419 // FIXME: it would be nice to optimize for the off-screen case.
420 buffer_view_->updateMetrics();
421 buffer_view_->cursor().fixIfBroken();
424 // update cursor position, because otherwise it has to wait until
425 // the blinking interval is over
426 if (cursor_visible_) {
431 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
433 update(0, 0, viewport()->width(), viewport()->height());
435 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
436 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
438 lyx_view_->updateStatusBar();
440 if (lyxerr.debugging(Debug::WORKAREA))
441 buffer_view_->coordCache().dump();
445 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
447 if (lyx_view_->isFullScreen() && lyx_view_->menuBar()->isVisible()) {
448 // FIXME HACK: we should not have to do this here. See related comment
449 // in GuiView::event() (QEvent::ShortcutOverride)
450 lyx_view_->menuBar()->hide();
453 // In order to avoid bad surprise in the middle of an operation,
454 // we better stop the blinking cursor...
455 // the cursor gets restarted in GuiView::restartCursor()
456 stopBlinkingCursor();
458 theLyXFunc().setLyXView(lyx_view_);
459 theLyXFunc().processKeySym(key, mod);
463 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
466 if (cmd0.action == LFUN_FILE_OPEN) {
467 lyx_view_->dispatch(cmd0);
471 theLyXFunc().setLyXView(lyx_view_);
475 if (cmd0.action == LFUN_MOUSE_PRESS) {
476 if (mod == ShiftModifier)
477 cmd = FuncRequest(cmd0, "region-select");
478 else if (mod == ControlModifier)
479 cmd = FuncRequest(cmd0, "paragraph-select");
486 bool const notJustMovingTheMouse =
487 cmd.action != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
489 // In order to avoid bad surprise in the middle of an operation, we better stop
490 // the blinking cursor.
491 if (notJustMovingTheMouse)
492 stopBlinkingCursor();
494 buffer_view_->mouseEventDispatch(cmd);
496 // Skip these when selecting
497 if (cmd.action != LFUN_MOUSE_MOTION) {
498 completer_->updateVisibility(false, false);
499 lyx_view_->updateDialogs();
500 lyx_view_->updateStatusBar();
503 // GUI tweaks except with mouse motion with no button pressed.
504 if (notJustMovingTheMouse) {
505 // Slight hack: this is only called currently when we
506 // clicked somewhere, so we force through the display
507 // of the new status here.
508 lyx_view_->clearMessage();
510 // Show the cursor immediately after any operation
511 startBlinkingCursor();
516 void GuiWorkArea::resizeBufferView()
518 // WARNING: Please don't put any code that will trigger a repaint here!
519 // We are already inside a paint event.
520 lyx_view_->setBusy(true);
523 buffer_view_->cursorPosAndHeight(p, h);
524 bool const cursor_in_view = buffer_view_->cursorInView(p, h);
525 buffer_view_->resize(viewport()->width(), viewport()->height());
527 buffer_view_->scrollToCursor();
530 // Update scrollbars which might have changed due different
531 // BufferView dimension. This is especially important when the
532 // BufferView goes from zero-size to the real-size for the first time,
533 // as the scrollbar paramters are then set for the first time.
536 lyx_view_->updateLayoutList();
537 lyx_view_->setBusy(false);
538 need_resize_ = false;
542 void GuiWorkArea::showCursor()
548 bool l_shape = false;
549 Font const & realfont = buffer_view_->cursor().real_current_font;
550 BufferParams const & bp = buffer_view_->buffer().params();
551 bool const samelang = realfont.language() == bp.language;
552 bool const isrtl = realfont.isVisibleRightToLeft();
554 if (!samelang || isrtl != bp.language->rightToLeft())
557 // The ERT language hack needs fixing up
558 if (realfont.language() == latex_language)
563 buffer_view_->cursorPosAndHeight(p, h);
564 // show cursor on screen
565 Cursor & cur = buffer_view_->cursor();
566 bool completable = cur.inset().showCompletionCursor()
567 && completer_->completionAvailable()
568 && !completer_->popupVisible()
569 && !completer_->inlineVisible();
570 if (buffer_view_->cursorInView(p, h)) {
571 cursor_visible_ = true;
572 showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
577 void GuiWorkArea::hideCursor()
579 if (!cursor_visible_)
582 cursor_visible_ = false;
587 void GuiWorkArea::toggleCursor()
596 void GuiWorkArea::updateScrollbar()
598 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
599 // WARNING: don't touch at the scrollbar value like this:
600 // verticalScrollBar()->setValue(scroll_.position);
601 // because this would cause a recursive signal/slot calling with
602 // GuiWorkArea::scrollTo
603 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
604 verticalScrollBar()->setPageStep(scroll_.page_step);
605 verticalScrollBar()->setSingleStep(scroll_.single_step);
606 verticalScrollBar()->setSliderPosition(scroll_.position);
610 void GuiWorkArea::scrollTo(int value)
612 stopBlinkingCursor();
613 buffer_view_->scrollDocView(value);
615 if (lyxrc.cursor_follows_scrollbar) {
616 buffer_view_->setCursorFromScrollbar();
617 lyx_view_->updateLayoutList();
619 // Show the cursor immediately after any operation.
620 startBlinkingCursor();
621 QApplication::syncX();
625 bool GuiWorkArea::event(QEvent * e)
628 case QEvent::ToolTip: {
629 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
630 if (lyxrc.use_tooltip) {
631 QPoint pos = helpEvent->pos();
632 if (pos.x() < viewport()->width()) {
633 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
634 QToolTip::showText(helpEvent->globalPos(), s);
637 QToolTip::hideText();
639 // Don't forget to accept the event!
644 case QEvent::ShortcutOverride: {
645 // We catch this event in order to catch the Tab or Shift+Tab key press
646 // which are otherwise reserved to focus switching between controls
648 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
649 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
650 || ke->modifiers() & Qt::ControlModifier)
651 return QAbstractScrollArea::event(e);
657 return QAbstractScrollArea::event(e);
663 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
665 QPoint pos = e->pos();
666 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
668 QAbstractScrollArea::contextMenuEvent(e);
671 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
673 QAbstractScrollArea::contextMenuEvent(e);
676 // Position the menu to the right.
677 // FIXME: menu position should be different for RTL text.
678 menu->exec(e->globalPos());
683 void GuiWorkArea::focusInEvent(QFocusEvent * e)
686 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << std::endl);
687 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
689 old_gwa->stopBlinkingCursor();
690 lyx_view_->setCurrentWorkArea(this);
693 if (lyx_view_->currentWorkArea() != this)
694 lyx_view_->setCurrentWorkArea(this);
696 startBlinkingCursor();
697 QAbstractScrollArea::focusInEvent(e);
701 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
703 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << std::endl);
704 stopBlinkingCursor();
705 QAbstractScrollArea::focusOutEvent(e);
709 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
711 if (dc_event_.active && dc_event_ == *e) {
712 dc_event_.active = false;
713 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
714 q_button_state(e->button()));
720 inputContext()->reset();
722 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
723 q_button_state(e->button()));
724 dispatch(cmd, q_key_state(e->modifiers()));
729 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
731 if (synthetic_mouse_event_.timeout.running())
732 synthetic_mouse_event_.timeout.stop();
734 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
735 q_button_state(e->button()));
741 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
743 // we kill the triple click if we move
744 doubleClickTimeout();
745 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
746 q_motion_state(e->buttons()));
750 // If we're above or below the work area...
751 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
752 // Make sure only a synthetic event can cause a page scroll,
753 // so they come at a steady rate:
755 // _Force_ a scroll up:
758 cmd.y = viewport()->height();
759 // Store the event, to be handled when the timeout expires.
760 synthetic_mouse_event_.cmd = cmd;
762 if (synthetic_mouse_event_.timeout.running())
763 // Discard the event. Note that it _may_ be handled
764 // when the timeout expires if
765 // synthetic_mouse_event_.cmd has not been overwritten.
766 // Ie, when the timeout expires, we handle the
767 // most recent event but discard all others that
768 // occurred after the one used to start the timeout
769 // in the first place.
772 synthetic_mouse_event_.restart_timeout = true;
773 synthetic_mouse_event_.timeout.start();
774 // Fall through to handle this event...
776 } else if (synthetic_mouse_event_.timeout.running()) {
777 // Store the event, to be possibly handled when the timeout
779 // Once the timeout has expired, normal control is returned
780 // to mouseMoveEvent (restart_timeout = false).
781 // This results in a much smoother 'feel' when moving the
782 // mouse back into the work area.
783 synthetic_mouse_event_.cmd = cmd;
784 synthetic_mouse_event_.restart_timeout = false;
788 // Has anything changed on-screen since the last QMouseEvent
790 double const scrollbar_value = verticalScrollBar()->value();
791 if (e->x() == synthetic_mouse_event_.x_old
792 && e->y() == synthetic_mouse_event_.y_old
793 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
794 // Nothing changed on-screen since the last QMouseEvent.
798 // Yes something has changed. Store the params used to check this.
799 synthetic_mouse_event_.x_old = e->x();
800 synthetic_mouse_event_.y_old = e->y();
801 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
803 // ... and dispatch the event to the LyX core.
808 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
810 // Wheel rotation by one notch results in a delta() of 120 (see
811 // documentation of QWheelEvent)
812 int const delta = ev->delta() / 120;
813 if (ev->modifiers() & Qt::ControlModifier) {
814 docstring arg = convert<docstring>(5 * delta);
815 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
819 // Take into account the desktop wide settings.
820 int const lines = qApp->wheelScrollLines();
821 int const page_step = verticalScrollBar()->pageStep();
822 // Test if the wheel mouse is set to one screen at a time.
823 int scroll_value = lines > page_step
824 ? page_step : lines * verticalScrollBar()->singleStep();
826 // Take into account the rotation.
827 scroll_value *= delta;
829 // Take into account user preference.
830 scroll_value *= lyxrc.mouse_wheel_speed;
831 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
832 << " delta = " << delta << " scroll_value = " << scroll_value
833 << " page_step = " << page_step);
835 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
841 void GuiWorkArea::generateSyntheticMouseEvent()
843 // Set things off to generate the _next_ 'pseudo' event.
844 if (synthetic_mouse_event_.restart_timeout)
845 synthetic_mouse_event_.timeout.start();
847 // Has anything changed on-screen since the last timeout signal
849 double const scrollbar_value = verticalScrollBar()->value();
850 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
851 // Yes it has. Store the params used to check this.
852 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
854 // ... and dispatch the event to the LyX core.
855 dispatch(synthetic_mouse_event_.cmd);
860 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
862 // Do not process here some keys if dialog_mode_ is set
864 && (ev->modifiers() == Qt::NoModifier
865 || ev->modifiers() == Qt::ShiftModifier)
866 && (ev->key() == Qt::Key_Escape
867 || ev->key() == Qt::Key_Enter
868 || ev->key() == Qt::Key_Return)
874 // intercept some keys if completion popup is visible
875 if (completer_->popupVisible()) {
879 completer_->activate();
885 // do nothing if there are other events
886 // (the auto repeated events come too fast)
887 // \todo FIXME: remove hard coded Qt keys, process the key binding
889 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
890 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
891 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
897 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
898 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
901 setKeySymbol(&sym, ev);
902 processKeySym(sym, q_key_state(ev->modifiers()));
907 void GuiWorkArea::doubleClickTimeout()
909 dc_event_.active = false;
913 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
915 dc_event_ = DoubleClick(ev);
916 QTimer::singleShot(QApplication::doubleClickInterval(), this,
917 SLOT(doubleClickTimeout()));
918 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
920 q_button_state(ev->button()));
926 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
928 QAbstractScrollArea::resizeEvent(ev);
934 void GuiWorkArea::update(int x, int y, int w, int h)
936 viewport()->repaint(x, y, w, h);
940 void GuiWorkArea::paintEvent(QPaintEvent * ev)
942 QRect const rc = ev->rect();
943 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
944 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
947 screen_ = QPixmap(viewport()->width(), viewport()->height());
953 QPainter pain(viewport());
954 pain.drawPixmap(rc, screen_, rc);
960 void GuiWorkArea::updateScreen()
962 GuiPainter pain(&screen_);
963 buffer_view_->draw(pain);
967 void GuiWorkArea::showCursor(int x, int y, int h,
968 bool l_shape, bool rtl, bool completable)
970 if (schedule_redraw_) {
971 // This happens when a graphic conversion is finished. As we don't know
972 // the size of the new graphics, it's better the update everything.
973 // We can't use redraw() here because this would trigger a infinite
974 // recursive loop with showCursor().
975 buffer_view_->resize(viewport()->width(), viewport()->height());
978 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
979 schedule_redraw_ = false;
980 // Show the cursor immediately after the update.
986 cursor_->update(x, y, h, l_shape, rtl, completable);
988 viewport()->update(cursor_->rect());
992 void GuiWorkArea::removeCursor()
995 //if (!qApp->focusWidget())
996 viewport()->update(cursor_->rect());
1000 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1002 QString const & commit_string = e->commitString();
1003 docstring const & preedit_string
1004 = qstring_to_ucs4(e->preeditString());
1006 if (!commit_string.isEmpty()) {
1008 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1009 << " commitString: " << e->commitString());
1013 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1014 for (int i = 0; i != commit_string.size(); ++i) {
1015 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1020 // Hide the cursor during the kana-kanji transformation.
1021 if (preedit_string.empty())
1022 startBlinkingCursor();
1024 stopBlinkingCursor();
1026 // last_width : for checking if last preedit string was/wasn't empty.
1027 static bool last_width = false;
1028 if (!last_width && preedit_string.empty()) {
1029 // if last_width is last length of preedit string.
1034 GuiPainter pain(&screen_);
1035 buffer_view_->updateMetrics();
1036 buffer_view_->draw(pain);
1037 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1038 FontMetrics const & fm = theFontMetrics(font);
1039 int height = fm.maxHeight();
1040 int cur_x = cursor_->rect().left();
1041 int cur_y = cursor_->rect().bottom();
1043 // redraw area of preedit string.
1044 update(0, cur_y - height, viewport()->width(),
1045 (height + 1) * preedit_lines_);
1047 if (preedit_string.empty()) {
1055 // att : stores an IM attribute.
1056 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1058 // get attributes of input method cursor.
1059 // cursor_pos : cursor position in preedit string.
1060 size_t cursor_pos = 0;
1061 bool cursor_is_visible = false;
1062 for (int i = 0; i != att.size(); ++i) {
1063 if (att.at(i).type == QInputMethodEvent::Cursor) {
1064 cursor_pos = att.at(i).start;
1065 cursor_is_visible = att.at(i).length != 0;
1070 size_t preedit_length = preedit_string.length();
1072 // get position of selection in input method.
1073 // FIXME: isn't there a way to do this simplier?
1074 // rStart : cursor position in selected string in IM.
1076 // rLength : selected string length in IM.
1078 if (cursor_pos < preedit_length) {
1079 for (int i = 0; i != att.size(); ++i) {
1080 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1081 if (att.at(i).start <= int(cursor_pos)
1082 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1083 rStart = att.at(i).start;
1084 rLength = att.at(i).length;
1085 if (!cursor_is_visible)
1086 cursor_pos += rLength;
1093 rStart = cursor_pos;
1097 int const right_margin = buffer_view_->rightMargin();
1098 Painter::preedit_style ps;
1099 // Most often there would be only one line:
1101 for (size_t pos = 0; pos != preedit_length; ++pos) {
1102 char_type const typed_char = preedit_string[pos];
1103 // reset preedit string style
1104 ps = Painter::preedit_default;
1106 // if we reached the right extremity of the screen, go to next line.
1107 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1108 cur_x = right_margin;
1109 cur_y += height + 1;
1112 // preedit strings are displayed with dashed underline
1113 // and partial strings are displayed white on black indicating
1114 // that we are in selecting mode in the input method.
1115 // FIXME: rLength == preedit_length is not a changing condition
1116 // FIXME: should be put out of the loop.
1118 && pos < rStart + rLength
1119 && !(cursor_pos < rLength && rLength == preedit_length))
1120 ps = Painter::preedit_selecting;
1122 if (pos == cursor_pos
1123 && (cursor_pos < rLength && rLength == preedit_length))
1124 ps = Painter::preedit_cursor;
1126 // draw one character and update cur_x.
1127 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1130 // update the preedit string screen area.
1131 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1132 (height + 1) * preedit_lines_);
1134 // Don't forget to accept the event!
1139 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1141 QRect cur_r(0, 0, 0, 0);
1143 // this is the CJK-specific composition window position.
1144 case Qt::ImMicroFocus:
1145 cur_r = cursor_->rect();
1146 if (preedit_lines_ != 1)
1148 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1149 // return lower right of cursor in LyX.
1152 return QWidget::inputMethodQuery(query);
1157 void GuiWorkArea::updateWindowTitle()
1159 docstring maximize_title;
1160 docstring minimize_title;
1162 Buffer & buf = buffer_view_->buffer();
1163 FileName const fileName = buf.fileName();
1164 if (!fileName.empty()) {
1165 maximize_title = fileName.displayName(30);
1166 minimize_title = from_utf8(fileName.onlyFileName());
1167 if (buf.lyxvc().inUse()) {
1168 if (buf.lyxvc().locker().empty())
1169 maximize_title += _(" (version control)");
1171 maximize_title += _(" (version control, locking)");
1173 if (!buf.isClean()) {
1174 maximize_title += _(" (changed)");
1175 minimize_title += char_type('*');
1177 if (buf.isReadonly())
1178 maximize_title += _(" (read only)");
1181 QString title = windowTitle();
1182 QString new_title = toqstr(maximize_title);
1183 if (title == new_title)
1186 QWidget::setWindowTitle(new_title);
1187 QWidget::setWindowIconText(toqstr(minimize_title));
1192 void GuiWorkArea::setReadOnly(bool)
1194 updateWindowTitle();
1195 if (this == lyx_view_->currentWorkArea())
1196 lyx_view_->updateDialogs();
1200 bool GuiWorkArea::isFullScreen()
1202 return lyx_view_ && lyx_view_->isFullScreen();
1206 ////////////////////////////////////////////////////////////////////
1210 ////////////////////////////////////////////////////////////////////
1213 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1215 buffer_ = theBufferList().newBuffer(
1216 support::FileName::tempName().absFilename() + "_embedded.internal");
1217 buffer_->setUnnamed(true);
1218 buffer_->setFullyLoaded(true);
1219 setBuffer(*buffer_);
1220 setDialogMode(true);
1224 EmbeddedWorkArea::~EmbeddedWorkArea()
1226 // No need to destroy buffer and bufferview here, because it is done
1227 // in theBuffeerList() destruction loop at application exit
1231 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1234 GuiWorkArea::closeEvent(ev);
1238 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1241 GuiWorkArea::hideEvent(ev);
1245 void EmbeddedWorkArea::disable()
1247 stopBlinkingCursor();
1248 if (view().currentWorkArea() != this)
1250 LASSERT(view().currentMainWorkArea(), /* */);
1251 view().setCurrentWorkArea(view().currentMainWorkArea());
1254 ////////////////////////////////////////////////////////////////////
1258 ////////////////////////////////////////////////////////////////////
1261 class NoTabFrameMacStyle : public QMacStyle {
1264 QRect subElementRect(SubElement element, const QStyleOption * option,
1265 const QWidget * widget = 0) const
1267 QRect rect = QMacStyle::subElementRect(element, option, widget);
1268 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1270 // The Qt Mac style puts the contents into a 3 pixel wide box
1271 // which looks very ugly and not like other Mac applications.
1272 // Hence we remove this here, and moreover the 16 pixel round
1273 // frame above if the tab bar is hidden.
1274 if (element == QStyle::SE_TabWidgetTabContents) {
1275 rect.adjust(- rect.left(), 0, rect.left(), 0);
1284 NoTabFrameMacStyle noTabFrameMacStyle;
1288 TabWorkArea::TabWorkArea(QWidget * parent)
1289 : QTabWidget(parent), clicked_tab_(-1)
1292 setStyle(&noTabFrameMacStyle);
1295 QPalette pal = palette();
1296 pal.setColor(QPalette::Active, QPalette::Button,
1297 pal.color(QPalette::Active, QPalette::Window));
1298 pal.setColor(QPalette::Disabled, QPalette::Button,
1299 pal.color(QPalette::Disabled, QPalette::Window));
1300 pal.setColor(QPalette::Inactive, QPalette::Button,
1301 pal.color(QPalette::Inactive, QPalette::Window));
1303 QObject::connect(this, SIGNAL(currentChanged(int)),
1304 this, SLOT(on_currentTabChanged(int)));
1306 closeBufferButton = new QToolButton(this);
1307 closeBufferButton->setPalette(pal);
1308 // FIXME: rename the icon to closebuffer.png
1309 closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1310 closeBufferButton->setText("Close File");
1311 closeBufferButton->setAutoRaise(true);
1312 closeBufferButton->setCursor(Qt::ArrowCursor);
1313 closeBufferButton->setToolTip(qt_("Close File"));
1314 closeBufferButton->setEnabled(true);
1315 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1316 this, SLOT(closeCurrentBuffer()));
1317 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1319 // setup drag'n'drop
1320 QTabBar* tb = new DragTabBar;
1321 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1322 this, SLOT(moveTab(int, int)));
1323 tb->setElideMode(Qt::ElideNone);
1326 // make us responsible for the context menu of the tabbar
1327 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1328 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1329 this, SLOT(showContextMenu(const QPoint &)));
1331 setUsesScrollButtons(true);
1335 void TabWorkArea::setFullScreen(bool full_screen)
1337 for (int i = 0; i != count(); ++i) {
1338 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1339 wa->setFullScreen(full_screen);
1342 if (lyxrc.full_screen_tabbar)
1343 showBar(!full_screen && count()>1);
1347 void TabWorkArea::showBar(bool show)
1349 tabBar()->setEnabled(show);
1350 tabBar()->setVisible(show);
1351 closeBufferButton->setVisible(show);
1355 GuiWorkArea * TabWorkArea::currentWorkArea()
1360 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1366 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1368 for (int i = 0; i != count(); ++i) {
1369 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1370 LASSERT(wa, return 0);
1371 if (&wa->bufferView().buffer() == &buffer)
1378 void TabWorkArea::closeAll()
1381 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1389 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1391 LASSERT(work_area, /**/);
1392 int index = indexOf(work_area);
1396 if (index == currentIndex())
1397 // Make sure the work area is up to date.
1398 on_currentTabChanged(index);
1400 // Switch to the work area.
1401 setCurrentIndex(index);
1402 work_area->setFocus();
1408 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1410 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1411 wa->setUpdatesEnabled(false);
1412 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1413 // when hiding it again below).
1414 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1415 showBar(count() > 0);
1416 addTab(wa, wa->windowTitle());
1417 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1418 this, SLOT(updateTabTexts()));
1419 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1420 setFullScreen(true);
1422 // Hide tabbar if there's only one tab.
1423 showBar(count() > 1);
1431 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1433 LASSERT(work_area, return false);
1434 int index = indexOf(work_area);
1438 work_area->setUpdatesEnabled(false);
1443 // make sure the next work area is enabled.
1444 currentWidget()->setUpdatesEnabled(true);
1445 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1446 setFullScreen(true);
1448 // Hide tabbar if there's only one tab.
1449 showBar(count() > 1);
1451 lastWorkAreaRemoved();
1460 void TabWorkArea::on_currentTabChanged(int i)
1462 // returns e.g. on application destruction
1465 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1466 LASSERT(wa, return);
1467 BufferView & bv = wa->bufferView();
1468 bv.cursor().fixIfBroken();
1470 wa->setUpdatesEnabled(true);
1474 currentWorkAreaChanged(wa);
1476 LYXERR(Debug::GUI, "currentTabChanged " << i
1477 << "File" << bv.buffer().absFileName());
1481 void TabWorkArea::closeCurrentBuffer()
1483 if (clicked_tab_ != -1)
1484 setCurrentIndex(clicked_tab_);
1486 // Before dispatching the LFUN we should be sure this
1487 // is the current workarea.
1488 currentWorkAreaChanged(currentWorkArea());
1490 lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1494 void TabWorkArea::closeCurrentTab()
1496 if (clicked_tab_ == -1)
1497 removeWorkArea(currentWorkArea());
1499 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1508 /// make vector happy
1511 DisplayPath(int tab, FileName const & filename)
1514 filename_ = toqstr(filename.onlyFileNameWithoutExt());
1515 postfix_ = toqstr(filename.absoluteFilePath()).
1516 split("/", QString::SkipEmptyParts);
1517 postfix_.pop_back();
1518 abs_ = toqstr(filename.absoluteFilePath());
1519 dottedPrefix_ = false;
1522 /// Absolute path for debugging.
1527 /// Add the first segment from the postfix or three dots to the prefix.
1528 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1529 /// when really needed.
1530 void shiftPathSegment(bool dotted)
1532 if (postfix_.count() <= 0)
1536 if (dottedPrefix_ && !prefix_.isEmpty())
1538 prefix_ += postfix_.front() + "/";
1540 dottedPrefix_ = dotted && !prefix_.isEmpty();
1541 postfix_.pop_front();
1544 QString displayString() const
1546 if (prefix_.isEmpty())
1549 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1550 return prefix_ + (dots ? ".../" : "") + filename_;
1553 QString forecastPathString() const
1555 if (postfix_.count() == 0)
1556 return displayString();
1559 + (dottedPrefix_ ? ".../" : "")
1560 + postfix_.front() + "/";
1563 bool final() const { return postfix_.empty(); }
1565 int tab() const { return tab_; }
1571 QStringList postfix_;
1584 bool operator<(DisplayPath const & a, DisplayPath const & b)
1586 return a.displayString() < b.displayString();
1590 bool operator==(DisplayPath const & a, DisplayPath const & b)
1592 return a.displayString() == b.displayString();
1596 void TabWorkArea::updateTabTexts()
1601 std::list<DisplayPath> paths;
1602 typedef std::list<DisplayPath>::iterator It;
1604 // collect full names first: path into postfix, empty prefix and
1605 // filename without extension
1606 for (size_t i = 0; i < n; ++i) {
1607 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(i));
1608 FileName const fn = i_wa->bufferView().buffer().fileName();
1609 paths.push_back(DisplayPath(i, fn));
1612 // go through path segments and see if it helps to make the path more unique
1613 bool somethingChanged = true;
1614 bool allFinal = false;
1615 while (somethingChanged && !allFinal) {
1616 // adding path segments changes order
1619 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1620 somethingChanged = false;
1623 // find segments which are not unique (i.e. non-atomic)
1624 It it = paths.begin();
1626 QString segString = it->displayString();
1627 for (; it != paths.end(); ++it) {
1628 // look to the next item
1633 allFinal = allFinal && it->final();
1635 LYXERR(Debug::GUI, "it = " << it->abs()
1636 << " => " << it->displayString());
1638 // still the same segment?
1640 if ((next != paths.end()
1641 && (nextString = next->displayString()) == segString))
1643 LYXERR(Debug::GUI, "segment ended");
1645 // only a trivial one with one element?
1646 if (it == segStart) {
1647 // start new segment
1649 segString = nextString;
1653 // we found a non-atomic segment segStart <= sit <= it < next.
1654 // Shift path segments and hope for the best
1655 // that it makes the path more unique.
1656 somethingChanged = true;
1658 QString dspString = sit->forecastPathString();
1659 LYXERR(Debug::GUI, "first forecast found for "
1660 << sit->abs() << " => " << dspString);
1662 bool moreUnique = false;
1663 for (; sit != next; ++sit) {
1664 if (sit->forecastPathString() != dspString) {
1665 LYXERR(Debug::GUI, "different forecast found for "
1666 << sit->abs() << " => " << sit->forecastPathString());
1670 LYXERR(Debug::GUI, "same forecast found for "
1671 << sit->abs() << " => " << dspString);
1674 // if the path segment helped, add it. Otherwise add dots
1675 bool dots = !moreUnique;
1676 LYXERR(Debug::GUI, "using dots = " << dots);
1677 for (sit = segStart; sit != next; ++sit) {
1678 sit->shiftPathSegment(dots);
1679 LYXERR(Debug::GUI, "shifting "
1680 << sit->abs() << " => " << sit->displayString());
1683 // start new segment
1685 segString = nextString;
1689 // set new tab titles
1690 for (It it = paths.begin(); it != paths.end(); ++it) {
1691 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(it->tab()));
1692 Buffer & buf = i_wa->bufferView().buffer();
1693 if (!buf.fileName().empty() && !buf.isClean())
1694 setTabText(it->tab(), it->displayString() + "*");
1696 setTabText(it->tab(), it->displayString());
1701 void TabWorkArea::showContextMenu(const QPoint & pos)
1704 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1705 if (clicked_tab_ == -1)
1710 popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
1711 qt_("Hide tab"), this, SLOT(closeCurrentTab()));
1712 popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
1713 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1714 popup.exec(tabBar()->mapToGlobal(pos));
1720 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1722 QWidget * w = widget(fromIndex);
1723 QIcon icon = tabIcon(fromIndex);
1724 QString text = tabText(fromIndex);
1726 setCurrentIndex(fromIndex);
1727 removeTab(fromIndex);
1728 insertTab(toIndex, w, icon, text);
1729 setCurrentIndex(toIndex);
1733 DragTabBar::DragTabBar(QWidget* parent)
1736 setAcceptDrops(true);
1740 #if QT_VERSION < 0x040300
1741 int DragTabBar::tabAt(QPoint const & position) const
1743 const int max = count();
1744 for (int i = 0; i < max; ++i) {
1745 if (tabRect(i).contains(position))
1753 void DragTabBar::mousePressEvent(QMouseEvent * event)
1755 if (event->button() == Qt::LeftButton)
1756 dragStartPos_ = event->pos();
1757 QTabBar::mousePressEvent(event);
1761 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1763 // If the left button isn't pressed anymore then return
1764 if (!(event->buttons() & Qt::LeftButton))
1767 // If the distance is too small then return
1768 if ((event->pos() - dragStartPos_).manhattanLength()
1769 < QApplication::startDragDistance())
1772 // did we hit something after all?
1773 int tab = tabAt(dragStartPos_);
1777 // simulate button release to remove highlight from button
1778 int i = currentIndex();
1779 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1780 event->button(), event->buttons(), 0);
1781 QTabBar::mouseReleaseEvent(&me);
1785 QDrag * drag = new QDrag(this);
1786 QMimeData * mimeData = new QMimeData;
1787 // a crude way to distinguish tab-reodering drops from other ones
1788 mimeData->setData("action", "tab-reordering") ;
1789 drag->setMimeData(mimeData);
1791 #if QT_VERSION >= 0x040300
1792 // get tab pixmap as cursor
1793 QRect r = tabRect(tab);
1794 QPixmap pixmap(r.size());
1795 render(&pixmap, - r.topLeft());
1796 drag->setPixmap(pixmap);
1799 drag->start(Qt::MoveAction);
1805 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1807 // Only accept if it's an tab-reordering request
1808 QMimeData const * m = event->mimeData();
1809 QStringList formats = m->formats();
1810 if (formats.contains("action")
1811 && m->data("action") == "tab-reordering")
1812 event->acceptProposedAction();
1816 void DragTabBar::dropEvent(QDropEvent * event)
1818 int fromIndex = tabAt(dragStartPos_);
1819 int toIndex = tabAt(event->pos());
1821 // Tell interested objects that
1822 if (fromIndex != toIndex)
1823 tabMoveRequested(fromIndex, toIndex);
1824 event->acceptProposedAction();
1828 } // namespace frontend
1831 #include "moc_GuiWorkArea.cpp"