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"
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>
53 #include <QMainWindow>
57 #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);
248 screen_ = QPixmap(viewport()->width(), viewport()->height());
249 cursor_ = new frontend::CursorWidget();
252 // HACK: Prevents an additional redraw when the scrollbar pops up
253 // which regularily happens on documents with more than one page.
254 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
255 // Since we have no geometry information yet, we assume that
256 // a document needs a scrollbar if there is more then four
257 // paragraph in the outermost text.
258 if (buffer.text().paragraphs().size() > 4)
259 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
260 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
263 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
264 setAcceptDrops(true);
265 setMouseTracking(true);
266 setMinimumSize(100, 70);
268 setFrameStyle(QFrame::NoFrame);
270 setFrameStyle(QFrame::Box);
274 viewport()->setAutoFillBackground(false);
275 // We don't need double-buffering nor SystemBackground on
276 // the viewport because we have our own backing pixmap.
277 viewport()->setAttribute(Qt::WA_NoSystemBackground);
279 setFocusPolicy(Qt::WheelFocus);
281 viewport()->setCursor(Qt::IBeamCursor);
283 synthetic_mouse_event_.timeout.timeout.connect(
284 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
287 // Initialize the vertical Scroll Bar
288 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
289 this, SLOT(scrollTo(int)));
291 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
292 << " viewport height: " << viewport()->height());
294 // Enables input methods for asian languages.
295 // Must be set when creating custom text editing widgets.
296 setAttribute(Qt::WA_InputMethodEnabled, true);
300 GuiWorkArea::~GuiWorkArea()
302 buffer_view_->buffer().workAreaManager().remove(this);
308 void GuiWorkArea::fixVerticalScrollBar()
311 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
315 void GuiWorkArea::close()
317 lyx_view_->removeWorkArea(this);
321 void GuiWorkArea::setFullScreen(bool full_screen)
323 buffer_view_->setFullScreen(full_screen);
325 setFrameStyle(QFrame::NoFrame);
326 if (lyxrc.full_screen_scrollbar)
327 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
330 setFrameStyle(QFrame::NoFrame);
332 setFrameStyle(QFrame::Box);
334 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
339 BufferView & GuiWorkArea::bufferView()
341 return *buffer_view_;
345 BufferView const & GuiWorkArea::bufferView() const
347 return *buffer_view_;
351 void GuiWorkArea::stopBlinkingCursor()
353 cursor_timeout_.stop();
358 void GuiWorkArea::startBlinkingCursor()
361 //we're not supposed to cache this value.
362 int const time = QApplication::cursorFlashTime() / 2;
365 cursor_timeout_.setInterval(time);
366 cursor_timeout_.start();
370 void GuiWorkArea::redraw()
373 // No need to redraw in this case.
376 // No need to do anything if this is the current view. The BufferView
377 // metrics are already up to date.
378 if (lyx_view_ != guiApp->currentView()
379 || lyx_view_->currentWorkArea() != this) {
380 // FIXME: it would be nice to optimize for the off-screen case.
381 buffer_view_->updateMetrics();
382 buffer_view_->cursor().fixIfBroken();
385 // update cursor position, because otherwise it has to wait until
386 // the blinking interval is over
387 if (cursor_visible_) {
392 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
394 update(0, 0, viewport()->width(), viewport()->height());
396 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
397 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
399 lyx_view_->updateStatusBar();
401 if (lyxerr.debugging(Debug::WORKAREA))
402 buffer_view_->coordCache().dump();
406 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
408 // In order to avoid bad surprise in the middle of an operation,
409 // we better stop the blinking cursor...
410 // the cursor gets restarted in GuiView::restartCursor()
411 stopBlinkingCursor();
413 theLyXFunc().setLyXView(lyx_view_);
414 theLyXFunc().processKeySym(key, mod);
418 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
421 if (cmd0.action == LFUN_FILE_OPEN) {
422 lyx_view_->dispatch(cmd0);
426 theLyXFunc().setLyXView(lyx_view_);
430 if (cmd0.action == LFUN_MOUSE_PRESS) {
431 if (mod == ShiftModifier)
432 cmd = FuncRequest(cmd0, "region-select");
433 else if (mod == ControlModifier)
434 cmd = FuncRequest(cmd0, "paragraph-select");
441 bool const notJustMovingTheMouse =
442 cmd.action != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
444 // In order to avoid bad surprise in the middle of an operation, we better stop
445 // the blinking cursor.
446 if (notJustMovingTheMouse)
447 stopBlinkingCursor();
449 buffer_view_->mouseEventDispatch(cmd);
451 // Skip these when selecting
452 if (cmd.action != LFUN_MOUSE_MOTION) {
453 completer_.updateVisibility(false, false);
454 lyx_view_->updateLayoutList();
455 lyx_view_->updateToolbars();
458 // GUI tweaks except with mouse motion with no button pressed.
459 if (notJustMovingTheMouse) {
460 // Slight hack: this is only called currently when we
461 // clicked somewhere, so we force through the display
462 // of the new status here.
463 lyx_view_->clearMessage();
465 // Show the cursor immediately after any operation
466 startBlinkingCursor();
471 void GuiWorkArea::resizeBufferView()
473 // WARNING: Please don't put any code that will trigger a repaint here!
474 // We are already inside a paint event.
475 lyx_view_->setBusy(true);
476 buffer_view_->resize(viewport()->width(), viewport()->height());
479 // Update scrollbars which might have changed due different
480 // BufferView dimension. This is especially important when the
481 // BufferView goes from zero-size to the real-size for the first time,
482 // as the scrollbar paramters are then set for the first time.
485 lyx_view_->updateLayoutList();
486 lyx_view_->setBusy(false);
487 need_resize_ = false;
491 void GuiWorkArea::showCursor()
497 bool l_shape = false;
498 Font const & realfont = buffer_view_->cursor().real_current_font;
499 BufferParams const & bp = buffer_view_->buffer().params();
500 bool const samelang = realfont.language() == bp.language;
501 bool const isrtl = realfont.isVisibleRightToLeft();
503 if (!samelang || isrtl != bp.language->rightToLeft())
506 // The ERT language hack needs fixing up
507 if (realfont.language() == latex_language)
510 Font const font = buffer_view_->cursor().getFont();
511 FontMetrics const & fm = theFontMetrics(font);
512 int const asc = fm.maxAscent();
513 int const des = fm.maxDescent();
517 Cursor & cur = buffer_view_->cursor();
521 // if it doesn't touch the screen, don't try to show it
522 bool cursorInView = true;
523 if (y + h < 0 || y >= viewport()->height())
524 cursorInView = false;
526 // show cursor on screen
527 bool completable = cur.inset().showCompletionCursor()
528 && completer_.completionAvailable()
529 && !completer_.popupVisible()
530 && !completer_.inlineVisible();
532 cursor_visible_ = true;
533 showCursor(x, y, h, l_shape, isrtl, completable);
538 void GuiWorkArea::hideCursor()
540 if (!cursor_visible_)
543 cursor_visible_ = false;
548 void GuiWorkArea::toggleCursor()
557 void GuiWorkArea::updateScrollbar()
559 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
561 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
562 verticalScrollBar()->setPageStep(scroll_.page_step);
563 verticalScrollBar()->setSingleStep(scroll_.single_step);
564 // Block the scrollbar signal to prevent recursive signal/slot calling.
565 verticalScrollBar()->blockSignals(true);
566 verticalScrollBar()->setValue(scroll_.position);
567 verticalScrollBar()->setSliderPosition(scroll_.position);
568 verticalScrollBar()->blockSignals(false);
572 void GuiWorkArea::scrollTo(int value)
574 stopBlinkingCursor();
575 buffer_view_->scrollDocView(value);
577 if (lyxrc.cursor_follows_scrollbar) {
578 buffer_view_->setCursorFromScrollbar();
579 lyx_view_->updateLayoutList();
581 // Show the cursor immediately after any operation.
582 startBlinkingCursor();
583 QApplication::syncX();
587 bool GuiWorkArea::event(QEvent * e)
590 case QEvent::ToolTip: {
591 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
592 if (lyxrc.use_tooltip) {
593 QPoint pos = helpEvent->pos();
594 if (pos.x() < viewport()->width()) {
595 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
596 QToolTip::showText(helpEvent->globalPos(), s);
599 QToolTip::hideText();
601 // Don't forget to accept the event!
606 case QEvent::ShortcutOverride: {
607 // We catch this event in order to catch the Tab or Shift+Tab key press
608 // which are otherwise reserved to focus switching between controls
610 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
611 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
612 || ke->modifiers() & Qt::ControlModifier)
613 return QAbstractScrollArea::event(e);
619 return QAbstractScrollArea::event(e);
625 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
627 QPoint pos = e->pos();
628 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
630 QAbstractScrollArea::contextMenuEvent(e);
633 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
635 QAbstractScrollArea::contextMenuEvent(e);
638 // Position the menu to the right.
639 // FIXME: menu position should be different for RTL text.
640 menu->exec(e->globalPos());
645 void GuiWorkArea::focusInEvent(QFocusEvent * e)
647 if (lyx_view_->currentWorkArea() != this)
648 lyx_view_->setCurrentWorkArea(this);
650 // Repaint the whole screen.
651 // Note: this is different from redraw() as only the backing pixmap
652 // will be redrawn, which is cheap.
653 viewport()->repaint();
655 startBlinkingCursor();
656 QAbstractScrollArea::focusInEvent(e);
660 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
662 stopBlinkingCursor();
663 QAbstractScrollArea::focusOutEvent(e);
667 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
669 if (dc_event_.active && dc_event_ == *e) {
670 dc_event_.active = false;
671 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
672 q_button_state(e->button()));
678 inputContext()->reset();
680 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
681 q_button_state(e->button()));
682 dispatch(cmd, q_key_state(e->modifiers()));
687 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
689 if (synthetic_mouse_event_.timeout.running())
690 synthetic_mouse_event_.timeout.stop();
692 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
693 q_button_state(e->button()));
699 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
701 // we kill the triple click if we move
702 doubleClickTimeout();
703 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
704 q_motion_state(e->buttons()));
708 // If we're above or below the work area...
709 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
710 // Make sure only a synthetic event can cause a page scroll,
711 // so they come at a steady rate:
713 // _Force_ a scroll up:
716 cmd.y = viewport()->height();
717 // Store the event, to be handled when the timeout expires.
718 synthetic_mouse_event_.cmd = cmd;
720 if (synthetic_mouse_event_.timeout.running())
721 // Discard the event. Note that it _may_ be handled
722 // when the timeout expires if
723 // synthetic_mouse_event_.cmd has not been overwritten.
724 // Ie, when the timeout expires, we handle the
725 // most recent event but discard all others that
726 // occurred after the one used to start the timeout
727 // in the first place.
730 synthetic_mouse_event_.restart_timeout = true;
731 synthetic_mouse_event_.timeout.start();
732 // Fall through to handle this event...
734 } else if (synthetic_mouse_event_.timeout.running()) {
735 // Store the event, to be possibly handled when the timeout
737 // Once the timeout has expired, normal control is returned
738 // to mouseMoveEvent (restart_timeout = false).
739 // This results in a much smoother 'feel' when moving the
740 // mouse back into the work area.
741 synthetic_mouse_event_.cmd = cmd;
742 synthetic_mouse_event_.restart_timeout = false;
746 // Has anything changed on-screen since the last QMouseEvent
748 double const scrollbar_value = verticalScrollBar()->value();
749 if (e->x() == synthetic_mouse_event_.x_old
750 && e->y() == synthetic_mouse_event_.y_old
751 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
752 // Nothing changed on-screen since the last QMouseEvent.
756 // Yes something has changed. Store the params used to check this.
757 synthetic_mouse_event_.x_old = e->x();
758 synthetic_mouse_event_.y_old = e->y();
759 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
761 // ... and dispatch the event to the LyX core.
766 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
768 // Wheel rotation by one notch results in a delta() of 120 (see
769 // documentation of QWheelEvent)
770 int delta = ev->delta() / 120;
771 if (ev->modifiers() & Qt::ControlModifier) {
772 lyxrc.zoom -= 5 * delta;
775 // The global QPixmapCache is used in GuiPainter to cache text
776 // painting so we must reset it.
777 QPixmapCache::clear();
778 guiApp->fontLoader().update();
779 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
781 double const lines = qApp->wheelScrollLines()
782 * lyxrc.mouse_wheel_speed * delta;
783 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << qApp->wheelScrollLines()
784 << " delta = " << ev->delta() << " lines = " << lines);
785 verticalScrollBar()->setValue(verticalScrollBar()->value() -
786 int(lines * verticalScrollBar()->singleStep()));
792 void GuiWorkArea::generateSyntheticMouseEvent()
794 // Set things off to generate the _next_ 'pseudo' event.
795 if (synthetic_mouse_event_.restart_timeout)
796 synthetic_mouse_event_.timeout.start();
798 // Has anything changed on-screen since the last timeout signal
800 double const scrollbar_value = verticalScrollBar()->value();
801 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
802 // Yes it has. Store the params used to check this.
803 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
805 // ... and dispatch the event to the LyX core.
806 dispatch(synthetic_mouse_event_.cmd);
811 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
813 // intercept some keys if completion popup is visible
814 if (completer_.popupVisible()) {
818 completer_.activate();
824 // intercept keys for the completion
825 if (ev->key() == Qt::Key_Tab) {
831 if (completer_.popupVisible() && ev->key() == Qt::Key_Escape) {
832 completer_.hidePopup();
837 if (completer_.inlineVisible() && ev->key() == Qt::Key_Escape) {
838 completer_.hideInline();
843 // do nothing if there are other events
844 // (the auto repeated events come too fast)
845 // \todo FIXME: remove hard coded Qt keys, process the key binding
847 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
848 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
849 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
855 LYXERR(Debug::KEY, " count: " << ev->count()
856 << " text: " << fromqstr(ev->text())
857 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
860 setKeySymbol(&sym, ev);
861 processKeySym(sym, q_key_state(ev->modifiers()));
866 void GuiWorkArea::doubleClickTimeout()
868 dc_event_.active = false;
872 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
874 dc_event_ = DoubleClick(ev);
875 QTimer::singleShot(QApplication::doubleClickInterval(), this,
876 SLOT(doubleClickTimeout()));
877 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
879 q_button_state(ev->button()));
885 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
887 QAbstractScrollArea::resizeEvent(ev);
893 void GuiWorkArea::update(int x, int y, int w, int h)
895 viewport()->repaint(x, y, w, h);
899 void GuiWorkArea::paintEvent(QPaintEvent * ev)
901 QRect const rc = ev->rect();
902 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
903 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
906 screen_ = QPixmap(viewport()->width(), viewport()->height());
912 QPainter pain(viewport());
913 pain.drawPixmap(rc, screen_, rc);
919 void GuiWorkArea::updateScreen()
921 GuiPainter pain(&screen_);
922 buffer_view_->draw(pain);
926 void GuiWorkArea::showCursor(int x, int y, int h,
927 bool l_shape, bool rtl, bool completable)
929 if (schedule_redraw_) {
930 buffer_view_->updateMetrics();
932 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
933 schedule_redraw_ = false;
934 // Show the cursor immediately after the update.
940 cursor_->update(x, y, h, l_shape, rtl, completable);
942 viewport()->update(cursor_->rect());
946 void GuiWorkArea::removeCursor()
949 //if (!qApp->focusWidget())
950 viewport()->update(cursor_->rect());
954 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
956 QString const & commit_string = e->commitString();
957 docstring const & preedit_string
958 = qstring_to_ucs4(e->preeditString());
960 if (!commit_string.isEmpty()) {
962 LYXERR(Debug::KEY, "preeditString: " << fromqstr(e->preeditString())
963 << " commitString: " << fromqstr(e->commitString()));
967 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
968 for (int i = 0; i != commit_string.size(); ++i) {
969 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
974 // Hide the cursor during the kana-kanji transformation.
975 if (preedit_string.empty())
976 startBlinkingCursor();
978 stopBlinkingCursor();
980 // last_width : for checking if last preedit string was/wasn't empty.
981 static bool last_width = false;
982 if (!last_width && preedit_string.empty()) {
983 // if last_width is last length of preedit string.
988 GuiPainter pain(&screen_);
989 buffer_view_->updateMetrics();
990 buffer_view_->draw(pain);
991 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
992 FontMetrics const & fm = theFontMetrics(font);
993 int height = fm.maxHeight();
994 int cur_x = cursor_->rect().left();
995 int cur_y = cursor_->rect().bottom();
997 // redraw area of preedit string.
998 update(0, cur_y - height, viewport()->width(),
999 (height + 1) * preedit_lines_);
1001 if (preedit_string.empty()) {
1009 // att : stores an IM attribute.
1010 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1012 // get attributes of input method cursor.
1013 // cursor_pos : cursor position in preedit string.
1014 size_t cursor_pos = 0;
1015 bool cursor_is_visible = false;
1016 for (int i = 0; i != att.size(); ++i) {
1017 if (att.at(i).type == QInputMethodEvent::Cursor) {
1018 cursor_pos = att.at(i).start;
1019 cursor_is_visible = att.at(i).length != 0;
1024 size_t preedit_length = preedit_string.length();
1026 // get position of selection in input method.
1027 // FIXME: isn't there a way to do this simplier?
1028 // rStart : cursor position in selected string in IM.
1030 // rLength : selected string length in IM.
1032 if (cursor_pos < preedit_length) {
1033 for (int i = 0; i != att.size(); ++i) {
1034 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1035 if (att.at(i).start <= int(cursor_pos)
1036 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1037 rStart = att.at(i).start;
1038 rLength = att.at(i).length;
1039 if (!cursor_is_visible)
1040 cursor_pos += rLength;
1047 rStart = cursor_pos;
1051 int const right_margin = buffer_view_->rightMargin();
1052 Painter::preedit_style ps;
1053 // Most often there would be only one line:
1055 for (size_t pos = 0; pos != preedit_length; ++pos) {
1056 char_type const typed_char = preedit_string[pos];
1057 // reset preedit string style
1058 ps = Painter::preedit_default;
1060 // if we reached the right extremity of the screen, go to next line.
1061 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1062 cur_x = right_margin;
1063 cur_y += height + 1;
1066 // preedit strings are displayed with dashed underline
1067 // and partial strings are displayed white on black indicating
1068 // that we are in selecting mode in the input method.
1069 // FIXME: rLength == preedit_length is not a changing condition
1070 // FIXME: should be put out of the loop.
1072 && pos < rStart + rLength
1073 && !(cursor_pos < rLength && rLength == preedit_length))
1074 ps = Painter::preedit_selecting;
1076 if (pos == cursor_pos
1077 && (cursor_pos < rLength && rLength == preedit_length))
1078 ps = Painter::preedit_cursor;
1080 // draw one character and update cur_x.
1081 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1084 // update the preedit string screen area.
1085 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1086 (height + 1) * preedit_lines_);
1088 // Don't forget to accept the event!
1093 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1095 QRect cur_r(0,0,0,0);
1097 // this is the CJK-specific composition window position.
1098 case Qt::ImMicroFocus:
1099 cur_r = cursor_->rect();
1100 if (preedit_lines_ != 1)
1102 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1103 // return lower right of cursor in LyX.
1106 return QWidget::inputMethodQuery(query);
1111 void GuiWorkArea::updateWindowTitle()
1113 docstring maximize_title;
1114 docstring minimize_title;
1116 Buffer & buf = buffer_view_->buffer();
1117 FileName const fileName = buf.fileName();
1118 if (!fileName.empty()) {
1119 maximize_title = fileName.displayName(30);
1120 minimize_title = from_utf8(fileName.onlyFileName());
1121 if (!buf.isClean()) {
1122 maximize_title += _(" (changed)");
1123 minimize_title += char_type('*');
1125 if (buf.isReadonly())
1126 maximize_title += _(" (read only)");
1129 QString title = windowTitle();
1130 QString new_title = toqstr(maximize_title);
1131 if (title == new_title)
1134 QWidget::setWindowTitle(new_title);
1135 QWidget::setWindowIconText(toqstr(minimize_title));
1140 void GuiWorkArea::setReadOnly(bool)
1142 updateWindowTitle();
1143 if (this == lyx_view_->currentWorkArea())
1144 lyx_view_->updateBufferDependent(false);
1148 bool GuiWorkArea::isFullScreen()
1150 return lyx_view_ && lyx_view_->isFullScreen();
1154 ////////////////////////////////////////////////////////////////////
1158 ////////////////////////////////////////////////////////////////////
1161 class NoTabFrameMacStyle : public QMacStyle {
1164 QRect subElementRect(SubElement element, const QStyleOption * option,
1165 const QWidget * widget = 0) const
1167 QRect rect = QMacStyle::subElementRect(element, option, widget);
1168 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1170 // The Qt Mac style puts the contents into a 3 pixel wide box
1171 // which looks very ugly and not like other Mac applications.
1172 // Hence we remove this here, and moreover the 16 pixel round
1173 // frame above if the tab bar is hidden.
1174 if (element == QStyle::SE_TabWidgetTabContents) {
1175 rect.adjust(- rect.left(), 0, rect.left(), 0);
1184 NoTabFrameMacStyle noTabFrameMacStyle;
1188 TabWorkArea::TabWorkArea(QWidget * parent)
1189 : QTabWidget(parent), clicked_tab_(-1)
1192 setStyle(&noTabFrameMacStyle);
1195 QPalette pal = palette();
1196 pal.setColor(QPalette::Active, QPalette::Button,
1197 pal.color(QPalette::Active, QPalette::Window));
1198 pal.setColor(QPalette::Disabled, QPalette::Button,
1199 pal.color(QPalette::Disabled, QPalette::Window));
1200 pal.setColor(QPalette::Inactive, QPalette::Button,
1201 pal.color(QPalette::Inactive, QPalette::Window));
1203 QObject::connect(this, SIGNAL(currentChanged(int)),
1204 this, SLOT(on_currentTabChanged(int)));
1206 QToolButton * closeBufferButton = new QToolButton(this);
1207 closeBufferButton->setPalette(pal);
1208 // FIXME: rename the icon to closebuffer.png
1209 closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1210 closeBufferButton->setText("Close File");
1211 closeBufferButton->setAutoRaise(true);
1212 closeBufferButton->setCursor(Qt::ArrowCursor);
1213 closeBufferButton->setToolTip(qt_("Close File"));
1214 closeBufferButton->setEnabled(true);
1215 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1216 this, SLOT(closeCurrentBuffer()));
1217 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1219 // setup drag'n'drop
1220 QTabBar* tb = new DragTabBar;
1221 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1222 this, SLOT(moveTab(int, int)));
1225 // make us responsible for the context menu of the tabbar
1226 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1227 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1228 this, SLOT(showContextMenu(const QPoint &)));
1230 setUsesScrollButtons(true);
1234 void TabWorkArea::setFullScreen(bool full_screen)
1236 for (int i = 0; i != count(); ++i) {
1237 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1238 wa->setFullScreen(full_screen);
1241 if (lyxrc.full_screen_tabbar)
1242 showBar(!full_screen && count()>1);
1246 void TabWorkArea::showBar(bool show)
1248 tabBar()->setEnabled(show);
1249 tabBar()->setVisible(show);
1253 GuiWorkArea * TabWorkArea::currentWorkArea()
1258 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1264 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1266 for (int i = 0; i != count(); ++i) {
1267 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1269 if (&wa->bufferView().buffer() == &buffer)
1276 void TabWorkArea::closeAll()
1279 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1287 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1289 LASSERT(work_area, /**/);
1290 int index = indexOf(work_area);
1294 if (index == currentIndex())
1295 // Make sure the work area is up to date.
1296 on_currentTabChanged(index);
1298 // Switch to the work area.
1299 setCurrentIndex(index);
1300 work_area->setFocus();
1306 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1308 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1309 wa->setUpdatesEnabled(false);
1310 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1311 // when hiding it again below).
1312 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1313 showBar(count() > 0);
1314 addTab(wa, wa->windowTitle());
1315 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1316 this, SLOT(updateTabText(GuiWorkArea *)));
1317 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1318 setFullScreen(true);
1320 // Hide tabbar if there's only one tab.
1321 showBar(count() > 1);
1327 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1329 LASSERT(work_area, /**/);
1330 int index = indexOf(work_area);
1334 work_area->setUpdatesEnabled(false);
1339 // make sure the next work area is enabled.
1340 currentWidget()->setUpdatesEnabled(true);
1341 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1342 setFullScreen(true);
1344 // Hide tabbar if there's only one tab.
1345 showBar(count() > 1);
1347 lastWorkAreaRemoved();
1353 void TabWorkArea::on_currentTabChanged(int i)
1355 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1357 BufferView & bv = wa->bufferView();
1358 bv.cursor().fixIfBroken();
1360 wa->setUpdatesEnabled(true);
1364 currentWorkAreaChanged(wa);
1366 LYXERR(Debug::GUI, "currentTabChanged " << i
1367 << "File" << bv.buffer().absFileName());
1371 void TabWorkArea::closeCurrentBuffer()
1373 if (clicked_tab_ != -1)
1374 setCurrentIndex(clicked_tab_);
1376 lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1380 void TabWorkArea::closeCurrentTab()
1382 if (clicked_tab_ == -1)
1383 removeWorkArea(currentWorkArea());
1385 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1392 void TabWorkArea::updateTabText(GuiWorkArea * wa)
1394 int const i = indexOf(wa);
1397 setTabText(i, wa->windowTitle());
1401 void TabWorkArea::showContextMenu(const QPoint & pos)
1404 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1405 if (clicked_tab_ != -1) {
1408 popup.addAction(QIcon(":/images/hidetab.png"),
1409 qt_("Hide tab"), this, SLOT(closeCurrentTab()));
1410 popup.addAction(QIcon(":/images/closetab.png"),
1411 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1412 popup.exec(tabBar()->mapToGlobal(pos));
1419 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1421 QWidget * w = widget(fromIndex);
1422 QIcon icon = tabIcon(fromIndex);
1423 QString text = tabText(fromIndex);
1425 setCurrentIndex(fromIndex);
1426 removeTab(fromIndex);
1427 insertTab(toIndex, w, icon, text);
1428 setCurrentIndex(toIndex);
1432 DragTabBar::DragTabBar(QWidget* parent)
1435 setAcceptDrops(true);
1439 #if QT_VERSION < 0x040300
1440 int DragTabBar::tabAt(QPoint const & position) const
1442 const int max = count();
1443 for (int i = 0; i < max; ++i) {
1444 if (tabRect(i).contains(position))
1452 void DragTabBar::mousePressEvent(QMouseEvent * event)
1454 if (event->button() == Qt::LeftButton)
1455 dragStartPos_ = event->pos();
1456 QTabBar::mousePressEvent(event);
1460 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1462 // If the left button isn't pressed anymore then return
1463 if (!(event->buttons() & Qt::LeftButton))
1466 // If the distance is too small then return
1467 if ((event->pos() - dragStartPos_).manhattanLength()
1468 < QApplication::startDragDistance())
1471 // did we hit something after all?
1472 int tab = tabAt(dragStartPos_);
1476 // simulate button release to remove highlight from button
1477 int i = currentIndex();
1478 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1479 event->button(), event->buttons(), 0);
1480 QTabBar::mouseReleaseEvent(&me);
1484 QDrag * drag = new QDrag(this);
1485 QMimeData * mimeData = new QMimeData;
1486 // a crude way to distinguish tab-reodering drops from other ones
1487 mimeData->setData("action", "tab-reordering") ;
1488 drag->setMimeData(mimeData);
1490 #if QT_VERSION >= 0x040300
1491 // get tab pixmap as cursor
1492 QRect r = tabRect(tab);
1493 QPixmap pixmap(r.size());
1494 render(&pixmap, - r.topLeft());
1495 drag->setPixmap(pixmap);
1498 drag->start(Qt::MoveAction);
1504 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1506 // Only accept if it's an tab-reordering request
1507 QMimeData const * m = event->mimeData();
1508 QStringList formats = m->formats();
1509 if (formats.contains("action")
1510 && m->data("action") == "tab-reordering")
1511 event->acceptProposedAction();
1515 void DragTabBar::dropEvent(QDropEvent * event)
1517 int fromIndex = tabAt(dragStartPos_);
1518 int toIndex = tabAt(event->pos());
1520 // Tell interested objects that
1521 if (fromIndex != toIndex)
1522 tabMoveRequested(fromIndex, toIndex);
1523 event->acceptProposedAction();
1527 } // namespace frontend
1530 #include "GuiWorkArea_moc.cpp"