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"
36 #include "MetricsInfo.h"
37 #include "qt_helpers.h"
41 #include "graphics/GraphicsImage.h"
42 #include "graphics/GraphicsLoader.h"
44 #include "support/debug.h"
45 #include "support/gettext.h"
46 #include "support/FileName.h"
48 #include "frontends/Application.h"
49 #include "frontends/FontMetrics.h"
50 #include "frontends/WorkAreaManager.h"
52 #include <QContextMenuEvent>
53 #include <QInputContext>
58 #include <QMainWindow>
62 #include <QPixmapCache>
65 #include <QToolButton>
69 #include <boost/bind.hpp>
75 extern "C" int XEventsQueued(Display *display, int mode);
79 int const CursorWidth = 2;
81 int const CursorWidth = 1;
83 int const TabIndicatorWidth = 3;
89 using namespace lyx::support;
94 /// return the LyX mouse button state from Qt's
95 static mouse_button::state q_button_state(Qt::MouseButton button)
97 mouse_button::state b = mouse_button::none;
100 b = mouse_button::button1;
103 b = mouse_button::button2;
105 case Qt::RightButton:
106 b = mouse_button::button3;
115 /// return the LyX mouse button state from Qt's
116 mouse_button::state q_motion_state(Qt::MouseButtons state)
118 mouse_button::state b = mouse_button::none;
119 if (state & Qt::LeftButton)
120 b |= mouse_button::button1;
121 if (state & Qt::MidButton)
122 b |= mouse_button::button2;
123 if (state & Qt::RightButton)
124 b |= mouse_button::button3;
135 void draw(QPainter & painter)
137 if (!show_ || !rect_.isValid())
141 int l = x_ - rect_.left();
142 int r = rect_.right() - x_;
143 int bot = rect_.bottom();
145 // draw vertica linel
146 painter.fillRect(x_, y, CursorWidth, rect_.height(), color_);
148 // draw RTL/LTR indication
149 painter.setPen(color_);
152 painter.drawLine(x_, bot, x_ - l, bot);
154 painter.drawLine(x_, bot, x_ + CursorWidth + r, bot);
157 // draw completion triangle
159 int m = y + rect_.height() / 2;
160 int d = TabIndicatorWidth - 1;
162 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
163 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
165 painter.drawLine(x_ + CursorWidth, m - d, x_ + CursorWidth + d, m);
166 painter.drawLine(x_ + CursorWidth, m + d, x_ + CursorWidth + d, m);
171 void update(int x, int y, int h, bool l_shape,
172 bool rtl, bool completable)
174 color_ = guiApp->colorCache().get(Color_cursor);
177 completable_ = completable;
180 // extension to left and right
184 // RTL/LTR indication
192 // completion triangle
195 l = max(l, TabIndicatorWidth);
197 r = max(r, TabIndicatorWidth);
200 // compute overall rectangle
201 rect_ = QRect(x - l, y, CursorWidth + r + l, h);
204 void show(bool set_show = true) { show_ = set_show; }
205 void hide() { show_ = false; }
207 QRect const & rect() { return rect_; }
210 /// cursor is in RTL or LTR text
212 /// indication for RTL or LTR
214 /// triangle to show that a completion is available
220 /// rectangle, possibly with l_shape and completion triangle
222 /// x position (were the vertical line is drawn)
227 // This is a 'heartbeat' generating synthetic mouse move events when the
228 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
229 SyntheticMouseEvent::SyntheticMouseEvent()
230 : timeout(200), restart_timeout(true),
231 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
236 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & lv)
237 : buffer_view_(new BufferView(buffer)), lyx_view_(&lv),
238 cursor_visible_(false),
239 need_resize_(false), schedule_redraw_(false),
240 preedit_lines_(1), completer_(new GuiCompleter(this))
242 buffer.workAreaManager().add(this);
244 connect(&cursor_timeout_, SIGNAL(timeout()),
245 this, SLOT(toggleCursor()));
247 int const time = QApplication::cursorFlashTime() / 2;
249 cursor_timeout_.setInterval(time);
250 cursor_timeout_.start();
252 // let's initialize this just to be safe
253 cursor_timeout_.setInterval(500);
256 screen_ = QPixmap(viewport()->width(), viewport()->height());
257 cursor_ = new frontend::CursorWidget();
260 // HACK: Prevents an additional redraw when the scrollbar pops up
261 // which regularily happens on documents with more than one page.
262 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
263 // Since we have no geometry information yet, we assume that
264 // a document needs a scrollbar if there is more then four
265 // paragraph in the outermost text.
266 if (buffer.text().paragraphs().size() > 4)
267 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
268 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
271 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
272 setAcceptDrops(true);
273 setMouseTracking(true);
274 setMinimumSize(100, 70);
276 setFrameStyle(QFrame::NoFrame);
278 setFrameStyle(QFrame::Box);
282 viewport()->setAutoFillBackground(false);
283 // We don't need double-buffering nor SystemBackground on
284 // the viewport because we have our own backing pixmap.
285 viewport()->setAttribute(Qt::WA_NoSystemBackground);
287 setFocusPolicy(Qt::WheelFocus);
289 viewport()->setCursor(Qt::IBeamCursor);
291 synthetic_mouse_event_.timeout.timeout.connect(
292 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
295 // Initialize the vertical Scroll Bar
296 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
297 this, SLOT(scrollTo(int)));
299 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
300 << " viewport height: " << viewport()->height());
302 // Enables input methods for asian languages.
303 // Must be set when creating custom text editing widgets.
304 setAttribute(Qt::WA_InputMethodEnabled, true);
308 GuiWorkArea::~GuiWorkArea()
310 buffer_view_->buffer().workAreaManager().remove(this);
317 void GuiWorkArea::fixVerticalScrollBar()
320 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
324 void GuiWorkArea::close()
326 lyx_view_->removeWorkArea(this);
330 void GuiWorkArea::setFullScreen(bool full_screen)
332 buffer_view_->setFullScreen(full_screen);
334 setFrameStyle(QFrame::NoFrame);
335 if (lyxrc.full_screen_scrollbar)
336 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
339 setFrameStyle(QFrame::NoFrame);
341 setFrameStyle(QFrame::Box);
343 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
348 BufferView & GuiWorkArea::bufferView()
350 return *buffer_view_;
354 BufferView const & GuiWorkArea::bufferView() const
356 return *buffer_view_;
360 void GuiWorkArea::stopBlinkingCursor()
362 cursor_timeout_.stop();
367 void GuiWorkArea::startBlinkingCursor()
370 //we're not supposed to cache this value.
371 int const time = QApplication::cursorFlashTime() / 2;
374 cursor_timeout_.setInterval(time);
375 cursor_timeout_.start();
379 void GuiWorkArea::redraw()
382 // No need to redraw in this case.
385 // No need to do anything if this is the current view. The BufferView
386 // metrics are already up to date.
387 if (lyx_view_ != guiApp->currentView()
388 || lyx_view_->currentWorkArea() != this) {
389 // FIXME: it would be nice to optimize for the off-screen case.
390 buffer_view_->updateMetrics();
391 buffer_view_->cursor().fixIfBroken();
394 // update cursor position, because otherwise it has to wait until
395 // the blinking interval is over
396 if (cursor_visible_) {
401 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
403 update(0, 0, viewport()->width(), viewport()->height());
405 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
406 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
408 lyx_view_->updateStatusBar();
410 if (lyxerr.debugging(Debug::WORKAREA))
411 buffer_view_->coordCache().dump();
415 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
417 if (lyx_view_->isFullScreen() && lyx_view_->menuBar()->isVisible()) {
418 // FIXME HACK: we should not have to do this here. See related comment
419 // in GuiView::event() (QEvent::ShortcutOverride)
420 lyx_view_->menuBar()->hide();
423 // In order to avoid bad surprise in the middle of an operation,
424 // we better stop the blinking cursor...
425 // the cursor gets restarted in GuiView::restartCursor()
426 stopBlinkingCursor();
428 theLyXFunc().setLyXView(lyx_view_);
429 theLyXFunc().processKeySym(key, mod);
433 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
436 if (cmd0.action == LFUN_FILE_OPEN) {
437 lyx_view_->dispatch(cmd0);
441 theLyXFunc().setLyXView(lyx_view_);
445 if (cmd0.action == LFUN_MOUSE_PRESS) {
446 if (mod == ShiftModifier)
447 cmd = FuncRequest(cmd0, "region-select");
448 else if (mod == ControlModifier)
449 cmd = FuncRequest(cmd0, "paragraph-select");
456 bool const notJustMovingTheMouse =
457 cmd.action != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
459 // In order to avoid bad surprise in the middle of an operation, we better stop
460 // the blinking cursor.
461 if (notJustMovingTheMouse)
462 stopBlinkingCursor();
464 buffer_view_->mouseEventDispatch(cmd);
466 // Skip these when selecting
467 if (cmd.action != LFUN_MOUSE_MOTION) {
468 completer_->updateVisibility(false, false);
469 lyx_view_->updateDialogs();
470 lyx_view_->updateStatusBar();
473 // GUI tweaks except with mouse motion with no button pressed.
474 if (notJustMovingTheMouse) {
475 // Slight hack: this is only called currently when we
476 // clicked somewhere, so we force through the display
477 // of the new status here.
478 lyx_view_->clearMessage();
480 // Show the cursor immediately after any operation
481 startBlinkingCursor();
486 void GuiWorkArea::resizeBufferView()
488 // WARNING: Please don't put any code that will trigger a repaint here!
489 // We are already inside a paint event.
490 lyx_view_->setBusy(true);
491 buffer_view_->resize(viewport()->width(), viewport()->height());
494 // Update scrollbars which might have changed due different
495 // BufferView dimension. This is especially important when the
496 // BufferView goes from zero-size to the real-size for the first time,
497 // as the scrollbar paramters are then set for the first time.
500 lyx_view_->updateLayoutList();
501 lyx_view_->setBusy(false);
502 need_resize_ = false;
506 void GuiWorkArea::showCursor()
512 bool l_shape = false;
513 Font const & realfont = buffer_view_->cursor().real_current_font;
514 BufferParams const & bp = buffer_view_->buffer().params();
515 bool const samelang = realfont.language() == bp.language;
516 bool const isrtl = realfont.isVisibleRightToLeft();
518 if (!samelang || isrtl != bp.language->rightToLeft())
521 // The ERT language hack needs fixing up
522 if (realfont.language() == latex_language)
525 Font const font = buffer_view_->cursor().getFont();
526 FontMetrics const & fm = theFontMetrics(font);
527 int const asc = fm.maxAscent();
528 int const des = fm.maxDescent();
532 Cursor & cur = buffer_view_->cursor();
536 // if it doesn't touch the screen, don't try to show it
537 bool cursorInView = true;
538 if (y + h < 0 || y >= viewport()->height())
539 cursorInView = false;
541 // show cursor on screen
542 bool completable = cur.inset().showCompletionCursor()
543 && completer_->completionAvailable()
544 && !completer_->popupVisible()
545 && !completer_->inlineVisible();
547 cursor_visible_ = true;
548 showCursor(x, y, h, l_shape, isrtl, completable);
553 void GuiWorkArea::hideCursor()
555 if (!cursor_visible_)
558 cursor_visible_ = false;
563 void GuiWorkArea::toggleCursor()
572 void GuiWorkArea::updateScrollbar()
574 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
575 // WARNING: don't touch at the scrollbar value like this:
576 // verticalScrollBar()->setValue(scroll_.position);
577 // because this would cause a recursive signal/slot calling with
578 // GuiWorkArea::scrollTo
579 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
580 verticalScrollBar()->setPageStep(scroll_.page_step);
581 verticalScrollBar()->setSingleStep(scroll_.single_step);
582 verticalScrollBar()->setSliderPosition(scroll_.position);
586 void GuiWorkArea::scrollTo(int value)
588 stopBlinkingCursor();
589 buffer_view_->scrollDocView(value);
591 if (lyxrc.cursor_follows_scrollbar) {
592 buffer_view_->setCursorFromScrollbar();
593 lyx_view_->updateLayoutList();
595 // Show the cursor immediately after any operation.
596 startBlinkingCursor();
597 QApplication::syncX();
601 bool GuiWorkArea::event(QEvent * e)
604 case QEvent::ToolTip: {
605 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
606 if (lyxrc.use_tooltip) {
607 QPoint pos = helpEvent->pos();
608 if (pos.x() < viewport()->width()) {
609 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
610 QToolTip::showText(helpEvent->globalPos(), s);
613 QToolTip::hideText();
615 // Don't forget to accept the event!
620 case QEvent::ShortcutOverride: {
621 // We catch this event in order to catch the Tab or Shift+Tab key press
622 // which are otherwise reserved to focus switching between controls
624 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
625 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
626 || ke->modifiers() & Qt::ControlModifier)
627 return QAbstractScrollArea::event(e);
633 return QAbstractScrollArea::event(e);
639 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
641 QPoint pos = e->pos();
642 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
644 QAbstractScrollArea::contextMenuEvent(e);
647 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
649 QAbstractScrollArea::contextMenuEvent(e);
652 // Position the menu to the right.
653 // FIXME: menu position should be different for RTL text.
654 menu->exec(e->globalPos());
659 void GuiWorkArea::focusInEvent(QFocusEvent * e)
661 if (lyx_view_->currentWorkArea() != this)
662 lyx_view_->setCurrentWorkArea(this);
664 startBlinkingCursor();
665 QAbstractScrollArea::focusInEvent(e);
669 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
671 stopBlinkingCursor();
672 QAbstractScrollArea::focusOutEvent(e);
676 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
678 if (dc_event_.active && dc_event_ == *e) {
679 dc_event_.active = false;
680 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
681 q_button_state(e->button()));
687 inputContext()->reset();
689 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
690 q_button_state(e->button()));
691 dispatch(cmd, q_key_state(e->modifiers()));
696 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
698 if (synthetic_mouse_event_.timeout.running())
699 synthetic_mouse_event_.timeout.stop();
701 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
702 q_button_state(e->button()));
708 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
710 // we kill the triple click if we move
711 doubleClickTimeout();
712 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
713 q_motion_state(e->buttons()));
717 // If we're above or below the work area...
718 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
719 // Make sure only a synthetic event can cause a page scroll,
720 // so they come at a steady rate:
722 // _Force_ a scroll up:
725 cmd.y = viewport()->height();
726 // Store the event, to be handled when the timeout expires.
727 synthetic_mouse_event_.cmd = cmd;
729 if (synthetic_mouse_event_.timeout.running())
730 // Discard the event. Note that it _may_ be handled
731 // when the timeout expires if
732 // synthetic_mouse_event_.cmd has not been overwritten.
733 // Ie, when the timeout expires, we handle the
734 // most recent event but discard all others that
735 // occurred after the one used to start the timeout
736 // in the first place.
739 synthetic_mouse_event_.restart_timeout = true;
740 synthetic_mouse_event_.timeout.start();
741 // Fall through to handle this event...
743 } else if (synthetic_mouse_event_.timeout.running()) {
744 // Store the event, to be possibly handled when the timeout
746 // Once the timeout has expired, normal control is returned
747 // to mouseMoveEvent (restart_timeout = false).
748 // This results in a much smoother 'feel' when moving the
749 // mouse back into the work area.
750 synthetic_mouse_event_.cmd = cmd;
751 synthetic_mouse_event_.restart_timeout = false;
755 // Has anything changed on-screen since the last QMouseEvent
757 double const scrollbar_value = verticalScrollBar()->value();
758 if (e->x() == synthetic_mouse_event_.x_old
759 && e->y() == synthetic_mouse_event_.y_old
760 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
761 // Nothing changed on-screen since the last QMouseEvent.
765 // Yes something has changed. Store the params used to check this.
766 synthetic_mouse_event_.x_old = e->x();
767 synthetic_mouse_event_.y_old = e->y();
768 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
770 // ... and dispatch the event to the LyX core.
775 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
777 // Wheel rotation by one notch results in a delta() of 120 (see
778 // documentation of QWheelEvent)
779 int const delta = ev->delta() / 120;
780 if (ev->modifiers() & Qt::ControlModifier) {
781 lyxrc.zoom -= 5 * delta;
784 // The global QPixmapCache is used in GuiPainter to cache text
785 // painting so we must reset it.
786 QPixmapCache::clear();
787 guiApp->fontLoader().update();
789 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
793 // Take into account the desktop wide settings.
794 int const lines = qApp->wheelScrollLines();
795 int const page_step = verticalScrollBar()->pageStep();
796 // Test if the wheel mouse is set to one screen at a time.
797 int scroll_value = lines > page_step
798 ? page_step : lines * verticalScrollBar()->singleStep();
800 // Take into account the rotation.
801 scroll_value *= delta;
803 // Take into account user preference.
804 scroll_value *= lyxrc.mouse_wheel_speed;
805 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
806 << " delta = " << delta << " scroll_value = " << scroll_value
807 << " page_step = " << page_step);
809 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
815 void GuiWorkArea::generateSyntheticMouseEvent()
817 // Set things off to generate the _next_ 'pseudo' event.
818 if (synthetic_mouse_event_.restart_timeout)
819 synthetic_mouse_event_.timeout.start();
821 // Has anything changed on-screen since the last timeout signal
823 double const scrollbar_value = verticalScrollBar()->value();
824 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
825 // Yes it has. Store the params used to check this.
826 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
828 // ... and dispatch the event to the LyX core.
829 dispatch(synthetic_mouse_event_.cmd);
834 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
836 // intercept some keys if completion popup is visible
837 if (completer_->popupVisible()) {
841 completer_->activate();
847 // intercept keys for the completion
848 if (ev->key() == Qt::Key_Tab) {
854 if (completer_->popupVisible() && ev->key() == Qt::Key_Escape) {
855 completer_->hidePopup();
860 if (completer_->inlineVisible() && ev->key() == Qt::Key_Escape) {
861 completer_->hideInline();
866 // do nothing if there are other events
867 // (the auto repeated events come too fast)
868 // \todo FIXME: remove hard coded Qt keys, process the key binding
870 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
871 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
872 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
878 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
879 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
882 setKeySymbol(&sym, ev);
883 processKeySym(sym, q_key_state(ev->modifiers()));
888 void GuiWorkArea::doubleClickTimeout()
890 dc_event_.active = false;
894 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
896 dc_event_ = DoubleClick(ev);
897 QTimer::singleShot(QApplication::doubleClickInterval(), this,
898 SLOT(doubleClickTimeout()));
899 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
901 q_button_state(ev->button()));
907 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
909 QAbstractScrollArea::resizeEvent(ev);
915 void GuiWorkArea::update(int x, int y, int w, int h)
917 viewport()->repaint(x, y, w, h);
921 void GuiWorkArea::paintEvent(QPaintEvent * ev)
923 QRect const rc = ev->rect();
924 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
925 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
928 screen_ = QPixmap(viewport()->width(), viewport()->height());
934 QPainter pain(viewport());
935 pain.drawPixmap(rc, screen_, rc);
941 void GuiWorkArea::updateScreen()
943 GuiPainter pain(&screen_);
944 buffer_view_->draw(pain);
948 void GuiWorkArea::showCursor(int x, int y, int h,
949 bool l_shape, bool rtl, bool completable)
951 if (schedule_redraw_) {
952 // This happens when a graphic conversion is finished. As we don't know
953 // the size of the new graphics, it's better the update everything.
954 // We can't use redraw() here because this would trigger a infinite
955 // recursive loop with showCursor().
956 buffer_view_->resize(viewport()->width(), viewport()->height());
959 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
960 schedule_redraw_ = false;
961 // Show the cursor immediately after the update.
967 cursor_->update(x, y, h, l_shape, rtl, completable);
969 viewport()->update(cursor_->rect());
973 void GuiWorkArea::removeCursor()
976 //if (!qApp->focusWidget())
977 viewport()->update(cursor_->rect());
981 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
983 QString const & commit_string = e->commitString();
984 docstring const & preedit_string
985 = qstring_to_ucs4(e->preeditString());
987 if (!commit_string.isEmpty()) {
989 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
990 << " commitString: " << e->commitString());
994 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
995 for (int i = 0; i != commit_string.size(); ++i) {
996 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1001 // Hide the cursor during the kana-kanji transformation.
1002 if (preedit_string.empty())
1003 startBlinkingCursor();
1005 stopBlinkingCursor();
1007 // last_width : for checking if last preedit string was/wasn't empty.
1008 static bool last_width = false;
1009 if (!last_width && preedit_string.empty()) {
1010 // if last_width is last length of preedit string.
1015 GuiPainter pain(&screen_);
1016 buffer_view_->updateMetrics();
1017 buffer_view_->draw(pain);
1018 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1019 FontMetrics const & fm = theFontMetrics(font);
1020 int height = fm.maxHeight();
1021 int cur_x = cursor_->rect().left();
1022 int cur_y = cursor_->rect().bottom();
1024 // redraw area of preedit string.
1025 update(0, cur_y - height, viewport()->width(),
1026 (height + 1) * preedit_lines_);
1028 if (preedit_string.empty()) {
1036 // att : stores an IM attribute.
1037 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1039 // get attributes of input method cursor.
1040 // cursor_pos : cursor position in preedit string.
1041 size_t cursor_pos = 0;
1042 bool cursor_is_visible = false;
1043 for (int i = 0; i != att.size(); ++i) {
1044 if (att.at(i).type == QInputMethodEvent::Cursor) {
1045 cursor_pos = att.at(i).start;
1046 cursor_is_visible = att.at(i).length != 0;
1051 size_t preedit_length = preedit_string.length();
1053 // get position of selection in input method.
1054 // FIXME: isn't there a way to do this simplier?
1055 // rStart : cursor position in selected string in IM.
1057 // rLength : selected string length in IM.
1059 if (cursor_pos < preedit_length) {
1060 for (int i = 0; i != att.size(); ++i) {
1061 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1062 if (att.at(i).start <= int(cursor_pos)
1063 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1064 rStart = att.at(i).start;
1065 rLength = att.at(i).length;
1066 if (!cursor_is_visible)
1067 cursor_pos += rLength;
1074 rStart = cursor_pos;
1078 int const right_margin = buffer_view_->rightMargin();
1079 Painter::preedit_style ps;
1080 // Most often there would be only one line:
1082 for (size_t pos = 0; pos != preedit_length; ++pos) {
1083 char_type const typed_char = preedit_string[pos];
1084 // reset preedit string style
1085 ps = Painter::preedit_default;
1087 // if we reached the right extremity of the screen, go to next line.
1088 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1089 cur_x = right_margin;
1090 cur_y += height + 1;
1093 // preedit strings are displayed with dashed underline
1094 // and partial strings are displayed white on black indicating
1095 // that we are in selecting mode in the input method.
1096 // FIXME: rLength == preedit_length is not a changing condition
1097 // FIXME: should be put out of the loop.
1099 && pos < rStart + rLength
1100 && !(cursor_pos < rLength && rLength == preedit_length))
1101 ps = Painter::preedit_selecting;
1103 if (pos == cursor_pos
1104 && (cursor_pos < rLength && rLength == preedit_length))
1105 ps = Painter::preedit_cursor;
1107 // draw one character and update cur_x.
1108 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1111 // update the preedit string screen area.
1112 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1113 (height + 1) * preedit_lines_);
1115 // Don't forget to accept the event!
1120 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1122 QRect cur_r(0,0,0,0);
1124 // this is the CJK-specific composition window position.
1125 case Qt::ImMicroFocus:
1126 cur_r = cursor_->rect();
1127 if (preedit_lines_ != 1)
1129 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1130 // return lower right of cursor in LyX.
1133 return QWidget::inputMethodQuery(query);
1138 void GuiWorkArea::updateWindowTitle()
1140 docstring maximize_title;
1141 docstring minimize_title;
1143 Buffer & buf = buffer_view_->buffer();
1144 FileName const fileName = buf.fileName();
1145 if (!fileName.empty()) {
1146 maximize_title = fileName.displayName(30);
1147 minimize_title = from_utf8(fileName.onlyFileName());
1148 if (!buf.isClean()) {
1149 maximize_title += _(" (changed)");
1150 minimize_title += char_type('*');
1152 if (buf.isReadonly())
1153 maximize_title += _(" (read only)");
1156 QString title = windowTitle();
1157 QString new_title = toqstr(maximize_title);
1158 if (title == new_title)
1161 QWidget::setWindowTitle(new_title);
1162 QWidget::setWindowIconText(toqstr(minimize_title));
1167 void GuiWorkArea::setReadOnly(bool)
1169 updateWindowTitle();
1170 if (this == lyx_view_->currentWorkArea())
1171 lyx_view_->updateDialogs();
1175 bool GuiWorkArea::isFullScreen()
1177 return lyx_view_ && lyx_view_->isFullScreen();
1181 ////////////////////////////////////////////////////////////////////
1185 ////////////////////////////////////////////////////////////////////
1188 class NoTabFrameMacStyle : public QMacStyle {
1191 QRect subElementRect(SubElement element, const QStyleOption * option,
1192 const QWidget * widget = 0) const
1194 QRect rect = QMacStyle::subElementRect(element, option, widget);
1195 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1197 // The Qt Mac style puts the contents into a 3 pixel wide box
1198 // which looks very ugly and not like other Mac applications.
1199 // Hence we remove this here, and moreover the 16 pixel round
1200 // frame above if the tab bar is hidden.
1201 if (element == QStyle::SE_TabWidgetTabContents) {
1202 rect.adjust(- rect.left(), 0, rect.left(), 0);
1211 NoTabFrameMacStyle noTabFrameMacStyle;
1215 TabWorkArea::TabWorkArea(QWidget * parent)
1216 : QTabWidget(parent), clicked_tab_(-1)
1219 setStyle(&noTabFrameMacStyle);
1222 QPalette pal = palette();
1223 pal.setColor(QPalette::Active, QPalette::Button,
1224 pal.color(QPalette::Active, QPalette::Window));
1225 pal.setColor(QPalette::Disabled, QPalette::Button,
1226 pal.color(QPalette::Disabled, QPalette::Window));
1227 pal.setColor(QPalette::Inactive, QPalette::Button,
1228 pal.color(QPalette::Inactive, QPalette::Window));
1230 QObject::connect(this, SIGNAL(currentChanged(int)),
1231 this, SLOT(on_currentTabChanged(int)));
1233 QToolButton * closeBufferButton = new QToolButton(this);
1234 closeBufferButton->setPalette(pal);
1235 // FIXME: rename the icon to closebuffer.png
1236 closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1237 closeBufferButton->setText("Close File");
1238 closeBufferButton->setAutoRaise(true);
1239 closeBufferButton->setCursor(Qt::ArrowCursor);
1240 closeBufferButton->setToolTip(qt_("Close File"));
1241 closeBufferButton->setEnabled(true);
1242 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1243 this, SLOT(closeCurrentBuffer()));
1244 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1246 // setup drag'n'drop
1247 QTabBar* tb = new DragTabBar;
1248 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1249 this, SLOT(moveTab(int, int)));
1250 tb->setElideMode(Qt::ElideNone);
1253 // make us responsible for the context menu of the tabbar
1254 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1255 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1256 this, SLOT(showContextMenu(const QPoint &)));
1258 setUsesScrollButtons(true);
1262 void TabWorkArea::setFullScreen(bool full_screen)
1264 for (int i = 0; i != count(); ++i) {
1265 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1266 wa->setFullScreen(full_screen);
1269 if (lyxrc.full_screen_tabbar)
1270 showBar(!full_screen && count()>1);
1274 void TabWorkArea::showBar(bool show)
1276 tabBar()->setEnabled(show);
1277 tabBar()->setVisible(show);
1281 GuiWorkArea * TabWorkArea::currentWorkArea()
1286 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1292 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1294 for (int i = 0; i != count(); ++i) {
1295 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1296 LASSERT(wa, return 0);
1297 if (&wa->bufferView().buffer() == &buffer)
1304 void TabWorkArea::closeAll()
1307 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1315 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1317 LASSERT(work_area, /**/);
1318 int index = indexOf(work_area);
1322 if (index == currentIndex())
1323 // Make sure the work area is up to date.
1324 on_currentTabChanged(index);
1326 // Switch to the work area.
1327 setCurrentIndex(index);
1328 work_area->setFocus();
1334 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1336 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1337 wa->setUpdatesEnabled(false);
1338 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1339 // when hiding it again below).
1340 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1341 showBar(count() > 0);
1342 addTab(wa, wa->windowTitle());
1343 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1344 this, SLOT(updateTabTexts()));
1345 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1346 setFullScreen(true);
1348 // Hide tabbar if there's only one tab.
1349 showBar(count() > 1);
1357 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1359 LASSERT(work_area, return false);
1360 int index = indexOf(work_area);
1364 work_area->setUpdatesEnabled(false);
1369 // make sure the next work area is enabled.
1370 currentWidget()->setUpdatesEnabled(true);
1371 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1372 setFullScreen(true);
1374 // Hide tabbar if there's only one tab.
1375 showBar(count() > 1);
1377 lastWorkAreaRemoved();
1386 void TabWorkArea::on_currentTabChanged(int i)
1388 // returns e.g. on application destruction
1391 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1392 LASSERT(wa, return);
1393 BufferView & bv = wa->bufferView();
1394 bv.cursor().fixIfBroken();
1396 wa->setUpdatesEnabled(true);
1400 currentWorkAreaChanged(wa);
1402 LYXERR(Debug::GUI, "currentTabChanged " << i
1403 << "File" << bv.buffer().absFileName());
1407 void TabWorkArea::closeCurrentBuffer()
1409 if (clicked_tab_ != -1)
1410 setCurrentIndex(clicked_tab_);
1412 lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1416 void TabWorkArea::closeCurrentTab()
1418 if (clicked_tab_ == -1)
1419 removeWorkArea(currentWorkArea());
1421 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1430 /// make vector happy
1433 DisplayPath(int tab, FileName const & filename)
1436 filename_ = toqstr(filename.onlyFileNameWithoutExt());
1437 postfix_ = toqstr(filename.absoluteFilePath()).
1438 split("/", QString::SkipEmptyParts);
1439 postfix_.pop_back();
1440 abs_ = toqstr(filename.absoluteFilePath());
1441 dottedPrefix_ = false;
1444 /// Absolute path for debugging.
1449 /// Add the first segment from the postfix or three dots to the prefix.
1450 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1451 /// when really needed.
1452 void shiftPathSegment(bool dotted)
1454 if (postfix_.count() <= 0)
1458 if (dottedPrefix_ && !prefix_.isEmpty())
1460 prefix_ += postfix_.front() + "/";
1462 dottedPrefix_ = dotted && !prefix_.isEmpty();
1463 postfix_.pop_front();
1466 QString displayString() const
1468 if (prefix_.isEmpty())
1471 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1472 return prefix_ + (dots ? ".../" : "") + filename_;
1475 QString forecastPathString() const
1477 if (postfix_.count() == 0)
1478 return displayString();
1481 + (dottedPrefix_ ? ".../" : "")
1482 + postfix_.front() + "/";
1485 bool final() const { return postfix_.empty(); }
1487 int tab() const { return tab_; }
1493 QStringList postfix_;
1506 bool operator<(DisplayPath const & a, DisplayPath const & b)
1508 return a.displayString() < b.displayString();
1512 bool operator==(DisplayPath const & a, DisplayPath const & b)
1514 return a.displayString() == b.displayString();
1518 void TabWorkArea::updateTabTexts()
1523 std::list<DisplayPath> paths;
1524 typedef std::list<DisplayPath>::iterator It;
1526 // collect full names first: path into postfix, empty prefix and
1527 // filename without extension
1528 for (size_t i = 0; i < n; ++i) {
1529 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(i));
1530 FileName const fn = i_wa->bufferView().buffer().fileName();
1531 paths.push_back(DisplayPath(i, fn));
1534 // go through path segments and see if it helps to make the path more unique
1535 bool somethingChanged = true;
1536 bool allFinal = false;
1537 while (somethingChanged && !allFinal) {
1538 // adding path segments changes order
1541 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1542 somethingChanged = false;
1545 // find segments which are not unique (i.e. non-atomic)
1546 It it = paths.begin();
1548 QString segString = it->displayString();
1549 for (; it != paths.end(); ++it) {
1550 // look to the next item
1555 allFinal = allFinal && it->final();
1557 LYXERR(Debug::GUI, "it = " << it->abs()
1558 << " => " << it->displayString());
1560 // still the same segment?
1562 if ((next != paths.end()
1563 && (nextString = next->displayString()) == segString))
1565 LYXERR(Debug::GUI, "segment ended");
1567 // only a trivial one with one element?
1568 if (it == segStart) {
1569 // start new segment
1571 segString = nextString;
1575 // we found a non-atomic segment segStart <= sit <= it < next.
1576 // Shift path segments and hope for the best
1577 // that it makes the path more unique.
1578 somethingChanged = true;
1580 QString dspString = sit->forecastPathString();
1581 LYXERR(Debug::GUI, "first forecast found for "
1582 << sit->abs() << " => " << dspString);
1584 bool moreUnique = false;
1585 for (; sit != next; ++sit) {
1586 if (sit->forecastPathString() != dspString) {
1587 LYXERR(Debug::GUI, "different forecast found for "
1588 << sit->abs() << " => " << sit->forecastPathString());
1592 LYXERR(Debug::GUI, "same forecast found for "
1593 << sit->abs() << " => " << dspString);
1596 // if the path segment helped, add it. Otherwise add dots
1597 bool dots = !moreUnique;
1598 LYXERR(Debug::GUI, "using dots = " << dots);
1599 for (sit = segStart; sit != next; ++sit) {
1600 sit->shiftPathSegment(dots);
1601 LYXERR(Debug::GUI, "shifting "
1602 << sit->abs() << " => " << sit->displayString());
1605 // start new segment
1607 segString = nextString;
1611 // set new tab titles
1612 for (It it = paths.begin(); it != paths.end(); ++it) {
1613 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(it->tab()));
1614 Buffer & buf = i_wa->bufferView().buffer();
1615 if (!buf.fileName().empty() && !buf.isClean())
1616 setTabText(it->tab(), it->displayString() + "*");
1618 setTabText(it->tab(), it->displayString());
1623 void TabWorkArea::showContextMenu(const QPoint & pos)
1626 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1627 if (clicked_tab_ == -1)
1632 popup.addAction(QIcon(":/images/hidetab.png"),
1633 qt_("Hide tab"), this, SLOT(closeCurrentTab()));
1634 popup.addAction(QIcon(":/images/closetab.png"),
1635 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1636 popup.exec(tabBar()->mapToGlobal(pos));
1642 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1644 QWidget * w = widget(fromIndex);
1645 QIcon icon = tabIcon(fromIndex);
1646 QString text = tabText(fromIndex);
1648 setCurrentIndex(fromIndex);
1649 removeTab(fromIndex);
1650 insertTab(toIndex, w, icon, text);
1651 setCurrentIndex(toIndex);
1655 DragTabBar::DragTabBar(QWidget* parent)
1658 setAcceptDrops(true);
1662 #if QT_VERSION < 0x040300
1663 int DragTabBar::tabAt(QPoint const & position) const
1665 const int max = count();
1666 for (int i = 0; i < max; ++i) {
1667 if (tabRect(i).contains(position))
1675 void DragTabBar::mousePressEvent(QMouseEvent * event)
1677 if (event->button() == Qt::LeftButton)
1678 dragStartPos_ = event->pos();
1679 QTabBar::mousePressEvent(event);
1683 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1685 // If the left button isn't pressed anymore then return
1686 if (!(event->buttons() & Qt::LeftButton))
1689 // If the distance is too small then return
1690 if ((event->pos() - dragStartPos_).manhattanLength()
1691 < QApplication::startDragDistance())
1694 // did we hit something after all?
1695 int tab = tabAt(dragStartPos_);
1699 // simulate button release to remove highlight from button
1700 int i = currentIndex();
1701 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1702 event->button(), event->buttons(), 0);
1703 QTabBar::mouseReleaseEvent(&me);
1707 QDrag * drag = new QDrag(this);
1708 QMimeData * mimeData = new QMimeData;
1709 // a crude way to distinguish tab-reodering drops from other ones
1710 mimeData->setData("action", "tab-reordering") ;
1711 drag->setMimeData(mimeData);
1713 #if QT_VERSION >= 0x040300
1714 // get tab pixmap as cursor
1715 QRect r = tabRect(tab);
1716 QPixmap pixmap(r.size());
1717 render(&pixmap, - r.topLeft());
1718 drag->setPixmap(pixmap);
1721 drag->start(Qt::MoveAction);
1727 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1729 // Only accept if it's an tab-reordering request
1730 QMimeData const * m = event->mimeData();
1731 QStringList formats = m->formats();
1732 if (formats.contains("action")
1733 && m->data("action") == "tab-reordering")
1734 event->acceptProposedAction();
1738 void DragTabBar::dropEvent(QDropEvent * event)
1740 int fromIndex = tabAt(dragStartPos_);
1741 int toIndex = tabAt(event->pos());
1743 // Tell interested objects that
1744 if (fromIndex != toIndex)
1745 tabMoveRequested(fromIndex, toIndex);
1746 event->acceptProposedAction();
1750 } // namespace frontend
1753 #include "GuiWorkArea_moc.cpp"