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);
316 void GuiWorkArea::fixVerticalScrollBar()
319 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
323 void GuiWorkArea::close()
325 lyx_view_->removeWorkArea(this);
329 void GuiWorkArea::setFullScreen(bool full_screen)
331 buffer_view_->setFullScreen(full_screen);
333 setFrameStyle(QFrame::NoFrame);
334 if (lyxrc.full_screen_scrollbar)
335 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
338 setFrameStyle(QFrame::NoFrame);
340 setFrameStyle(QFrame::Box);
342 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
347 BufferView & GuiWorkArea::bufferView()
349 return *buffer_view_;
353 BufferView const & GuiWorkArea::bufferView() const
355 return *buffer_view_;
359 void GuiWorkArea::stopBlinkingCursor()
361 cursor_timeout_.stop();
366 void GuiWorkArea::startBlinkingCursor()
369 //we're not supposed to cache this value.
370 int const time = QApplication::cursorFlashTime() / 2;
373 cursor_timeout_.setInterval(time);
374 cursor_timeout_.start();
378 void GuiWorkArea::redraw()
381 // No need to redraw in this case.
384 // No need to do anything if this is the current view. The BufferView
385 // metrics are already up to date.
386 if (lyx_view_ != guiApp->currentView()
387 || lyx_view_->currentWorkArea() != this) {
388 // FIXME: it would be nice to optimize for the off-screen case.
389 buffer_view_->updateMetrics();
390 buffer_view_->cursor().fixIfBroken();
393 // update cursor position, because otherwise it has to wait until
394 // the blinking interval is over
395 if (cursor_visible_) {
400 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
402 update(0, 0, viewport()->width(), viewport()->height());
404 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
405 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
407 lyx_view_->updateStatusBar();
409 if (lyxerr.debugging(Debug::WORKAREA))
410 buffer_view_->coordCache().dump();
414 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
416 if (lyx_view_->isFullScreen() && lyx_view_->menuBar()->isVisible()) {
417 // FIXME HACK: we should not have to do this here. See related comment
418 // in GuiView::event() (QEvent::ShortcutOverride)
419 lyx_view_->menuBar()->hide();
422 // In order to avoid bad surprise in the middle of an operation,
423 // we better stop the blinking cursor...
424 // the cursor gets restarted in GuiView::restartCursor()
425 stopBlinkingCursor();
427 theLyXFunc().setLyXView(lyx_view_);
428 theLyXFunc().processKeySym(key, mod);
432 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
435 if (cmd0.action == LFUN_FILE_OPEN) {
436 lyx_view_->dispatch(cmd0);
440 theLyXFunc().setLyXView(lyx_view_);
444 if (cmd0.action == LFUN_MOUSE_PRESS) {
445 if (mod == ShiftModifier)
446 cmd = FuncRequest(cmd0, "region-select");
447 else if (mod == ControlModifier)
448 cmd = FuncRequest(cmd0, "paragraph-select");
455 bool const notJustMovingTheMouse =
456 cmd.action != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
458 // In order to avoid bad surprise in the middle of an operation, we better stop
459 // the blinking cursor.
460 if (notJustMovingTheMouse)
461 stopBlinkingCursor();
463 buffer_view_->mouseEventDispatch(cmd);
465 // Skip these when selecting
466 if (cmd.action != LFUN_MOUSE_MOTION) {
467 completer_->updateVisibility(false, false);
468 lyx_view_->updateDialogs();
469 lyx_view_->updateStatusBar();
472 // GUI tweaks except with mouse motion with no button pressed.
473 if (notJustMovingTheMouse) {
474 // Slight hack: this is only called currently when we
475 // clicked somewhere, so we force through the display
476 // of the new status here.
477 lyx_view_->clearMessage();
479 // Show the cursor immediately after any operation
480 startBlinkingCursor();
485 void GuiWorkArea::resizeBufferView()
487 // WARNING: Please don't put any code that will trigger a repaint here!
488 // We are already inside a paint event.
489 lyx_view_->setBusy(true);
490 buffer_view_->resize(viewport()->width(), viewport()->height());
493 // Update scrollbars which might have changed due different
494 // BufferView dimension. This is especially important when the
495 // BufferView goes from zero-size to the real-size for the first time,
496 // as the scrollbar paramters are then set for the first time.
499 lyx_view_->updateLayoutList();
500 lyx_view_->setBusy(false);
501 need_resize_ = false;
505 void GuiWorkArea::showCursor()
511 bool l_shape = false;
512 Font const & realfont = buffer_view_->cursor().real_current_font;
513 BufferParams const & bp = buffer_view_->buffer().params();
514 bool const samelang = realfont.language() == bp.language;
515 bool const isrtl = realfont.isVisibleRightToLeft();
517 if (!samelang || isrtl != bp.language->rightToLeft())
520 // The ERT language hack needs fixing up
521 if (realfont.language() == latex_language)
524 Font const font = buffer_view_->cursor().getFont();
525 FontMetrics const & fm = theFontMetrics(font);
526 int const asc = fm.maxAscent();
527 int const des = fm.maxDescent();
531 Cursor & cur = buffer_view_->cursor();
535 // if it doesn't touch the screen, don't try to show it
536 bool cursorInView = true;
537 if (y + h < 0 || y >= viewport()->height())
538 cursorInView = false;
540 // show cursor on screen
541 bool completable = cur.inset().showCompletionCursor()
542 && completer_->completionAvailable()
543 && !completer_->popupVisible()
544 && !completer_->inlineVisible();
546 cursor_visible_ = true;
547 showCursor(x, y, h, l_shape, isrtl, completable);
552 void GuiWorkArea::hideCursor()
554 if (!cursor_visible_)
557 cursor_visible_ = false;
562 void GuiWorkArea::toggleCursor()
571 void GuiWorkArea::updateScrollbar()
573 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
574 // WARNING: don't touch at the scrollbar value like this:
575 // verticalScrollBar()->setValue(scroll_.position);
576 // because this would cause a recursive signal/slot calling with
577 // GuiWorkArea::scrollTo
578 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
579 verticalScrollBar()->setPageStep(scroll_.page_step);
580 verticalScrollBar()->setSingleStep(scroll_.single_step);
581 verticalScrollBar()->setSliderPosition(scroll_.position);
585 void GuiWorkArea::scrollTo(int value)
587 stopBlinkingCursor();
588 buffer_view_->scrollDocView(value);
590 if (lyxrc.cursor_follows_scrollbar) {
591 buffer_view_->setCursorFromScrollbar();
592 lyx_view_->updateLayoutList();
594 // Show the cursor immediately after any operation.
595 startBlinkingCursor();
596 QApplication::syncX();
600 bool GuiWorkArea::event(QEvent * e)
603 case QEvent::ToolTip: {
604 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
605 if (lyxrc.use_tooltip) {
606 QPoint pos = helpEvent->pos();
607 if (pos.x() < viewport()->width()) {
608 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
609 QToolTip::showText(helpEvent->globalPos(), s);
612 QToolTip::hideText();
614 // Don't forget to accept the event!
619 case QEvent::ShortcutOverride: {
620 // We catch this event in order to catch the Tab or Shift+Tab key press
621 // which are otherwise reserved to focus switching between controls
623 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
624 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
625 || ke->modifiers() & Qt::ControlModifier)
626 return QAbstractScrollArea::event(e);
632 return QAbstractScrollArea::event(e);
638 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
640 QPoint pos = e->pos();
641 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
643 QAbstractScrollArea::contextMenuEvent(e);
646 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
648 QAbstractScrollArea::contextMenuEvent(e);
651 // Position the menu to the right.
652 // FIXME: menu position should be different for RTL text.
653 menu->exec(e->globalPos());
658 void GuiWorkArea::focusInEvent(QFocusEvent * e)
660 if (lyx_view_->currentWorkArea() != this)
661 lyx_view_->setCurrentWorkArea(this);
663 startBlinkingCursor();
664 QAbstractScrollArea::focusInEvent(e);
668 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
670 stopBlinkingCursor();
671 QAbstractScrollArea::focusOutEvent(e);
675 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
677 if (dc_event_.active && dc_event_ == *e) {
678 dc_event_.active = false;
679 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
680 q_button_state(e->button()));
686 inputContext()->reset();
688 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
689 q_button_state(e->button()));
690 dispatch(cmd, q_key_state(e->modifiers()));
695 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
697 if (synthetic_mouse_event_.timeout.running())
698 synthetic_mouse_event_.timeout.stop();
700 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
701 q_button_state(e->button()));
707 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
709 // we kill the triple click if we move
710 doubleClickTimeout();
711 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
712 q_motion_state(e->buttons()));
716 // If we're above or below the work area...
717 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
718 // Make sure only a synthetic event can cause a page scroll,
719 // so they come at a steady rate:
721 // _Force_ a scroll up:
724 cmd.y = viewport()->height();
725 // Store the event, to be handled when the timeout expires.
726 synthetic_mouse_event_.cmd = cmd;
728 if (synthetic_mouse_event_.timeout.running())
729 // Discard the event. Note that it _may_ be handled
730 // when the timeout expires if
731 // synthetic_mouse_event_.cmd has not been overwritten.
732 // Ie, when the timeout expires, we handle the
733 // most recent event but discard all others that
734 // occurred after the one used to start the timeout
735 // in the first place.
738 synthetic_mouse_event_.restart_timeout = true;
739 synthetic_mouse_event_.timeout.start();
740 // Fall through to handle this event...
742 } else if (synthetic_mouse_event_.timeout.running()) {
743 // Store the event, to be possibly handled when the timeout
745 // Once the timeout has expired, normal control is returned
746 // to mouseMoveEvent (restart_timeout = false).
747 // This results in a much smoother 'feel' when moving the
748 // mouse back into the work area.
749 synthetic_mouse_event_.cmd = cmd;
750 synthetic_mouse_event_.restart_timeout = false;
754 // Has anything changed on-screen since the last QMouseEvent
756 double const scrollbar_value = verticalScrollBar()->value();
757 if (e->x() == synthetic_mouse_event_.x_old
758 && e->y() == synthetic_mouse_event_.y_old
759 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
760 // Nothing changed on-screen since the last QMouseEvent.
764 // Yes something has changed. Store the params used to check this.
765 synthetic_mouse_event_.x_old = e->x();
766 synthetic_mouse_event_.y_old = e->y();
767 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
769 // ... and dispatch the event to the LyX core.
774 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
776 // Wheel rotation by one notch results in a delta() of 120 (see
777 // documentation of QWheelEvent)
778 int const delta = ev->delta() / 120;
779 if (ev->modifiers() & Qt::ControlModifier) {
780 lyxrc.zoom -= 5 * delta;
783 // The global QPixmapCache is used in GuiPainter to cache text
784 // painting so we must reset it.
785 QPixmapCache::clear();
786 guiApp->fontLoader().update();
788 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
792 // Take into account the desktop wide settings.
793 int const lines = qApp->wheelScrollLines();
794 int const page_step = verticalScrollBar()->pageStep();
795 // Test if the wheel mouse is set to one screen at a time.
796 int scroll_value = lines > page_step
797 ? page_step : lines * verticalScrollBar()->singleStep();
799 // Take into account the rotation.
800 scroll_value *= delta;
802 // Take into account user preference.
803 scroll_value *= lyxrc.mouse_wheel_speed;
804 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
805 << " delta = " << delta << " scroll_value = " << scroll_value
806 << " page_step = " << page_step);
808 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
814 void GuiWorkArea::generateSyntheticMouseEvent()
816 // Set things off to generate the _next_ 'pseudo' event.
817 if (synthetic_mouse_event_.restart_timeout)
818 synthetic_mouse_event_.timeout.start();
820 // Has anything changed on-screen since the last timeout signal
822 double const scrollbar_value = verticalScrollBar()->value();
823 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
824 // Yes it has. Store the params used to check this.
825 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
827 // ... and dispatch the event to the LyX core.
828 dispatch(synthetic_mouse_event_.cmd);
833 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
835 // intercept some keys if completion popup is visible
836 if (completer_->popupVisible()) {
840 completer_->activate();
846 // intercept keys for the completion
847 if (ev->key() == Qt::Key_Tab) {
853 if (completer_->popupVisible() && ev->key() == Qt::Key_Escape) {
854 completer_->hidePopup();
859 if (completer_->inlineVisible() && ev->key() == Qt::Key_Escape) {
860 completer_->hideInline();
865 // do nothing if there are other events
866 // (the auto repeated events come too fast)
867 // \todo FIXME: remove hard coded Qt keys, process the key binding
869 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
870 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
871 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
877 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
878 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
881 setKeySymbol(&sym, ev);
882 processKeySym(sym, q_key_state(ev->modifiers()));
887 void GuiWorkArea::doubleClickTimeout()
889 dc_event_.active = false;
893 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
895 dc_event_ = DoubleClick(ev);
896 QTimer::singleShot(QApplication::doubleClickInterval(), this,
897 SLOT(doubleClickTimeout()));
898 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
900 q_button_state(ev->button()));
906 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
908 QAbstractScrollArea::resizeEvent(ev);
914 void GuiWorkArea::update(int x, int y, int w, int h)
916 viewport()->repaint(x, y, w, h);
920 void GuiWorkArea::paintEvent(QPaintEvent * ev)
922 QRect const rc = ev->rect();
923 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
924 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
927 screen_ = QPixmap(viewport()->width(), viewport()->height());
933 QPainter pain(viewport());
934 pain.drawPixmap(rc, screen_, rc);
940 void GuiWorkArea::updateScreen()
942 GuiPainter pain(&screen_);
943 buffer_view_->draw(pain);
947 void GuiWorkArea::showCursor(int x, int y, int h,
948 bool l_shape, bool rtl, bool completable)
950 if (schedule_redraw_) {
951 // This happens when a graphic conversion is finished. As we don't know
952 // the size of the new graphics, it's better the update everything.
953 // We can't use redraw() here because this would trigger a infinite
954 // recursive loop with showCursor().
955 buffer_view_->resize(viewport()->width(), viewport()->height());
958 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
959 schedule_redraw_ = false;
960 // Show the cursor immediately after the update.
966 cursor_->update(x, y, h, l_shape, rtl, completable);
968 viewport()->update(cursor_->rect());
972 void GuiWorkArea::removeCursor()
975 //if (!qApp->focusWidget())
976 viewport()->update(cursor_->rect());
980 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
982 QString const & commit_string = e->commitString();
983 docstring const & preedit_string
984 = qstring_to_ucs4(e->preeditString());
986 if (!commit_string.isEmpty()) {
988 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
989 << " commitString: " << e->commitString());
993 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
994 for (int i = 0; i != commit_string.size(); ++i) {
995 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1000 // Hide the cursor during the kana-kanji transformation.
1001 if (preedit_string.empty())
1002 startBlinkingCursor();
1004 stopBlinkingCursor();
1006 // last_width : for checking if last preedit string was/wasn't empty.
1007 static bool last_width = false;
1008 if (!last_width && preedit_string.empty()) {
1009 // if last_width is last length of preedit string.
1014 GuiPainter pain(&screen_);
1015 buffer_view_->updateMetrics();
1016 buffer_view_->draw(pain);
1017 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1018 FontMetrics const & fm = theFontMetrics(font);
1019 int height = fm.maxHeight();
1020 int cur_x = cursor_->rect().left();
1021 int cur_y = cursor_->rect().bottom();
1023 // redraw area of preedit string.
1024 update(0, cur_y - height, viewport()->width(),
1025 (height + 1) * preedit_lines_);
1027 if (preedit_string.empty()) {
1035 // att : stores an IM attribute.
1036 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1038 // get attributes of input method cursor.
1039 // cursor_pos : cursor position in preedit string.
1040 size_t cursor_pos = 0;
1041 bool cursor_is_visible = false;
1042 for (int i = 0; i != att.size(); ++i) {
1043 if (att.at(i).type == QInputMethodEvent::Cursor) {
1044 cursor_pos = att.at(i).start;
1045 cursor_is_visible = att.at(i).length != 0;
1050 size_t preedit_length = preedit_string.length();
1052 // get position of selection in input method.
1053 // FIXME: isn't there a way to do this simplier?
1054 // rStart : cursor position in selected string in IM.
1056 // rLength : selected string length in IM.
1058 if (cursor_pos < preedit_length) {
1059 for (int i = 0; i != att.size(); ++i) {
1060 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1061 if (att.at(i).start <= int(cursor_pos)
1062 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1063 rStart = att.at(i).start;
1064 rLength = att.at(i).length;
1065 if (!cursor_is_visible)
1066 cursor_pos += rLength;
1073 rStart = cursor_pos;
1077 int const right_margin = buffer_view_->rightMargin();
1078 Painter::preedit_style ps;
1079 // Most often there would be only one line:
1081 for (size_t pos = 0; pos != preedit_length; ++pos) {
1082 char_type const typed_char = preedit_string[pos];
1083 // reset preedit string style
1084 ps = Painter::preedit_default;
1086 // if we reached the right extremity of the screen, go to next line.
1087 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1088 cur_x = right_margin;
1089 cur_y += height + 1;
1092 // preedit strings are displayed with dashed underline
1093 // and partial strings are displayed white on black indicating
1094 // that we are in selecting mode in the input method.
1095 // FIXME: rLength == preedit_length is not a changing condition
1096 // FIXME: should be put out of the loop.
1098 && pos < rStart + rLength
1099 && !(cursor_pos < rLength && rLength == preedit_length))
1100 ps = Painter::preedit_selecting;
1102 if (pos == cursor_pos
1103 && (cursor_pos < rLength && rLength == preedit_length))
1104 ps = Painter::preedit_cursor;
1106 // draw one character and update cur_x.
1107 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1110 // update the preedit string screen area.
1111 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1112 (height + 1) * preedit_lines_);
1114 // Don't forget to accept the event!
1119 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1121 QRect cur_r(0,0,0,0);
1123 // this is the CJK-specific composition window position.
1124 case Qt::ImMicroFocus:
1125 cur_r = cursor_->rect();
1126 if (preedit_lines_ != 1)
1128 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1129 // return lower right of cursor in LyX.
1132 return QWidget::inputMethodQuery(query);
1137 void GuiWorkArea::updateWindowTitle()
1139 docstring maximize_title;
1140 docstring minimize_title;
1142 Buffer & buf = buffer_view_->buffer();
1143 FileName const fileName = buf.fileName();
1144 if (!fileName.empty()) {
1145 maximize_title = fileName.displayName(30);
1146 minimize_title = from_utf8(fileName.onlyFileName());
1147 if (!buf.isClean()) {
1148 maximize_title += _(" (changed)");
1149 minimize_title += char_type('*');
1151 if (buf.isReadonly())
1152 maximize_title += _(" (read only)");
1155 QString title = windowTitle();
1156 QString new_title = toqstr(maximize_title);
1157 if (title == new_title)
1160 QWidget::setWindowTitle(new_title);
1161 QWidget::setWindowIconText(toqstr(minimize_title));
1166 void GuiWorkArea::setReadOnly(bool)
1168 updateWindowTitle();
1169 if (this == lyx_view_->currentWorkArea())
1170 lyx_view_->updateDialogs();
1174 bool GuiWorkArea::isFullScreen()
1176 return lyx_view_ && lyx_view_->isFullScreen();
1180 ////////////////////////////////////////////////////////////////////
1184 ////////////////////////////////////////////////////////////////////
1187 class NoTabFrameMacStyle : public QMacStyle {
1190 QRect subElementRect(SubElement element, const QStyleOption * option,
1191 const QWidget * widget = 0) const
1193 QRect rect = QMacStyle::subElementRect(element, option, widget);
1194 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1196 // The Qt Mac style puts the contents into a 3 pixel wide box
1197 // which looks very ugly and not like other Mac applications.
1198 // Hence we remove this here, and moreover the 16 pixel round
1199 // frame above if the tab bar is hidden.
1200 if (element == QStyle::SE_TabWidgetTabContents) {
1201 rect.adjust(- rect.left(), 0, rect.left(), 0);
1210 NoTabFrameMacStyle noTabFrameMacStyle;
1214 TabWorkArea::TabWorkArea(QWidget * parent)
1215 : QTabWidget(parent), clicked_tab_(-1)
1218 setStyle(&noTabFrameMacStyle);
1221 QPalette pal = palette();
1222 pal.setColor(QPalette::Active, QPalette::Button,
1223 pal.color(QPalette::Active, QPalette::Window));
1224 pal.setColor(QPalette::Disabled, QPalette::Button,
1225 pal.color(QPalette::Disabled, QPalette::Window));
1226 pal.setColor(QPalette::Inactive, QPalette::Button,
1227 pal.color(QPalette::Inactive, QPalette::Window));
1229 QObject::connect(this, SIGNAL(currentChanged(int)),
1230 this, SLOT(on_currentTabChanged(int)));
1232 QToolButton * closeBufferButton = new QToolButton(this);
1233 closeBufferButton->setPalette(pal);
1234 // FIXME: rename the icon to closebuffer.png
1235 closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1236 closeBufferButton->setText("Close File");
1237 closeBufferButton->setAutoRaise(true);
1238 closeBufferButton->setCursor(Qt::ArrowCursor);
1239 closeBufferButton->setToolTip(qt_("Close File"));
1240 closeBufferButton->setEnabled(true);
1241 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1242 this, SLOT(closeCurrentBuffer()));
1243 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1245 // setup drag'n'drop
1246 QTabBar* tb = new DragTabBar;
1247 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1248 this, SLOT(moveTab(int, int)));
1249 tb->setElideMode(Qt::ElideNone);
1252 // make us responsible for the context menu of the tabbar
1253 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1254 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1255 this, SLOT(showContextMenu(const QPoint &)));
1257 setUsesScrollButtons(true);
1261 void TabWorkArea::setFullScreen(bool full_screen)
1263 for (int i = 0; i != count(); ++i) {
1264 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1265 wa->setFullScreen(full_screen);
1268 if (lyxrc.full_screen_tabbar)
1269 showBar(!full_screen && count()>1);
1273 void TabWorkArea::showBar(bool show)
1275 tabBar()->setEnabled(show);
1276 tabBar()->setVisible(show);
1280 GuiWorkArea * TabWorkArea::currentWorkArea()
1285 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1291 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1293 for (int i = 0; i != count(); ++i) {
1294 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1295 LASSERT(wa, return 0);
1296 if (&wa->bufferView().buffer() == &buffer)
1303 void TabWorkArea::closeAll()
1306 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1314 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1316 LASSERT(work_area, /**/);
1317 int index = indexOf(work_area);
1321 if (index == currentIndex())
1322 // Make sure the work area is up to date.
1323 on_currentTabChanged(index);
1325 // Switch to the work area.
1326 setCurrentIndex(index);
1327 work_area->setFocus();
1333 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1335 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1336 wa->setUpdatesEnabled(false);
1337 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1338 // when hiding it again below).
1339 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1340 showBar(count() > 0);
1341 addTab(wa, wa->windowTitle());
1342 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1343 this, SLOT(updateTabTexts()));
1344 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1345 setFullScreen(true);
1347 // Hide tabbar if there's only one tab.
1348 showBar(count() > 1);
1356 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1358 LASSERT(work_area, return false);
1359 int index = indexOf(work_area);
1363 work_area->setUpdatesEnabled(false);
1368 // make sure the next work area is enabled.
1369 currentWidget()->setUpdatesEnabled(true);
1370 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1371 setFullScreen(true);
1373 // Hide tabbar if there's only one tab.
1374 showBar(count() > 1);
1376 lastWorkAreaRemoved();
1385 void TabWorkArea::on_currentTabChanged(int i)
1387 // returns e.g. on application destruction
1390 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1391 LASSERT(wa, return);
1392 BufferView & bv = wa->bufferView();
1393 bv.cursor().fixIfBroken();
1395 wa->setUpdatesEnabled(true);
1399 currentWorkAreaChanged(wa);
1401 LYXERR(Debug::GUI, "currentTabChanged " << i
1402 << "File" << bv.buffer().absFileName());
1406 void TabWorkArea::closeCurrentBuffer()
1408 if (clicked_tab_ != -1)
1409 setCurrentIndex(clicked_tab_);
1411 lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1415 void TabWorkArea::closeCurrentTab()
1417 if (clicked_tab_ == -1)
1418 removeWorkArea(currentWorkArea());
1420 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1429 /// make vector happy
1432 DisplayPath(int tab, FileName const & filename)
1435 filename_ = toqstr(filename.onlyFileNameWithoutExt());
1436 postfix_ = toqstr(filename.absoluteFilePath()).
1437 split("/", QString::SkipEmptyParts);
1438 postfix_.pop_back();
1439 abs_ = toqstr(filename.absoluteFilePath());
1440 dottedPrefix_ = false;
1443 /// Absolute path for debugging.
1448 /// Add the first segment from the postfix or three dots to the prefix.
1449 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1450 /// when really needed.
1451 void shiftPathSegment(bool dotted)
1453 if (postfix_.count() <= 0)
1457 if (dottedPrefix_ && !prefix_.isEmpty())
1459 prefix_ += postfix_.front() + "/";
1461 dottedPrefix_ = dotted && !prefix_.isEmpty();
1462 postfix_.pop_front();
1465 QString displayString() const
1467 if (prefix_.isEmpty())
1470 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1471 return prefix_ + (dots ? ".../" : "") + filename_;
1474 QString forecastPathString() const
1476 if (postfix_.count() == 0)
1477 return displayString();
1480 + (dottedPrefix_ ? ".../" : "")
1481 + postfix_.front() + "/";
1484 bool final() const { return postfix_.empty(); }
1486 int tab() const { return tab_; }
1492 QStringList postfix_;
1505 bool operator<(DisplayPath const & a, DisplayPath const & b)
1507 return a.displayString() < b.displayString();
1511 bool operator==(DisplayPath const & a, DisplayPath const & b)
1513 return a.displayString() == b.displayString();
1517 void TabWorkArea::updateTabTexts()
1522 std::list<DisplayPath> paths;
1523 typedef std::list<DisplayPath>::iterator It;
1525 // collect full names first: path into postfix, empty prefix and
1526 // filename without extension
1527 for (size_t i = 0; i < n; ++i) {
1528 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(i));
1529 FileName const fn = i_wa->bufferView().buffer().fileName();
1530 paths.push_back(DisplayPath(i, fn));
1533 // go through path segments and see if it helps to make the path more unique
1534 bool somethingChanged = true;
1535 bool allFinal = false;
1536 while (somethingChanged && !allFinal) {
1537 // adding path segments changes order
1540 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1541 somethingChanged = false;
1544 // find segments which are not unique (i.e. non-atomic)
1545 It it = paths.begin();
1547 QString segString = it->displayString();
1548 for (; it != paths.end(); ++it) {
1549 // look to the next item
1554 allFinal = allFinal && it->final();
1556 LYXERR(Debug::GUI, "it = " << it->abs()
1557 << " => " << it->displayString());
1559 // still the same segment?
1561 if ((next != paths.end()
1562 && (nextString = next->displayString()) == segString))
1564 LYXERR(Debug::GUI, "segment ended");
1566 // only a trivial one with one element?
1567 if (it == segStart) {
1568 // start new segment
1570 segString = nextString;
1574 // we found a non-atomic segment segStart <= sit <= it < next.
1575 // Shift path segments and hope for the best
1576 // that it makes the path more unique.
1577 somethingChanged = true;
1579 QString dspString = sit->forecastPathString();
1580 LYXERR(Debug::GUI, "first forecast found for "
1581 << sit->abs() << " => " << dspString);
1583 bool moreUnique = false;
1584 for (; sit != next; ++sit) {
1585 if (sit->forecastPathString() != dspString) {
1586 LYXERR(Debug::GUI, "different forecast found for "
1587 << sit->abs() << " => " << sit->forecastPathString());
1591 LYXERR(Debug::GUI, "same forecast found for "
1592 << sit->abs() << " => " << dspString);
1595 // if the path segment helped, add it. Otherwise add dots
1596 bool dots = !moreUnique;
1597 LYXERR(Debug::GUI, "using dots = " << dots);
1598 for (sit = segStart; sit != next; ++sit) {
1599 sit->shiftPathSegment(dots);
1600 LYXERR(Debug::GUI, "shifting "
1601 << sit->abs() << " => " << sit->displayString());
1604 // start new segment
1606 segString = nextString;
1610 // set new tab titles
1611 for (It it = paths.begin(); it != paths.end(); ++it) {
1612 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(it->tab()));
1613 Buffer & buf = i_wa->bufferView().buffer();
1614 if (!buf.fileName().empty() && !buf.isClean())
1615 setTabText(it->tab(), it->displayString() + "*");
1617 setTabText(it->tab(), it->displayString());
1622 void TabWorkArea::showContextMenu(const QPoint & pos)
1625 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1626 if (clicked_tab_ == -1)
1631 popup.addAction(QIcon(":/images/hidetab.png"),
1632 qt_("Hide tab"), this, SLOT(closeCurrentTab()));
1633 popup.addAction(QIcon(":/images/closetab.png"),
1634 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1635 popup.exec(tabBar()->mapToGlobal(pos));
1641 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1643 QWidget * w = widget(fromIndex);
1644 QIcon icon = tabIcon(fromIndex);
1645 QString text = tabText(fromIndex);
1647 setCurrentIndex(fromIndex);
1648 removeTab(fromIndex);
1649 insertTab(toIndex, w, icon, text);
1650 setCurrentIndex(toIndex);
1654 DragTabBar::DragTabBar(QWidget* parent)
1657 setAcceptDrops(true);
1661 #if QT_VERSION < 0x040300
1662 int DragTabBar::tabAt(QPoint const & position) const
1664 const int max = count();
1665 for (int i = 0; i < max; ++i) {
1666 if (tabRect(i).contains(position))
1674 void DragTabBar::mousePressEvent(QMouseEvent * event)
1676 if (event->button() == Qt::LeftButton)
1677 dragStartPos_ = event->pos();
1678 QTabBar::mousePressEvent(event);
1682 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1684 // If the left button isn't pressed anymore then return
1685 if (!(event->buttons() & Qt::LeftButton))
1688 // If the distance is too small then return
1689 if ((event->pos() - dragStartPos_).manhattanLength()
1690 < QApplication::startDragDistance())
1693 // did we hit something after all?
1694 int tab = tabAt(dragStartPos_);
1698 // simulate button release to remove highlight from button
1699 int i = currentIndex();
1700 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1701 event->button(), event->buttons(), 0);
1702 QTabBar::mouseReleaseEvent(&me);
1706 QDrag * drag = new QDrag(this);
1707 QMimeData * mimeData = new QMimeData;
1708 // a crude way to distinguish tab-reodering drops from other ones
1709 mimeData->setData("action", "tab-reordering") ;
1710 drag->setMimeData(mimeData);
1712 #if QT_VERSION >= 0x040300
1713 // get tab pixmap as cursor
1714 QRect r = tabRect(tab);
1715 QPixmap pixmap(r.size());
1716 render(&pixmap, - r.topLeft());
1717 drag->setPixmap(pixmap);
1720 drag->start(Qt::MoveAction);
1726 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1728 // Only accept if it's an tab-reordering request
1729 QMimeData const * m = event->mimeData();
1730 QStringList formats = m->formats();
1731 if (formats.contains("action")
1732 && m->data("action") == "tab-reordering")
1733 event->acceptProposedAction();
1737 void DragTabBar::dropEvent(QDropEvent * event)
1739 int fromIndex = tabAt(dragStartPos_);
1740 int toIndex = tabAt(event->pos());
1742 // Tell interested objects that
1743 if (fromIndex != toIndex)
1744 tabMoveRequested(fromIndex, toIndex);
1745 event->acceptProposedAction();
1749 } // namespace frontend
1752 #include "GuiWorkArea_moc.cpp"