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/debug.h"
47 #include "support/gettext.h"
48 #include "support/FileName.h"
50 #include "frontends/Application.h"
51 #include "frontends/FontMetrics.h"
52 #include "frontends/WorkAreaManager.h"
54 #include <QContextMenuEvent>
55 #include <QInputContext>
60 #include <QMainWindow>
64 #include <QPixmapCache>
67 #include <QToolButton>
71 #include <boost/bind.hpp>
77 extern "C" int XEventsQueued(Display *display, int mode);
81 int const CursorWidth = 2;
83 int const CursorWidth = 1;
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;
137 void draw(QPainter & painter)
139 if (!show_ || !rect_.isValid())
143 int l = x_ - rect_.left();
144 int r = rect_.right() - x_;
145 int bot = rect_.bottom();
147 // draw vertica linel
148 painter.fillRect(x_, y, CursorWidth, rect_.height(), color_);
150 // draw RTL/LTR indication
151 painter.setPen(color_);
154 painter.drawLine(x_, bot, x_ - l, bot);
156 painter.drawLine(x_, bot, x_ + CursorWidth + r, bot);
159 // draw completion triangle
161 int m = y + rect_.height() / 2;
162 int d = TabIndicatorWidth - 1;
164 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
165 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
167 painter.drawLine(x_ + CursorWidth, m - d, x_ + CursorWidth + d, m);
168 painter.drawLine(x_ + CursorWidth, m + d, x_ + CursorWidth + d, m);
173 void update(int x, int y, int h, bool l_shape,
174 bool rtl, bool completable)
176 color_ = guiApp->colorCache().get(Color_cursor);
179 completable_ = completable;
182 // extension to left and right
186 // RTL/LTR indication
194 // completion triangle
197 l = max(l, TabIndicatorWidth);
199 r = max(r, TabIndicatorWidth);
202 // compute overall rectangle
203 rect_ = QRect(x - l, y, CursorWidth + r + l, h);
206 void show(bool set_show = true) { show_ = set_show; }
207 void hide() { show_ = false; }
209 QRect const & rect() { return rect_; }
212 /// cursor is in RTL or LTR text
214 /// indication for RTL or LTR
216 /// triangle to show that a completion is available
222 /// rectangle, possibly with l_shape and completion triangle
224 /// x position (were the vertical line is drawn)
229 // This is a 'heartbeat' generating synthetic mouse move events when the
230 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
231 SyntheticMouseEvent::SyntheticMouseEvent()
232 : timeout(200), restart_timeout(true),
233 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
237 GuiWorkArea::GuiWorkArea(QWidget *)
238 : buffer_view_(0), lyx_view_(0),
239 cursor_visible_(false),
240 need_resize_(false), schedule_redraw_(false),
241 preedit_lines_(1), completer_(new GuiCompleter(this))
246 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
247 : buffer_view_(0), lyx_view_(0),
248 cursor_visible_(false),
249 need_resize_(false), schedule_redraw_(false),
250 preedit_lines_(1), completer_(new GuiCompleter(this))
258 void GuiWorkArea::init()
261 connect(&cursor_timeout_, SIGNAL(timeout()),
262 this, SLOT(toggleCursor()));
264 int const time = QApplication::cursorFlashTime() / 2;
266 cursor_timeout_.setInterval(time);
267 cursor_timeout_.start();
269 // let's initialize this just to be safe
270 cursor_timeout_.setInterval(500);
273 screen_ = QPixmap(viewport()->width(), viewport()->height());
274 cursor_ = new frontend::CursorWidget();
277 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
278 setAcceptDrops(true);
279 setMouseTracking(true);
280 setMinimumSize(100, 70);
282 setFrameStyle(QFrame::NoFrame);
284 setFrameStyle(QFrame::Box);
288 viewport()->setAutoFillBackground(false);
289 // We don't need double-buffering nor SystemBackground on
290 // the viewport because we have our own backing pixmap.
291 viewport()->setAttribute(Qt::WA_NoSystemBackground);
293 setFocusPolicy(Qt::StrongFocus);
295 viewport()->setCursor(Qt::IBeamCursor);
297 synthetic_mouse_event_.timeout.timeout.connect(
298 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
301 // Initialize the vertical Scroll Bar
302 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
303 this, SLOT(scrollTo(int)));
305 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
306 << " viewport height: " << viewport()->height());
308 // Enables input methods for asian languages.
309 // Must be set when creating custom text editing widgets.
310 setAttribute(Qt::WA_InputMethodEnabled, true);
312 dialog_mode_ = false;
316 GuiWorkArea::~GuiWorkArea()
318 buffer_view_->buffer().workAreaManager().remove(this);
321 // Completer has a QObject parent and is thus automatically destroyed.
322 // delete completer_;
326 void GuiWorkArea::setGuiView(GuiView & gv)
332 void GuiWorkArea::setBuffer(Buffer & buffer)
335 buffer_view_ = new BufferView(buffer),
336 buffer.workAreaManager().add(this);
338 // HACK: Prevents an additional redraw when the scrollbar pops up
339 // which regularily happens on documents with more than one page.
340 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
341 // Since we have no geometry information yet, we assume that
342 // a document needs a scrollbar if there is more then four
343 // paragraph in the outermost text.
344 if (buffer.text().paragraphs().size() > 4)
345 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
346 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
350 void GuiWorkArea::fixVerticalScrollBar()
353 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
357 void GuiWorkArea::close()
359 lyx_view_->removeWorkArea(this);
363 void GuiWorkArea::setFullScreen(bool full_screen)
365 buffer_view_->setFullScreen(full_screen);
367 setFrameStyle(QFrame::NoFrame);
368 if (lyxrc.full_screen_scrollbar)
369 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
372 setFrameStyle(QFrame::NoFrame);
374 setFrameStyle(QFrame::Box);
376 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
381 BufferView & GuiWorkArea::bufferView()
383 return *buffer_view_;
387 BufferView const & GuiWorkArea::bufferView() const
389 return *buffer_view_;
393 void GuiWorkArea::stopBlinkingCursor()
395 cursor_timeout_.stop();
400 void GuiWorkArea::startBlinkingCursor()
403 //we're not supposed to cache this value.
404 int const time = QApplication::cursorFlashTime() / 2;
407 cursor_timeout_.setInterval(time);
408 cursor_timeout_.start();
412 void GuiWorkArea::redraw()
415 // No need to redraw in this case.
418 // No need to do anything if this is the current view. The BufferView
419 // metrics are already up to date.
420 if (lyx_view_ != guiApp->currentView()
421 || lyx_view_->currentWorkArea() != this) {
422 // FIXME: it would be nice to optimize for the off-screen case.
423 buffer_view_->updateMetrics();
424 buffer_view_->cursor().fixIfBroken();
427 // update cursor position, because otherwise it has to wait until
428 // the blinking interval is over
429 if (cursor_visible_) {
434 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
436 update(0, 0, viewport()->width(), viewport()->height());
438 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
439 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
441 lyx_view_->updateStatusBar();
443 if (lyxerr.debugging(Debug::WORKAREA))
444 buffer_view_->coordCache().dump();
448 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
450 if (lyx_view_->isFullScreen() && lyx_view_->menuBar()->isVisible()) {
451 // FIXME HACK: we should not have to do this here. See related comment
452 // in GuiView::event() (QEvent::ShortcutOverride)
453 lyx_view_->menuBar()->hide();
456 // In order to avoid bad surprise in the middle of an operation,
457 // we better stop the blinking cursor...
458 // the cursor gets restarted in GuiView::restartCursor()
459 stopBlinkingCursor();
461 theLyXFunc().setLyXView(lyx_view_);
462 theLyXFunc().processKeySym(key, mod);
466 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
469 if (cmd0.action == LFUN_FILE_OPEN) {
470 lyx_view_->dispatch(cmd0);
474 theLyXFunc().setLyXView(lyx_view_);
478 if (cmd0.action == LFUN_MOUSE_PRESS) {
479 if (mod == ShiftModifier)
480 cmd = FuncRequest(cmd0, "region-select");
481 else if (mod == ControlModifier)
482 cmd = FuncRequest(cmd0, "paragraph-select");
489 bool const notJustMovingTheMouse =
490 cmd.action != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
492 // In order to avoid bad surprise in the middle of an operation, we better stop
493 // the blinking cursor.
494 if (notJustMovingTheMouse)
495 stopBlinkingCursor();
497 buffer_view_->mouseEventDispatch(cmd);
499 // Skip these when selecting
500 if (cmd.action != LFUN_MOUSE_MOTION) {
501 completer_->updateVisibility(false, false);
502 lyx_view_->updateDialogs();
503 lyx_view_->updateStatusBar();
506 // GUI tweaks except with mouse motion with no button pressed.
507 if (notJustMovingTheMouse) {
508 // Slight hack: this is only called currently when we
509 // clicked somewhere, so we force through the display
510 // of the new status here.
511 lyx_view_->clearMessage();
513 // Show the cursor immediately after any operation
514 startBlinkingCursor();
519 void GuiWorkArea::resizeBufferView()
521 // WARNING: Please don't put any code that will trigger a repaint here!
522 // We are already inside a paint event.
523 lyx_view_->setBusy(true);
524 buffer_view_->resize(viewport()->width(), viewport()->height());
527 // Update scrollbars which might have changed due different
528 // BufferView dimension. This is especially important when the
529 // BufferView goes from zero-size to the real-size for the first time,
530 // as the scrollbar paramters are then set for the first time.
533 lyx_view_->updateLayoutList();
534 lyx_view_->setBusy(false);
535 need_resize_ = false;
539 void GuiWorkArea::showCursor()
545 bool l_shape = false;
546 Font const & realfont = buffer_view_->cursor().real_current_font;
547 BufferParams const & bp = buffer_view_->buffer().params();
548 bool const samelang = realfont.language() == bp.language;
549 bool const isrtl = realfont.isVisibleRightToLeft();
551 if (!samelang || isrtl != bp.language->rightToLeft())
554 // The ERT language hack needs fixing up
555 if (realfont.language() == latex_language)
558 Font const font = buffer_view_->cursor().getFont();
559 FontMetrics const & fm = theFontMetrics(font);
560 int const asc = fm.maxAscent();
561 int const des = fm.maxDescent();
565 Cursor & cur = buffer_view_->cursor();
569 // if it doesn't touch the screen, don't try to show it
570 bool cursorInView = true;
571 if (y + h < 0 || y >= viewport()->height()
572 || !cur.bv().paragraphVisible(cur))
573 cursorInView = false;
575 // show cursor on screen
576 bool completable = cur.inset().showCompletionCursor()
577 && completer_->completionAvailable()
578 && !completer_->popupVisible()
579 && !completer_->inlineVisible();
581 cursor_visible_ = true;
582 showCursor(x, y, h, l_shape, isrtl, completable);
587 void GuiWorkArea::hideCursor()
589 if (!cursor_visible_)
592 cursor_visible_ = false;
597 void GuiWorkArea::toggleCursor()
606 void GuiWorkArea::updateScrollbar()
608 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
609 // WARNING: don't touch at the scrollbar value like this:
610 // verticalScrollBar()->setValue(scroll_.position);
611 // because this would cause a recursive signal/slot calling with
612 // GuiWorkArea::scrollTo
613 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
614 verticalScrollBar()->setPageStep(scroll_.page_step);
615 verticalScrollBar()->setSingleStep(scroll_.single_step);
616 verticalScrollBar()->setSliderPosition(scroll_.position);
620 void GuiWorkArea::scrollTo(int value)
622 stopBlinkingCursor();
623 buffer_view_->scrollDocView(value);
625 if (lyxrc.cursor_follows_scrollbar) {
626 buffer_view_->setCursorFromScrollbar();
627 lyx_view_->updateLayoutList();
629 // Show the cursor immediately after any operation.
630 startBlinkingCursor();
631 QApplication::syncX();
635 bool GuiWorkArea::event(QEvent * e)
638 case QEvent::ToolTip: {
639 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
640 if (lyxrc.use_tooltip) {
641 QPoint pos = helpEvent->pos();
642 if (pos.x() < viewport()->width()) {
643 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
644 QToolTip::showText(helpEvent->globalPos(), s);
647 QToolTip::hideText();
649 // Don't forget to accept the event!
654 case QEvent::ShortcutOverride: {
655 // We catch this event in order to catch the Tab or Shift+Tab key press
656 // which are otherwise reserved to focus switching between controls
658 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
659 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
660 || ke->modifiers() & Qt::ControlModifier)
661 return QAbstractScrollArea::event(e);
667 return QAbstractScrollArea::event(e);
673 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
675 QPoint pos = e->pos();
676 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
678 QAbstractScrollArea::contextMenuEvent(e);
681 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
683 QAbstractScrollArea::contextMenuEvent(e);
686 // Position the menu to the right.
687 // FIXME: menu position should be different for RTL text.
688 menu->exec(e->globalPos());
693 void GuiWorkArea::focusInEvent(QFocusEvent * e)
696 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << std::endl);
697 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
699 old_gwa->stopBlinkingCursor();
700 lyx_view_->setCurrentWorkArea(this);
703 if (lyx_view_->currentWorkArea() != this)
704 lyx_view_->setCurrentWorkArea(this);
706 startBlinkingCursor();
707 QAbstractScrollArea::focusInEvent(e);
711 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
713 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << std::endl);
714 stopBlinkingCursor();
715 QAbstractScrollArea::focusOutEvent(e);
719 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
721 if (dc_event_.active && dc_event_ == *e) {
722 dc_event_.active = false;
723 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
724 q_button_state(e->button()));
730 inputContext()->reset();
732 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
733 q_button_state(e->button()));
734 dispatch(cmd, q_key_state(e->modifiers()));
739 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
741 if (synthetic_mouse_event_.timeout.running())
742 synthetic_mouse_event_.timeout.stop();
744 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
745 q_button_state(e->button()));
751 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
753 // we kill the triple click if we move
754 doubleClickTimeout();
755 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
756 q_motion_state(e->buttons()));
760 // If we're above or below the work area...
761 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
762 // Make sure only a synthetic event can cause a page scroll,
763 // so they come at a steady rate:
765 // _Force_ a scroll up:
768 cmd.y = viewport()->height();
769 // Store the event, to be handled when the timeout expires.
770 synthetic_mouse_event_.cmd = cmd;
772 if (synthetic_mouse_event_.timeout.running())
773 // Discard the event. Note that it _may_ be handled
774 // when the timeout expires if
775 // synthetic_mouse_event_.cmd has not been overwritten.
776 // Ie, when the timeout expires, we handle the
777 // most recent event but discard all others that
778 // occurred after the one used to start the timeout
779 // in the first place.
782 synthetic_mouse_event_.restart_timeout = true;
783 synthetic_mouse_event_.timeout.start();
784 // Fall through to handle this event...
786 } else if (synthetic_mouse_event_.timeout.running()) {
787 // Store the event, to be possibly handled when the timeout
789 // Once the timeout has expired, normal control is returned
790 // to mouseMoveEvent (restart_timeout = false).
791 // This results in a much smoother 'feel' when moving the
792 // mouse back into the work area.
793 synthetic_mouse_event_.cmd = cmd;
794 synthetic_mouse_event_.restart_timeout = false;
798 // Has anything changed on-screen since the last QMouseEvent
800 double const scrollbar_value = verticalScrollBar()->value();
801 if (e->x() == synthetic_mouse_event_.x_old
802 && e->y() == synthetic_mouse_event_.y_old
803 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
804 // Nothing changed on-screen since the last QMouseEvent.
808 // Yes something has changed. Store the params used to check this.
809 synthetic_mouse_event_.x_old = e->x();
810 synthetic_mouse_event_.y_old = e->y();
811 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
813 // ... and dispatch the event to the LyX core.
818 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
820 // Wheel rotation by one notch results in a delta() of 120 (see
821 // documentation of QWheelEvent)
822 int const delta = ev->delta() / 120;
823 if (ev->modifiers() & Qt::ControlModifier) {
824 lyxrc.zoom += 5 * delta;
827 // The global QPixmapCache is used in GuiPainter to cache text
828 // painting so we must reset it.
829 QPixmapCache::clear();
830 guiApp->fontLoader().update();
832 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
836 // Take into account the desktop wide settings.
837 int const lines = qApp->wheelScrollLines();
838 int const page_step = verticalScrollBar()->pageStep();
839 // Test if the wheel mouse is set to one screen at a time.
840 int scroll_value = lines > page_step
841 ? page_step : lines * verticalScrollBar()->singleStep();
843 // Take into account the rotation.
844 scroll_value *= delta;
846 // Take into account user preference.
847 scroll_value *= lyxrc.mouse_wheel_speed;
848 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
849 << " delta = " << delta << " scroll_value = " << scroll_value
850 << " page_step = " << page_step);
852 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
858 void GuiWorkArea::generateSyntheticMouseEvent()
860 // Set things off to generate the _next_ 'pseudo' event.
861 if (synthetic_mouse_event_.restart_timeout)
862 synthetic_mouse_event_.timeout.start();
864 // Has anything changed on-screen since the last timeout signal
866 double const scrollbar_value = verticalScrollBar()->value();
867 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
868 // Yes it has. Store the params used to check this.
869 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
871 // ... and dispatch the event to the LyX core.
872 dispatch(synthetic_mouse_event_.cmd);
877 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
879 // Do not process here some keys if dialog_mode_ is set
881 && (ev->modifiers() == Qt::NoModifier
882 || ev->modifiers() == Qt::ShiftModifier)
883 && (ev->key() == Qt::Key_Escape
884 || ev->key() == Qt::Key_Enter
885 || ev->key() == Qt::Key_Return)
891 // intercept some keys if completion popup is visible
892 if (completer_->popupVisible()) {
896 completer_->activate();
902 // do nothing if there are other events
903 // (the auto repeated events come too fast)
904 // \todo FIXME: remove hard coded Qt keys, process the key binding
906 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
907 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
908 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
914 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
915 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
918 setKeySymbol(&sym, ev);
919 processKeySym(sym, q_key_state(ev->modifiers()));
924 void GuiWorkArea::doubleClickTimeout()
926 dc_event_.active = false;
930 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
932 dc_event_ = DoubleClick(ev);
933 QTimer::singleShot(QApplication::doubleClickInterval(), this,
934 SLOT(doubleClickTimeout()));
935 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
937 q_button_state(ev->button()));
943 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
945 QAbstractScrollArea::resizeEvent(ev);
951 void GuiWorkArea::update(int x, int y, int w, int h)
953 viewport()->repaint(x, y, w, h);
957 void GuiWorkArea::paintEvent(QPaintEvent * ev)
959 QRect const rc = ev->rect();
960 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
961 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
964 screen_ = QPixmap(viewport()->width(), viewport()->height());
970 QPainter pain(viewport());
971 pain.drawPixmap(rc, screen_, rc);
977 void GuiWorkArea::updateScreen()
979 GuiPainter pain(&screen_);
980 buffer_view_->draw(pain);
984 void GuiWorkArea::showCursor(int x, int y, int h,
985 bool l_shape, bool rtl, bool completable)
987 if (schedule_redraw_) {
988 // This happens when a graphic conversion is finished. As we don't know
989 // the size of the new graphics, it's better the update everything.
990 // We can't use redraw() here because this would trigger a infinite
991 // recursive loop with showCursor().
992 buffer_view_->resize(viewport()->width(), viewport()->height());
995 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
996 schedule_redraw_ = false;
997 // Show the cursor immediately after the update.
1003 cursor_->update(x, y, h, l_shape, rtl, completable);
1005 viewport()->update(cursor_->rect());
1009 void GuiWorkArea::removeCursor()
1012 //if (!qApp->focusWidget())
1013 viewport()->update(cursor_->rect());
1017 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1019 QString const & commit_string = e->commitString();
1020 docstring const & preedit_string
1021 = qstring_to_ucs4(e->preeditString());
1023 if (!commit_string.isEmpty()) {
1025 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1026 << " commitString: " << e->commitString());
1030 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1031 for (int i = 0; i != commit_string.size(); ++i) {
1032 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1037 // Hide the cursor during the kana-kanji transformation.
1038 if (preedit_string.empty())
1039 startBlinkingCursor();
1041 stopBlinkingCursor();
1043 // last_width : for checking if last preedit string was/wasn't empty.
1044 static bool last_width = false;
1045 if (!last_width && preedit_string.empty()) {
1046 // if last_width is last length of preedit string.
1051 GuiPainter pain(&screen_);
1052 buffer_view_->updateMetrics();
1053 buffer_view_->draw(pain);
1054 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1055 FontMetrics const & fm = theFontMetrics(font);
1056 int height = fm.maxHeight();
1057 int cur_x = cursor_->rect().left();
1058 int cur_y = cursor_->rect().bottom();
1060 // redraw area of preedit string.
1061 update(0, cur_y - height, viewport()->width(),
1062 (height + 1) * preedit_lines_);
1064 if (preedit_string.empty()) {
1072 // att : stores an IM attribute.
1073 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1075 // get attributes of input method cursor.
1076 // cursor_pos : cursor position in preedit string.
1077 size_t cursor_pos = 0;
1078 bool cursor_is_visible = false;
1079 for (int i = 0; i != att.size(); ++i) {
1080 if (att.at(i).type == QInputMethodEvent::Cursor) {
1081 cursor_pos = att.at(i).start;
1082 cursor_is_visible = att.at(i).length != 0;
1087 size_t preedit_length = preedit_string.length();
1089 // get position of selection in input method.
1090 // FIXME: isn't there a way to do this simplier?
1091 // rStart : cursor position in selected string in IM.
1093 // rLength : selected string length in IM.
1095 if (cursor_pos < preedit_length) {
1096 for (int i = 0; i != att.size(); ++i) {
1097 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1098 if (att.at(i).start <= int(cursor_pos)
1099 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1100 rStart = att.at(i).start;
1101 rLength = att.at(i).length;
1102 if (!cursor_is_visible)
1103 cursor_pos += rLength;
1110 rStart = cursor_pos;
1114 int const right_margin = buffer_view_->rightMargin();
1115 Painter::preedit_style ps;
1116 // Most often there would be only one line:
1118 for (size_t pos = 0; pos != preedit_length; ++pos) {
1119 char_type const typed_char = preedit_string[pos];
1120 // reset preedit string style
1121 ps = Painter::preedit_default;
1123 // if we reached the right extremity of the screen, go to next line.
1124 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1125 cur_x = right_margin;
1126 cur_y += height + 1;
1129 // preedit strings are displayed with dashed underline
1130 // and partial strings are displayed white on black indicating
1131 // that we are in selecting mode in the input method.
1132 // FIXME: rLength == preedit_length is not a changing condition
1133 // FIXME: should be put out of the loop.
1135 && pos < rStart + rLength
1136 && !(cursor_pos < rLength && rLength == preedit_length))
1137 ps = Painter::preedit_selecting;
1139 if (pos == cursor_pos
1140 && (cursor_pos < rLength && rLength == preedit_length))
1141 ps = Painter::preedit_cursor;
1143 // draw one character and update cur_x.
1144 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1147 // update the preedit string screen area.
1148 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1149 (height + 1) * preedit_lines_);
1151 // Don't forget to accept the event!
1156 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1158 QRect cur_r(0, 0, 0, 0);
1160 // this is the CJK-specific composition window position.
1161 case Qt::ImMicroFocus:
1162 cur_r = cursor_->rect();
1163 if (preedit_lines_ != 1)
1165 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1166 // return lower right of cursor in LyX.
1169 return QWidget::inputMethodQuery(query);
1174 void GuiWorkArea::updateWindowTitle()
1176 docstring maximize_title;
1177 docstring minimize_title;
1179 Buffer & buf = buffer_view_->buffer();
1180 FileName const fileName = buf.fileName();
1181 if (!fileName.empty()) {
1182 maximize_title = fileName.displayName(30);
1183 minimize_title = from_utf8(fileName.onlyFileName());
1184 if (buf.lyxvc().inUse()) {
1185 if (buf.lyxvc().locker().empty())
1186 maximize_title += _(" (version control)");
1188 maximize_title += _(" (version control, locking)");
1190 if (!buf.isClean()) {
1191 maximize_title += _(" (changed)");
1192 minimize_title += char_type('*');
1194 if (buf.isReadonly())
1195 maximize_title += _(" (read only)");
1198 QString title = windowTitle();
1199 QString new_title = toqstr(maximize_title);
1200 if (title == new_title)
1203 QWidget::setWindowTitle(new_title);
1204 QWidget::setWindowIconText(toqstr(minimize_title));
1209 void GuiWorkArea::setReadOnly(bool)
1211 updateWindowTitle();
1212 if (this == lyx_view_->currentWorkArea())
1213 lyx_view_->updateDialogs();
1217 bool GuiWorkArea::isFullScreen()
1219 return lyx_view_ && lyx_view_->isFullScreen();
1223 ////////////////////////////////////////////////////////////////////
1227 ////////////////////////////////////////////////////////////////////
1230 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1232 buffer_ = theBufferList().newBuffer(
1233 support::FileName::tempName().absFilename() + "_embedded.internal");
1234 buffer_->setUnnamed(true);
1235 buffer_->setFullyLoaded(true);
1236 setBuffer(*buffer_);
1237 setDialogMode(true);
1241 EmbeddedWorkArea::~EmbeddedWorkArea()
1243 // No need to destroy buffer and bufferview here, because it is done
1244 // in theBuffeerList() destruction loop at application exit
1248 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1251 GuiWorkArea::closeEvent(ev);
1255 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1258 GuiWorkArea::hideEvent(ev);
1262 void EmbeddedWorkArea::disable()
1264 stopBlinkingCursor();
1265 if (view().currentWorkArea() != this)
1267 LASSERT(view().currentMainWorkArea(), /* */);
1268 view().setCurrentWorkArea(view().currentMainWorkArea());
1271 ////////////////////////////////////////////////////////////////////
1275 ////////////////////////////////////////////////////////////////////
1278 class NoTabFrameMacStyle : public QMacStyle {
1281 QRect subElementRect(SubElement element, const QStyleOption * option,
1282 const QWidget * widget = 0) const
1284 QRect rect = QMacStyle::subElementRect(element, option, widget);
1285 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1287 // The Qt Mac style puts the contents into a 3 pixel wide box
1288 // which looks very ugly and not like other Mac applications.
1289 // Hence we remove this here, and moreover the 16 pixel round
1290 // frame above if the tab bar is hidden.
1291 if (element == QStyle::SE_TabWidgetTabContents) {
1292 rect.adjust(- rect.left(), 0, rect.left(), 0);
1301 NoTabFrameMacStyle noTabFrameMacStyle;
1305 TabWorkArea::TabWorkArea(QWidget * parent)
1306 : QTabWidget(parent), clicked_tab_(-1)
1309 setStyle(&noTabFrameMacStyle);
1312 QPalette pal = palette();
1313 pal.setColor(QPalette::Active, QPalette::Button,
1314 pal.color(QPalette::Active, QPalette::Window));
1315 pal.setColor(QPalette::Disabled, QPalette::Button,
1316 pal.color(QPalette::Disabled, QPalette::Window));
1317 pal.setColor(QPalette::Inactive, QPalette::Button,
1318 pal.color(QPalette::Inactive, QPalette::Window));
1320 QObject::connect(this, SIGNAL(currentChanged(int)),
1321 this, SLOT(on_currentTabChanged(int)));
1323 closeBufferButton = new QToolButton(this);
1324 closeBufferButton->setPalette(pal);
1325 // FIXME: rename the icon to closebuffer.png
1326 closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1327 closeBufferButton->setText("Close File");
1328 closeBufferButton->setAutoRaise(true);
1329 closeBufferButton->setCursor(Qt::ArrowCursor);
1330 closeBufferButton->setToolTip(qt_("Close File"));
1331 closeBufferButton->setEnabled(true);
1332 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1333 this, SLOT(closeCurrentBuffer()));
1334 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1336 // setup drag'n'drop
1337 QTabBar* tb = new DragTabBar;
1338 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1339 this, SLOT(moveTab(int, int)));
1340 tb->setElideMode(Qt::ElideNone);
1343 // make us responsible for the context menu of the tabbar
1344 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1345 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1346 this, SLOT(showContextMenu(const QPoint &)));
1348 setUsesScrollButtons(true);
1352 void TabWorkArea::setFullScreen(bool full_screen)
1354 for (int i = 0; i != count(); ++i) {
1355 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1356 wa->setFullScreen(full_screen);
1359 if (lyxrc.full_screen_tabbar)
1360 showBar(!full_screen && count()>1);
1364 void TabWorkArea::showBar(bool show)
1366 tabBar()->setEnabled(show);
1367 tabBar()->setVisible(show);
1368 closeBufferButton->setVisible(show);
1372 GuiWorkArea * TabWorkArea::currentWorkArea()
1377 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1383 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1385 for (int i = 0; i != count(); ++i) {
1386 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1387 LASSERT(wa, return 0);
1388 if (&wa->bufferView().buffer() == &buffer)
1395 void TabWorkArea::closeAll()
1398 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1406 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1408 LASSERT(work_area, /**/);
1409 int index = indexOf(work_area);
1413 if (index == currentIndex())
1414 // Make sure the work area is up to date.
1415 on_currentTabChanged(index);
1417 // Switch to the work area.
1418 setCurrentIndex(index);
1419 work_area->setFocus();
1425 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1427 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1428 wa->setUpdatesEnabled(false);
1429 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1430 // when hiding it again below).
1431 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1432 showBar(count() > 0);
1433 addTab(wa, wa->windowTitle());
1434 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1435 this, SLOT(updateTabTexts()));
1436 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1437 setFullScreen(true);
1439 // Hide tabbar if there's only one tab.
1440 showBar(count() > 1);
1448 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1450 LASSERT(work_area, return false);
1451 int index = indexOf(work_area);
1455 work_area->setUpdatesEnabled(false);
1460 // make sure the next work area is enabled.
1461 currentWidget()->setUpdatesEnabled(true);
1462 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1463 setFullScreen(true);
1465 // Hide tabbar if there's only one tab.
1466 showBar(count() > 1);
1468 lastWorkAreaRemoved();
1477 void TabWorkArea::on_currentTabChanged(int i)
1479 // returns e.g. on application destruction
1482 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1483 LASSERT(wa, return);
1484 BufferView & bv = wa->bufferView();
1485 bv.cursor().fixIfBroken();
1487 wa->setUpdatesEnabled(true);
1491 currentWorkAreaChanged(wa);
1493 LYXERR(Debug::GUI, "currentTabChanged " << i
1494 << "File" << bv.buffer().absFileName());
1498 void TabWorkArea::closeCurrentBuffer()
1500 if (clicked_tab_ != -1)
1501 setCurrentIndex(clicked_tab_);
1503 // Before dispatching the LFUN we should be sure this
1504 // is the current workarea.
1505 currentWorkAreaChanged(currentWorkArea());
1507 lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1511 void TabWorkArea::closeCurrentTab()
1513 if (clicked_tab_ == -1)
1514 removeWorkArea(currentWorkArea());
1516 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1525 /// make vector happy
1528 DisplayPath(int tab, FileName const & filename)
1531 filename_ = toqstr(filename.onlyFileNameWithoutExt());
1532 postfix_ = toqstr(filename.absoluteFilePath()).
1533 split("/", QString::SkipEmptyParts);
1534 postfix_.pop_back();
1535 abs_ = toqstr(filename.absoluteFilePath());
1536 dottedPrefix_ = false;
1539 /// Absolute path for debugging.
1544 /// Add the first segment from the postfix or three dots to the prefix.
1545 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1546 /// when really needed.
1547 void shiftPathSegment(bool dotted)
1549 if (postfix_.count() <= 0)
1553 if (dottedPrefix_ && !prefix_.isEmpty())
1555 prefix_ += postfix_.front() + "/";
1557 dottedPrefix_ = dotted && !prefix_.isEmpty();
1558 postfix_.pop_front();
1561 QString displayString() const
1563 if (prefix_.isEmpty())
1566 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1567 return prefix_ + (dots ? ".../" : "") + filename_;
1570 QString forecastPathString() const
1572 if (postfix_.count() == 0)
1573 return displayString();
1576 + (dottedPrefix_ ? ".../" : "")
1577 + postfix_.front() + "/";
1580 bool final() const { return postfix_.empty(); }
1582 int tab() const { return tab_; }
1588 QStringList postfix_;
1601 bool operator<(DisplayPath const & a, DisplayPath const & b)
1603 return a.displayString() < b.displayString();
1607 bool operator==(DisplayPath const & a, DisplayPath const & b)
1609 return a.displayString() == b.displayString();
1613 void TabWorkArea::updateTabTexts()
1618 std::list<DisplayPath> paths;
1619 typedef std::list<DisplayPath>::iterator It;
1621 // collect full names first: path into postfix, empty prefix and
1622 // filename without extension
1623 for (size_t i = 0; i < n; ++i) {
1624 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(i));
1625 FileName const fn = i_wa->bufferView().buffer().fileName();
1626 paths.push_back(DisplayPath(i, fn));
1629 // go through path segments and see if it helps to make the path more unique
1630 bool somethingChanged = true;
1631 bool allFinal = false;
1632 while (somethingChanged && !allFinal) {
1633 // adding path segments changes order
1636 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1637 somethingChanged = false;
1640 // find segments which are not unique (i.e. non-atomic)
1641 It it = paths.begin();
1643 QString segString = it->displayString();
1644 for (; it != paths.end(); ++it) {
1645 // look to the next item
1650 allFinal = allFinal && it->final();
1652 LYXERR(Debug::GUI, "it = " << it->abs()
1653 << " => " << it->displayString());
1655 // still the same segment?
1657 if ((next != paths.end()
1658 && (nextString = next->displayString()) == segString))
1660 LYXERR(Debug::GUI, "segment ended");
1662 // only a trivial one with one element?
1663 if (it == segStart) {
1664 // start new segment
1666 segString = nextString;
1670 // we found a non-atomic segment segStart <= sit <= it < next.
1671 // Shift path segments and hope for the best
1672 // that it makes the path more unique.
1673 somethingChanged = true;
1675 QString dspString = sit->forecastPathString();
1676 LYXERR(Debug::GUI, "first forecast found for "
1677 << sit->abs() << " => " << dspString);
1679 bool moreUnique = false;
1680 for (; sit != next; ++sit) {
1681 if (sit->forecastPathString() != dspString) {
1682 LYXERR(Debug::GUI, "different forecast found for "
1683 << sit->abs() << " => " << sit->forecastPathString());
1687 LYXERR(Debug::GUI, "same forecast found for "
1688 << sit->abs() << " => " << dspString);
1691 // if the path segment helped, add it. Otherwise add dots
1692 bool dots = !moreUnique;
1693 LYXERR(Debug::GUI, "using dots = " << dots);
1694 for (sit = segStart; sit != next; ++sit) {
1695 sit->shiftPathSegment(dots);
1696 LYXERR(Debug::GUI, "shifting "
1697 << sit->abs() << " => " << sit->displayString());
1700 // start new segment
1702 segString = nextString;
1706 // set new tab titles
1707 for (It it = paths.begin(); it != paths.end(); ++it) {
1708 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(it->tab()));
1709 Buffer & buf = i_wa->bufferView().buffer();
1710 if (!buf.fileName().empty() && !buf.isClean())
1711 setTabText(it->tab(), it->displayString() + "*");
1713 setTabText(it->tab(), it->displayString());
1718 void TabWorkArea::showContextMenu(const QPoint & pos)
1721 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1722 if (clicked_tab_ == -1)
1727 popup.addAction(QIcon(":/images/hidetab.png"),
1728 qt_("Hide tab"), this, SLOT(closeCurrentTab()));
1729 popup.addAction(QIcon(":/images/closetab.png"),
1730 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1731 popup.exec(tabBar()->mapToGlobal(pos));
1737 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1739 QWidget * w = widget(fromIndex);
1740 QIcon icon = tabIcon(fromIndex);
1741 QString text = tabText(fromIndex);
1743 setCurrentIndex(fromIndex);
1744 removeTab(fromIndex);
1745 insertTab(toIndex, w, icon, text);
1746 setCurrentIndex(toIndex);
1750 DragTabBar::DragTabBar(QWidget* parent)
1753 setAcceptDrops(true);
1757 #if QT_VERSION < 0x040300
1758 int DragTabBar::tabAt(QPoint const & position) const
1760 const int max = count();
1761 for (int i = 0; i < max; ++i) {
1762 if (tabRect(i).contains(position))
1770 void DragTabBar::mousePressEvent(QMouseEvent * event)
1772 if (event->button() == Qt::LeftButton)
1773 dragStartPos_ = event->pos();
1774 QTabBar::mousePressEvent(event);
1778 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1780 // If the left button isn't pressed anymore then return
1781 if (!(event->buttons() & Qt::LeftButton))
1784 // If the distance is too small then return
1785 if ((event->pos() - dragStartPos_).manhattanLength()
1786 < QApplication::startDragDistance())
1789 // did we hit something after all?
1790 int tab = tabAt(dragStartPos_);
1794 // simulate button release to remove highlight from button
1795 int i = currentIndex();
1796 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1797 event->button(), event->buttons(), 0);
1798 QTabBar::mouseReleaseEvent(&me);
1802 QDrag * drag = new QDrag(this);
1803 QMimeData * mimeData = new QMimeData;
1804 // a crude way to distinguish tab-reodering drops from other ones
1805 mimeData->setData("action", "tab-reordering") ;
1806 drag->setMimeData(mimeData);
1808 #if QT_VERSION >= 0x040300
1809 // get tab pixmap as cursor
1810 QRect r = tabRect(tab);
1811 QPixmap pixmap(r.size());
1812 render(&pixmap, - r.topLeft());
1813 drag->setPixmap(pixmap);
1816 drag->start(Qt::MoveAction);
1822 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1824 // Only accept if it's an tab-reordering request
1825 QMimeData const * m = event->mimeData();
1826 QStringList formats = m->formats();
1827 if (formats.contains("action")
1828 && m->data("action") == "tab-reordering")
1829 event->acceptProposedAction();
1833 void DragTabBar::dropEvent(QDropEvent * event)
1835 int fromIndex = tabAt(dragStartPos_);
1836 int toIndex = tabAt(event->pos());
1838 // Tell interested objects that
1839 if (fromIndex != toIndex)
1840 tabMoveRequested(fromIndex, toIndex);
1841 event->acceptProposedAction();
1845 } // namespace frontend
1848 #include "moc_GuiWorkArea.cpp"