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 "BufferParams.h"
22 #include "BufferView.h"
23 #include "CoordCache.h"
26 #include "FuncRequest.h"
27 #include "GuiApplication.h"
28 #include "GuiCompleter.h"
29 #include "GuiKeySymbol.h"
30 #include "GuiPainter.h"
32 #include "KeySymbol.h"
37 #include "MetricsInfo.h"
38 #include "qt_helpers.h"
42 #include "graphics/GraphicsImage.h"
43 #include "graphics/GraphicsLoader.h"
45 #include "support/debug.h"
46 #include "support/gettext.h"
47 #include "support/FileName.h"
49 #include "frontends/Application.h"
50 #include "frontends/FontMetrics.h"
51 #include "frontends/WorkAreaManager.h"
53 #include <QContextMenuEvent>
54 #include <QInputContext>
59 #include <QMainWindow>
63 #include <QPixmapCache>
66 #include <QToolButton>
70 #include <boost/bind.hpp>
76 extern "C" int XEventsQueued(Display *display, int mode);
80 int const CursorWidth = 2;
82 int const CursorWidth = 1;
84 int const TabIndicatorWidth = 3;
90 using namespace lyx::support;
95 /// return the LyX mouse button state from Qt's
96 static mouse_button::state q_button_state(Qt::MouseButton button)
98 mouse_button::state b = mouse_button::none;
101 b = mouse_button::button1;
104 b = mouse_button::button2;
106 case Qt::RightButton:
107 b = mouse_button::button3;
116 /// return the LyX mouse button state from Qt's
117 mouse_button::state q_motion_state(Qt::MouseButtons state)
119 mouse_button::state b = mouse_button::none;
120 if (state & Qt::LeftButton)
121 b |= mouse_button::button1;
122 if (state & Qt::MidButton)
123 b |= mouse_button::button2;
124 if (state & Qt::RightButton)
125 b |= mouse_button::button3;
136 void draw(QPainter & painter)
138 if (!show_ || !rect_.isValid())
142 int l = x_ - rect_.left();
143 int r = rect_.right() - x_;
144 int bot = rect_.bottom();
146 // draw vertica linel
147 painter.fillRect(x_, y, CursorWidth, rect_.height(), color_);
149 // draw RTL/LTR indication
150 painter.setPen(color_);
153 painter.drawLine(x_, bot, x_ - l, bot);
155 painter.drawLine(x_, bot, x_ + CursorWidth + r, bot);
158 // draw completion triangle
160 int m = y + rect_.height() / 2;
161 int d = TabIndicatorWidth - 1;
163 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
164 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
166 painter.drawLine(x_ + CursorWidth, m - d, x_ + CursorWidth + d, m);
167 painter.drawLine(x_ + CursorWidth, m + d, x_ + CursorWidth + d, m);
172 void update(int x, int y, int h, bool l_shape,
173 bool rtl, bool completable)
175 color_ = guiApp->colorCache().get(Color_cursor);
178 completable_ = completable;
181 // extension to left and right
185 // RTL/LTR indication
193 // completion triangle
196 l = max(l, TabIndicatorWidth);
198 r = max(r, TabIndicatorWidth);
201 // compute overall rectangle
202 rect_ = QRect(x - l, y, CursorWidth + r + l, h);
205 void show(bool set_show = true) { show_ = set_show; }
206 void hide() { show_ = false; }
208 QRect const & rect() { return rect_; }
211 /// cursor is in RTL or LTR text
213 /// indication for RTL or LTR
215 /// triangle to show that a completion is available
221 /// rectangle, possibly with l_shape and completion triangle
223 /// x position (were the vertical line is drawn)
228 // This is a 'heartbeat' generating synthetic mouse move events when the
229 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
230 SyntheticMouseEvent::SyntheticMouseEvent()
231 : timeout(200), restart_timeout(true),
232 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
237 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & lv)
238 : buffer_view_(new BufferView(buffer)), lyx_view_(&lv),
239 cursor_visible_(false),
240 need_resize_(false), schedule_redraw_(false),
241 preedit_lines_(1), completer_(new GuiCompleter(this))
243 buffer.workAreaManager().add(this);
245 connect(&cursor_timeout_, SIGNAL(timeout()),
246 this, SLOT(toggleCursor()));
248 int const time = QApplication::cursorFlashTime() / 2;
250 cursor_timeout_.setInterval(time);
251 cursor_timeout_.start();
253 // let's initialize this just to be safe
254 cursor_timeout_.setInterval(500);
257 screen_ = QPixmap(viewport()->width(), viewport()->height());
258 cursor_ = new frontend::CursorWidget();
261 // HACK: Prevents an additional redraw when the scrollbar pops up
262 // which regularily happens on documents with more than one page.
263 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
264 // Since we have no geometry information yet, we assume that
265 // a document needs a scrollbar if there is more then four
266 // paragraph in the outermost text.
267 if (buffer.text().paragraphs().size() > 4)
268 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
269 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
272 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
273 setAcceptDrops(true);
274 setMouseTracking(true);
275 setMinimumSize(100, 70);
277 setFrameStyle(QFrame::NoFrame);
279 setFrameStyle(QFrame::Box);
283 viewport()->setAutoFillBackground(false);
284 // We don't need double-buffering nor SystemBackground on
285 // the viewport because we have our own backing pixmap.
286 viewport()->setAttribute(Qt::WA_NoSystemBackground);
288 setFocusPolicy(Qt::WheelFocus);
290 viewport()->setCursor(Qt::IBeamCursor);
292 synthetic_mouse_event_.timeout.timeout.connect(
293 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
296 // Initialize the vertical Scroll Bar
297 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
298 this, SLOT(scrollTo(int)));
300 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
301 << " viewport height: " << viewport()->height());
303 // Enables input methods for asian languages.
304 // Must be set when creating custom text editing widgets.
305 setAttribute(Qt::WA_InputMethodEnabled, true);
309 GuiWorkArea::~GuiWorkArea()
311 buffer_view_->buffer().workAreaManager().remove(this);
314 // Completer has a QObject parent and is thus automatically destroyed.
315 // delete completer_;
319 void GuiWorkArea::fixVerticalScrollBar()
322 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
326 void GuiWorkArea::close()
328 lyx_view_->removeWorkArea(this);
332 void GuiWorkArea::setFullScreen(bool full_screen)
334 buffer_view_->setFullScreen(full_screen);
336 setFrameStyle(QFrame::NoFrame);
337 if (lyxrc.full_screen_scrollbar)
338 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
341 setFrameStyle(QFrame::NoFrame);
343 setFrameStyle(QFrame::Box);
345 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
350 BufferView & GuiWorkArea::bufferView()
352 return *buffer_view_;
356 BufferView const & GuiWorkArea::bufferView() const
358 return *buffer_view_;
362 void GuiWorkArea::stopBlinkingCursor()
364 cursor_timeout_.stop();
369 void GuiWorkArea::startBlinkingCursor()
372 //we're not supposed to cache this value.
373 int const time = QApplication::cursorFlashTime() / 2;
376 cursor_timeout_.setInterval(time);
377 cursor_timeout_.start();
381 void GuiWorkArea::redraw()
384 // No need to redraw in this case.
387 // No need to do anything if this is the current view. The BufferView
388 // metrics are already up to date.
389 if (lyx_view_ != guiApp->currentView()
390 || lyx_view_->currentWorkArea() != this) {
391 // FIXME: it would be nice to optimize for the off-screen case.
392 buffer_view_->updateMetrics();
393 buffer_view_->cursor().fixIfBroken();
396 // update cursor position, because otherwise it has to wait until
397 // the blinking interval is over
398 if (cursor_visible_) {
403 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
405 update(0, 0, viewport()->width(), viewport()->height());
407 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
408 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
410 lyx_view_->updateStatusBar();
412 if (lyxerr.debugging(Debug::WORKAREA))
413 buffer_view_->coordCache().dump();
417 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
419 if (lyx_view_->isFullScreen() && lyx_view_->menuBar()->isVisible()) {
420 // FIXME HACK: we should not have to do this here. See related comment
421 // in GuiView::event() (QEvent::ShortcutOverride)
422 lyx_view_->menuBar()->hide();
425 // In order to avoid bad surprise in the middle of an operation,
426 // we better stop the blinking cursor...
427 // the cursor gets restarted in GuiView::restartCursor()
428 stopBlinkingCursor();
430 theLyXFunc().setLyXView(lyx_view_);
431 theLyXFunc().processKeySym(key, mod);
435 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
438 if (cmd0.action == LFUN_FILE_OPEN) {
439 lyx_view_->dispatch(cmd0);
443 theLyXFunc().setLyXView(lyx_view_);
447 if (cmd0.action == LFUN_MOUSE_PRESS) {
448 if (mod == ShiftModifier)
449 cmd = FuncRequest(cmd0, "region-select");
450 else if (mod == ControlModifier)
451 cmd = FuncRequest(cmd0, "paragraph-select");
458 bool const notJustMovingTheMouse =
459 cmd.action != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
461 // In order to avoid bad surprise in the middle of an operation, we better stop
462 // the blinking cursor.
463 if (notJustMovingTheMouse)
464 stopBlinkingCursor();
466 buffer_view_->mouseEventDispatch(cmd);
468 // Skip these when selecting
469 if (cmd.action != LFUN_MOUSE_MOTION) {
470 completer_->updateVisibility(false, false);
471 lyx_view_->updateDialogs();
472 lyx_view_->updateStatusBar();
475 // GUI tweaks except with mouse motion with no button pressed.
476 if (notJustMovingTheMouse) {
477 // Slight hack: this is only called currently when we
478 // clicked somewhere, so we force through the display
479 // of the new status here.
480 lyx_view_->clearMessage();
482 // Show the cursor immediately after any operation
483 startBlinkingCursor();
488 void GuiWorkArea::resizeBufferView()
490 // WARNING: Please don't put any code that will trigger a repaint here!
491 // We are already inside a paint event.
492 lyx_view_->setBusy(true);
493 buffer_view_->resize(viewport()->width(), viewport()->height());
496 // Update scrollbars which might have changed due different
497 // BufferView dimension. This is especially important when the
498 // BufferView goes from zero-size to the real-size for the first time,
499 // as the scrollbar paramters are then set for the first time.
502 lyx_view_->updateLayoutList();
503 lyx_view_->setBusy(false);
504 need_resize_ = false;
508 void GuiWorkArea::showCursor()
514 bool l_shape = false;
515 Font const & realfont = buffer_view_->cursor().real_current_font;
516 BufferParams const & bp = buffer_view_->buffer().params();
517 bool const samelang = realfont.language() == bp.language;
518 bool const isrtl = realfont.isVisibleRightToLeft();
520 if (!samelang || isrtl != bp.language->rightToLeft())
523 // The ERT language hack needs fixing up
524 if (realfont.language() == latex_language)
527 Font const font = buffer_view_->cursor().getFont();
528 FontMetrics const & fm = theFontMetrics(font);
529 int const asc = fm.maxAscent();
530 int const des = fm.maxDescent();
534 Cursor & cur = buffer_view_->cursor();
538 // if it doesn't touch the screen, don't try to show it
539 bool cursorInView = true;
540 if (y + h < 0 || y >= viewport()->height())
541 cursorInView = false;
543 // show cursor on screen
544 bool completable = cur.inset().showCompletionCursor()
545 && completer_->completionAvailable()
546 && !completer_->popupVisible()
547 && !completer_->inlineVisible();
549 cursor_visible_ = true;
550 showCursor(x, y, h, l_shape, isrtl, completable);
555 void GuiWorkArea::hideCursor()
557 if (!cursor_visible_)
560 cursor_visible_ = false;
565 void GuiWorkArea::toggleCursor()
574 void GuiWorkArea::updateScrollbar()
576 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
577 // WARNING: don't touch at the scrollbar value like this:
578 // verticalScrollBar()->setValue(scroll_.position);
579 // because this would cause a recursive signal/slot calling with
580 // GuiWorkArea::scrollTo
581 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
582 verticalScrollBar()->setPageStep(scroll_.page_step);
583 verticalScrollBar()->setSingleStep(scroll_.single_step);
584 verticalScrollBar()->setSliderPosition(scroll_.position);
588 void GuiWorkArea::scrollTo(int value)
590 stopBlinkingCursor();
591 buffer_view_->scrollDocView(value);
593 if (lyxrc.cursor_follows_scrollbar) {
594 buffer_view_->setCursorFromScrollbar();
595 lyx_view_->updateLayoutList();
597 // Show the cursor immediately after any operation.
598 startBlinkingCursor();
599 QApplication::syncX();
603 bool GuiWorkArea::event(QEvent * e)
606 case QEvent::ToolTip: {
607 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
608 if (lyxrc.use_tooltip) {
609 QPoint pos = helpEvent->pos();
610 if (pos.x() < viewport()->width()) {
611 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
612 QToolTip::showText(helpEvent->globalPos(), s);
615 QToolTip::hideText();
617 // Don't forget to accept the event!
622 case QEvent::ShortcutOverride: {
623 // We catch this event in order to catch the Tab or Shift+Tab key press
624 // which are otherwise reserved to focus switching between controls
626 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
627 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
628 || ke->modifiers() & Qt::ControlModifier)
629 return QAbstractScrollArea::event(e);
635 return QAbstractScrollArea::event(e);
641 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
643 QPoint pos = e->pos();
644 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
646 QAbstractScrollArea::contextMenuEvent(e);
649 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
651 QAbstractScrollArea::contextMenuEvent(e);
654 // Position the menu to the right.
655 // FIXME: menu position should be different for RTL text.
656 menu->exec(e->globalPos());
661 void GuiWorkArea::focusInEvent(QFocusEvent * e)
663 if (lyx_view_->currentWorkArea() != this)
664 lyx_view_->setCurrentWorkArea(this);
666 startBlinkingCursor();
667 QAbstractScrollArea::focusInEvent(e);
671 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
673 stopBlinkingCursor();
674 QAbstractScrollArea::focusOutEvent(e);
678 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
680 if (dc_event_.active && dc_event_ == *e) {
681 dc_event_.active = false;
682 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
683 q_button_state(e->button()));
689 inputContext()->reset();
691 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
692 q_button_state(e->button()));
693 dispatch(cmd, q_key_state(e->modifiers()));
698 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
700 if (synthetic_mouse_event_.timeout.running())
701 synthetic_mouse_event_.timeout.stop();
703 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
704 q_button_state(e->button()));
710 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
712 // we kill the triple click if we move
713 doubleClickTimeout();
714 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
715 q_motion_state(e->buttons()));
719 // If we're above or below the work area...
720 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
721 // Make sure only a synthetic event can cause a page scroll,
722 // so they come at a steady rate:
724 // _Force_ a scroll up:
727 cmd.y = viewport()->height();
728 // Store the event, to be handled when the timeout expires.
729 synthetic_mouse_event_.cmd = cmd;
731 if (synthetic_mouse_event_.timeout.running())
732 // Discard the event. Note that it _may_ be handled
733 // when the timeout expires if
734 // synthetic_mouse_event_.cmd has not been overwritten.
735 // Ie, when the timeout expires, we handle the
736 // most recent event but discard all others that
737 // occurred after the one used to start the timeout
738 // in the first place.
741 synthetic_mouse_event_.restart_timeout = true;
742 synthetic_mouse_event_.timeout.start();
743 // Fall through to handle this event...
745 } else if (synthetic_mouse_event_.timeout.running()) {
746 // Store the event, to be possibly handled when the timeout
748 // Once the timeout has expired, normal control is returned
749 // to mouseMoveEvent (restart_timeout = false).
750 // This results in a much smoother 'feel' when moving the
751 // mouse back into the work area.
752 synthetic_mouse_event_.cmd = cmd;
753 synthetic_mouse_event_.restart_timeout = false;
757 // Has anything changed on-screen since the last QMouseEvent
759 double const scrollbar_value = verticalScrollBar()->value();
760 if (e->x() == synthetic_mouse_event_.x_old
761 && e->y() == synthetic_mouse_event_.y_old
762 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
763 // Nothing changed on-screen since the last QMouseEvent.
767 // Yes something has changed. Store the params used to check this.
768 synthetic_mouse_event_.x_old = e->x();
769 synthetic_mouse_event_.y_old = e->y();
770 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
772 // ... and dispatch the event to the LyX core.
777 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
779 // Wheel rotation by one notch results in a delta() of 120 (see
780 // documentation of QWheelEvent)
781 int const delta = ev->delta() / 120;
782 if (ev->modifiers() & Qt::ControlModifier) {
783 lyxrc.zoom += 5 * delta;
786 // The global QPixmapCache is used in GuiPainter to cache text
787 // painting so we must reset it.
788 QPixmapCache::clear();
789 guiApp->fontLoader().update();
791 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
795 // Take into account the desktop wide settings.
796 int const lines = qApp->wheelScrollLines();
797 int const page_step = verticalScrollBar()->pageStep();
798 // Test if the wheel mouse is set to one screen at a time.
799 int scroll_value = lines > page_step
800 ? page_step : lines * verticalScrollBar()->singleStep();
802 // Take into account the rotation.
803 scroll_value *= delta;
805 // Take into account user preference.
806 scroll_value *= lyxrc.mouse_wheel_speed;
807 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
808 << " delta = " << delta << " scroll_value = " << scroll_value
809 << " page_step = " << page_step);
811 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
817 void GuiWorkArea::generateSyntheticMouseEvent()
819 // Set things off to generate the _next_ 'pseudo' event.
820 if (synthetic_mouse_event_.restart_timeout)
821 synthetic_mouse_event_.timeout.start();
823 // Has anything changed on-screen since the last timeout signal
825 double const scrollbar_value = verticalScrollBar()->value();
826 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
827 // Yes it has. Store the params used to check this.
828 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
830 // ... and dispatch the event to the LyX core.
831 dispatch(synthetic_mouse_event_.cmd);
836 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
838 // intercept some keys if completion popup is visible
839 if (completer_->popupVisible()) {
843 completer_->activate();
849 // intercept keys for the completion
850 if ((completer_->popupVisible() || completer_->inlineVisible())
851 && ev->key() == Qt::Key_Tab) {
857 if (completer_->popupVisible() && ev->key() == Qt::Key_Escape) {
858 completer_->hidePopup();
863 if (completer_->inlineVisible() && ev->key() == Qt::Key_Escape) {
864 completer_->hideInline();
869 // do nothing if there are other events
870 // (the auto repeated events come too fast)
871 // \todo FIXME: remove hard coded Qt keys, process the key binding
873 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
874 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
875 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
881 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
882 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
885 setKeySymbol(&sym, ev);
886 processKeySym(sym, q_key_state(ev->modifiers()));
891 void GuiWorkArea::doubleClickTimeout()
893 dc_event_.active = false;
897 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
899 dc_event_ = DoubleClick(ev);
900 QTimer::singleShot(QApplication::doubleClickInterval(), this,
901 SLOT(doubleClickTimeout()));
902 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
904 q_button_state(ev->button()));
910 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
912 QAbstractScrollArea::resizeEvent(ev);
918 void GuiWorkArea::update(int x, int y, int w, int h)
920 viewport()->repaint(x, y, w, h);
924 void GuiWorkArea::paintEvent(QPaintEvent * ev)
926 QRect const rc = ev->rect();
927 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
928 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
931 screen_ = QPixmap(viewport()->width(), viewport()->height());
937 QPainter pain(viewport());
938 pain.drawPixmap(rc, screen_, rc);
944 void GuiWorkArea::updateScreen()
946 GuiPainter pain(&screen_);
947 buffer_view_->draw(pain);
951 void GuiWorkArea::showCursor(int x, int y, int h,
952 bool l_shape, bool rtl, bool completable)
954 if (schedule_redraw_) {
955 // This happens when a graphic conversion is finished. As we don't know
956 // the size of the new graphics, it's better the update everything.
957 // We can't use redraw() here because this would trigger a infinite
958 // recursive loop with showCursor().
959 buffer_view_->resize(viewport()->width(), viewport()->height());
962 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
963 schedule_redraw_ = false;
964 // Show the cursor immediately after the update.
970 cursor_->update(x, y, h, l_shape, rtl, completable);
972 viewport()->update(cursor_->rect());
976 void GuiWorkArea::removeCursor()
979 //if (!qApp->focusWidget())
980 viewport()->update(cursor_->rect());
984 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
986 QString const & commit_string = e->commitString();
987 docstring const & preedit_string
988 = qstring_to_ucs4(e->preeditString());
990 if (!commit_string.isEmpty()) {
992 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
993 << " commitString: " << e->commitString());
997 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
998 for (int i = 0; i != commit_string.size(); ++i) {
999 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1004 // Hide the cursor during the kana-kanji transformation.
1005 if (preedit_string.empty())
1006 startBlinkingCursor();
1008 stopBlinkingCursor();
1010 // last_width : for checking if last preedit string was/wasn't empty.
1011 static bool last_width = false;
1012 if (!last_width && preedit_string.empty()) {
1013 // if last_width is last length of preedit string.
1018 GuiPainter pain(&screen_);
1019 buffer_view_->updateMetrics();
1020 buffer_view_->draw(pain);
1021 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1022 FontMetrics const & fm = theFontMetrics(font);
1023 int height = fm.maxHeight();
1024 int cur_x = cursor_->rect().left();
1025 int cur_y = cursor_->rect().bottom();
1027 // redraw area of preedit string.
1028 update(0, cur_y - height, viewport()->width(),
1029 (height + 1) * preedit_lines_);
1031 if (preedit_string.empty()) {
1039 // att : stores an IM attribute.
1040 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1042 // get attributes of input method cursor.
1043 // cursor_pos : cursor position in preedit string.
1044 size_t cursor_pos = 0;
1045 bool cursor_is_visible = false;
1046 for (int i = 0; i != att.size(); ++i) {
1047 if (att.at(i).type == QInputMethodEvent::Cursor) {
1048 cursor_pos = att.at(i).start;
1049 cursor_is_visible = att.at(i).length != 0;
1054 size_t preedit_length = preedit_string.length();
1056 // get position of selection in input method.
1057 // FIXME: isn't there a way to do this simplier?
1058 // rStart : cursor position in selected string in IM.
1060 // rLength : selected string length in IM.
1062 if (cursor_pos < preedit_length) {
1063 for (int i = 0; i != att.size(); ++i) {
1064 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1065 if (att.at(i).start <= int(cursor_pos)
1066 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1067 rStart = att.at(i).start;
1068 rLength = att.at(i).length;
1069 if (!cursor_is_visible)
1070 cursor_pos += rLength;
1077 rStart = cursor_pos;
1081 int const right_margin = buffer_view_->rightMargin();
1082 Painter::preedit_style ps;
1083 // Most often there would be only one line:
1085 for (size_t pos = 0; pos != preedit_length; ++pos) {
1086 char_type const typed_char = preedit_string[pos];
1087 // reset preedit string style
1088 ps = Painter::preedit_default;
1090 // if we reached the right extremity of the screen, go to next line.
1091 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1092 cur_x = right_margin;
1093 cur_y += height + 1;
1096 // preedit strings are displayed with dashed underline
1097 // and partial strings are displayed white on black indicating
1098 // that we are in selecting mode in the input method.
1099 // FIXME: rLength == preedit_length is not a changing condition
1100 // FIXME: should be put out of the loop.
1102 && pos < rStart + rLength
1103 && !(cursor_pos < rLength && rLength == preedit_length))
1104 ps = Painter::preedit_selecting;
1106 if (pos == cursor_pos
1107 && (cursor_pos < rLength && rLength == preedit_length))
1108 ps = Painter::preedit_cursor;
1110 // draw one character and update cur_x.
1111 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1114 // update the preedit string screen area.
1115 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1116 (height + 1) * preedit_lines_);
1118 // Don't forget to accept the event!
1123 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1125 QRect cur_r(0,0,0,0);
1127 // this is the CJK-specific composition window position.
1128 case Qt::ImMicroFocus:
1129 cur_r = cursor_->rect();
1130 if (preedit_lines_ != 1)
1132 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1133 // return lower right of cursor in LyX.
1136 return QWidget::inputMethodQuery(query);
1141 void GuiWorkArea::updateWindowTitle()
1143 docstring maximize_title;
1144 docstring minimize_title;
1146 Buffer & buf = buffer_view_->buffer();
1147 FileName const fileName = buf.fileName();
1148 if (!fileName.empty()) {
1149 maximize_title = fileName.displayName(30);
1150 minimize_title = from_utf8(fileName.onlyFileName());
1151 if (buf.lyxvc().inUse())
1152 maximize_title += _(" (version control)");
1153 if (!buf.isClean()) {
1154 maximize_title += _(" (changed)");
1155 minimize_title += char_type('*');
1157 if (buf.isReadonly())
1158 maximize_title += _(" (read only)");
1161 QString title = windowTitle();
1162 QString new_title = toqstr(maximize_title);
1163 if (title == new_title)
1166 QWidget::setWindowTitle(new_title);
1167 QWidget::setWindowIconText(toqstr(minimize_title));
1172 void GuiWorkArea::setReadOnly(bool)
1174 updateWindowTitle();
1175 if (this == lyx_view_->currentWorkArea())
1176 lyx_view_->updateDialogs();
1180 bool GuiWorkArea::isFullScreen()
1182 return lyx_view_ && lyx_view_->isFullScreen();
1186 ////////////////////////////////////////////////////////////////////
1190 ////////////////////////////////////////////////////////////////////
1193 class NoTabFrameMacStyle : public QMacStyle {
1196 QRect subElementRect(SubElement element, const QStyleOption * option,
1197 const QWidget * widget = 0) const
1199 QRect rect = QMacStyle::subElementRect(element, option, widget);
1200 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1202 // The Qt Mac style puts the contents into a 3 pixel wide box
1203 // which looks very ugly and not like other Mac applications.
1204 // Hence we remove this here, and moreover the 16 pixel round
1205 // frame above if the tab bar is hidden.
1206 if (element == QStyle::SE_TabWidgetTabContents) {
1207 rect.adjust(- rect.left(), 0, rect.left(), 0);
1216 NoTabFrameMacStyle noTabFrameMacStyle;
1220 TabWorkArea::TabWorkArea(QWidget * parent)
1221 : QTabWidget(parent), clicked_tab_(-1)
1224 setStyle(&noTabFrameMacStyle);
1227 QPalette pal = palette();
1228 pal.setColor(QPalette::Active, QPalette::Button,
1229 pal.color(QPalette::Active, QPalette::Window));
1230 pal.setColor(QPalette::Disabled, QPalette::Button,
1231 pal.color(QPalette::Disabled, QPalette::Window));
1232 pal.setColor(QPalette::Inactive, QPalette::Button,
1233 pal.color(QPalette::Inactive, QPalette::Window));
1235 QObject::connect(this, SIGNAL(currentChanged(int)),
1236 this, SLOT(on_currentTabChanged(int)));
1238 QToolButton * closeBufferButton = new QToolButton(this);
1239 closeBufferButton->setPalette(pal);
1240 // FIXME: rename the icon to closebuffer.png
1241 closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1242 closeBufferButton->setText("Close File");
1243 closeBufferButton->setAutoRaise(true);
1244 closeBufferButton->setCursor(Qt::ArrowCursor);
1245 closeBufferButton->setToolTip(qt_("Close File"));
1246 closeBufferButton->setEnabled(true);
1247 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1248 this, SLOT(closeCurrentBuffer()));
1249 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1251 // setup drag'n'drop
1252 QTabBar* tb = new DragTabBar;
1253 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1254 this, SLOT(moveTab(int, int)));
1255 tb->setElideMode(Qt::ElideNone);
1258 // make us responsible for the context menu of the tabbar
1259 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1260 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1261 this, SLOT(showContextMenu(const QPoint &)));
1263 setUsesScrollButtons(true);
1267 void TabWorkArea::setFullScreen(bool full_screen)
1269 for (int i = 0; i != count(); ++i) {
1270 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1271 wa->setFullScreen(full_screen);
1274 if (lyxrc.full_screen_tabbar)
1275 showBar(!full_screen && count()>1);
1279 void TabWorkArea::showBar(bool show)
1281 tabBar()->setEnabled(show);
1282 tabBar()->setVisible(show);
1286 GuiWorkArea * TabWorkArea::currentWorkArea()
1291 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1297 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1299 for (int i = 0; i != count(); ++i) {
1300 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1301 LASSERT(wa, return 0);
1302 if (&wa->bufferView().buffer() == &buffer)
1309 void TabWorkArea::closeAll()
1312 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1320 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1322 LASSERT(work_area, /**/);
1323 int index = indexOf(work_area);
1327 if (index == currentIndex())
1328 // Make sure the work area is up to date.
1329 on_currentTabChanged(index);
1331 // Switch to the work area.
1332 setCurrentIndex(index);
1333 work_area->setFocus();
1339 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1341 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1342 wa->setUpdatesEnabled(false);
1343 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1344 // when hiding it again below).
1345 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1346 showBar(count() > 0);
1347 addTab(wa, wa->windowTitle());
1348 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1349 this, SLOT(updateTabTexts()));
1350 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1351 setFullScreen(true);
1353 // Hide tabbar if there's only one tab.
1354 showBar(count() > 1);
1362 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1364 LASSERT(work_area, return false);
1365 int index = indexOf(work_area);
1369 work_area->setUpdatesEnabled(false);
1374 // make sure the next work area is enabled.
1375 currentWidget()->setUpdatesEnabled(true);
1376 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1377 setFullScreen(true);
1379 // Hide tabbar if there's only one tab.
1380 showBar(count() > 1);
1382 lastWorkAreaRemoved();
1391 void TabWorkArea::on_currentTabChanged(int i)
1393 // returns e.g. on application destruction
1396 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1397 LASSERT(wa, return);
1398 BufferView & bv = wa->bufferView();
1399 bv.cursor().fixIfBroken();
1401 wa->setUpdatesEnabled(true);
1405 currentWorkAreaChanged(wa);
1407 LYXERR(Debug::GUI, "currentTabChanged " << i
1408 << "File" << bv.buffer().absFileName());
1412 void TabWorkArea::closeCurrentBuffer()
1414 if (clicked_tab_ != -1)
1415 setCurrentIndex(clicked_tab_);
1417 lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1421 void TabWorkArea::closeCurrentTab()
1423 if (clicked_tab_ == -1)
1424 removeWorkArea(currentWorkArea());
1426 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1435 /// make vector happy
1438 DisplayPath(int tab, FileName const & filename)
1441 filename_ = toqstr(filename.onlyFileNameWithoutExt());
1442 postfix_ = toqstr(filename.absoluteFilePath()).
1443 split("/", QString::SkipEmptyParts);
1444 postfix_.pop_back();
1445 abs_ = toqstr(filename.absoluteFilePath());
1446 dottedPrefix_ = false;
1449 /// Absolute path for debugging.
1454 /// Add the first segment from the postfix or three dots to the prefix.
1455 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1456 /// when really needed.
1457 void shiftPathSegment(bool dotted)
1459 if (postfix_.count() <= 0)
1463 if (dottedPrefix_ && !prefix_.isEmpty())
1465 prefix_ += postfix_.front() + "/";
1467 dottedPrefix_ = dotted && !prefix_.isEmpty();
1468 postfix_.pop_front();
1471 QString displayString() const
1473 if (prefix_.isEmpty())
1476 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1477 return prefix_ + (dots ? ".../" : "") + filename_;
1480 QString forecastPathString() const
1482 if (postfix_.count() == 0)
1483 return displayString();
1486 + (dottedPrefix_ ? ".../" : "")
1487 + postfix_.front() + "/";
1490 bool final() const { return postfix_.empty(); }
1492 int tab() const { return tab_; }
1498 QStringList postfix_;
1511 bool operator<(DisplayPath const & a, DisplayPath const & b)
1513 return a.displayString() < b.displayString();
1517 bool operator==(DisplayPath const & a, DisplayPath const & b)
1519 return a.displayString() == b.displayString();
1523 void TabWorkArea::updateTabTexts()
1528 std::list<DisplayPath> paths;
1529 typedef std::list<DisplayPath>::iterator It;
1531 // collect full names first: path into postfix, empty prefix and
1532 // filename without extension
1533 for (size_t i = 0; i < n; ++i) {
1534 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(i));
1535 FileName const fn = i_wa->bufferView().buffer().fileName();
1536 paths.push_back(DisplayPath(i, fn));
1539 // go through path segments and see if it helps to make the path more unique
1540 bool somethingChanged = true;
1541 bool allFinal = false;
1542 while (somethingChanged && !allFinal) {
1543 // adding path segments changes order
1546 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1547 somethingChanged = false;
1550 // find segments which are not unique (i.e. non-atomic)
1551 It it = paths.begin();
1553 QString segString = it->displayString();
1554 for (; it != paths.end(); ++it) {
1555 // look to the next item
1560 allFinal = allFinal && it->final();
1562 LYXERR(Debug::GUI, "it = " << it->abs()
1563 << " => " << it->displayString());
1565 // still the same segment?
1567 if ((next != paths.end()
1568 && (nextString = next->displayString()) == segString))
1570 LYXERR(Debug::GUI, "segment ended");
1572 // only a trivial one with one element?
1573 if (it == segStart) {
1574 // start new segment
1576 segString = nextString;
1580 // we found a non-atomic segment segStart <= sit <= it < next.
1581 // Shift path segments and hope for the best
1582 // that it makes the path more unique.
1583 somethingChanged = true;
1585 QString dspString = sit->forecastPathString();
1586 LYXERR(Debug::GUI, "first forecast found for "
1587 << sit->abs() << " => " << dspString);
1589 bool moreUnique = false;
1590 for (; sit != next; ++sit) {
1591 if (sit->forecastPathString() != dspString) {
1592 LYXERR(Debug::GUI, "different forecast found for "
1593 << sit->abs() << " => " << sit->forecastPathString());
1597 LYXERR(Debug::GUI, "same forecast found for "
1598 << sit->abs() << " => " << dspString);
1601 // if the path segment helped, add it. Otherwise add dots
1602 bool dots = !moreUnique;
1603 LYXERR(Debug::GUI, "using dots = " << dots);
1604 for (sit = segStart; sit != next; ++sit) {
1605 sit->shiftPathSegment(dots);
1606 LYXERR(Debug::GUI, "shifting "
1607 << sit->abs() << " => " << sit->displayString());
1610 // start new segment
1612 segString = nextString;
1616 // set new tab titles
1617 for (It it = paths.begin(); it != paths.end(); ++it) {
1618 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(it->tab()));
1619 Buffer & buf = i_wa->bufferView().buffer();
1620 if (!buf.fileName().empty() && !buf.isClean())
1621 setTabText(it->tab(), it->displayString() + "*");
1623 setTabText(it->tab(), it->displayString());
1628 void TabWorkArea::showContextMenu(const QPoint & pos)
1631 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1632 if (clicked_tab_ == -1)
1637 popup.addAction(QIcon(":/images/hidetab.png"),
1638 qt_("Hide tab"), this, SLOT(closeCurrentTab()));
1639 popup.addAction(QIcon(":/images/closetab.png"),
1640 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1641 popup.exec(tabBar()->mapToGlobal(pos));
1647 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1649 QWidget * w = widget(fromIndex);
1650 QIcon icon = tabIcon(fromIndex);
1651 QString text = tabText(fromIndex);
1653 setCurrentIndex(fromIndex);
1654 removeTab(fromIndex);
1655 insertTab(toIndex, w, icon, text);
1656 setCurrentIndex(toIndex);
1660 DragTabBar::DragTabBar(QWidget* parent)
1663 setAcceptDrops(true);
1667 #if QT_VERSION < 0x040300
1668 int DragTabBar::tabAt(QPoint const & position) const
1670 const int max = count();
1671 for (int i = 0; i < max; ++i) {
1672 if (tabRect(i).contains(position))
1680 void DragTabBar::mousePressEvent(QMouseEvent * event)
1682 if (event->button() == Qt::LeftButton)
1683 dragStartPos_ = event->pos();
1684 QTabBar::mousePressEvent(event);
1688 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1690 // If the left button isn't pressed anymore then return
1691 if (!(event->buttons() & Qt::LeftButton))
1694 // If the distance is too small then return
1695 if ((event->pos() - dragStartPos_).manhattanLength()
1696 < QApplication::startDragDistance())
1699 // did we hit something after all?
1700 int tab = tabAt(dragStartPos_);
1704 // simulate button release to remove highlight from button
1705 int i = currentIndex();
1706 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1707 event->button(), event->buttons(), 0);
1708 QTabBar::mouseReleaseEvent(&me);
1712 QDrag * drag = new QDrag(this);
1713 QMimeData * mimeData = new QMimeData;
1714 // a crude way to distinguish tab-reodering drops from other ones
1715 mimeData->setData("action", "tab-reordering") ;
1716 drag->setMimeData(mimeData);
1718 #if QT_VERSION >= 0x040300
1719 // get tab pixmap as cursor
1720 QRect r = tabRect(tab);
1721 QPixmap pixmap(r.size());
1722 render(&pixmap, - r.topLeft());
1723 drag->setPixmap(pixmap);
1726 drag->start(Qt::MoveAction);
1732 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1734 // Only accept if it's an tab-reordering request
1735 QMimeData const * m = event->mimeData();
1736 QStringList formats = m->formats();
1737 if (formats.contains("action")
1738 && m->data("action") == "tab-reordering")
1739 event->acceptProposedAction();
1743 void DragTabBar::dropEvent(QDropEvent * event)
1745 int fromIndex = tabAt(dragStartPos_);
1746 int toIndex = tabAt(event->pos());
1748 // Tell interested objects that
1749 if (fromIndex != toIndex)
1750 tabMoveRequested(fromIndex, toIndex);
1751 event->acceptProposedAction();
1755 } // namespace frontend
1758 #include "GuiWorkArea_moc.cpp"