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"
26 #include "GuiPopupMenu.h"
28 #include "KeySymbol.h"
32 #include "MetricsInfo.h"
33 #include "qt_helpers.h"
36 #include "graphics/GraphicsImage.h"
37 #include "graphics/GraphicsLoader.h"
39 #include "support/debug.h"
40 #include "support/gettext.h"
41 #include "support/FileName.h"
43 #include "frontends/Application.h"
44 #include "frontends/FontMetrics.h"
45 #include "frontends/WorkAreaManager.h"
47 #include <QContextMenuEvent>
48 #include <QInputContext>
50 #include <QMainWindow>
56 #include <QToolButton>
59 #include <boost/bind.hpp>
63 extern "C" int XEventsQueued(Display *display, int mode);
67 int const CursorWidth = 2;
69 int const CursorWidth = 1;
71 int const TabIndicatorWidth = 3;
77 using namespace lyx::support;
82 /// return the LyX mouse button state from Qt's
83 static mouse_button::state q_button_state(Qt::MouseButton button)
85 mouse_button::state b = mouse_button::none;
88 b = mouse_button::button1;
91 b = mouse_button::button2;
94 b = mouse_button::button3;
103 /// return the LyX mouse button state from Qt's
104 mouse_button::state q_motion_state(Qt::MouseButtons state)
106 mouse_button::state b = mouse_button::none;
107 if (state & Qt::LeftButton)
108 b |= mouse_button::button1;
109 if (state & Qt::MidButton)
110 b |= mouse_button::button2;
111 if (state & Qt::RightButton)
112 b |= mouse_button::button3;
123 void draw(QPainter & painter)
125 if (!show_ || !rect_.isValid())
129 int l = x_ - rect_.left();
130 int r = rect_.right() - x_;
131 int bot = rect_.bottom();
133 // draw vertica linel
134 painter.fillRect(x_, y, CursorWidth, rect_.height(), color_);
136 // draw RTL/LTR indication
137 painter.setPen(color_);
140 painter.drawLine(x_, bot, x_ - l, bot);
142 painter.drawLine(x_, bot, x_ + CursorWidth + r, bot);
145 // draw completion triangle
147 int m = y + rect_.height() / 2;
148 int d = TabIndicatorWidth - 1;
150 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
151 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
153 painter.drawLine(x_ + CursorWidth, m - d, x_ + CursorWidth + d, m);
154 painter.drawLine(x_ + CursorWidth, m + d, x_ + CursorWidth + d, m);
159 void update(int x, int y, int h, bool l_shape,
160 bool rtl, bool completable)
162 color_ = guiApp->colorCache().get(Color_cursor);
165 completable_ = completable;
168 // extension to left and right
172 // RTL/LTR indication
180 // completion triangle
183 l = max(l, TabIndicatorWidth);
185 r = max(r, TabIndicatorWidth);
188 // compute overall rectangle
189 rect_ = QRect(x - l, y, CursorWidth + r + l, h);
192 void show(bool set_show = true) { show_ = set_show; }
193 void hide() { show_ = false; }
195 QRect const & rect() { return rect_; }
198 /// cursor is in RTL or LTR text
200 /// indication for RTL or LTR
202 /// triangle to show that a completion is available
208 /// rectangle, possibly with l_shape and completion triangle
210 /// x position (were the vertical line is drawn)
215 // This is a 'heartbeat' generating synthetic mouse move events when the
216 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
217 SyntheticMouseEvent::SyntheticMouseEvent()
218 : timeout(200), restart_timeout(true),
219 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
224 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & lv)
225 : buffer_view_(new BufferView(buffer)), lyx_view_(&lv),
226 cursor_visible_(false),
227 need_resize_(false), schedule_redraw_(false),
228 preedit_lines_(1), completer_(this)
230 buffer.workAreaManager().add(this);
232 connect(&cursor_timeout_, SIGNAL(timeout()),
233 this, SLOT(toggleCursor()));
235 int const time = QApplication::cursorFlashTime() / 2;
237 cursor_timeout_.setInterval(time);
238 cursor_timeout_.start();
240 // let's initialize this just to be safe
241 cursor_timeout_.setInterval(500);
243 screen_ = QPixmap(viewport()->width(), viewport()->height());
244 cursor_ = new frontend::CursorWidget();
247 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
248 setAcceptDrops(true);
249 setMouseTracking(true);
250 setMinimumSize(100, 70);
253 viewport()->setAutoFillBackground(false);
254 // We don't need double-buffering nor SystemBackground on
255 // the viewport because we have our own backing pixmap.
256 viewport()->setAttribute(Qt::WA_NoSystemBackground);
258 setFocusPolicy(Qt::WheelFocus);
260 viewport()->setCursor(Qt::IBeamCursor);
262 synthetic_mouse_event_.timeout.timeout.connect(
263 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
266 // Initialize the vertical Scroll Bar
267 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
268 this, SLOT(scrollTo(int)));
270 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
271 << " viewport height: " << viewport()->height());
273 // Enables input methods for asian languages.
274 // Must be set when creating custom text editing widgets.
275 setAttribute(Qt::WA_InputMethodEnabled, true);
279 GuiWorkArea::~GuiWorkArea()
281 buffer_view_->buffer().workAreaManager().remove(this);
287 void GuiWorkArea::close()
289 lyx_view_->removeWorkArea(this);
293 void GuiWorkArea::setFullScreen(bool full_screen)
295 buffer_view_->setFullScreen(full_screen);
297 setFrameStyle(QFrame::NoFrame);
298 if (lyxrc.full_screen_scrollbar)
299 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
301 setFrameStyle(QFrame::Box);
302 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
307 BufferView & GuiWorkArea::bufferView()
309 return *buffer_view_;
313 BufferView const & GuiWorkArea::bufferView() const
315 return *buffer_view_;
319 void GuiWorkArea::stopBlinkingCursor()
321 cursor_timeout_.stop();
326 void GuiWorkArea::startBlinkingCursor()
329 //we're not supposed to cache this value.
330 int const time = QApplication::cursorFlashTime() / 2;
333 cursor_timeout_.setInterval(time);
334 cursor_timeout_.start();
338 void GuiWorkArea::redraw()
341 // No need to redraw in this case.
344 // No need to do anything if this is the current view. The BufferView
345 // metrics are already up to date.
346 if (lyx_view_ != guiApp->currentView()
347 || lyx_view_->currentWorkArea() != this) {
348 // FIXME: it would be nice to optimize for the off-screen case.
349 buffer_view_->updateMetrics();
350 buffer_view_->cursor().fixIfBroken();
353 // update cursor position, because otherwise it has to wait until
354 // the blinking interval is over
355 if (cursor_visible_) {
360 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
362 update(0, 0, viewport()->width(), viewport()->height());
364 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
365 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
367 lyx_view_->updateStatusBar();
369 if (lyxerr.debugging(Debug::WORKAREA))
370 buffer_view_->coordCache().dump();
374 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
376 // In order to avoid bad surprise in the middle of an operation,
377 // we better stop the blinking cursor...
378 // the cursor gets restarted in GuiView::restartCursor()
379 stopBlinkingCursor();
381 theLyXFunc().setLyXView(lyx_view_);
382 theLyXFunc().processKeySym(key, mod);
387 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
390 if (cmd0.action == LFUN_FILE_OPEN) {
391 lyx_view_->dispatch(cmd0);
395 theLyXFunc().setLyXView(lyx_view_);
399 if (cmd0.action == LFUN_MOUSE_PRESS) {
400 if (mod == ShiftModifier)
401 cmd = FuncRequest(cmd0, "region-select");
402 else if (mod == ControlModifier)
403 cmd = FuncRequest(cmd0, "paragraph-select");
410 bool const notJustMovingTheMouse =
411 cmd.action != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
413 // In order to avoid bad surprise in the middle of an operation, we better stop
414 // the blinking cursor.
415 if (notJustMovingTheMouse)
416 stopBlinkingCursor();
418 buffer_view_->mouseEventDispatch(cmd);
420 // Skip these when selecting
421 if (cmd.action != LFUN_MOUSE_MOTION) {
422 completer_.updateVisibility(false, false);
423 lyx_view_->updateLayoutList();
424 lyx_view_->updateToolbars();
427 // GUI tweaks except with mouse motion with no button pressed.
428 if (notJustMovingTheMouse) {
429 // Slight hack: this is only called currently when we
430 // clicked somewhere, so we force through the display
431 // of the new status here.
432 lyx_view_->clearMessage();
434 // Show the cursor immediately after any operation
435 startBlinkingCursor();
440 void GuiWorkArea::resizeBufferView()
442 // WARNING: Please don't put any code that will trigger a repaint here!
443 // We are already inside a paint event.
444 lyx_view_->setBusy(true);
445 buffer_view_->resize(viewport()->width(), viewport()->height());
448 // Update scrollbars which might have changed due different
449 // BufferView dimension. This is especially important when the
450 // BufferView goes from zero-size to the real-size for the first time,
451 // as the scrollbar paramters are then set for the first time.
454 lyx_view_->updateLayoutList();
455 lyx_view_->setBusy(false);
456 need_resize_ = false;
460 void GuiWorkArea::showCursor()
466 bool l_shape = false;
467 Font const & realfont = buffer_view_->cursor().real_current_font;
468 BufferParams const & bp = buffer_view_->buffer().params();
469 bool const samelang = realfont.language() == bp.language;
470 bool const isrtl = realfont.isVisibleRightToLeft();
472 if (!samelang || isrtl != bp.language->rightToLeft())
475 // The ERT language hack needs fixing up
476 if (realfont.language() == latex_language)
479 Font const font = buffer_view_->cursor().getFont();
480 FontMetrics const & fm = theFontMetrics(font);
481 int const asc = fm.maxAscent();
482 int const des = fm.maxDescent();
486 Cursor & cur = buffer_view_->cursor();
490 // if it doesn't touch the screen, don't try to show it
491 bool cursorInView = true;
492 if (y + h < 0 || y >= viewport()->height())
493 cursorInView = false;
495 // show cursor on screen
496 bool completable = completer_.completionAvailable()
497 && !completer_.popupVisible()
498 && !completer_.inlineVisible();
500 cursor_visible_ = true;
501 showCursor(x, y, h, l_shape, isrtl, completable);
506 void GuiWorkArea::hideCursor()
508 if (!cursor_visible_)
511 cursor_visible_ = false;
516 void GuiWorkArea::toggleCursor()
525 void GuiWorkArea::updateScrollbar()
527 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
529 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
530 verticalScrollBar()->setPageStep(scroll_.page_step);
531 verticalScrollBar()->setSingleStep(scroll_.single_step);
532 // Block the scrollbar signal to prevent recursive signal/slot calling.
533 verticalScrollBar()->blockSignals(true);
534 verticalScrollBar()->setValue(scroll_.position);
535 verticalScrollBar()->setSliderPosition(scroll_.position);
536 verticalScrollBar()->blockSignals(false);
540 void GuiWorkArea::scrollTo(int value)
542 stopBlinkingCursor();
543 buffer_view_->scrollDocView(value);
545 if (lyxrc.cursor_follows_scrollbar) {
546 buffer_view_->setCursorFromScrollbar();
547 lyx_view_->updateLayoutList();
549 // Show the cursor immediately after any operation.
550 startBlinkingCursor();
551 QApplication::syncX();
555 bool GuiWorkArea::event(QEvent * e)
558 case QEvent::ToolTip: {
559 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
560 if (lyxrc.use_tooltip) {
561 QPoint pos = helpEvent->pos();
562 if (pos.x() < viewport()->width()) {
563 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
564 QToolTip::showText(helpEvent->globalPos(), s);
567 QToolTip::hideText();
569 // Don't forget to accept the event!
574 case QEvent::ShortcutOverride: {
575 // We catch this event in order to catch the Tab or Shift+Tab key press
576 // which are otherwise reserved to focus switching between controls
578 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
579 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
580 || ke->modifiers() & Qt::ControlModifier)
581 return QAbstractScrollArea::event(e);
587 return QAbstractScrollArea::event(e);
593 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
595 QPoint pos = e->pos();
596 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
598 QAbstractScrollArea::contextMenuEvent(e);
601 QMenu * menu = guiApp->menus().menu(toqstr(name));
603 QAbstractScrollArea::contextMenuEvent(e);
606 // Position the menu to the right.
607 // FIXME: menu position should be different for RTL text.
608 menu->exec(e->globalPos());
613 void GuiWorkArea::focusInEvent(QFocusEvent * e)
615 if (lyx_view_->currentWorkArea() != this)
616 lyx_view_->setCurrentWorkArea(this);
618 // Repaint the whole screen.
619 // Note: this is different from redraw() as only the backing pixmap
620 // will be redrawn, which is cheap.
621 viewport()->repaint();
623 startBlinkingCursor();
624 QAbstractScrollArea::focusInEvent(e);
628 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
630 stopBlinkingCursor();
631 QAbstractScrollArea::focusOutEvent(e);
635 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
637 if (dc_event_.active && dc_event_ == *e) {
638 dc_event_.active = false;
639 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
640 q_button_state(e->button()));
646 inputContext()->reset();
648 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
649 q_button_state(e->button()));
650 dispatch(cmd, q_key_state(e->modifiers()));
655 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
657 if (synthetic_mouse_event_.timeout.running())
658 synthetic_mouse_event_.timeout.stop();
660 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
661 q_button_state(e->button()));
667 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
669 // we kill the triple click if we move
670 doubleClickTimeout();
671 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
672 q_motion_state(e->buttons()));
676 // If we're above or below the work area...
677 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
678 // Make sure only a synthetic event can cause a page scroll,
679 // so they come at a steady rate:
681 // _Force_ a scroll up:
684 cmd.y = viewport()->height();
685 // Store the event, to be handled when the timeout expires.
686 synthetic_mouse_event_.cmd = cmd;
688 if (synthetic_mouse_event_.timeout.running())
689 // Discard the event. Note that it _may_ be handled
690 // when the timeout expires if
691 // synthetic_mouse_event_.cmd has not been overwritten.
692 // Ie, when the timeout expires, we handle the
693 // most recent event but discard all others that
694 // occurred after the one used to start the timeout
695 // in the first place.
698 synthetic_mouse_event_.restart_timeout = true;
699 synthetic_mouse_event_.timeout.start();
700 // Fall through to handle this event...
702 } else if (synthetic_mouse_event_.timeout.running()) {
703 // Store the event, to be possibly handled when the timeout
705 // Once the timeout has expired, normal control is returned
706 // to mouseMoveEvent (restart_timeout = false).
707 // This results in a much smoother 'feel' when moving the
708 // mouse back into the work area.
709 synthetic_mouse_event_.cmd = cmd;
710 synthetic_mouse_event_.restart_timeout = false;
714 // Has anything changed on-screen since the last QMouseEvent
716 double const scrollbar_value = verticalScrollBar()->value();
717 if (e->x() == synthetic_mouse_event_.x_old
718 && e->y() == synthetic_mouse_event_.y_old
719 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
720 // Nothing changed on-screen since the last QMouseEvent.
724 // Yes something has changed. Store the params used to check this.
725 synthetic_mouse_event_.x_old = e->x();
726 synthetic_mouse_event_.y_old = e->y();
727 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
729 // ... and dispatch the event to the LyX core.
734 void GuiWorkArea::wheelEvent(QWheelEvent * e)
736 // Wheel rotation by one notch results in a delta() of 120 (see
737 // documentation of QWheelEvent)
738 double const lines = qApp->wheelScrollLines()
739 * lyxrc.mouse_wheel_speed
740 * e->delta() / 120.0;
741 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << qApp->wheelScrollLines()
742 << " delta = " << e->delta()
743 << " lines = " << lines);
744 verticalScrollBar()->setValue(verticalScrollBar()->value() -
745 int(lines * verticalScrollBar()->singleStep()));
750 void GuiWorkArea::generateSyntheticMouseEvent()
752 // Set things off to generate the _next_ 'pseudo' event.
753 if (synthetic_mouse_event_.restart_timeout)
754 synthetic_mouse_event_.timeout.start();
756 // Has anything changed on-screen since the last timeout signal
758 double const scrollbar_value = verticalScrollBar()->value();
759 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
760 // Yes it has. Store the params used to check this.
761 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
763 // ... and dispatch the event to the LyX core.
764 dispatch(synthetic_mouse_event_.cmd);
769 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
771 // intercept some keys if completion popup is visible
772 if (completer_.popupVisible()) {
776 completer_.activate();
782 // intercept keys for the completion
783 if (ev->key() == Qt::Key_Tab) {
789 if (completer_.popupVisible() && ev->key() == Qt::Key_Escape) {
790 completer_.hidePopup();
795 if (completer_.inlineVisible() && ev->key() == Qt::Key_Escape) {
796 completer_.hideInline();
801 // do nothing if there are other events
802 // (the auto repeated events come too fast)
803 // \todo FIXME: remove hard coded Qt keys, process the key binding
805 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
806 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
807 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
813 LYXERR(Debug::KEY, " count: " << ev->count()
814 << " text: " << fromqstr(ev->text())
815 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
818 setKeySymbol(&sym, ev);
819 processKeySym(sym, q_key_state(ev->modifiers()));
824 void GuiWorkArea::doubleClickTimeout()
826 dc_event_.active = false;
830 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
832 dc_event_ = DoubleClick(ev);
833 QTimer::singleShot(QApplication::doubleClickInterval(), this,
834 SLOT(doubleClickTimeout()));
835 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
837 q_button_state(ev->button()));
843 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
845 QAbstractScrollArea::resizeEvent(ev);
851 void GuiWorkArea::update(int x, int y, int w, int h)
853 viewport()->repaint(x, y, w, h);
857 void GuiWorkArea::paintEvent(QPaintEvent * ev)
859 QRect const rc = ev->rect();
860 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
861 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
864 screen_ = QPixmap(viewport()->width(), viewport()->height());
870 QPainter pain(viewport());
871 pain.drawPixmap(rc, screen_, rc);
877 void GuiWorkArea::updateScreen()
879 GuiPainter pain(&screen_);
880 buffer_view_->draw(pain);
884 void GuiWorkArea::showCursor(int x, int y, int h,
885 bool l_shape, bool rtl, bool completable)
887 if (schedule_redraw_) {
888 buffer_view_->updateMetrics();
890 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
891 schedule_redraw_ = false;
892 // Show the cursor immediately after the update.
898 cursor_->update(x, y, h, l_shape, rtl, completable);
900 viewport()->update(cursor_->rect());
904 void GuiWorkArea::removeCursor()
907 //if (!qApp->focusWidget())
908 viewport()->update(cursor_->rect());
912 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
914 QString const & commit_string = e->commitString();
915 docstring const & preedit_string
916 = qstring_to_ucs4(e->preeditString());
918 if (!commit_string.isEmpty()) {
920 LYXERR(Debug::KEY, "preeditString: " << fromqstr(e->preeditString())
921 << " commitString: " << fromqstr(e->commitString()));
925 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
926 for (int i = 0; i != commit_string.size(); ++i) {
927 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
932 // Hide the cursor during the kana-kanji transformation.
933 if (preedit_string.empty())
934 startBlinkingCursor();
936 stopBlinkingCursor();
938 // last_width : for checking if last preedit string was/wasn't empty.
939 static bool last_width = false;
940 if (!last_width && preedit_string.empty()) {
941 // if last_width is last length of preedit string.
946 GuiPainter pain(&screen_);
947 buffer_view_->updateMetrics();
948 buffer_view_->draw(pain);
949 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
950 FontMetrics const & fm = theFontMetrics(font);
951 int height = fm.maxHeight();
952 int cur_x = cursor_->rect().left();
953 int cur_y = cursor_->rect().bottom();
955 // redraw area of preedit string.
956 update(0, cur_y - height, viewport()->width(),
957 (height + 1) * preedit_lines_);
959 if (preedit_string.empty()) {
967 // att : stores an IM attribute.
968 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
970 // get attributes of input method cursor.
971 // cursor_pos : cursor position in preedit string.
972 size_t cursor_pos = 0;
973 bool cursor_is_visible = false;
974 for (int i = 0; i != att.size(); ++i) {
975 if (att.at(i).type == QInputMethodEvent::Cursor) {
976 cursor_pos = att.at(i).start;
977 cursor_is_visible = att.at(i).length != 0;
982 size_t preedit_length = preedit_string.length();
984 // get position of selection in input method.
985 // FIXME: isn't there a way to do this simplier?
986 // rStart : cursor position in selected string in IM.
988 // rLength : selected string length in IM.
990 if (cursor_pos < preedit_length) {
991 for (int i = 0; i != att.size(); ++i) {
992 if (att.at(i).type == QInputMethodEvent::TextFormat) {
993 if (att.at(i).start <= int(cursor_pos)
994 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
995 rStart = att.at(i).start;
996 rLength = att.at(i).length;
997 if (!cursor_is_visible)
998 cursor_pos += rLength;
1005 rStart = cursor_pos;
1009 int const right_margin = buffer_view_->rightMargin();
1010 Painter::preedit_style ps;
1011 // Most often there would be only one line:
1013 for (size_t pos = 0; pos != preedit_length; ++pos) {
1014 char_type const typed_char = preedit_string[pos];
1015 // reset preedit string style
1016 ps = Painter::preedit_default;
1018 // if we reached the right extremity of the screen, go to next line.
1019 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1020 cur_x = right_margin;
1021 cur_y += height + 1;
1024 // preedit strings are displayed with dashed underline
1025 // and partial strings are displayed white on black indicating
1026 // that we are in selecting mode in the input method.
1027 // FIXME: rLength == preedit_length is not a changing condition
1028 // FIXME: should be put out of the loop.
1030 && pos < rStart + rLength
1031 && !(cursor_pos < rLength && rLength == preedit_length))
1032 ps = Painter::preedit_selecting;
1034 if (pos == cursor_pos
1035 && (cursor_pos < rLength && rLength == preedit_length))
1036 ps = Painter::preedit_cursor;
1038 // draw one character and update cur_x.
1039 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1042 // update the preedit string screen area.
1043 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1044 (height + 1) * preedit_lines_);
1046 // Don't forget to accept the event!
1051 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1053 QRect cur_r(0,0,0,0);
1055 // this is the CJK-specific composition window position.
1056 case Qt::ImMicroFocus:
1057 cur_r = cursor_->rect();
1058 if (preedit_lines_ != 1)
1060 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1061 // return lower right of cursor in LyX.
1064 return QWidget::inputMethodQuery(query);
1069 void GuiWorkArea::updateWindowTitle()
1071 docstring maximize_title;
1072 docstring minimize_title;
1074 Buffer & buf = buffer_view_->buffer();
1075 FileName const fileName = buf.fileName();
1076 if (!fileName.empty()) {
1077 maximize_title = fileName.displayName(30);
1078 minimize_title = from_utf8(fileName.onlyFileName());
1079 if (!buf.isClean()) {
1080 maximize_title += _(" (changed)");
1081 minimize_title += char_type('*');
1083 if (buf.isReadonly())
1084 maximize_title += _(" (read only)");
1087 QString title = windowTitle();
1088 QString new_title = toqstr(maximize_title);
1089 if (title == new_title)
1092 QWidget::setWindowTitle(new_title);
1093 QWidget::setWindowIconText(toqstr(minimize_title));
1098 void GuiWorkArea::setReadOnly(bool)
1100 updateWindowTitle();
1101 if (this == lyx_view_->currentWorkArea())
1102 lyx_view_->updateBufferDependent(false);
1106 bool GuiWorkArea::isFullScreen()
1108 return lyx_view_ && lyx_view_->isFullScreen();
1112 ////////////////////////////////////////////////////////////////////
1116 ////////////////////////////////////////////////////////////////////
1118 TabWorkArea::TabWorkArea(QWidget * parent) : QTabWidget(parent)
1120 QPalette pal = palette();
1121 pal.setColor(QPalette::Active, QPalette::Button,
1122 pal.color(QPalette::Active, QPalette::Window));
1123 pal.setColor(QPalette::Disabled, QPalette::Button,
1124 pal.color(QPalette::Disabled, QPalette::Window));
1125 pal.setColor(QPalette::Inactive, QPalette::Button,
1126 pal.color(QPalette::Inactive, QPalette::Window));
1128 QObject::connect(this, SIGNAL(currentChanged(int)),
1129 this, SLOT(on_currentTabChanged(int)));
1131 QToolButton * closeBufferButton = new QToolButton(this);
1132 closeBufferButton->setPalette(pal);
1133 // FIXME: rename the icon to closebuffer.png
1134 closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1135 closeBufferButton->setText("Close File");
1136 closeBufferButton->setAutoRaise(true);
1137 closeBufferButton->setCursor(Qt::ArrowCursor);
1138 closeBufferButton->setToolTip(qt_("Close File"));
1139 closeBufferButton->setEnabled(true);
1140 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1141 this, SLOT(closeCurrentBuffer()));
1142 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1144 QToolButton * closeTabButton = new QToolButton(this);
1145 closeTabButton->setPalette(pal);
1146 closeTabButton->setIcon(QIcon(":/images/hidetab.png"));
1147 closeTabButton->setText("Hide tab");
1148 closeTabButton->setAutoRaise(true);
1149 closeTabButton->setCursor(Qt::ArrowCursor);
1150 closeTabButton->setToolTip(qt_("Hide tab"));
1151 closeTabButton->setEnabled(true);
1152 QObject::connect(closeTabButton, SIGNAL(clicked()),
1153 this, SLOT(closeCurrentTab()));
1154 setCornerWidget(closeTabButton, Qt::TopLeftCorner);
1156 setUsesScrollButtons(true);
1160 void TabWorkArea::setFullScreen(bool full_screen)
1162 for (int i = 0; i != count(); ++i) {
1163 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1164 wa->setFullScreen(full_screen);
1167 if (lyxrc.full_screen_tabbar)
1168 showBar(!full_screen && count()>1);
1172 void TabWorkArea::showBar(bool show)
1174 tabBar()->setEnabled(show);
1175 tabBar()->setVisible(show);
1179 GuiWorkArea * TabWorkArea::currentWorkArea()
1184 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1190 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1192 for (int i = 0; i != count(); ++i) {
1193 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1195 if (&wa->bufferView().buffer() == &buffer)
1202 void TabWorkArea::closeAll()
1205 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1213 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1215 BOOST_ASSERT(work_area);
1216 int index = indexOf(work_area);
1220 if (index == currentIndex())
1221 // Make sure the work area is up to date.
1222 on_currentTabChanged(index);
1224 // Switch to the work area.
1225 setCurrentIndex(index);
1226 work_area->setFocus();
1232 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1234 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1235 wa->setUpdatesEnabled(false);
1236 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1237 // when hiding it again below).
1238 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1239 showBar(count() > 0);
1240 addTab(wa, wa->windowTitle());
1241 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1242 this, SLOT(updateTabText(GuiWorkArea *)));
1243 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1244 setFullScreen(true);
1246 // Hide tabbar if there's only one tab.
1247 showBar(count() > 1);
1253 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1255 BOOST_ASSERT(work_area);
1256 int index = indexOf(work_area);
1260 work_area->setUpdatesEnabled(false);
1265 // make sure the next work area is enabled.
1266 currentWidget()->setUpdatesEnabled(true);
1267 if ((currentWorkArea() && currentWorkArea()->isFullScreen()))
1268 setFullScreen(true);
1270 // Hide tabbar if there's only one tab.
1271 showBar(count() > 1);
1277 void TabWorkArea::on_currentTabChanged(int i)
1279 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1281 BufferView & bv = wa->bufferView();
1282 bv.cursor().fixIfBroken();
1284 wa->setUpdatesEnabled(true);
1288 currentWorkAreaChanged(wa);
1290 LYXERR(Debug::GUI, "currentTabChanged " << i
1291 << "File" << bv.buffer().absFileName());
1295 void TabWorkArea::closeCurrentBuffer()
1297 lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1301 void TabWorkArea::closeCurrentTab()
1303 removeWorkArea(currentWorkArea());
1307 void TabWorkArea::updateTabText(GuiWorkArea * wa)
1309 int const i = indexOf(wa);
1312 setTabText(i, wa->windowTitle());
1315 } // namespace frontend
1318 #include "GuiWorkArea_moc.cpp"