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>
60 #include <QToolButton>
63 #include <boost/bind.hpp>
67 extern "C" int XEventsQueued(Display *display, int mode);
71 int const CursorWidth = 2;
73 int const CursorWidth = 1;
75 int const TabIndicatorWidth = 3;
81 using namespace lyx::support;
86 /// return the LyX mouse button state from Qt's
87 static mouse_button::state q_button_state(Qt::MouseButton button)
89 mouse_button::state b = mouse_button::none;
92 b = mouse_button::button1;
95 b = mouse_button::button2;
98 b = mouse_button::button3;
107 /// return the LyX mouse button state from Qt's
108 mouse_button::state q_motion_state(Qt::MouseButtons state)
110 mouse_button::state b = mouse_button::none;
111 if (state & Qt::LeftButton)
112 b |= mouse_button::button1;
113 if (state & Qt::MidButton)
114 b |= mouse_button::button2;
115 if (state & Qt::RightButton)
116 b |= mouse_button::button3;
127 void draw(QPainter & painter)
129 if (!show_ || !rect_.isValid())
133 int l = x_ - rect_.left();
134 int r = rect_.right() - x_;
135 int bot = rect_.bottom();
137 // draw vertica linel
138 painter.fillRect(x_, y, CursorWidth, rect_.height(), color_);
140 // draw RTL/LTR indication
141 painter.setPen(color_);
144 painter.drawLine(x_, bot, x_ - l, bot);
146 painter.drawLine(x_, bot, x_ + CursorWidth + r, bot);
149 // draw completion triangle
151 int m = y + rect_.height() / 2;
152 int d = TabIndicatorWidth - 1;
154 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
155 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
157 painter.drawLine(x_ + CursorWidth, m - d, x_ + CursorWidth + d, m);
158 painter.drawLine(x_ + CursorWidth, m + d, x_ + CursorWidth + d, m);
163 void update(int x, int y, int h, bool l_shape,
164 bool rtl, bool completable)
166 color_ = guiApp->colorCache().get(Color_cursor);
169 completable_ = completable;
172 // extension to left and right
176 // RTL/LTR indication
184 // completion triangle
187 l = max(l, TabIndicatorWidth);
189 r = max(r, TabIndicatorWidth);
192 // compute overall rectangle
193 rect_ = QRect(x - l, y, CursorWidth + r + l, h);
196 void show(bool set_show = true) { show_ = set_show; }
197 void hide() { show_ = false; }
199 QRect const & rect() { return rect_; }
202 /// cursor is in RTL or LTR text
204 /// indication for RTL or LTR
206 /// triangle to show that a completion is available
212 /// rectangle, possibly with l_shape and completion triangle
214 /// x position (were the vertical line is drawn)
219 // This is a 'heartbeat' generating synthetic mouse move events when the
220 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
221 SyntheticMouseEvent::SyntheticMouseEvent()
222 : timeout(200), restart_timeout(true),
223 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
228 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & lv)
229 : buffer_view_(new BufferView(buffer)), lyx_view_(&lv),
230 cursor_visible_(false),
231 need_resize_(false), schedule_redraw_(false),
232 preedit_lines_(1), completer_(this)
234 buffer.workAreaManager().add(this);
236 connect(&cursor_timeout_, SIGNAL(timeout()),
237 this, SLOT(toggleCursor()));
239 int const time = QApplication::cursorFlashTime() / 2;
241 cursor_timeout_.setInterval(time);
242 cursor_timeout_.start();
244 // let's initialize this just to be safe
245 cursor_timeout_.setInterval(500);
247 screen_ = QPixmap(viewport()->width(), viewport()->height());
248 cursor_ = new frontend::CursorWidget();
251 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
252 setAcceptDrops(true);
253 setMouseTracking(true);
254 setMinimumSize(100, 70);
256 setFrameStyle(QFrame::NoFrame);
258 setFrameStyle(QFrame::Box);
262 viewport()->setAutoFillBackground(false);
263 // We don't need double-buffering nor SystemBackground on
264 // the viewport because we have our own backing pixmap.
265 viewport()->setAttribute(Qt::WA_NoSystemBackground);
267 setFocusPolicy(Qt::WheelFocus);
269 viewport()->setCursor(Qt::IBeamCursor);
271 synthetic_mouse_event_.timeout.timeout.connect(
272 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
275 // Initialize the vertical Scroll Bar
276 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
277 this, SLOT(scrollTo(int)));
279 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
280 << " viewport height: " << viewport()->height());
282 // Enables input methods for asian languages.
283 // Must be set when creating custom text editing widgets.
284 setAttribute(Qt::WA_InputMethodEnabled, true);
288 GuiWorkArea::~GuiWorkArea()
290 buffer_view_->buffer().workAreaManager().remove(this);
296 void GuiWorkArea::close()
298 lyx_view_->removeWorkArea(this);
302 void GuiWorkArea::setFullScreen(bool full_screen)
304 buffer_view_->setFullScreen(full_screen);
306 setFrameStyle(QFrame::NoFrame);
307 if (lyxrc.full_screen_scrollbar)
308 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
311 setFrameStyle(QFrame::NoFrame);
313 setFrameStyle(QFrame::Box);
315 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
320 BufferView & GuiWorkArea::bufferView()
322 return *buffer_view_;
326 BufferView const & GuiWorkArea::bufferView() const
328 return *buffer_view_;
332 void GuiWorkArea::stopBlinkingCursor()
334 cursor_timeout_.stop();
339 void GuiWorkArea::startBlinkingCursor()
342 //we're not supposed to cache this value.
343 int const time = QApplication::cursorFlashTime() / 2;
346 cursor_timeout_.setInterval(time);
347 cursor_timeout_.start();
351 void GuiWorkArea::redraw()
354 // No need to redraw in this case.
357 // No need to do anything if this is the current view. The BufferView
358 // metrics are already up to date.
359 if (lyx_view_ != guiApp->currentView()
360 || lyx_view_->currentWorkArea() != this) {
361 // FIXME: it would be nice to optimize for the off-screen case.
362 buffer_view_->updateMetrics();
363 buffer_view_->cursor().fixIfBroken();
366 // update cursor position, because otherwise it has to wait until
367 // the blinking interval is over
368 if (cursor_visible_) {
373 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
375 update(0, 0, viewport()->width(), viewport()->height());
377 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
378 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
380 lyx_view_->updateStatusBar();
382 if (lyxerr.debugging(Debug::WORKAREA))
383 buffer_view_->coordCache().dump();
387 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
389 // In order to avoid bad surprise in the middle of an operation,
390 // we better stop the blinking cursor...
391 // the cursor gets restarted in GuiView::restartCursor()
392 stopBlinkingCursor();
394 theLyXFunc().setLyXView(lyx_view_);
395 theLyXFunc().processKeySym(key, mod);
400 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
403 if (cmd0.action == LFUN_FILE_OPEN) {
404 lyx_view_->dispatch(cmd0);
408 theLyXFunc().setLyXView(lyx_view_);
412 if (cmd0.action == LFUN_MOUSE_PRESS) {
413 if (mod == ShiftModifier)
414 cmd = FuncRequest(cmd0, "region-select");
415 else if (mod == ControlModifier)
416 cmd = FuncRequest(cmd0, "paragraph-select");
423 bool const notJustMovingTheMouse =
424 cmd.action != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
426 // In order to avoid bad surprise in the middle of an operation, we better stop
427 // the blinking cursor.
428 if (notJustMovingTheMouse)
429 stopBlinkingCursor();
431 buffer_view_->mouseEventDispatch(cmd);
433 // Skip these when selecting
434 if (cmd.action != LFUN_MOUSE_MOTION) {
435 completer_.updateVisibility(false, false);
436 lyx_view_->updateLayoutList();
437 lyx_view_->updateToolbars();
440 // GUI tweaks except with mouse motion with no button pressed.
441 if (notJustMovingTheMouse) {
442 // Slight hack: this is only called currently when we
443 // clicked somewhere, so we force through the display
444 // of the new status here.
445 lyx_view_->clearMessage();
447 // Show the cursor immediately after any operation
448 startBlinkingCursor();
453 void GuiWorkArea::resizeBufferView()
455 // WARNING: Please don't put any code that will trigger a repaint here!
456 // We are already inside a paint event.
457 lyx_view_->setBusy(true);
458 buffer_view_->resize(viewport()->width(), viewport()->height());
461 // Update scrollbars which might have changed due different
462 // BufferView dimension. This is especially important when the
463 // BufferView goes from zero-size to the real-size for the first time,
464 // as the scrollbar paramters are then set for the first time.
467 lyx_view_->updateLayoutList();
468 lyx_view_->setBusy(false);
469 need_resize_ = false;
473 void GuiWorkArea::showCursor()
479 bool l_shape = false;
480 Font const & realfont = buffer_view_->cursor().real_current_font;
481 BufferParams const & bp = buffer_view_->buffer().params();
482 bool const samelang = realfont.language() == bp.language;
483 bool const isrtl = realfont.isVisibleRightToLeft();
485 if (!samelang || isrtl != bp.language->rightToLeft())
488 // The ERT language hack needs fixing up
489 if (realfont.language() == latex_language)
492 Font const font = buffer_view_->cursor().getFont();
493 FontMetrics const & fm = theFontMetrics(font);
494 int const asc = fm.maxAscent();
495 int const des = fm.maxDescent();
499 Cursor & cur = buffer_view_->cursor();
503 // if it doesn't touch the screen, don't try to show it
504 bool cursorInView = true;
505 if (y + h < 0 || y >= viewport()->height())
506 cursorInView = false;
508 // show cursor on screen
509 bool completable = completer_.completionAvailable()
510 && !completer_.popupVisible()
511 && !completer_.inlineVisible();
513 cursor_visible_ = true;
514 showCursor(x, y, h, l_shape, isrtl, completable);
519 void GuiWorkArea::hideCursor()
521 if (!cursor_visible_)
524 cursor_visible_ = false;
529 void GuiWorkArea::toggleCursor()
538 void GuiWorkArea::updateScrollbar()
540 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
542 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
543 verticalScrollBar()->setPageStep(scroll_.page_step);
544 verticalScrollBar()->setSingleStep(scroll_.single_step);
545 // Block the scrollbar signal to prevent recursive signal/slot calling.
546 verticalScrollBar()->blockSignals(true);
547 verticalScrollBar()->setValue(scroll_.position);
548 verticalScrollBar()->setSliderPosition(scroll_.position);
549 verticalScrollBar()->blockSignals(false);
553 void GuiWorkArea::scrollTo(int value)
555 stopBlinkingCursor();
556 buffer_view_->scrollDocView(value);
558 if (lyxrc.cursor_follows_scrollbar) {
559 buffer_view_->setCursorFromScrollbar();
560 lyx_view_->updateLayoutList();
562 // Show the cursor immediately after any operation.
563 startBlinkingCursor();
564 QApplication::syncX();
568 bool GuiWorkArea::event(QEvent * e)
571 case QEvent::ToolTip: {
572 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
573 if (lyxrc.use_tooltip) {
574 QPoint pos = helpEvent->pos();
575 if (pos.x() < viewport()->width()) {
576 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
577 QToolTip::showText(helpEvent->globalPos(), s);
580 QToolTip::hideText();
582 // Don't forget to accept the event!
587 case QEvent::ShortcutOverride: {
588 // We catch this event in order to catch the Tab or Shift+Tab key press
589 // which are otherwise reserved to focus switching between controls
591 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
592 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
593 || ke->modifiers() & Qt::ControlModifier)
594 return QAbstractScrollArea::event(e);
600 return QAbstractScrollArea::event(e);
606 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
608 QPoint pos = e->pos();
609 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
611 QAbstractScrollArea::contextMenuEvent(e);
614 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
616 QAbstractScrollArea::contextMenuEvent(e);
619 // Position the menu to the right.
620 // FIXME: menu position should be different for RTL text.
621 menu->exec(e->globalPos());
626 void GuiWorkArea::focusInEvent(QFocusEvent * e)
628 if (lyx_view_->currentWorkArea() != this)
629 lyx_view_->setCurrentWorkArea(this);
631 // Repaint the whole screen.
632 // Note: this is different from redraw() as only the backing pixmap
633 // will be redrawn, which is cheap.
634 viewport()->repaint();
636 startBlinkingCursor();
637 QAbstractScrollArea::focusInEvent(e);
641 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
643 stopBlinkingCursor();
644 QAbstractScrollArea::focusOutEvent(e);
648 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
650 if (dc_event_.active && dc_event_ == *e) {
651 dc_event_.active = false;
652 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
653 q_button_state(e->button()));
659 inputContext()->reset();
661 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
662 q_button_state(e->button()));
663 dispatch(cmd, q_key_state(e->modifiers()));
668 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
670 if (synthetic_mouse_event_.timeout.running())
671 synthetic_mouse_event_.timeout.stop();
673 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
674 q_button_state(e->button()));
680 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
682 // we kill the triple click if we move
683 doubleClickTimeout();
684 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
685 q_motion_state(e->buttons()));
689 // If we're above or below the work area...
690 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
691 // Make sure only a synthetic event can cause a page scroll,
692 // so they come at a steady rate:
694 // _Force_ a scroll up:
697 cmd.y = viewport()->height();
698 // Store the event, to be handled when the timeout expires.
699 synthetic_mouse_event_.cmd = cmd;
701 if (synthetic_mouse_event_.timeout.running())
702 // Discard the event. Note that it _may_ be handled
703 // when the timeout expires if
704 // synthetic_mouse_event_.cmd has not been overwritten.
705 // Ie, when the timeout expires, we handle the
706 // most recent event but discard all others that
707 // occurred after the one used to start the timeout
708 // in the first place.
711 synthetic_mouse_event_.restart_timeout = true;
712 synthetic_mouse_event_.timeout.start();
713 // Fall through to handle this event...
715 } else if (synthetic_mouse_event_.timeout.running()) {
716 // Store the event, to be possibly handled when the timeout
718 // Once the timeout has expired, normal control is returned
719 // to mouseMoveEvent (restart_timeout = false).
720 // This results in a much smoother 'feel' when moving the
721 // mouse back into the work area.
722 synthetic_mouse_event_.cmd = cmd;
723 synthetic_mouse_event_.restart_timeout = false;
727 // Has anything changed on-screen since the last QMouseEvent
729 double const scrollbar_value = verticalScrollBar()->value();
730 if (e->x() == synthetic_mouse_event_.x_old
731 && e->y() == synthetic_mouse_event_.y_old
732 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
733 // Nothing changed on-screen since the last QMouseEvent.
737 // Yes something has changed. Store the params used to check this.
738 synthetic_mouse_event_.x_old = e->x();
739 synthetic_mouse_event_.y_old = e->y();
740 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
742 // ... and dispatch the event to the LyX core.
747 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
749 // Wheel rotation by one notch results in a delta() of 120 (see
750 // documentation of QWheelEvent)
751 int delta = ev->delta() / 120;
752 if (ev->modifiers() & Qt::ControlModifier) {
753 lyxrc.zoom -= 5 * delta;
756 // The global QPixmapCache is used in GuiPainter to cache text
757 // painting so we must reset it.
758 QPixmapCache::clear();
759 guiApp->fontLoader().update();
760 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
762 double const lines = qApp->wheelScrollLines()
763 * lyxrc.mouse_wheel_speed * delta;
764 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << qApp->wheelScrollLines()
765 << " delta = " << ev->delta() << " lines = " << lines);
766 verticalScrollBar()->setValue(verticalScrollBar()->value() -
767 int(lines * verticalScrollBar()->singleStep()));
773 void GuiWorkArea::generateSyntheticMouseEvent()
775 // Set things off to generate the _next_ 'pseudo' event.
776 if (synthetic_mouse_event_.restart_timeout)
777 synthetic_mouse_event_.timeout.start();
779 // Has anything changed on-screen since the last timeout signal
781 double const scrollbar_value = verticalScrollBar()->value();
782 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
783 // Yes it has. Store the params used to check this.
784 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
786 // ... and dispatch the event to the LyX core.
787 dispatch(synthetic_mouse_event_.cmd);
792 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
794 // intercept some keys if completion popup is visible
795 if (completer_.popupVisible()) {
799 completer_.activate();
805 // intercept keys for the completion
806 if (ev->key() == Qt::Key_Tab) {
812 if (completer_.popupVisible() && ev->key() == Qt::Key_Escape) {
813 completer_.hidePopup();
818 if (completer_.inlineVisible() && ev->key() == Qt::Key_Escape) {
819 completer_.hideInline();
824 // do nothing if there are other events
825 // (the auto repeated events come too fast)
826 // \todo FIXME: remove hard coded Qt keys, process the key binding
828 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
829 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
830 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
836 LYXERR(Debug::KEY, " count: " << ev->count()
837 << " text: " << fromqstr(ev->text())
838 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
841 setKeySymbol(&sym, ev);
842 processKeySym(sym, q_key_state(ev->modifiers()));
847 void GuiWorkArea::doubleClickTimeout()
849 dc_event_.active = false;
853 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
855 dc_event_ = DoubleClick(ev);
856 QTimer::singleShot(QApplication::doubleClickInterval(), this,
857 SLOT(doubleClickTimeout()));
858 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
860 q_button_state(ev->button()));
866 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
868 QAbstractScrollArea::resizeEvent(ev);
874 void GuiWorkArea::update(int x, int y, int w, int h)
876 viewport()->repaint(x, y, w, h);
880 void GuiWorkArea::paintEvent(QPaintEvent * ev)
882 QRect const rc = ev->rect();
883 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
884 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
887 screen_ = QPixmap(viewport()->width(), viewport()->height());
893 QPainter pain(viewport());
894 pain.drawPixmap(rc, screen_, rc);
900 void GuiWorkArea::updateScreen()
902 GuiPainter pain(&screen_);
903 buffer_view_->draw(pain);
907 void GuiWorkArea::showCursor(int x, int y, int h,
908 bool l_shape, bool rtl, bool completable)
910 if (schedule_redraw_) {
911 buffer_view_->updateMetrics();
913 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
914 schedule_redraw_ = false;
915 // Show the cursor immediately after the update.
921 cursor_->update(x, y, h, l_shape, rtl, completable);
923 viewport()->update(cursor_->rect());
927 void GuiWorkArea::removeCursor()
930 //if (!qApp->focusWidget())
931 viewport()->update(cursor_->rect());
935 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
937 QString const & commit_string = e->commitString();
938 docstring const & preedit_string
939 = qstring_to_ucs4(e->preeditString());
941 if (!commit_string.isEmpty()) {
943 LYXERR(Debug::KEY, "preeditString: " << fromqstr(e->preeditString())
944 << " commitString: " << fromqstr(e->commitString()));
948 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
949 for (int i = 0; i != commit_string.size(); ++i) {
950 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
955 // Hide the cursor during the kana-kanji transformation.
956 if (preedit_string.empty())
957 startBlinkingCursor();
959 stopBlinkingCursor();
961 // last_width : for checking if last preedit string was/wasn't empty.
962 static bool last_width = false;
963 if (!last_width && preedit_string.empty()) {
964 // if last_width is last length of preedit string.
969 GuiPainter pain(&screen_);
970 buffer_view_->updateMetrics();
971 buffer_view_->draw(pain);
972 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
973 FontMetrics const & fm = theFontMetrics(font);
974 int height = fm.maxHeight();
975 int cur_x = cursor_->rect().left();
976 int cur_y = cursor_->rect().bottom();
978 // redraw area of preedit string.
979 update(0, cur_y - height, viewport()->width(),
980 (height + 1) * preedit_lines_);
982 if (preedit_string.empty()) {
990 // att : stores an IM attribute.
991 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
993 // get attributes of input method cursor.
994 // cursor_pos : cursor position in preedit string.
995 size_t cursor_pos = 0;
996 bool cursor_is_visible = false;
997 for (int i = 0; i != att.size(); ++i) {
998 if (att.at(i).type == QInputMethodEvent::Cursor) {
999 cursor_pos = att.at(i).start;
1000 cursor_is_visible = att.at(i).length != 0;
1005 size_t preedit_length = preedit_string.length();
1007 // get position of selection in input method.
1008 // FIXME: isn't there a way to do this simplier?
1009 // rStart : cursor position in selected string in IM.
1011 // rLength : selected string length in IM.
1013 if (cursor_pos < preedit_length) {
1014 for (int i = 0; i != att.size(); ++i) {
1015 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1016 if (att.at(i).start <= int(cursor_pos)
1017 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1018 rStart = att.at(i).start;
1019 rLength = att.at(i).length;
1020 if (!cursor_is_visible)
1021 cursor_pos += rLength;
1028 rStart = cursor_pos;
1032 int const right_margin = buffer_view_->rightMargin();
1033 Painter::preedit_style ps;
1034 // Most often there would be only one line:
1036 for (size_t pos = 0; pos != preedit_length; ++pos) {
1037 char_type const typed_char = preedit_string[pos];
1038 // reset preedit string style
1039 ps = Painter::preedit_default;
1041 // if we reached the right extremity of the screen, go to next line.
1042 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1043 cur_x = right_margin;
1044 cur_y += height + 1;
1047 // preedit strings are displayed with dashed underline
1048 // and partial strings are displayed white on black indicating
1049 // that we are in selecting mode in the input method.
1050 // FIXME: rLength == preedit_length is not a changing condition
1051 // FIXME: should be put out of the loop.
1053 && pos < rStart + rLength
1054 && !(cursor_pos < rLength && rLength == preedit_length))
1055 ps = Painter::preedit_selecting;
1057 if (pos == cursor_pos
1058 && (cursor_pos < rLength && rLength == preedit_length))
1059 ps = Painter::preedit_cursor;
1061 // draw one character and update cur_x.
1062 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1065 // update the preedit string screen area.
1066 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1067 (height + 1) * preedit_lines_);
1069 // Don't forget to accept the event!
1074 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1076 QRect cur_r(0,0,0,0);
1078 // this is the CJK-specific composition window position.
1079 case Qt::ImMicroFocus:
1080 cur_r = cursor_->rect();
1081 if (preedit_lines_ != 1)
1083 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1084 // return lower right of cursor in LyX.
1087 return QWidget::inputMethodQuery(query);
1092 void GuiWorkArea::updateWindowTitle()
1094 docstring maximize_title;
1095 docstring minimize_title;
1097 Buffer & buf = buffer_view_->buffer();
1098 FileName const fileName = buf.fileName();
1099 if (!fileName.empty()) {
1100 maximize_title = fileName.displayName(30);
1101 minimize_title = from_utf8(fileName.onlyFileName());
1102 if (!buf.isClean()) {
1103 maximize_title += _(" (changed)");
1104 minimize_title += char_type('*');
1106 if (buf.isReadonly())
1107 maximize_title += _(" (read only)");
1110 QString title = windowTitle();
1111 QString new_title = toqstr(maximize_title);
1112 if (title == new_title)
1115 QWidget::setWindowTitle(new_title);
1116 QWidget::setWindowIconText(toqstr(minimize_title));
1121 void GuiWorkArea::setReadOnly(bool)
1123 updateWindowTitle();
1124 if (this == lyx_view_->currentWorkArea())
1125 lyx_view_->updateBufferDependent(false);
1129 bool GuiWorkArea::isFullScreen()
1131 return lyx_view_ && lyx_view_->isFullScreen();
1135 ////////////////////////////////////////////////////////////////////
1139 ////////////////////////////////////////////////////////////////////
1142 class NoTabFrameMacStyle : public QMacStyle {
1145 QRect subElementRect(SubElement element, const QStyleOption * option,
1146 const QWidget * widget = 0 ) const
1148 QRect rect = QMacStyle::subElementRect(element, option, widget);
1149 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1151 // The Qt Mac style puts the contents into a 3 pixel wide box
1152 // which looks very ugly and not like other Mac applications.
1153 // Hence we remove this here, and moreover the 16 pixel round
1154 // frame above if the tab bar is hidden.
1155 if (element == QStyle::SE_TabWidgetTabContents) {
1156 rect.adjust(- rect.left(), 0, rect.left(), 0);
1165 NoTabFrameMacStyle noTabFramemacStyle;
1169 TabWorkArea::TabWorkArea(QWidget * parent) : QTabWidget(parent)
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 QToolButton * closeTabButton = new QToolButton(this);
1200 closeTabButton->setPalette(pal);
1201 closeTabButton->setIcon(QIcon(":/images/hidetab.png"));
1202 closeTabButton->setText("Hide tab");
1203 closeTabButton->setAutoRaise(true);
1204 closeTabButton->setCursor(Qt::ArrowCursor);
1205 closeTabButton->setToolTip(qt_("Hide tab"));
1206 closeTabButton->setEnabled(true);
1207 QObject::connect(closeTabButton, SIGNAL(clicked()),
1208 this, SLOT(closeCurrentTab()));
1209 setCornerWidget(closeTabButton, Qt::TopLeftCorner);
1211 setUsesScrollButtons(true);
1215 void TabWorkArea::setFullScreen(bool full_screen)
1217 for (int i = 0; i != count(); ++i) {
1218 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1219 wa->setFullScreen(full_screen);
1222 if (lyxrc.full_screen_tabbar)
1223 showBar(!full_screen && count()>1);
1227 void TabWorkArea::showBar(bool show)
1229 tabBar()->setEnabled(show);
1230 tabBar()->setVisible(show);
1234 GuiWorkArea * TabWorkArea::currentWorkArea()
1239 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1245 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1247 for (int i = 0; i != count(); ++i) {
1248 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1250 if (&wa->bufferView().buffer() == &buffer)
1257 void TabWorkArea::closeAll()
1260 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1268 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1270 BOOST_ASSERT(work_area);
1271 int index = indexOf(work_area);
1275 if (index == currentIndex())
1276 // Make sure the work area is up to date.
1277 on_currentTabChanged(index);
1279 // Switch to the work area.
1280 setCurrentIndex(index);
1281 work_area->setFocus();
1287 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1289 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1290 wa->setUpdatesEnabled(false);
1291 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1292 // when hiding it again below).
1293 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1294 showBar(count() > 0);
1295 addTab(wa, wa->windowTitle());
1296 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1297 this, SLOT(updateTabText(GuiWorkArea *)));
1298 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1299 setFullScreen(true);
1301 // Hide tabbar if there's only one tab.
1302 showBar(count() > 1);
1308 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1310 BOOST_ASSERT(work_area);
1311 int index = indexOf(work_area);
1315 work_area->setUpdatesEnabled(false);
1320 // make sure the next work area is enabled.
1321 currentWidget()->setUpdatesEnabled(true);
1322 if ((currentWorkArea() && currentWorkArea()->isFullScreen()))
1323 setFullScreen(true);
1325 // Hide tabbar if there's only one tab.
1326 showBar(count() > 1);
1332 void TabWorkArea::on_currentTabChanged(int i)
1334 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1336 BufferView & bv = wa->bufferView();
1337 bv.cursor().fixIfBroken();
1339 wa->setUpdatesEnabled(true);
1343 currentWorkAreaChanged(wa);
1345 LYXERR(Debug::GUI, "currentTabChanged " << i
1346 << "File" << bv.buffer().absFileName());
1350 void TabWorkArea::closeCurrentBuffer()
1352 lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1356 void TabWorkArea::closeCurrentTab()
1358 removeWorkArea(currentWorkArea());
1362 void TabWorkArea::updateTabText(GuiWorkArea * wa)
1364 int const i = indexOf(wa);
1367 setTabText(i, wa->windowTitle());
1370 } // namespace frontend
1373 #include "GuiWorkArea_moc.cpp"