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());
523 // Update scrollbars which might have changed due different
524 // BufferView dimension. This is especially important when the
525 // BufferView goes from zero-size to the real-size for the first time,
526 // as the scrollbar paramters are then set for the first time.
529 lyx_view_->updateLayoutList();
530 lyx_view_->setBusy(false);
531 need_resize_ = false;
535 void GuiWorkArea::showCursor()
541 bool l_shape = false;
542 Font const & realfont = buffer_view_->cursor().real_current_font;
543 BufferParams const & bp = buffer_view_->buffer().params();
544 bool const samelang = realfont.language() == bp.language;
545 bool const isrtl = realfont.isVisibleRightToLeft();
547 if (!samelang || isrtl != bp.language->rightToLeft())
550 // The ERT language hack needs fixing up
551 if (realfont.language() == latex_language)
554 Font const font = buffer_view_->cursor().getFont();
555 FontMetrics const & fm = theFontMetrics(font);
556 int const asc = fm.maxAscent();
557 int const des = fm.maxDescent();
561 Cursor & cur = buffer_view_->cursor();
565 // if it doesn't touch the screen, don't try to show it
566 bool cursorInView = true;
567 if (y + h < 0 || y >= viewport()->height()
568 || !cur.bv().paragraphVisible(cur))
569 cursorInView = false;
571 // show cursor on screen
572 bool completable = cur.inset().showCompletionCursor()
573 && completer_->completionAvailable()
574 && !completer_->popupVisible()
575 && !completer_->inlineVisible();
577 cursor_visible_ = true;
578 showCursor(x, y, h, l_shape, isrtl, completable);
583 void GuiWorkArea::hideCursor()
585 if (!cursor_visible_)
588 cursor_visible_ = false;
593 void GuiWorkArea::toggleCursor()
602 void GuiWorkArea::updateScrollbar()
604 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
605 // WARNING: don't touch at the scrollbar value like this:
606 // verticalScrollBar()->setValue(scroll_.position);
607 // because this would cause a recursive signal/slot calling with
608 // GuiWorkArea::scrollTo
609 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
610 verticalScrollBar()->setPageStep(scroll_.page_step);
611 verticalScrollBar()->setSingleStep(scroll_.single_step);
612 verticalScrollBar()->setSliderPosition(scroll_.position);
616 void GuiWorkArea::scrollTo(int value)
618 stopBlinkingCursor();
619 buffer_view_->scrollDocView(value);
621 if (lyxrc.cursor_follows_scrollbar) {
622 buffer_view_->setCursorFromScrollbar();
623 lyx_view_->updateLayoutList();
625 // Show the cursor immediately after any operation.
626 startBlinkingCursor();
627 QApplication::syncX();
631 bool GuiWorkArea::event(QEvent * e)
634 case QEvent::ToolTip: {
635 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
636 if (lyxrc.use_tooltip) {
637 QPoint pos = helpEvent->pos();
638 if (pos.x() < viewport()->width()) {
639 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
640 QToolTip::showText(helpEvent->globalPos(), s);
643 QToolTip::hideText();
645 // Don't forget to accept the event!
650 case QEvent::ShortcutOverride: {
651 // We catch this event in order to catch the Tab or Shift+Tab key press
652 // which are otherwise reserved to focus switching between controls
654 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
655 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
656 || ke->modifiers() & Qt::ControlModifier)
657 return QAbstractScrollArea::event(e);
663 return QAbstractScrollArea::event(e);
669 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
671 QPoint pos = e->pos();
672 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
674 QAbstractScrollArea::contextMenuEvent(e);
677 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
679 QAbstractScrollArea::contextMenuEvent(e);
682 // Position the menu to the right.
683 // FIXME: menu position should be different for RTL text.
684 menu->exec(e->globalPos());
689 void GuiWorkArea::focusInEvent(QFocusEvent * e)
692 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << std::endl);
693 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
695 old_gwa->stopBlinkingCursor();
696 lyx_view_->setCurrentWorkArea(this);
699 if (lyx_view_->currentWorkArea() != this)
700 lyx_view_->setCurrentWorkArea(this);
702 startBlinkingCursor();
703 QAbstractScrollArea::focusInEvent(e);
707 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
709 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << std::endl);
710 stopBlinkingCursor();
711 QAbstractScrollArea::focusOutEvent(e);
715 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
717 if (dc_event_.active && dc_event_ == *e) {
718 dc_event_.active = false;
719 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
720 q_button_state(e->button()));
726 inputContext()->reset();
728 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
729 q_button_state(e->button()));
730 dispatch(cmd, q_key_state(e->modifiers()));
735 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
737 if (synthetic_mouse_event_.timeout.running())
738 synthetic_mouse_event_.timeout.stop();
740 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
741 q_button_state(e->button()));
747 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
749 // we kill the triple click if we move
750 doubleClickTimeout();
751 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
752 q_motion_state(e->buttons()));
756 // If we're above or below the work area...
757 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
758 // Make sure only a synthetic event can cause a page scroll,
759 // so they come at a steady rate:
761 // _Force_ a scroll up:
764 cmd.y = viewport()->height();
765 // Store the event, to be handled when the timeout expires.
766 synthetic_mouse_event_.cmd = cmd;
768 if (synthetic_mouse_event_.timeout.running())
769 // Discard the event. Note that it _may_ be handled
770 // when the timeout expires if
771 // synthetic_mouse_event_.cmd has not been overwritten.
772 // Ie, when the timeout expires, we handle the
773 // most recent event but discard all others that
774 // occurred after the one used to start the timeout
775 // in the first place.
778 synthetic_mouse_event_.restart_timeout = true;
779 synthetic_mouse_event_.timeout.start();
780 // Fall through to handle this event...
782 } else if (synthetic_mouse_event_.timeout.running()) {
783 // Store the event, to be possibly handled when the timeout
785 // Once the timeout has expired, normal control is returned
786 // to mouseMoveEvent (restart_timeout = false).
787 // This results in a much smoother 'feel' when moving the
788 // mouse back into the work area.
789 synthetic_mouse_event_.cmd = cmd;
790 synthetic_mouse_event_.restart_timeout = false;
794 // Has anything changed on-screen since the last QMouseEvent
796 double const scrollbar_value = verticalScrollBar()->value();
797 if (e->x() == synthetic_mouse_event_.x_old
798 && e->y() == synthetic_mouse_event_.y_old
799 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
800 // Nothing changed on-screen since the last QMouseEvent.
804 // Yes something has changed. Store the params used to check this.
805 synthetic_mouse_event_.x_old = e->x();
806 synthetic_mouse_event_.y_old = e->y();
807 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
809 // ... and dispatch the event to the LyX core.
814 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
816 // Wheel rotation by one notch results in a delta() of 120 (see
817 // documentation of QWheelEvent)
818 int const delta = ev->delta() / 120;
819 if (ev->modifiers() & Qt::ControlModifier) {
820 lyxrc.zoom += 5 * delta;
823 // The global QPixmapCache is used in GuiPainter to cache text
824 // painting so we must reset it.
825 QPixmapCache::clear();
826 guiApp->fontLoader().update();
828 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
832 // Take into account the desktop wide settings.
833 int const lines = qApp->wheelScrollLines();
834 int const page_step = verticalScrollBar()->pageStep();
835 // Test if the wheel mouse is set to one screen at a time.
836 int scroll_value = lines > page_step
837 ? page_step : lines * verticalScrollBar()->singleStep();
839 // Take into account the rotation.
840 scroll_value *= delta;
842 // Take into account user preference.
843 scroll_value *= lyxrc.mouse_wheel_speed;
844 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
845 << " delta = " << delta << " scroll_value = " << scroll_value
846 << " page_step = " << page_step);
848 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
854 void GuiWorkArea::generateSyntheticMouseEvent()
856 // Set things off to generate the _next_ 'pseudo' event.
857 if (synthetic_mouse_event_.restart_timeout)
858 synthetic_mouse_event_.timeout.start();
860 // Has anything changed on-screen since the last timeout signal
862 double const scrollbar_value = verticalScrollBar()->value();
863 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
864 // Yes it has. Store the params used to check this.
865 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
867 // ... and dispatch the event to the LyX core.
868 dispatch(synthetic_mouse_event_.cmd);
873 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
875 // Do not process here some keys if dialog_mode_ is set
877 && (ev->modifiers() == Qt::NoModifier
878 || ev->modifiers() == Qt::ShiftModifier)
879 && (ev->key() == Qt::Key_Escape
880 || ev->key() == Qt::Key_Enter
881 || ev->key() == Qt::Key_Return)
887 // intercept some keys if completion popup is visible
888 if (completer_->popupVisible()) {
892 completer_->activate();
898 // do nothing if there are other events
899 // (the auto repeated events come too fast)
900 // \todo FIXME: remove hard coded Qt keys, process the key binding
902 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
903 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
904 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
910 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
911 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
914 setKeySymbol(&sym, ev);
915 processKeySym(sym, q_key_state(ev->modifiers()));
920 void GuiWorkArea::doubleClickTimeout()
922 dc_event_.active = false;
926 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
928 dc_event_ = DoubleClick(ev);
929 QTimer::singleShot(QApplication::doubleClickInterval(), this,
930 SLOT(doubleClickTimeout()));
931 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
933 q_button_state(ev->button()));
939 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
941 QAbstractScrollArea::resizeEvent(ev);
947 void GuiWorkArea::update(int x, int y, int w, int h)
949 viewport()->repaint(x, y, w, h);
953 void GuiWorkArea::paintEvent(QPaintEvent * ev)
955 QRect const rc = ev->rect();
956 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
957 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
960 screen_ = QPixmap(viewport()->width(), viewport()->height());
966 QPainter pain(viewport());
967 pain.drawPixmap(rc, screen_, rc);
973 void GuiWorkArea::updateScreen()
975 GuiPainter pain(&screen_);
976 buffer_view_->draw(pain);
980 void GuiWorkArea::showCursor(int x, int y, int h,
981 bool l_shape, bool rtl, bool completable)
983 if (schedule_redraw_) {
984 // This happens when a graphic conversion is finished. As we don't know
985 // the size of the new graphics, it's better the update everything.
986 // We can't use redraw() here because this would trigger a infinite
987 // recursive loop with showCursor().
988 buffer_view_->resize(viewport()->width(), viewport()->height());
991 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
992 schedule_redraw_ = false;
993 // Show the cursor immediately after the update.
999 cursor_->update(x, y, h, l_shape, rtl, completable);
1001 viewport()->update(cursor_->rect());
1005 void GuiWorkArea::removeCursor()
1008 //if (!qApp->focusWidget())
1009 viewport()->update(cursor_->rect());
1013 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1015 QString const & commit_string = e->commitString();
1016 docstring const & preedit_string
1017 = qstring_to_ucs4(e->preeditString());
1019 if (!commit_string.isEmpty()) {
1021 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1022 << " commitString: " << e->commitString());
1026 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1027 for (int i = 0; i != commit_string.size(); ++i) {
1028 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1033 // Hide the cursor during the kana-kanji transformation.
1034 if (preedit_string.empty())
1035 startBlinkingCursor();
1037 stopBlinkingCursor();
1039 // last_width : for checking if last preedit string was/wasn't empty.
1040 static bool last_width = false;
1041 if (!last_width && preedit_string.empty()) {
1042 // if last_width is last length of preedit string.
1047 GuiPainter pain(&screen_);
1048 buffer_view_->updateMetrics();
1049 buffer_view_->draw(pain);
1050 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1051 FontMetrics const & fm = theFontMetrics(font);
1052 int height = fm.maxHeight();
1053 int cur_x = cursor_->rect().left();
1054 int cur_y = cursor_->rect().bottom();
1056 // redraw area of preedit string.
1057 update(0, cur_y - height, viewport()->width(),
1058 (height + 1) * preedit_lines_);
1060 if (preedit_string.empty()) {
1068 // att : stores an IM attribute.
1069 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1071 // get attributes of input method cursor.
1072 // cursor_pos : cursor position in preedit string.
1073 size_t cursor_pos = 0;
1074 bool cursor_is_visible = false;
1075 for (int i = 0; i != att.size(); ++i) {
1076 if (att.at(i).type == QInputMethodEvent::Cursor) {
1077 cursor_pos = att.at(i).start;
1078 cursor_is_visible = att.at(i).length != 0;
1083 size_t preedit_length = preedit_string.length();
1085 // get position of selection in input method.
1086 // FIXME: isn't there a way to do this simplier?
1087 // rStart : cursor position in selected string in IM.
1089 // rLength : selected string length in IM.
1091 if (cursor_pos < preedit_length) {
1092 for (int i = 0; i != att.size(); ++i) {
1093 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1094 if (att.at(i).start <= int(cursor_pos)
1095 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1096 rStart = att.at(i).start;
1097 rLength = att.at(i).length;
1098 if (!cursor_is_visible)
1099 cursor_pos += rLength;
1106 rStart = cursor_pos;
1110 int const right_margin = buffer_view_->rightMargin();
1111 Painter::preedit_style ps;
1112 // Most often there would be only one line:
1114 for (size_t pos = 0; pos != preedit_length; ++pos) {
1115 char_type const typed_char = preedit_string[pos];
1116 // reset preedit string style
1117 ps = Painter::preedit_default;
1119 // if we reached the right extremity of the screen, go to next line.
1120 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1121 cur_x = right_margin;
1122 cur_y += height + 1;
1125 // preedit strings are displayed with dashed underline
1126 // and partial strings are displayed white on black indicating
1127 // that we are in selecting mode in the input method.
1128 // FIXME: rLength == preedit_length is not a changing condition
1129 // FIXME: should be put out of the loop.
1131 && pos < rStart + rLength
1132 && !(cursor_pos < rLength && rLength == preedit_length))
1133 ps = Painter::preedit_selecting;
1135 if (pos == cursor_pos
1136 && (cursor_pos < rLength && rLength == preedit_length))
1137 ps = Painter::preedit_cursor;
1139 // draw one character and update cur_x.
1140 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1143 // update the preedit string screen area.
1144 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1145 (height + 1) * preedit_lines_);
1147 // Don't forget to accept the event!
1152 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1154 QRect cur_r(0, 0, 0, 0);
1156 // this is the CJK-specific composition window position.
1157 case Qt::ImMicroFocus:
1158 cur_r = cursor_->rect();
1159 if (preedit_lines_ != 1)
1161 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1162 // return lower right of cursor in LyX.
1165 return QWidget::inputMethodQuery(query);
1170 void GuiWorkArea::updateWindowTitle()
1172 docstring maximize_title;
1173 docstring minimize_title;
1175 Buffer & buf = buffer_view_->buffer();
1176 FileName const fileName = buf.fileName();
1177 if (!fileName.empty()) {
1178 maximize_title = fileName.displayName(30);
1179 minimize_title = from_utf8(fileName.onlyFileName());
1180 if (buf.lyxvc().inUse()) {
1181 if (buf.lyxvc().locker().empty())
1182 maximize_title += _(" (version control)");
1184 maximize_title += _(" (version control, locking)");
1186 if (!buf.isClean()) {
1187 maximize_title += _(" (changed)");
1188 minimize_title += char_type('*');
1190 if (buf.isReadonly())
1191 maximize_title += _(" (read only)");
1194 QString title = windowTitle();
1195 QString new_title = toqstr(maximize_title);
1196 if (title == new_title)
1199 QWidget::setWindowTitle(new_title);
1200 QWidget::setWindowIconText(toqstr(minimize_title));
1205 void GuiWorkArea::setReadOnly(bool)
1207 updateWindowTitle();
1208 if (this == lyx_view_->currentWorkArea())
1209 lyx_view_->updateDialogs();
1213 bool GuiWorkArea::isFullScreen()
1215 return lyx_view_ && lyx_view_->isFullScreen();
1219 ////////////////////////////////////////////////////////////////////
1223 ////////////////////////////////////////////////////////////////////
1226 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1228 buffer_ = theBufferList().newBuffer(
1229 support::FileName::tempName().absFilename() + "_embedded.internal");
1230 buffer_->setUnnamed(true);
1231 buffer_->setFullyLoaded(true);
1232 setBuffer(*buffer_);
1233 setDialogMode(true);
1237 EmbeddedWorkArea::~EmbeddedWorkArea()
1239 // No need to destroy buffer and bufferview here, because it is done
1240 // in theBuffeerList() destruction loop at application exit
1244 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1247 GuiWorkArea::closeEvent(ev);
1251 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1254 GuiWorkArea::hideEvent(ev);
1258 void EmbeddedWorkArea::disable()
1260 stopBlinkingCursor();
1261 if (view().currentWorkArea() != this)
1263 LASSERT(view().currentMainWorkArea(), /* */);
1264 view().setCurrentWorkArea(view().currentMainWorkArea());
1267 ////////////////////////////////////////////////////////////////////
1271 ////////////////////////////////////////////////////////////////////
1274 class NoTabFrameMacStyle : public QMacStyle {
1277 QRect subElementRect(SubElement element, const QStyleOption * option,
1278 const QWidget * widget = 0) const
1280 QRect rect = QMacStyle::subElementRect(element, option, widget);
1281 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1283 // The Qt Mac style puts the contents into a 3 pixel wide box
1284 // which looks very ugly and not like other Mac applications.
1285 // Hence we remove this here, and moreover the 16 pixel round
1286 // frame above if the tab bar is hidden.
1287 if (element == QStyle::SE_TabWidgetTabContents) {
1288 rect.adjust(- rect.left(), 0, rect.left(), 0);
1297 NoTabFrameMacStyle noTabFrameMacStyle;
1301 TabWorkArea::TabWorkArea(QWidget * parent)
1302 : QTabWidget(parent), clicked_tab_(-1)
1305 setStyle(&noTabFrameMacStyle);
1308 QPalette pal = palette();
1309 pal.setColor(QPalette::Active, QPalette::Button,
1310 pal.color(QPalette::Active, QPalette::Window));
1311 pal.setColor(QPalette::Disabled, QPalette::Button,
1312 pal.color(QPalette::Disabled, QPalette::Window));
1313 pal.setColor(QPalette::Inactive, QPalette::Button,
1314 pal.color(QPalette::Inactive, QPalette::Window));
1316 QObject::connect(this, SIGNAL(currentChanged(int)),
1317 this, SLOT(on_currentTabChanged(int)));
1319 closeBufferButton = new QToolButton(this);
1320 closeBufferButton->setPalette(pal);
1321 // FIXME: rename the icon to closebuffer.png
1322 closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1323 closeBufferButton->setText("Close File");
1324 closeBufferButton->setAutoRaise(true);
1325 closeBufferButton->setCursor(Qt::ArrowCursor);
1326 closeBufferButton->setToolTip(qt_("Close File"));
1327 closeBufferButton->setEnabled(true);
1328 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1329 this, SLOT(closeCurrentBuffer()));
1330 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1332 // setup drag'n'drop
1333 QTabBar* tb = new DragTabBar;
1334 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1335 this, SLOT(moveTab(int, int)));
1336 tb->setElideMode(Qt::ElideNone);
1339 // make us responsible for the context menu of the tabbar
1340 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1341 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1342 this, SLOT(showContextMenu(const QPoint &)));
1344 setUsesScrollButtons(true);
1348 void TabWorkArea::setFullScreen(bool full_screen)
1350 for (int i = 0; i != count(); ++i) {
1351 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1352 wa->setFullScreen(full_screen);
1355 if (lyxrc.full_screen_tabbar)
1356 showBar(!full_screen && count()>1);
1360 void TabWorkArea::showBar(bool show)
1362 tabBar()->setEnabled(show);
1363 tabBar()->setVisible(show);
1364 closeBufferButton->setVisible(show);
1368 GuiWorkArea * TabWorkArea::currentWorkArea()
1373 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1379 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1381 for (int i = 0; i != count(); ++i) {
1382 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1383 LASSERT(wa, return 0);
1384 if (&wa->bufferView().buffer() == &buffer)
1391 void TabWorkArea::closeAll()
1394 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1402 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1404 LASSERT(work_area, /**/);
1405 int index = indexOf(work_area);
1409 if (index == currentIndex())
1410 // Make sure the work area is up to date.
1411 on_currentTabChanged(index);
1413 // Switch to the work area.
1414 setCurrentIndex(index);
1415 work_area->setFocus();
1421 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1423 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1424 wa->setUpdatesEnabled(false);
1425 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1426 // when hiding it again below).
1427 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1428 showBar(count() > 0);
1429 addTab(wa, wa->windowTitle());
1430 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1431 this, SLOT(updateTabTexts()));
1432 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1433 setFullScreen(true);
1435 // Hide tabbar if there's only one tab.
1436 showBar(count() > 1);
1444 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1446 LASSERT(work_area, return false);
1447 int index = indexOf(work_area);
1451 work_area->setUpdatesEnabled(false);
1456 // make sure the next work area is enabled.
1457 currentWidget()->setUpdatesEnabled(true);
1458 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1459 setFullScreen(true);
1461 // Hide tabbar if there's only one tab.
1462 showBar(count() > 1);
1464 lastWorkAreaRemoved();
1473 void TabWorkArea::on_currentTabChanged(int i)
1475 // returns e.g. on application destruction
1478 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1479 LASSERT(wa, return);
1480 BufferView & bv = wa->bufferView();
1481 bv.cursor().fixIfBroken();
1483 wa->setUpdatesEnabled(true);
1487 currentWorkAreaChanged(wa);
1489 LYXERR(Debug::GUI, "currentTabChanged " << i
1490 << "File" << bv.buffer().absFileName());
1494 void TabWorkArea::closeCurrentBuffer()
1496 if (clicked_tab_ != -1)
1497 setCurrentIndex(clicked_tab_);
1499 // Before dispatching the LFUN we should be sure this
1500 // is the current workarea.
1501 currentWorkAreaChanged(currentWorkArea());
1503 lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1507 void TabWorkArea::closeCurrentTab()
1509 if (clicked_tab_ == -1)
1510 removeWorkArea(currentWorkArea());
1512 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1521 /// make vector happy
1524 DisplayPath(int tab, FileName const & filename)
1527 filename_ = toqstr(filename.onlyFileNameWithoutExt());
1528 postfix_ = toqstr(filename.absoluteFilePath()).
1529 split("/", QString::SkipEmptyParts);
1530 postfix_.pop_back();
1531 abs_ = toqstr(filename.absoluteFilePath());
1532 dottedPrefix_ = false;
1535 /// Absolute path for debugging.
1540 /// Add the first segment from the postfix or three dots to the prefix.
1541 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1542 /// when really needed.
1543 void shiftPathSegment(bool dotted)
1545 if (postfix_.count() <= 0)
1549 if (dottedPrefix_ && !prefix_.isEmpty())
1551 prefix_ += postfix_.front() + "/";
1553 dottedPrefix_ = dotted && !prefix_.isEmpty();
1554 postfix_.pop_front();
1557 QString displayString() const
1559 if (prefix_.isEmpty())
1562 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1563 return prefix_ + (dots ? ".../" : "") + filename_;
1566 QString forecastPathString() const
1568 if (postfix_.count() == 0)
1569 return displayString();
1572 + (dottedPrefix_ ? ".../" : "")
1573 + postfix_.front() + "/";
1576 bool final() const { return postfix_.empty(); }
1578 int tab() const { return tab_; }
1584 QStringList postfix_;
1597 bool operator<(DisplayPath const & a, DisplayPath const & b)
1599 return a.displayString() < b.displayString();
1603 bool operator==(DisplayPath const & a, DisplayPath const & b)
1605 return a.displayString() == b.displayString();
1609 void TabWorkArea::updateTabTexts()
1614 std::list<DisplayPath> paths;
1615 typedef std::list<DisplayPath>::iterator It;
1617 // collect full names first: path into postfix, empty prefix and
1618 // filename without extension
1619 for (size_t i = 0; i < n; ++i) {
1620 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(i));
1621 FileName const fn = i_wa->bufferView().buffer().fileName();
1622 paths.push_back(DisplayPath(i, fn));
1625 // go through path segments and see if it helps to make the path more unique
1626 bool somethingChanged = true;
1627 bool allFinal = false;
1628 while (somethingChanged && !allFinal) {
1629 // adding path segments changes order
1632 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1633 somethingChanged = false;
1636 // find segments which are not unique (i.e. non-atomic)
1637 It it = paths.begin();
1639 QString segString = it->displayString();
1640 for (; it != paths.end(); ++it) {
1641 // look to the next item
1646 allFinal = allFinal && it->final();
1648 LYXERR(Debug::GUI, "it = " << it->abs()
1649 << " => " << it->displayString());
1651 // still the same segment?
1653 if ((next != paths.end()
1654 && (nextString = next->displayString()) == segString))
1656 LYXERR(Debug::GUI, "segment ended");
1658 // only a trivial one with one element?
1659 if (it == segStart) {
1660 // start new segment
1662 segString = nextString;
1666 // we found a non-atomic segment segStart <= sit <= it < next.
1667 // Shift path segments and hope for the best
1668 // that it makes the path more unique.
1669 somethingChanged = true;
1671 QString dspString = sit->forecastPathString();
1672 LYXERR(Debug::GUI, "first forecast found for "
1673 << sit->abs() << " => " << dspString);
1675 bool moreUnique = false;
1676 for (; sit != next; ++sit) {
1677 if (sit->forecastPathString() != dspString) {
1678 LYXERR(Debug::GUI, "different forecast found for "
1679 << sit->abs() << " => " << sit->forecastPathString());
1683 LYXERR(Debug::GUI, "same forecast found for "
1684 << sit->abs() << " => " << dspString);
1687 // if the path segment helped, add it. Otherwise add dots
1688 bool dots = !moreUnique;
1689 LYXERR(Debug::GUI, "using dots = " << dots);
1690 for (sit = segStart; sit != next; ++sit) {
1691 sit->shiftPathSegment(dots);
1692 LYXERR(Debug::GUI, "shifting "
1693 << sit->abs() << " => " << sit->displayString());
1696 // start new segment
1698 segString = nextString;
1702 // set new tab titles
1703 for (It it = paths.begin(); it != paths.end(); ++it) {
1704 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(it->tab()));
1705 Buffer & buf = i_wa->bufferView().buffer();
1706 if (!buf.fileName().empty() && !buf.isClean())
1707 setTabText(it->tab(), it->displayString() + "*");
1709 setTabText(it->tab(), it->displayString());
1714 void TabWorkArea::showContextMenu(const QPoint & pos)
1717 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1718 if (clicked_tab_ == -1)
1723 popup.addAction(QIcon(":/images/hidetab.png"),
1724 qt_("Hide tab"), this, SLOT(closeCurrentTab()));
1725 popup.addAction(QIcon(":/images/closetab.png"),
1726 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1727 popup.exec(tabBar()->mapToGlobal(pos));
1733 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1735 QWidget * w = widget(fromIndex);
1736 QIcon icon = tabIcon(fromIndex);
1737 QString text = tabText(fromIndex);
1739 setCurrentIndex(fromIndex);
1740 removeTab(fromIndex);
1741 insertTab(toIndex, w, icon, text);
1742 setCurrentIndex(toIndex);
1746 DragTabBar::DragTabBar(QWidget* parent)
1749 setAcceptDrops(true);
1753 #if QT_VERSION < 0x040300
1754 int DragTabBar::tabAt(QPoint const & position) const
1756 const int max = count();
1757 for (int i = 0; i < max; ++i) {
1758 if (tabRect(i).contains(position))
1766 void DragTabBar::mousePressEvent(QMouseEvent * event)
1768 if (event->button() == Qt::LeftButton)
1769 dragStartPos_ = event->pos();
1770 QTabBar::mousePressEvent(event);
1774 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1776 // If the left button isn't pressed anymore then return
1777 if (!(event->buttons() & Qt::LeftButton))
1780 // If the distance is too small then return
1781 if ((event->pos() - dragStartPos_).manhattanLength()
1782 < QApplication::startDragDistance())
1785 // did we hit something after all?
1786 int tab = tabAt(dragStartPos_);
1790 // simulate button release to remove highlight from button
1791 int i = currentIndex();
1792 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1793 event->button(), event->buttons(), 0);
1794 QTabBar::mouseReleaseEvent(&me);
1798 QDrag * drag = new QDrag(this);
1799 QMimeData * mimeData = new QMimeData;
1800 // a crude way to distinguish tab-reodering drops from other ones
1801 mimeData->setData("action", "tab-reordering") ;
1802 drag->setMimeData(mimeData);
1804 #if QT_VERSION >= 0x040300
1805 // get tab pixmap as cursor
1806 QRect r = tabRect(tab);
1807 QPixmap pixmap(r.size());
1808 render(&pixmap, - r.topLeft());
1809 drag->setPixmap(pixmap);
1812 drag->start(Qt::MoveAction);
1818 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1820 // Only accept if it's an tab-reordering request
1821 QMimeData const * m = event->mimeData();
1822 QStringList formats = m->formats();
1823 if (formats.contains("action")
1824 && m->data("action") == "tab-reordering")
1825 event->acceptProposedAction();
1829 void DragTabBar::dropEvent(QDropEvent * event)
1831 int fromIndex = tabAt(dragStartPos_);
1832 int toIndex = tabAt(event->pos());
1834 // Tell interested objects that
1835 if (fromIndex != toIndex)
1836 tabMoveRequested(fromIndex, toIndex);
1837 event->acceptProposedAction();
1841 } // namespace frontend
1844 #include "moc_GuiWorkArea.cpp"