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);
281 setFrameStyle(QFrame::NoFrame);
284 viewport()->setAutoFillBackground(false);
285 // We don't need double-buffering nor SystemBackground on
286 // the viewport because we have our own backing pixmap.
287 viewport()->setAttribute(Qt::WA_NoSystemBackground);
289 setFocusPolicy(Qt::StrongFocus);
291 viewport()->setCursor(Qt::IBeamCursor);
293 synthetic_mouse_event_.timeout.timeout.connect(
294 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
297 // Initialize the vertical Scroll Bar
298 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
299 this, SLOT(scrollTo(int)));
301 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
302 << " viewport height: " << viewport()->height());
304 // Enables input methods for asian languages.
305 // Must be set when creating custom text editing widgets.
306 setAttribute(Qt::WA_InputMethodEnabled, true);
308 dialog_mode_ = false;
312 GuiWorkArea::~GuiWorkArea()
314 buffer_view_->buffer().workAreaManager().remove(this);
317 // Completer has a QObject parent and is thus automatically destroyed.
318 // delete completer_;
322 void GuiWorkArea::setGuiView(GuiView & gv)
328 void GuiWorkArea::setBuffer(Buffer & buffer)
331 buffer_view_ = new BufferView(buffer),
332 buffer.workAreaManager().add(this);
334 // HACK: Prevents an additional redraw when the scrollbar pops up
335 // which regularily happens on documents with more than one page.
336 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
337 // Since we have no geometry information yet, we assume that
338 // a document needs a scrollbar if there is more then four
339 // paragraph in the outermost text.
340 if (buffer.text().paragraphs().size() > 4)
341 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
342 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
346 void GuiWorkArea::fixVerticalScrollBar()
349 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
353 void GuiWorkArea::close()
355 lyx_view_->removeWorkArea(this);
359 void GuiWorkArea::setFullScreen(bool full_screen)
361 buffer_view_->setFullScreen(full_screen);
363 setFrameStyle(QFrame::NoFrame);
364 if (lyxrc.full_screen_scrollbar)
365 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
368 setFrameStyle(QFrame::NoFrame);
370 setFrameStyle(QFrame::Box);
372 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
377 BufferView & GuiWorkArea::bufferView()
379 return *buffer_view_;
383 BufferView const & GuiWorkArea::bufferView() const
385 return *buffer_view_;
389 void GuiWorkArea::stopBlinkingCursor()
391 cursor_timeout_.stop();
396 void GuiWorkArea::startBlinkingCursor()
399 //we're not supposed to cache this value.
400 int const time = QApplication::cursorFlashTime() / 2;
403 cursor_timeout_.setInterval(time);
404 cursor_timeout_.start();
408 void GuiWorkArea::redraw()
411 // No need to redraw in this case.
414 // No need to do anything if this is the current view. The BufferView
415 // metrics are already up to date.
416 if (lyx_view_ != guiApp->currentView()
417 || lyx_view_->currentWorkArea() != this) {
418 // FIXME: it would be nice to optimize for the off-screen case.
419 buffer_view_->updateMetrics();
420 buffer_view_->cursor().fixIfBroken();
423 // update cursor position, because otherwise it has to wait until
424 // the blinking interval is over
425 if (cursor_visible_) {
430 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
432 update(0, 0, viewport()->width(), viewport()->height());
434 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
435 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
437 lyx_view_->updateStatusBar();
439 if (lyxerr.debugging(Debug::WORKAREA))
440 buffer_view_->coordCache().dump();
444 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
446 if (lyx_view_->isFullScreen() && lyx_view_->menuBar()->isVisible()) {
447 // FIXME HACK: we should not have to do this here. See related comment
448 // in GuiView::event() (QEvent::ShortcutOverride)
449 lyx_view_->menuBar()->hide();
452 // In order to avoid bad surprise in the middle of an operation,
453 // we better stop the blinking cursor...
454 // the cursor gets restarted in GuiView::restartCursor()
455 stopBlinkingCursor();
457 theLyXFunc().setLyXView(lyx_view_);
458 theLyXFunc().processKeySym(key, mod);
462 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
465 if (cmd0.action == LFUN_FILE_OPEN) {
466 lyx_view_->dispatch(cmd0);
470 theLyXFunc().setLyXView(lyx_view_);
474 if (cmd0.action == LFUN_MOUSE_PRESS) {
475 if (mod == ShiftModifier)
476 cmd = FuncRequest(cmd0, "region-select");
477 else if (mod == ControlModifier)
478 cmd = FuncRequest(cmd0, "paragraph-select");
485 bool const notJustMovingTheMouse =
486 cmd.action != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
488 // In order to avoid bad surprise in the middle of an operation, we better stop
489 // the blinking cursor.
490 if (notJustMovingTheMouse)
491 stopBlinkingCursor();
493 buffer_view_->mouseEventDispatch(cmd);
495 // Skip these when selecting
496 if (cmd.action != LFUN_MOUSE_MOTION) {
497 completer_->updateVisibility(false, false);
498 lyx_view_->updateDialogs();
499 lyx_view_->updateStatusBar();
502 // GUI tweaks except with mouse motion with no button pressed.
503 if (notJustMovingTheMouse) {
504 // Slight hack: this is only called currently when we
505 // clicked somewhere, so we force through the display
506 // of the new status here.
507 lyx_view_->clearMessage();
509 // Show the cursor immediately after any operation
510 startBlinkingCursor();
515 void GuiWorkArea::resizeBufferView()
517 // WARNING: Please don't put any code that will trigger a repaint here!
518 // We are already inside a paint event.
519 lyx_view_->setBusy(true);
520 buffer_view_->resize(viewport()->width(), viewport()->height());
521 buffer_view_->scrollToCursor();
524 // Update scrollbars which might have changed due different
525 // BufferView dimension. This is especially important when the
526 // BufferView goes from zero-size to the real-size for the first time,
527 // as the scrollbar paramters are then set for the first time.
530 lyx_view_->updateLayoutList();
531 lyx_view_->setBusy(false);
532 need_resize_ = false;
536 void GuiWorkArea::showCursor()
542 bool l_shape = false;
543 Font const & realfont = buffer_view_->cursor().real_current_font;
544 BufferParams const & bp = buffer_view_->buffer().params();
545 bool const samelang = realfont.language() == bp.language;
546 bool const isrtl = realfont.isVisibleRightToLeft();
548 if (!samelang || isrtl != bp.language->rightToLeft())
551 // The ERT language hack needs fixing up
552 if (realfont.language() == latex_language)
555 Font const font = buffer_view_->cursor().getFont();
556 FontMetrics const & fm = theFontMetrics(font);
557 int const asc = fm.maxAscent();
558 int const des = fm.maxDescent();
562 Cursor & cur = buffer_view_->cursor();
566 // if it doesn't touch the screen, don't try to show it
567 bool cursorInView = true;
568 if (y + h < 0 || y >= viewport()->height()
569 || !cur.bv().paragraphVisible(cur))
570 cursorInView = false;
572 // show cursor on screen
573 bool completable = cur.inset().showCompletionCursor()
574 && completer_->completionAvailable()
575 && !completer_->popupVisible()
576 && !completer_->inlineVisible();
578 cursor_visible_ = true;
579 showCursor(x, y, h, l_shape, isrtl, completable);
584 void GuiWorkArea::hideCursor()
586 if (!cursor_visible_)
589 cursor_visible_ = false;
594 void GuiWorkArea::toggleCursor()
603 void GuiWorkArea::updateScrollbar()
605 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
606 // WARNING: don't touch at the scrollbar value like this:
607 // verticalScrollBar()->setValue(scroll_.position);
608 // because this would cause a recursive signal/slot calling with
609 // GuiWorkArea::scrollTo
610 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
611 verticalScrollBar()->setPageStep(scroll_.page_step);
612 verticalScrollBar()->setSingleStep(scroll_.single_step);
613 verticalScrollBar()->setSliderPosition(scroll_.position);
617 void GuiWorkArea::scrollTo(int value)
619 stopBlinkingCursor();
620 buffer_view_->scrollDocView(value);
622 if (lyxrc.cursor_follows_scrollbar) {
623 buffer_view_->setCursorFromScrollbar();
624 lyx_view_->updateLayoutList();
626 // Show the cursor immediately after any operation.
627 startBlinkingCursor();
628 QApplication::syncX();
632 bool GuiWorkArea::event(QEvent * e)
635 case QEvent::ToolTip: {
636 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
637 if (lyxrc.use_tooltip) {
638 QPoint pos = helpEvent->pos();
639 if (pos.x() < viewport()->width()) {
640 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
641 QToolTip::showText(helpEvent->globalPos(), s);
644 QToolTip::hideText();
646 // Don't forget to accept the event!
651 case QEvent::ShortcutOverride: {
652 // We catch this event in order to catch the Tab or Shift+Tab key press
653 // which are otherwise reserved to focus switching between controls
655 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
656 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
657 || ke->modifiers() & Qt::ControlModifier)
658 return QAbstractScrollArea::event(e);
664 return QAbstractScrollArea::event(e);
670 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
672 QPoint pos = e->pos();
673 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
675 QAbstractScrollArea::contextMenuEvent(e);
678 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
680 QAbstractScrollArea::contextMenuEvent(e);
683 // Position the menu to the right.
684 // FIXME: menu position should be different for RTL text.
685 menu->exec(e->globalPos());
690 void GuiWorkArea::focusInEvent(QFocusEvent * e)
693 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << std::endl);
694 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
696 old_gwa->stopBlinkingCursor();
697 lyx_view_->setCurrentWorkArea(this);
700 if (lyx_view_->currentWorkArea() != this)
701 lyx_view_->setCurrentWorkArea(this);
703 startBlinkingCursor();
704 QAbstractScrollArea::focusInEvent(e);
708 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
710 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << std::endl);
711 stopBlinkingCursor();
712 QAbstractScrollArea::focusOutEvent(e);
716 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
718 if (dc_event_.active && dc_event_ == *e) {
719 dc_event_.active = false;
720 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
721 q_button_state(e->button()));
727 inputContext()->reset();
729 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
730 q_button_state(e->button()));
731 dispatch(cmd, q_key_state(e->modifiers()));
736 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
738 if (synthetic_mouse_event_.timeout.running())
739 synthetic_mouse_event_.timeout.stop();
741 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
742 q_button_state(e->button()));
748 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
750 // we kill the triple click if we move
751 doubleClickTimeout();
752 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
753 q_motion_state(e->buttons()));
757 // If we're above or below the work area...
758 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
759 // Make sure only a synthetic event can cause a page scroll,
760 // so they come at a steady rate:
762 // _Force_ a scroll up:
765 cmd.y = viewport()->height();
766 // Store the event, to be handled when the timeout expires.
767 synthetic_mouse_event_.cmd = cmd;
769 if (synthetic_mouse_event_.timeout.running())
770 // Discard the event. Note that it _may_ be handled
771 // when the timeout expires if
772 // synthetic_mouse_event_.cmd has not been overwritten.
773 // Ie, when the timeout expires, we handle the
774 // most recent event but discard all others that
775 // occurred after the one used to start the timeout
776 // in the first place.
779 synthetic_mouse_event_.restart_timeout = true;
780 synthetic_mouse_event_.timeout.start();
781 // Fall through to handle this event...
783 } else if (synthetic_mouse_event_.timeout.running()) {
784 // Store the event, to be possibly handled when the timeout
786 // Once the timeout has expired, normal control is returned
787 // to mouseMoveEvent (restart_timeout = false).
788 // This results in a much smoother 'feel' when moving the
789 // mouse back into the work area.
790 synthetic_mouse_event_.cmd = cmd;
791 synthetic_mouse_event_.restart_timeout = false;
795 // Has anything changed on-screen since the last QMouseEvent
797 double const scrollbar_value = verticalScrollBar()->value();
798 if (e->x() == synthetic_mouse_event_.x_old
799 && e->y() == synthetic_mouse_event_.y_old
800 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
801 // Nothing changed on-screen since the last QMouseEvent.
805 // Yes something has changed. Store the params used to check this.
806 synthetic_mouse_event_.x_old = e->x();
807 synthetic_mouse_event_.y_old = e->y();
808 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
810 // ... and dispatch the event to the LyX core.
815 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
817 // Wheel rotation by one notch results in a delta() of 120 (see
818 // documentation of QWheelEvent)
819 int const delta = ev->delta() / 120;
820 if (ev->modifiers() & Qt::ControlModifier) {
821 lyxrc.zoom += 5 * delta;
824 // The global QPixmapCache is used in GuiPainter to cache text
825 // painting so we must reset it.
826 QPixmapCache::clear();
827 guiApp->fontLoader().update();
829 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
833 // Take into account the desktop wide settings.
834 int const lines = qApp->wheelScrollLines();
835 int const page_step = verticalScrollBar()->pageStep();
836 // Test if the wheel mouse is set to one screen at a time.
837 int scroll_value = lines > page_step
838 ? page_step : lines * verticalScrollBar()->singleStep();
840 // Take into account the rotation.
841 scroll_value *= delta;
843 // Take into account user preference.
844 scroll_value *= lyxrc.mouse_wheel_speed;
845 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
846 << " delta = " << delta << " scroll_value = " << scroll_value
847 << " page_step = " << page_step);
849 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
855 void GuiWorkArea::generateSyntheticMouseEvent()
857 // Set things off to generate the _next_ 'pseudo' event.
858 if (synthetic_mouse_event_.restart_timeout)
859 synthetic_mouse_event_.timeout.start();
861 // Has anything changed on-screen since the last timeout signal
863 double const scrollbar_value = verticalScrollBar()->value();
864 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
865 // Yes it has. Store the params used to check this.
866 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
868 // ... and dispatch the event to the LyX core.
869 dispatch(synthetic_mouse_event_.cmd);
874 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
876 // Do not process here some keys if dialog_mode_ is set
878 && (ev->modifiers() == Qt::NoModifier
879 || ev->modifiers() == Qt::ShiftModifier)
880 && (ev->key() == Qt::Key_Escape
881 || ev->key() == Qt::Key_Enter
882 || ev->key() == Qt::Key_Return)
888 // intercept some keys if completion popup is visible
889 if (completer_->popupVisible()) {
893 completer_->activate();
899 // do nothing if there are other events
900 // (the auto repeated events come too fast)
901 // \todo FIXME: remove hard coded Qt keys, process the key binding
903 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
904 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
905 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
911 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
912 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
915 setKeySymbol(&sym, ev);
916 processKeySym(sym, q_key_state(ev->modifiers()));
921 void GuiWorkArea::doubleClickTimeout()
923 dc_event_.active = false;
927 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
929 dc_event_ = DoubleClick(ev);
930 QTimer::singleShot(QApplication::doubleClickInterval(), this,
931 SLOT(doubleClickTimeout()));
932 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
934 q_button_state(ev->button()));
940 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
942 QAbstractScrollArea::resizeEvent(ev);
948 void GuiWorkArea::update(int x, int y, int w, int h)
950 viewport()->repaint(x, y, w, h);
954 void GuiWorkArea::paintEvent(QPaintEvent * ev)
956 QRect const rc = ev->rect();
957 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
958 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
961 screen_ = QPixmap(viewport()->width(), viewport()->height());
967 QPainter pain(viewport());
968 pain.drawPixmap(rc, screen_, rc);
974 void GuiWorkArea::updateScreen()
976 GuiPainter pain(&screen_);
977 buffer_view_->draw(pain);
981 void GuiWorkArea::showCursor(int x, int y, int h,
982 bool l_shape, bool rtl, bool completable)
984 if (schedule_redraw_) {
985 // This happens when a graphic conversion is finished. As we don't know
986 // the size of the new graphics, it's better the update everything.
987 // We can't use redraw() here because this would trigger a infinite
988 // recursive loop with showCursor().
989 buffer_view_->resize(viewport()->width(), viewport()->height());
992 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
993 schedule_redraw_ = false;
994 // Show the cursor immediately after the update.
1000 cursor_->update(x, y, h, l_shape, rtl, completable);
1002 viewport()->update(cursor_->rect());
1006 void GuiWorkArea::removeCursor()
1009 //if (!qApp->focusWidget())
1010 viewport()->update(cursor_->rect());
1014 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1016 QString const & commit_string = e->commitString();
1017 docstring const & preedit_string
1018 = qstring_to_ucs4(e->preeditString());
1020 if (!commit_string.isEmpty()) {
1022 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1023 << " commitString: " << e->commitString());
1027 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1028 for (int i = 0; i != commit_string.size(); ++i) {
1029 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1034 // Hide the cursor during the kana-kanji transformation.
1035 if (preedit_string.empty())
1036 startBlinkingCursor();
1038 stopBlinkingCursor();
1040 // last_width : for checking if last preedit string was/wasn't empty.
1041 static bool last_width = false;
1042 if (!last_width && preedit_string.empty()) {
1043 // if last_width is last length of preedit string.
1048 GuiPainter pain(&screen_);
1049 buffer_view_->updateMetrics();
1050 buffer_view_->draw(pain);
1051 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1052 FontMetrics const & fm = theFontMetrics(font);
1053 int height = fm.maxHeight();
1054 int cur_x = cursor_->rect().left();
1055 int cur_y = cursor_->rect().bottom();
1057 // redraw area of preedit string.
1058 update(0, cur_y - height, viewport()->width(),
1059 (height + 1) * preedit_lines_);
1061 if (preedit_string.empty()) {
1069 // att : stores an IM attribute.
1070 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1072 // get attributes of input method cursor.
1073 // cursor_pos : cursor position in preedit string.
1074 size_t cursor_pos = 0;
1075 bool cursor_is_visible = false;
1076 for (int i = 0; i != att.size(); ++i) {
1077 if (att.at(i).type == QInputMethodEvent::Cursor) {
1078 cursor_pos = att.at(i).start;
1079 cursor_is_visible = att.at(i).length != 0;
1084 size_t preedit_length = preedit_string.length();
1086 // get position of selection in input method.
1087 // FIXME: isn't there a way to do this simplier?
1088 // rStart : cursor position in selected string in IM.
1090 // rLength : selected string length in IM.
1092 if (cursor_pos < preedit_length) {
1093 for (int i = 0; i != att.size(); ++i) {
1094 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1095 if (att.at(i).start <= int(cursor_pos)
1096 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1097 rStart = att.at(i).start;
1098 rLength = att.at(i).length;
1099 if (!cursor_is_visible)
1100 cursor_pos += rLength;
1107 rStart = cursor_pos;
1111 int const right_margin = buffer_view_->rightMargin();
1112 Painter::preedit_style ps;
1113 // Most often there would be only one line:
1115 for (size_t pos = 0; pos != preedit_length; ++pos) {
1116 char_type const typed_char = preedit_string[pos];
1117 // reset preedit string style
1118 ps = Painter::preedit_default;
1120 // if we reached the right extremity of the screen, go to next line.
1121 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1122 cur_x = right_margin;
1123 cur_y += height + 1;
1126 // preedit strings are displayed with dashed underline
1127 // and partial strings are displayed white on black indicating
1128 // that we are in selecting mode in the input method.
1129 // FIXME: rLength == preedit_length is not a changing condition
1130 // FIXME: should be put out of the loop.
1132 && pos < rStart + rLength
1133 && !(cursor_pos < rLength && rLength == preedit_length))
1134 ps = Painter::preedit_selecting;
1136 if (pos == cursor_pos
1137 && (cursor_pos < rLength && rLength == preedit_length))
1138 ps = Painter::preedit_cursor;
1140 // draw one character and update cur_x.
1141 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1144 // update the preedit string screen area.
1145 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1146 (height + 1) * preedit_lines_);
1148 // Don't forget to accept the event!
1153 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1155 QRect cur_r(0, 0, 0, 0);
1157 // this is the CJK-specific composition window position.
1158 case Qt::ImMicroFocus:
1159 cur_r = cursor_->rect();
1160 if (preedit_lines_ != 1)
1162 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1163 // return lower right of cursor in LyX.
1166 return QWidget::inputMethodQuery(query);
1171 void GuiWorkArea::updateWindowTitle()
1173 docstring maximize_title;
1174 docstring minimize_title;
1176 Buffer & buf = buffer_view_->buffer();
1177 FileName const fileName = buf.fileName();
1178 if (!fileName.empty()) {
1179 maximize_title = fileName.displayName(30);
1180 minimize_title = from_utf8(fileName.onlyFileName());
1181 if (buf.lyxvc().inUse()) {
1182 if (buf.lyxvc().locker().empty())
1183 maximize_title += _(" (version control)");
1185 maximize_title += _(" (version control, locking)");
1187 if (!buf.isClean()) {
1188 maximize_title += _(" (changed)");
1189 minimize_title += char_type('*');
1191 if (buf.isReadonly())
1192 maximize_title += _(" (read only)");
1195 QString title = windowTitle();
1196 QString new_title = toqstr(maximize_title);
1197 if (title == new_title)
1200 QWidget::setWindowTitle(new_title);
1201 QWidget::setWindowIconText(toqstr(minimize_title));
1206 void GuiWorkArea::setReadOnly(bool)
1208 updateWindowTitle();
1209 if (this == lyx_view_->currentWorkArea())
1210 lyx_view_->updateDialogs();
1214 bool GuiWorkArea::isFullScreen()
1216 return lyx_view_ && lyx_view_->isFullScreen();
1220 ////////////////////////////////////////////////////////////////////
1224 ////////////////////////////////////////////////////////////////////
1227 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1229 buffer_ = theBufferList().newBuffer(
1230 support::FileName::tempName().absFilename() + "_embedded.internal");
1231 buffer_->setUnnamed(true);
1232 buffer_->setFullyLoaded(true);
1233 setBuffer(*buffer_);
1234 setDialogMode(true);
1238 EmbeddedWorkArea::~EmbeddedWorkArea()
1240 // No need to destroy buffer and bufferview here, because it is done
1241 // in theBuffeerList() destruction loop at application exit
1245 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1248 GuiWorkArea::closeEvent(ev);
1252 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1255 GuiWorkArea::hideEvent(ev);
1259 void EmbeddedWorkArea::disable()
1261 stopBlinkingCursor();
1262 if (view().currentWorkArea() != this)
1264 LASSERT(view().currentMainWorkArea(), /* */);
1265 view().setCurrentWorkArea(view().currentMainWorkArea());
1268 ////////////////////////////////////////////////////////////////////
1272 ////////////////////////////////////////////////////////////////////
1275 class NoTabFrameMacStyle : public QMacStyle {
1278 QRect subElementRect(SubElement element, const QStyleOption * option,
1279 const QWidget * widget = 0) const
1281 QRect rect = QMacStyle::subElementRect(element, option, widget);
1282 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1284 // The Qt Mac style puts the contents into a 3 pixel wide box
1285 // which looks very ugly and not like other Mac applications.
1286 // Hence we remove this here, and moreover the 16 pixel round
1287 // frame above if the tab bar is hidden.
1288 if (element == QStyle::SE_TabWidgetTabContents) {
1289 rect.adjust(- rect.left(), 0, rect.left(), 0);
1298 NoTabFrameMacStyle noTabFrameMacStyle;
1302 TabWorkArea::TabWorkArea(QWidget * parent)
1303 : QTabWidget(parent), clicked_tab_(-1)
1306 setStyle(&noTabFrameMacStyle);
1309 QPalette pal = palette();
1310 pal.setColor(QPalette::Active, QPalette::Button,
1311 pal.color(QPalette::Active, QPalette::Window));
1312 pal.setColor(QPalette::Disabled, QPalette::Button,
1313 pal.color(QPalette::Disabled, QPalette::Window));
1314 pal.setColor(QPalette::Inactive, QPalette::Button,
1315 pal.color(QPalette::Inactive, QPalette::Window));
1317 QObject::connect(this, SIGNAL(currentChanged(int)),
1318 this, SLOT(on_currentTabChanged(int)));
1320 closeBufferButton = new QToolButton(this);
1321 closeBufferButton->setPalette(pal);
1322 // FIXME: rename the icon to closebuffer.png
1323 closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1324 closeBufferButton->setText("Close File");
1325 closeBufferButton->setAutoRaise(true);
1326 closeBufferButton->setCursor(Qt::ArrowCursor);
1327 closeBufferButton->setToolTip(qt_("Close File"));
1328 closeBufferButton->setEnabled(true);
1329 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1330 this, SLOT(closeCurrentBuffer()));
1331 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1333 // setup drag'n'drop
1334 QTabBar* tb = new DragTabBar;
1335 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1336 this, SLOT(moveTab(int, int)));
1337 tb->setElideMode(Qt::ElideNone);
1340 // make us responsible for the context menu of the tabbar
1341 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1342 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1343 this, SLOT(showContextMenu(const QPoint &)));
1345 setUsesScrollButtons(true);
1349 void TabWorkArea::setFullScreen(bool full_screen)
1351 for (int i = 0; i != count(); ++i) {
1352 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1353 wa->setFullScreen(full_screen);
1356 if (lyxrc.full_screen_tabbar)
1357 showBar(!full_screen && count()>1);
1361 void TabWorkArea::showBar(bool show)
1363 tabBar()->setEnabled(show);
1364 tabBar()->setVisible(show);
1365 closeBufferButton->setVisible(show);
1369 GuiWorkArea * TabWorkArea::currentWorkArea()
1374 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1380 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1382 for (int i = 0; i != count(); ++i) {
1383 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1384 LASSERT(wa, return 0);
1385 if (&wa->bufferView().buffer() == &buffer)
1392 void TabWorkArea::closeAll()
1395 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1403 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1405 LASSERT(work_area, /**/);
1406 int index = indexOf(work_area);
1410 if (index == currentIndex())
1411 // Make sure the work area is up to date.
1412 on_currentTabChanged(index);
1414 // Switch to the work area.
1415 setCurrentIndex(index);
1416 work_area->setFocus();
1422 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1424 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1425 wa->setUpdatesEnabled(false);
1426 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1427 // when hiding it again below).
1428 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1429 showBar(count() > 0);
1430 addTab(wa, wa->windowTitle());
1431 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1432 this, SLOT(updateTabTexts()));
1433 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1434 setFullScreen(true);
1436 // Hide tabbar if there's only one tab.
1437 showBar(count() > 1);
1445 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1447 LASSERT(work_area, return false);
1448 int index = indexOf(work_area);
1452 work_area->setUpdatesEnabled(false);
1457 // make sure the next work area is enabled.
1458 currentWidget()->setUpdatesEnabled(true);
1459 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1460 setFullScreen(true);
1462 // Hide tabbar if there's only one tab.
1463 showBar(count() > 1);
1465 lastWorkAreaRemoved();
1474 void TabWorkArea::on_currentTabChanged(int i)
1476 // returns e.g. on application destruction
1479 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1480 LASSERT(wa, return);
1481 BufferView & bv = wa->bufferView();
1482 bv.cursor().fixIfBroken();
1484 wa->setUpdatesEnabled(true);
1488 currentWorkAreaChanged(wa);
1490 LYXERR(Debug::GUI, "currentTabChanged " << i
1491 << "File" << bv.buffer().absFileName());
1495 void TabWorkArea::closeCurrentBuffer()
1497 if (clicked_tab_ != -1)
1498 setCurrentIndex(clicked_tab_);
1500 // Before dispatching the LFUN we should be sure this
1501 // is the current workarea.
1502 currentWorkAreaChanged(currentWorkArea());
1504 lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1508 void TabWorkArea::closeCurrentTab()
1510 if (clicked_tab_ == -1)
1511 removeWorkArea(currentWorkArea());
1513 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1522 /// make vector happy
1525 DisplayPath(int tab, FileName const & filename)
1528 filename_ = toqstr(filename.onlyFileNameWithoutExt());
1529 postfix_ = toqstr(filename.absoluteFilePath()).
1530 split("/", QString::SkipEmptyParts);
1531 postfix_.pop_back();
1532 abs_ = toqstr(filename.absoluteFilePath());
1533 dottedPrefix_ = false;
1536 /// Absolute path for debugging.
1541 /// Add the first segment from the postfix or three dots to the prefix.
1542 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1543 /// when really needed.
1544 void shiftPathSegment(bool dotted)
1546 if (postfix_.count() <= 0)
1550 if (dottedPrefix_ && !prefix_.isEmpty())
1552 prefix_ += postfix_.front() + "/";
1554 dottedPrefix_ = dotted && !prefix_.isEmpty();
1555 postfix_.pop_front();
1558 QString displayString() const
1560 if (prefix_.isEmpty())
1563 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1564 return prefix_ + (dots ? ".../" : "") + filename_;
1567 QString forecastPathString() const
1569 if (postfix_.count() == 0)
1570 return displayString();
1573 + (dottedPrefix_ ? ".../" : "")
1574 + postfix_.front() + "/";
1577 bool final() const { return postfix_.empty(); }
1579 int tab() const { return tab_; }
1585 QStringList postfix_;
1598 bool operator<(DisplayPath const & a, DisplayPath const & b)
1600 return a.displayString() < b.displayString();
1604 bool operator==(DisplayPath const & a, DisplayPath const & b)
1606 return a.displayString() == b.displayString();
1610 void TabWorkArea::updateTabTexts()
1615 std::list<DisplayPath> paths;
1616 typedef std::list<DisplayPath>::iterator It;
1618 // collect full names first: path into postfix, empty prefix and
1619 // filename without extension
1620 for (size_t i = 0; i < n; ++i) {
1621 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(i));
1622 FileName const fn = i_wa->bufferView().buffer().fileName();
1623 paths.push_back(DisplayPath(i, fn));
1626 // go through path segments and see if it helps to make the path more unique
1627 bool somethingChanged = true;
1628 bool allFinal = false;
1629 while (somethingChanged && !allFinal) {
1630 // adding path segments changes order
1633 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1634 somethingChanged = false;
1637 // find segments which are not unique (i.e. non-atomic)
1638 It it = paths.begin();
1640 QString segString = it->displayString();
1641 for (; it != paths.end(); ++it) {
1642 // look to the next item
1647 allFinal = allFinal && it->final();
1649 LYXERR(Debug::GUI, "it = " << it->abs()
1650 << " => " << it->displayString());
1652 // still the same segment?
1654 if ((next != paths.end()
1655 && (nextString = next->displayString()) == segString))
1657 LYXERR(Debug::GUI, "segment ended");
1659 // only a trivial one with one element?
1660 if (it == segStart) {
1661 // start new segment
1663 segString = nextString;
1667 // we found a non-atomic segment segStart <= sit <= it < next.
1668 // Shift path segments and hope for the best
1669 // that it makes the path more unique.
1670 somethingChanged = true;
1672 QString dspString = sit->forecastPathString();
1673 LYXERR(Debug::GUI, "first forecast found for "
1674 << sit->abs() << " => " << dspString);
1676 bool moreUnique = false;
1677 for (; sit != next; ++sit) {
1678 if (sit->forecastPathString() != dspString) {
1679 LYXERR(Debug::GUI, "different forecast found for "
1680 << sit->abs() << " => " << sit->forecastPathString());
1684 LYXERR(Debug::GUI, "same forecast found for "
1685 << sit->abs() << " => " << dspString);
1688 // if the path segment helped, add it. Otherwise add dots
1689 bool dots = !moreUnique;
1690 LYXERR(Debug::GUI, "using dots = " << dots);
1691 for (sit = segStart; sit != next; ++sit) {
1692 sit->shiftPathSegment(dots);
1693 LYXERR(Debug::GUI, "shifting "
1694 << sit->abs() << " => " << sit->displayString());
1697 // start new segment
1699 segString = nextString;
1703 // set new tab titles
1704 for (It it = paths.begin(); it != paths.end(); ++it) {
1705 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(it->tab()));
1706 Buffer & buf = i_wa->bufferView().buffer();
1707 if (!buf.fileName().empty() && !buf.isClean())
1708 setTabText(it->tab(), it->displayString() + "*");
1710 setTabText(it->tab(), it->displayString());
1715 void TabWorkArea::showContextMenu(const QPoint & pos)
1718 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1719 if (clicked_tab_ == -1)
1724 popup.addAction(QIcon(":/images/hidetab.png"),
1725 qt_("Hide tab"), this, SLOT(closeCurrentTab()));
1726 popup.addAction(QIcon(":/images/closetab.png"),
1727 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1728 popup.exec(tabBar()->mapToGlobal(pos));
1734 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1736 QWidget * w = widget(fromIndex);
1737 QIcon icon = tabIcon(fromIndex);
1738 QString text = tabText(fromIndex);
1740 setCurrentIndex(fromIndex);
1741 removeTab(fromIndex);
1742 insertTab(toIndex, w, icon, text);
1743 setCurrentIndex(toIndex);
1747 DragTabBar::DragTabBar(QWidget* parent)
1750 setAcceptDrops(true);
1754 #if QT_VERSION < 0x040300
1755 int DragTabBar::tabAt(QPoint const & position) const
1757 const int max = count();
1758 for (int i = 0; i < max; ++i) {
1759 if (tabRect(i).contains(position))
1767 void DragTabBar::mousePressEvent(QMouseEvent * event)
1769 if (event->button() == Qt::LeftButton)
1770 dragStartPos_ = event->pos();
1771 QTabBar::mousePressEvent(event);
1775 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1777 // If the left button isn't pressed anymore then return
1778 if (!(event->buttons() & Qt::LeftButton))
1781 // If the distance is too small then return
1782 if ((event->pos() - dragStartPos_).manhattanLength()
1783 < QApplication::startDragDistance())
1786 // did we hit something after all?
1787 int tab = tabAt(dragStartPos_);
1791 // simulate button release to remove highlight from button
1792 int i = currentIndex();
1793 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1794 event->button(), event->buttons(), 0);
1795 QTabBar::mouseReleaseEvent(&me);
1799 QDrag * drag = new QDrag(this);
1800 QMimeData * mimeData = new QMimeData;
1801 // a crude way to distinguish tab-reodering drops from other ones
1802 mimeData->setData("action", "tab-reordering") ;
1803 drag->setMimeData(mimeData);
1805 #if QT_VERSION >= 0x040300
1806 // get tab pixmap as cursor
1807 QRect r = tabRect(tab);
1808 QPixmap pixmap(r.size());
1809 render(&pixmap, - r.topLeft());
1810 drag->setPixmap(pixmap);
1813 drag->start(Qt::MoveAction);
1819 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1821 // Only accept if it's an tab-reordering request
1822 QMimeData const * m = event->mimeData();
1823 QStringList formats = m->formats();
1824 if (formats.contains("action")
1825 && m->data("action") == "tab-reordering")
1826 event->acceptProposedAction();
1830 void DragTabBar::dropEvent(QDropEvent * event)
1832 int fromIndex = tabAt(dragStartPos_);
1833 int toIndex = tabAt(event->pos());
1835 // Tell interested objects that
1836 if (fromIndex != toIndex)
1837 tabMoveRequested(fromIndex, toIndex);
1838 event->acceptProposedAction();
1842 } // namespace frontend
1845 #include "moc_GuiWorkArea.cpp"