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"
17 #include "BufferParams.h"
18 #include "BufferView.h"
19 #include "CoordCache.h"
22 #include "FuncRequest.h"
23 #include "GuiApplication.h"
24 #include "GuiKeySymbol.h"
25 #include "GuiPainter.h"
27 #include "KeySymbol.h"
31 #include "MetricsInfo.h"
32 #include "qt_helpers.h"
35 #include "graphics/GraphicsImage.h"
36 #include "graphics/GraphicsLoader.h"
38 #include "support/debug.h"
39 #include "support/gettext.h"
40 #include "support/FileName.h"
42 #include "frontends/Application.h"
43 #include "frontends/FontMetrics.h"
44 #include "frontends/WorkAreaManager.h"
46 #include <QContextMenuEvent>
47 #include <QInputContext>
52 #include <QMainWindow>
56 #include <QPixmapCache>
59 #include <QToolButton>
62 #include <boost/bind.hpp>
66 extern "C" int XEventsQueued(Display *display, int mode);
70 int const CursorWidth = 2;
72 int const CursorWidth = 1;
74 int const TabIndicatorWidth = 3;
80 using namespace lyx::support;
85 /// return the LyX mouse button state from Qt's
86 static mouse_button::state q_button_state(Qt::MouseButton button)
88 mouse_button::state b = mouse_button::none;
91 b = mouse_button::button1;
94 b = mouse_button::button2;
97 b = mouse_button::button3;
106 /// return the LyX mouse button state from Qt's
107 mouse_button::state q_motion_state(Qt::MouseButtons state)
109 mouse_button::state b = mouse_button::none;
110 if (state & Qt::LeftButton)
111 b |= mouse_button::button1;
112 if (state & Qt::MidButton)
113 b |= mouse_button::button2;
114 if (state & Qt::RightButton)
115 b |= mouse_button::button3;
126 void draw(QPainter & painter)
128 if (!show_ || !rect_.isValid())
132 int l = x_ - rect_.left();
133 int r = rect_.right() - x_;
134 int bot = rect_.bottom();
136 // draw vertica linel
137 painter.fillRect(x_, y, CursorWidth, rect_.height(), color_);
139 // draw RTL/LTR indication
140 painter.setPen(color_);
143 painter.drawLine(x_, bot, x_ - l, bot);
145 painter.drawLine(x_, bot, x_ + CursorWidth + r, bot);
148 // draw completion triangle
150 int m = y + rect_.height() / 2;
151 int d = TabIndicatorWidth - 1;
153 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
154 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
156 painter.drawLine(x_ + CursorWidth, m - d, x_ + CursorWidth + d, m);
157 painter.drawLine(x_ + CursorWidth, m + d, x_ + CursorWidth + d, m);
162 void update(int x, int y, int h, bool l_shape,
163 bool rtl, bool completable)
165 color_ = guiApp->colorCache().get(Color_cursor);
168 completable_ = completable;
171 // extension to left and right
175 // RTL/LTR indication
183 // completion triangle
186 l = max(l, TabIndicatorWidth);
188 r = max(r, TabIndicatorWidth);
191 // compute overall rectangle
192 rect_ = QRect(x - l, y, CursorWidth + r + l, h);
195 void show(bool set_show = true) { show_ = set_show; }
196 void hide() { show_ = false; }
198 QRect const & rect() { return rect_; }
201 /// cursor is in RTL or LTR text
203 /// indication for RTL or LTR
205 /// triangle to show that a completion is available
211 /// rectangle, possibly with l_shape and completion triangle
213 /// x position (were the vertical line is drawn)
218 // This is a 'heartbeat' generating synthetic mouse move events when the
219 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
220 SyntheticMouseEvent::SyntheticMouseEvent()
221 : timeout(200), restart_timeout(true),
222 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
227 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & lv)
228 : buffer_view_(new BufferView(buffer)), lyx_view_(&lv),
229 cursor_visible_(false),
230 need_resize_(false), schedule_redraw_(false),
231 preedit_lines_(1), completer_(this)
233 buffer.workAreaManager().add(this);
235 connect(&cursor_timeout_, SIGNAL(timeout()),
236 this, SLOT(toggleCursor()));
238 int const time = QApplication::cursorFlashTime() / 2;
240 cursor_timeout_.setInterval(time);
241 cursor_timeout_.start();
243 // let's initialize this just to be safe
244 cursor_timeout_.setInterval(500);
246 screen_ = QPixmap(viewport()->width(), viewport()->height());
247 cursor_ = new frontend::CursorWidget();
250 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
251 setAcceptDrops(true);
252 setMouseTracking(true);
253 setMinimumSize(100, 70);
255 setFrameStyle(QFrame::NoFrame);
257 setFrameStyle(QFrame::Box);
261 viewport()->setAutoFillBackground(false);
262 // We don't need double-buffering nor SystemBackground on
263 // the viewport because we have our own backing pixmap.
264 viewport()->setAttribute(Qt::WA_NoSystemBackground);
266 setFocusPolicy(Qt::WheelFocus);
268 viewport()->setCursor(Qt::IBeamCursor);
270 synthetic_mouse_event_.timeout.timeout.connect(
271 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
274 // Initialize the vertical Scroll Bar
275 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
276 this, SLOT(scrollTo(int)));
278 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
279 << " viewport height: " << viewport()->height());
281 // Enables input methods for asian languages.
282 // Must be set when creating custom text editing widgets.
283 setAttribute(Qt::WA_InputMethodEnabled, true);
287 GuiWorkArea::~GuiWorkArea()
289 buffer_view_->buffer().workAreaManager().remove(this);
295 void GuiWorkArea::close()
297 lyx_view_->removeWorkArea(this);
301 void GuiWorkArea::setFullScreen(bool full_screen)
303 buffer_view_->setFullScreen(full_screen);
305 setFrameStyle(QFrame::NoFrame);
306 if (lyxrc.full_screen_scrollbar)
307 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
310 setFrameStyle(QFrame::NoFrame);
312 setFrameStyle(QFrame::Box);
314 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
319 BufferView & GuiWorkArea::bufferView()
321 return *buffer_view_;
325 BufferView const & GuiWorkArea::bufferView() const
327 return *buffer_view_;
331 void GuiWorkArea::stopBlinkingCursor()
333 cursor_timeout_.stop();
338 void GuiWorkArea::startBlinkingCursor()
341 //we're not supposed to cache this value.
342 int const time = QApplication::cursorFlashTime() / 2;
345 cursor_timeout_.setInterval(time);
346 cursor_timeout_.start();
350 void GuiWorkArea::redraw()
353 // No need to redraw in this case.
356 // No need to do anything if this is the current view. The BufferView
357 // metrics are already up to date.
358 if (lyx_view_ != guiApp->currentView()
359 || lyx_view_->currentWorkArea() != this) {
360 // FIXME: it would be nice to optimize for the off-screen case.
361 buffer_view_->updateMetrics();
362 buffer_view_->cursor().fixIfBroken();
365 // update cursor position, because otherwise it has to wait until
366 // the blinking interval is over
367 if (cursor_visible_) {
372 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
374 update(0, 0, viewport()->width(), viewport()->height());
376 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
377 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
379 lyx_view_->updateStatusBar();
381 if (lyxerr.debugging(Debug::WORKAREA))
382 buffer_view_->coordCache().dump();
386 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
388 // In order to avoid bad surprise in the middle of an operation,
389 // we better stop the blinking cursor...
390 // the cursor gets restarted in GuiView::restartCursor()
391 stopBlinkingCursor();
393 theLyXFunc().setLyXView(lyx_view_);
394 theLyXFunc().processKeySym(key, mod);
399 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
402 if (cmd0.action == LFUN_FILE_OPEN) {
403 lyx_view_->dispatch(cmd0);
407 theLyXFunc().setLyXView(lyx_view_);
411 if (cmd0.action == LFUN_MOUSE_PRESS) {
412 if (mod == ShiftModifier)
413 cmd = FuncRequest(cmd0, "region-select");
414 else if (mod == ControlModifier)
415 cmd = FuncRequest(cmd0, "paragraph-select");
422 bool const notJustMovingTheMouse =
423 cmd.action != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
425 // In order to avoid bad surprise in the middle of an operation, we better stop
426 // the blinking cursor.
427 if (notJustMovingTheMouse)
428 stopBlinkingCursor();
430 buffer_view_->mouseEventDispatch(cmd);
432 // Skip these when selecting
433 if (cmd.action != LFUN_MOUSE_MOTION) {
434 completer_.updateVisibility(false, false);
435 lyx_view_->updateLayoutList();
436 lyx_view_->updateToolbars();
439 // GUI tweaks except with mouse motion with no button pressed.
440 if (notJustMovingTheMouse) {
441 // Slight hack: this is only called currently when we
442 // clicked somewhere, so we force through the display
443 // of the new status here.
444 lyx_view_->clearMessage();
446 // Show the cursor immediately after any operation
447 startBlinkingCursor();
452 void GuiWorkArea::resizeBufferView()
454 // WARNING: Please don't put any code that will trigger a repaint here!
455 // We are already inside a paint event.
456 lyx_view_->setBusy(true);
457 buffer_view_->resize(viewport()->width(), viewport()->height());
460 // Update scrollbars which might have changed due different
461 // BufferView dimension. This is especially important when the
462 // BufferView goes from zero-size to the real-size for the first time,
463 // as the scrollbar paramters are then set for the first time.
466 lyx_view_->updateLayoutList();
467 lyx_view_->setBusy(false);
468 need_resize_ = false;
472 void GuiWorkArea::showCursor()
478 bool l_shape = false;
479 Font const & realfont = buffer_view_->cursor().real_current_font;
480 BufferParams const & bp = buffer_view_->buffer().params();
481 bool const samelang = realfont.language() == bp.language;
482 bool const isrtl = realfont.isVisibleRightToLeft();
484 if (!samelang || isrtl != bp.language->rightToLeft())
487 // The ERT language hack needs fixing up
488 if (realfont.language() == latex_language)
491 Font const font = buffer_view_->cursor().getFont();
492 FontMetrics const & fm = theFontMetrics(font);
493 int const asc = fm.maxAscent();
494 int const des = fm.maxDescent();
498 Cursor & cur = buffer_view_->cursor();
502 // if it doesn't touch the screen, don't try to show it
503 bool cursorInView = true;
504 if (y + h < 0 || y >= viewport()->height())
505 cursorInView = false;
507 // show cursor on screen
508 bool completable = completer_.completionAvailable()
509 && !completer_.popupVisible()
510 && !completer_.inlineVisible();
512 cursor_visible_ = true;
513 showCursor(x, y, h, l_shape, isrtl, completable);
518 void GuiWorkArea::hideCursor()
520 if (!cursor_visible_)
523 cursor_visible_ = false;
528 void GuiWorkArea::toggleCursor()
537 void GuiWorkArea::updateScrollbar()
539 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
541 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
542 verticalScrollBar()->setPageStep(scroll_.page_step);
543 verticalScrollBar()->setSingleStep(scroll_.single_step);
544 // Block the scrollbar signal to prevent recursive signal/slot calling.
545 verticalScrollBar()->blockSignals(true);
546 verticalScrollBar()->setValue(scroll_.position);
547 verticalScrollBar()->setSliderPosition(scroll_.position);
548 verticalScrollBar()->blockSignals(false);
552 void GuiWorkArea::scrollTo(int value)
554 stopBlinkingCursor();
555 buffer_view_->scrollDocView(value);
557 if (lyxrc.cursor_follows_scrollbar) {
558 buffer_view_->setCursorFromScrollbar();
559 lyx_view_->updateLayoutList();
561 // Show the cursor immediately after any operation.
562 startBlinkingCursor();
563 QApplication::syncX();
567 bool GuiWorkArea::event(QEvent * e)
570 case QEvent::ToolTip: {
571 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
572 if (lyxrc.use_tooltip) {
573 QPoint pos = helpEvent->pos();
574 if (pos.x() < viewport()->width()) {
575 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
576 QToolTip::showText(helpEvent->globalPos(), s);
579 QToolTip::hideText();
581 // Don't forget to accept the event!
586 case QEvent::ShortcutOverride: {
587 // We catch this event in order to catch the Tab or Shift+Tab key press
588 // which are otherwise reserved to focus switching between controls
590 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
591 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
592 || ke->modifiers() & Qt::ControlModifier)
593 return QAbstractScrollArea::event(e);
599 return QAbstractScrollArea::event(e);
605 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
607 QPoint pos = e->pos();
608 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
610 QAbstractScrollArea::contextMenuEvent(e);
613 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
615 QAbstractScrollArea::contextMenuEvent(e);
618 // Position the menu to the right.
619 // FIXME: menu position should be different for RTL text.
620 menu->exec(e->globalPos());
625 void GuiWorkArea::focusInEvent(QFocusEvent * e)
627 if (lyx_view_->currentWorkArea() != this)
628 lyx_view_->setCurrentWorkArea(this);
630 // Repaint the whole screen.
631 // Note: this is different from redraw() as only the backing pixmap
632 // will be redrawn, which is cheap.
633 viewport()->repaint();
635 startBlinkingCursor();
636 QAbstractScrollArea::focusInEvent(e);
640 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
642 stopBlinkingCursor();
643 QAbstractScrollArea::focusOutEvent(e);
647 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
649 if (dc_event_.active && dc_event_ == *e) {
650 dc_event_.active = false;
651 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
652 q_button_state(e->button()));
658 inputContext()->reset();
660 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
661 q_button_state(e->button()));
662 dispatch(cmd, q_key_state(e->modifiers()));
667 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
669 if (synthetic_mouse_event_.timeout.running())
670 synthetic_mouse_event_.timeout.stop();
672 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
673 q_button_state(e->button()));
679 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
681 // we kill the triple click if we move
682 doubleClickTimeout();
683 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
684 q_motion_state(e->buttons()));
688 // If we're above or below the work area...
689 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
690 // Make sure only a synthetic event can cause a page scroll,
691 // so they come at a steady rate:
693 // _Force_ a scroll up:
696 cmd.y = viewport()->height();
697 // Store the event, to be handled when the timeout expires.
698 synthetic_mouse_event_.cmd = cmd;
700 if (synthetic_mouse_event_.timeout.running())
701 // Discard the event. Note that it _may_ be handled
702 // when the timeout expires if
703 // synthetic_mouse_event_.cmd has not been overwritten.
704 // Ie, when the timeout expires, we handle the
705 // most recent event but discard all others that
706 // occurred after the one used to start the timeout
707 // in the first place.
710 synthetic_mouse_event_.restart_timeout = true;
711 synthetic_mouse_event_.timeout.start();
712 // Fall through to handle this event...
714 } else if (synthetic_mouse_event_.timeout.running()) {
715 // Store the event, to be possibly handled when the timeout
717 // Once the timeout has expired, normal control is returned
718 // to mouseMoveEvent (restart_timeout = false).
719 // This results in a much smoother 'feel' when moving the
720 // mouse back into the work area.
721 synthetic_mouse_event_.cmd = cmd;
722 synthetic_mouse_event_.restart_timeout = false;
726 // Has anything changed on-screen since the last QMouseEvent
728 double const scrollbar_value = verticalScrollBar()->value();
729 if (e->x() == synthetic_mouse_event_.x_old
730 && e->y() == synthetic_mouse_event_.y_old
731 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
732 // Nothing changed on-screen since the last QMouseEvent.
736 // Yes something has changed. Store the params used to check this.
737 synthetic_mouse_event_.x_old = e->x();
738 synthetic_mouse_event_.y_old = e->y();
739 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
741 // ... and dispatch the event to the LyX core.
746 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
748 // Wheel rotation by one notch results in a delta() of 120 (see
749 // documentation of QWheelEvent)
750 int delta = ev->delta() / 120;
751 if (ev->modifiers() & Qt::ControlModifier) {
752 lyxrc.zoom -= 5 * delta;
755 // The global QPixmapCache is used in GuiPainter to cache text
756 // painting so we must reset it.
757 QPixmapCache::clear();
758 guiApp->fontLoader().update();
759 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
761 double const lines = qApp->wheelScrollLines()
762 * lyxrc.mouse_wheel_speed * delta;
763 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << qApp->wheelScrollLines()
764 << " delta = " << ev->delta() << " lines = " << lines);
765 verticalScrollBar()->setValue(verticalScrollBar()->value() -
766 int(lines * verticalScrollBar()->singleStep()));
772 void GuiWorkArea::generateSyntheticMouseEvent()
774 // Set things off to generate the _next_ 'pseudo' event.
775 if (synthetic_mouse_event_.restart_timeout)
776 synthetic_mouse_event_.timeout.start();
778 // Has anything changed on-screen since the last timeout signal
780 double const scrollbar_value = verticalScrollBar()->value();
781 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
782 // Yes it has. Store the params used to check this.
783 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
785 // ... and dispatch the event to the LyX core.
786 dispatch(synthetic_mouse_event_.cmd);
791 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
793 // intercept some keys if completion popup is visible
794 if (completer_.popupVisible()) {
798 completer_.activate();
804 // intercept keys for the completion
805 if (ev->key() == Qt::Key_Tab) {
811 if (completer_.popupVisible() && ev->key() == Qt::Key_Escape) {
812 completer_.hidePopup();
817 if (completer_.inlineVisible() && ev->key() == Qt::Key_Escape) {
818 completer_.hideInline();
823 // do nothing if there are other events
824 // (the auto repeated events come too fast)
825 // \todo FIXME: remove hard coded Qt keys, process the key binding
827 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
828 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
829 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
835 LYXERR(Debug::KEY, " count: " << ev->count()
836 << " text: " << fromqstr(ev->text())
837 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
840 setKeySymbol(&sym, ev);
841 processKeySym(sym, q_key_state(ev->modifiers()));
846 void GuiWorkArea::doubleClickTimeout()
848 dc_event_.active = false;
852 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
854 dc_event_ = DoubleClick(ev);
855 QTimer::singleShot(QApplication::doubleClickInterval(), this,
856 SLOT(doubleClickTimeout()));
857 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
859 q_button_state(ev->button()));
865 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
867 QAbstractScrollArea::resizeEvent(ev);
873 void GuiWorkArea::update(int x, int y, int w, int h)
875 viewport()->repaint(x, y, w, h);
879 void GuiWorkArea::paintEvent(QPaintEvent * ev)
881 QRect const rc = ev->rect();
882 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
883 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
886 screen_ = QPixmap(viewport()->width(), viewport()->height());
892 QPainter pain(viewport());
893 pain.drawPixmap(rc, screen_, rc);
899 void GuiWorkArea::updateScreen()
901 GuiPainter pain(&screen_);
902 buffer_view_->draw(pain);
906 void GuiWorkArea::showCursor(int x, int y, int h,
907 bool l_shape, bool rtl, bool completable)
909 if (schedule_redraw_) {
910 buffer_view_->updateMetrics();
912 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
913 schedule_redraw_ = false;
914 // Show the cursor immediately after the update.
920 cursor_->update(x, y, h, l_shape, rtl, completable);
922 viewport()->update(cursor_->rect());
926 void GuiWorkArea::removeCursor()
929 //if (!qApp->focusWidget())
930 viewport()->update(cursor_->rect());
934 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
936 QString const & commit_string = e->commitString();
937 docstring const & preedit_string
938 = qstring_to_ucs4(e->preeditString());
940 if (!commit_string.isEmpty()) {
942 LYXERR(Debug::KEY, "preeditString: " << fromqstr(e->preeditString())
943 << " commitString: " << fromqstr(e->commitString()));
947 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
948 for (int i = 0; i != commit_string.size(); ++i) {
949 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
954 // Hide the cursor during the kana-kanji transformation.
955 if (preedit_string.empty())
956 startBlinkingCursor();
958 stopBlinkingCursor();
960 // last_width : for checking if last preedit string was/wasn't empty.
961 static bool last_width = false;
962 if (!last_width && preedit_string.empty()) {
963 // if last_width is last length of preedit string.
968 GuiPainter pain(&screen_);
969 buffer_view_->updateMetrics();
970 buffer_view_->draw(pain);
971 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
972 FontMetrics const & fm = theFontMetrics(font);
973 int height = fm.maxHeight();
974 int cur_x = cursor_->rect().left();
975 int cur_y = cursor_->rect().bottom();
977 // redraw area of preedit string.
978 update(0, cur_y - height, viewport()->width(),
979 (height + 1) * preedit_lines_);
981 if (preedit_string.empty()) {
989 // att : stores an IM attribute.
990 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
992 // get attributes of input method cursor.
993 // cursor_pos : cursor position in preedit string.
994 size_t cursor_pos = 0;
995 bool cursor_is_visible = false;
996 for (int i = 0; i != att.size(); ++i) {
997 if (att.at(i).type == QInputMethodEvent::Cursor) {
998 cursor_pos = att.at(i).start;
999 cursor_is_visible = att.at(i).length != 0;
1004 size_t preedit_length = preedit_string.length();
1006 // get position of selection in input method.
1007 // FIXME: isn't there a way to do this simplier?
1008 // rStart : cursor position in selected string in IM.
1010 // rLength : selected string length in IM.
1012 if (cursor_pos < preedit_length) {
1013 for (int i = 0; i != att.size(); ++i) {
1014 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1015 if (att.at(i).start <= int(cursor_pos)
1016 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1017 rStart = att.at(i).start;
1018 rLength = att.at(i).length;
1019 if (!cursor_is_visible)
1020 cursor_pos += rLength;
1027 rStart = cursor_pos;
1031 int const right_margin = buffer_view_->rightMargin();
1032 Painter::preedit_style ps;
1033 // Most often there would be only one line:
1035 for (size_t pos = 0; pos != preedit_length; ++pos) {
1036 char_type const typed_char = preedit_string[pos];
1037 // reset preedit string style
1038 ps = Painter::preedit_default;
1040 // if we reached the right extremity of the screen, go to next line.
1041 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1042 cur_x = right_margin;
1043 cur_y += height + 1;
1046 // preedit strings are displayed with dashed underline
1047 // and partial strings are displayed white on black indicating
1048 // that we are in selecting mode in the input method.
1049 // FIXME: rLength == preedit_length is not a changing condition
1050 // FIXME: should be put out of the loop.
1052 && pos < rStart + rLength
1053 && !(cursor_pos < rLength && rLength == preedit_length))
1054 ps = Painter::preedit_selecting;
1056 if (pos == cursor_pos
1057 && (cursor_pos < rLength && rLength == preedit_length))
1058 ps = Painter::preedit_cursor;
1060 // draw one character and update cur_x.
1061 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1064 // update the preedit string screen area.
1065 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1066 (height + 1) * preedit_lines_);
1068 // Don't forget to accept the event!
1073 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1075 QRect cur_r(0,0,0,0);
1077 // this is the CJK-specific composition window position.
1078 case Qt::ImMicroFocus:
1079 cur_r = cursor_->rect();
1080 if (preedit_lines_ != 1)
1082 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1083 // return lower right of cursor in LyX.
1086 return QWidget::inputMethodQuery(query);
1091 void GuiWorkArea::updateWindowTitle()
1093 docstring maximize_title;
1094 docstring minimize_title;
1096 Buffer & buf = buffer_view_->buffer();
1097 FileName const fileName = buf.fileName();
1098 if (!fileName.empty()) {
1099 maximize_title = fileName.displayName(30);
1100 minimize_title = from_utf8(fileName.onlyFileName());
1101 if (!buf.isClean()) {
1102 maximize_title += _(" (changed)");
1103 minimize_title += char_type('*');
1105 if (buf.isReadonly())
1106 maximize_title += _(" (read only)");
1109 QString title = windowTitle();
1110 QString new_title = toqstr(maximize_title);
1111 if (title == new_title)
1114 QWidget::setWindowTitle(new_title);
1115 QWidget::setWindowIconText(toqstr(minimize_title));
1120 void GuiWorkArea::setReadOnly(bool)
1122 updateWindowTitle();
1123 if (this == lyx_view_->currentWorkArea())
1124 lyx_view_->updateBufferDependent(false);
1128 bool GuiWorkArea::isFullScreen()
1130 return lyx_view_ && lyx_view_->isFullScreen();
1134 ////////////////////////////////////////////////////////////////////
1138 ////////////////////////////////////////////////////////////////////
1141 class NoTabFrameMacStyle : public QMacStyle {
1144 QRect subElementRect(SubElement element, const QStyleOption * option,
1145 const QWidget * widget = 0 ) const
1147 QRect rect = QMacStyle::subElementRect(element, option, widget);
1148 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1150 // The Qt Mac style puts the contents into a 3 pixel wide box
1151 // which looks very ugly and not like other Mac applications.
1152 // Hence we remove this here, and moreover the 16 pixel round
1153 // frame above if the tab bar is hidden.
1154 if (element == QStyle::SE_TabWidgetTabContents) {
1155 rect.adjust(- rect.left(), 0, rect.left(), 0);
1164 NoTabFrameMacStyle noTabFrameMacStyle;
1168 TabWorkArea::TabWorkArea(QWidget * parent)
1169 : QTabWidget(parent), clicked_tab_(-1)
1172 setStyle(&noTabFrameMacStyle);
1175 QPalette pal = palette();
1176 pal.setColor(QPalette::Active, QPalette::Button,
1177 pal.color(QPalette::Active, QPalette::Window));
1178 pal.setColor(QPalette::Disabled, QPalette::Button,
1179 pal.color(QPalette::Disabled, QPalette::Window));
1180 pal.setColor(QPalette::Inactive, QPalette::Button,
1181 pal.color(QPalette::Inactive, QPalette::Window));
1183 QObject::connect(this, SIGNAL(currentChanged(int)),
1184 this, SLOT(on_currentTabChanged(int)));
1186 QToolButton * closeBufferButton = new QToolButton(this);
1187 closeBufferButton->setPalette(pal);
1188 // FIXME: rename the icon to closebuffer.png
1189 closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1190 closeBufferButton->setText("Close File");
1191 closeBufferButton->setAutoRaise(true);
1192 closeBufferButton->setCursor(Qt::ArrowCursor);
1193 closeBufferButton->setToolTip(qt_("Close File"));
1194 closeBufferButton->setEnabled(true);
1195 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1196 this, SLOT(closeCurrentBuffer()));
1197 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1199 // setup drag'n'drop
1200 QTabBar* tb = new DragTabBar;
1201 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1202 this, SLOT(moveTab(int, int)));
1205 // make us responsible for the context menu of the tabbar
1206 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1207 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1208 this, SLOT(showContextMenu(const QPoint &)));
1210 setUsesScrollButtons(true);
1214 void TabWorkArea::setFullScreen(bool full_screen)
1216 for (int i = 0; i != count(); ++i) {
1217 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1218 wa->setFullScreen(full_screen);
1221 if (lyxrc.full_screen_tabbar)
1222 showBar(!full_screen && count()>1);
1226 void TabWorkArea::showBar(bool show)
1228 tabBar()->setEnabled(show);
1229 tabBar()->setVisible(show);
1233 GuiWorkArea * TabWorkArea::currentWorkArea()
1238 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1244 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1246 for (int i = 0; i != count(); ++i) {
1247 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1249 if (&wa->bufferView().buffer() == &buffer)
1256 void TabWorkArea::closeAll()
1259 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1267 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1269 BOOST_ASSERT(work_area);
1270 int index = indexOf(work_area);
1274 if (index == currentIndex())
1275 // Make sure the work area is up to date.
1276 on_currentTabChanged(index);
1278 // Switch to the work area.
1279 setCurrentIndex(index);
1280 work_area->setFocus();
1286 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1288 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1289 wa->setUpdatesEnabled(false);
1290 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1291 // when hiding it again below).
1292 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1293 showBar(count() > 0);
1294 addTab(wa, wa->windowTitle());
1295 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1296 this, SLOT(updateTabText(GuiWorkArea *)));
1297 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1298 setFullScreen(true);
1300 // Hide tabbar if there's only one tab.
1301 showBar(count() > 1);
1307 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1309 BOOST_ASSERT(work_area);
1310 int index = indexOf(work_area);
1314 work_area->setUpdatesEnabled(false);
1319 // make sure the next work area is enabled.
1320 currentWidget()->setUpdatesEnabled(true);
1321 if ((currentWorkArea() && currentWorkArea()->isFullScreen()))
1322 setFullScreen(true);
1324 // Hide tabbar if there's only one tab.
1325 showBar(count() > 1);
1327 lastWorkAreaRemoved();
1333 void TabWorkArea::on_currentTabChanged(int i)
1335 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1337 BufferView & bv = wa->bufferView();
1338 bv.cursor().fixIfBroken();
1340 wa->setUpdatesEnabled(true);
1344 currentWorkAreaChanged(wa);
1346 LYXERR(Debug::GUI, "currentTabChanged " << i
1347 << "File" << bv.buffer().absFileName());
1351 void TabWorkArea::closeCurrentBuffer()
1353 if (clicked_tab_ != -1)
1354 setCurrentIndex(clicked_tab_);
1356 lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1360 void TabWorkArea::closeCurrentTab()
1362 if (clicked_tab_ == -1)
1363 removeWorkArea(currentWorkArea());
1365 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1372 void TabWorkArea::updateTabText(GuiWorkArea * wa)
1374 int const i = indexOf(wa);
1377 setTabText(i, wa->windowTitle());
1381 void TabWorkArea::showContextMenu(const QPoint & pos)
1384 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1385 if (clicked_tab_ != -1) {
1388 popup.addAction(QIcon(":/images/hidetab.png"),
1389 qt_("Hide tab"), this, SLOT(closeCurrentTab()));
1390 popup.addAction(QIcon(":/images/closetab.png"),
1391 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1392 popup.exec(tabBar()->mapToGlobal(pos));
1399 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1401 QWidget * w = widget(fromIndex);
1402 QIcon icon = tabIcon(fromIndex);
1403 QString text = tabText(fromIndex);
1405 setCurrentIndex(fromIndex);
1406 removeTab(fromIndex);
1407 insertTab(toIndex, w, icon, text);
1408 setCurrentIndex(toIndex);
1412 DragTabBar::DragTabBar(QWidget* parent)
1415 setAcceptDrops(true);
1419 #if QT_VERSION < 0x040300
1420 int DragTabBar::tabAt(QPoint const & position) const
1422 const int max = count();
1423 for (int i = 0; i < max; ++i) {
1424 if (tabRect(i).contains(position))
1432 void DragTabBar::mousePressEvent(QMouseEvent * event)
1434 if (event->button() == Qt::LeftButton)
1435 dragStartPos_ = event->pos();
1436 QTabBar::mousePressEvent(event);
1440 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1442 // If the left button isn't pressed anymore then return
1443 if (!(event->buttons() & Qt::LeftButton))
1446 // If the distance is too small then return
1447 if ((event->pos() - dragStartPos_).manhattanLength()
1448 < QApplication::startDragDistance())
1451 // did we hit something after all?
1452 int tab = tabAt(dragStartPos_);
1456 // simulate button release to remove highlight from button
1457 int i = currentIndex();
1458 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1459 event->button(), event->buttons(), 0);
1460 QTabBar::mouseReleaseEvent(&me);
1464 QDrag * drag = new QDrag(this);
1465 QMimeData * mimeData = new QMimeData;
1466 // a crude way to distinguish tab-reodering drops from other ones
1467 mimeData->setData("action", "tab-reordering") ;
1468 drag->setMimeData(mimeData);
1470 #if QT_VERSION >= 0x040300
1471 // FIXME: gives garbage for tab != 0.
1472 // get tab pixmap as cursor
1473 QRect r = tabRect(tab);
1474 QPixmap pixmap(r.size());
1475 render(&pixmap, r.topLeft());
1476 drag->setPixmap(pixmap);
1483 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1485 // Only accept if it's an tab-reordering request
1486 QMimeData const * m = event->mimeData();
1487 QStringList formats = m->formats();
1488 if (formats.contains("action")
1489 && m->data("action") == "tab-reordering")
1490 event->acceptProposedAction();
1494 void DragTabBar::dropEvent(QDropEvent * event)
1496 int fromIndex = tabAt(dragStartPos_);
1497 int toIndex = tabAt(event->pos());
1499 // Tell interested objects that
1500 if (fromIndex != toIndex)
1501 tabMoveRequested(fromIndex, toIndex);
1502 event->acceptProposedAction();
1506 } // namespace frontend
1509 #include "GuiWorkArea_moc.cpp"