2 * \file GuiWorkArea.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Abdelrazak Younes
9 * Full author contact details are available in file CREDITS.
14 #include "GuiWorkArea.h"
16 #include "ColorCache.h"
17 #include "FontLoader.h"
21 #include "BufferParams.h"
22 #include "BufferView.h"
23 #include "CoordCache.h"
26 #include "FuncRequest.h"
27 #include "GuiApplication.h"
28 #include "GuiCompleter.h"
29 #include "GuiKeySymbol.h"
30 #include "GuiPainter.h"
32 #include "KeySymbol.h"
36 #include "MetricsInfo.h"
37 #include "qt_helpers.h"
41 #include "graphics/GraphicsImage.h"
42 #include "graphics/GraphicsLoader.h"
44 #include "support/debug.h"
45 #include "support/gettext.h"
46 #include "support/FileName.h"
48 #include "frontends/Application.h"
49 #include "frontends/FontMetrics.h"
50 #include "frontends/WorkAreaManager.h"
52 #include <QContextMenuEvent>
53 #include <QInputContext>
58 #include <QMainWindow>
62 #include <QPixmapCache>
65 #include <QToolButton>
69 #include <boost/bind.hpp>
75 extern "C" int XEventsQueued(Display *display, int mode);
79 int const CursorWidth = 2;
81 int const CursorWidth = 1;
83 int const TabIndicatorWidth = 3;
89 using namespace lyx::support;
94 /// return the LyX mouse button state from Qt's
95 static mouse_button::state q_button_state(Qt::MouseButton button)
97 mouse_button::state b = mouse_button::none;
100 b = mouse_button::button1;
103 b = mouse_button::button2;
105 case Qt::RightButton:
106 b = mouse_button::button3;
115 /// return the LyX mouse button state from Qt's
116 mouse_button::state q_motion_state(Qt::MouseButtons state)
118 mouse_button::state b = mouse_button::none;
119 if (state & Qt::LeftButton)
120 b |= mouse_button::button1;
121 if (state & Qt::MidButton)
122 b |= mouse_button::button2;
123 if (state & Qt::RightButton)
124 b |= mouse_button::button3;
135 void draw(QPainter & painter)
137 if (!show_ || !rect_.isValid())
141 int l = x_ - rect_.left();
142 int r = rect_.right() - x_;
143 int bot = rect_.bottom();
145 // draw vertica linel
146 painter.fillRect(x_, y, CursorWidth, rect_.height(), color_);
148 // draw RTL/LTR indication
149 painter.setPen(color_);
152 painter.drawLine(x_, bot, x_ - l, bot);
154 painter.drawLine(x_, bot, x_ + CursorWidth + r, bot);
157 // draw completion triangle
159 int m = y + rect_.height() / 2;
160 int d = TabIndicatorWidth - 1;
162 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
163 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
165 painter.drawLine(x_ + CursorWidth, m - d, x_ + CursorWidth + d, m);
166 painter.drawLine(x_ + CursorWidth, m + d, x_ + CursorWidth + d, m);
171 void update(int x, int y, int h, bool l_shape,
172 bool rtl, bool completable)
174 color_ = guiApp->colorCache().get(Color_cursor);
177 completable_ = completable;
180 // extension to left and right
184 // RTL/LTR indication
192 // completion triangle
195 l = max(l, TabIndicatorWidth);
197 r = max(r, TabIndicatorWidth);
200 // compute overall rectangle
201 rect_ = QRect(x - l, y, CursorWidth + r + l, h);
204 void show(bool set_show = true) { show_ = set_show; }
205 void hide() { show_ = false; }
207 QRect const & rect() { return rect_; }
210 /// cursor is in RTL or LTR text
212 /// indication for RTL or LTR
214 /// triangle to show that a completion is available
220 /// rectangle, possibly with l_shape and completion triangle
222 /// x position (were the vertical line is drawn)
227 // This is a 'heartbeat' generating synthetic mouse move events when the
228 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
229 SyntheticMouseEvent::SyntheticMouseEvent()
230 : timeout(200), restart_timeout(true),
231 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
236 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & lv)
237 : buffer_view_(new BufferView(buffer)), lyx_view_(&lv),
238 cursor_visible_(false),
239 need_resize_(false), schedule_redraw_(false),
240 preedit_lines_(1), completer_(new GuiCompleter(this))
242 buffer.workAreaManager().add(this);
244 connect(&cursor_timeout_, SIGNAL(timeout()),
245 this, SLOT(toggleCursor()));
247 int const time = QApplication::cursorFlashTime() / 2;
249 cursor_timeout_.setInterval(time);
250 cursor_timeout_.start();
252 // let's initialize this just to be safe
253 cursor_timeout_.setInterval(500);
256 screen_ = QPixmap(viewport()->width(), viewport()->height());
257 cursor_ = new frontend::CursorWidget();
260 // HACK: Prevents an additional redraw when the scrollbar pops up
261 // which regularily happens on documents with more than one page.
262 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
263 // Since we have no geometry information yet, we assume that
264 // a document needs a scrollbar if there is more then four
265 // paragraph in the outermost text.
266 if (buffer.text().paragraphs().size() > 4)
267 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
268 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
271 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
272 setAcceptDrops(true);
273 setMouseTracking(true);
274 setMinimumSize(100, 70);
276 setFrameStyle(QFrame::NoFrame);
278 setFrameStyle(QFrame::Box);
282 viewport()->setAutoFillBackground(false);
283 // We don't need double-buffering nor SystemBackground on
284 // the viewport because we have our own backing pixmap.
285 viewport()->setAttribute(Qt::WA_NoSystemBackground);
287 setFocusPolicy(Qt::WheelFocus);
289 viewport()->setCursor(Qt::IBeamCursor);
291 synthetic_mouse_event_.timeout.timeout.connect(
292 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
295 // Initialize the vertical Scroll Bar
296 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
297 this, SLOT(scrollTo(int)));
299 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
300 << " viewport height: " << viewport()->height());
302 // Enables input methods for asian languages.
303 // Must be set when creating custom text editing widgets.
304 setAttribute(Qt::WA_InputMethodEnabled, true);
308 GuiWorkArea::~GuiWorkArea()
310 buffer_view_->buffer().workAreaManager().remove(this);
313 // Completer has a QObject parent and is thus automatically destroyed.
314 // delete completer_;
318 void GuiWorkArea::fixVerticalScrollBar()
321 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
325 void GuiWorkArea::close()
327 lyx_view_->removeWorkArea(this);
331 void GuiWorkArea::setFullScreen(bool full_screen)
333 buffer_view_->setFullScreen(full_screen);
335 setFrameStyle(QFrame::NoFrame);
336 if (lyxrc.full_screen_scrollbar)
337 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
340 setFrameStyle(QFrame::NoFrame);
342 setFrameStyle(QFrame::Box);
344 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
349 BufferView & GuiWorkArea::bufferView()
351 return *buffer_view_;
355 BufferView const & GuiWorkArea::bufferView() const
357 return *buffer_view_;
361 void GuiWorkArea::stopBlinkingCursor()
363 cursor_timeout_.stop();
368 void GuiWorkArea::startBlinkingCursor()
371 //we're not supposed to cache this value.
372 int const time = QApplication::cursorFlashTime() / 2;
375 cursor_timeout_.setInterval(time);
376 cursor_timeout_.start();
380 void GuiWorkArea::redraw()
383 // No need to redraw in this case.
386 // No need to do anything if this is the current view. The BufferView
387 // metrics are already up to date.
388 if (lyx_view_ != guiApp->currentView()
389 || lyx_view_->currentWorkArea() != this) {
390 // FIXME: it would be nice to optimize for the off-screen case.
391 buffer_view_->updateMetrics();
392 buffer_view_->cursor().fixIfBroken();
395 // update cursor position, because otherwise it has to wait until
396 // the blinking interval is over
397 if (cursor_visible_) {
402 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
404 update(0, 0, viewport()->width(), viewport()->height());
406 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
407 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
409 lyx_view_->updateStatusBar();
411 if (lyxerr.debugging(Debug::WORKAREA))
412 buffer_view_->coordCache().dump();
416 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
418 if (lyx_view_->isFullScreen() && lyx_view_->menuBar()->isVisible()) {
419 // FIXME HACK: we should not have to do this here. See related comment
420 // in GuiView::event() (QEvent::ShortcutOverride)
421 lyx_view_->menuBar()->hide();
424 // In order to avoid bad surprise in the middle of an operation,
425 // we better stop the blinking cursor...
426 // the cursor gets restarted in GuiView::restartCursor()
427 stopBlinkingCursor();
429 theLyXFunc().setLyXView(lyx_view_);
430 theLyXFunc().processKeySym(key, mod);
434 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
437 if (cmd0.action == LFUN_FILE_OPEN) {
438 lyx_view_->dispatch(cmd0);
442 theLyXFunc().setLyXView(lyx_view_);
446 if (cmd0.action == LFUN_MOUSE_PRESS) {
447 if (mod == ShiftModifier)
448 cmd = FuncRequest(cmd0, "region-select");
449 else if (mod == ControlModifier)
450 cmd = FuncRequest(cmd0, "paragraph-select");
457 bool const notJustMovingTheMouse =
458 cmd.action != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
460 // In order to avoid bad surprise in the middle of an operation, we better stop
461 // the blinking cursor.
462 if (notJustMovingTheMouse)
463 stopBlinkingCursor();
465 buffer_view_->mouseEventDispatch(cmd);
467 // Skip these when selecting
468 if (cmd.action != LFUN_MOUSE_MOTION) {
469 completer_->updateVisibility(false, false);
470 lyx_view_->updateDialogs();
471 lyx_view_->updateStatusBar();
474 // GUI tweaks except with mouse motion with no button pressed.
475 if (notJustMovingTheMouse) {
476 // Slight hack: this is only called currently when we
477 // clicked somewhere, so we force through the display
478 // of the new status here.
479 lyx_view_->clearMessage();
481 // Show the cursor immediately after any operation
482 startBlinkingCursor();
487 void GuiWorkArea::resizeBufferView()
489 // WARNING: Please don't put any code that will trigger a repaint here!
490 // We are already inside a paint event.
491 lyx_view_->setBusy(true);
492 buffer_view_->resize(viewport()->width(), viewport()->height());
495 // Update scrollbars which might have changed due different
496 // BufferView dimension. This is especially important when the
497 // BufferView goes from zero-size to the real-size for the first time,
498 // as the scrollbar paramters are then set for the first time.
501 lyx_view_->updateLayoutList();
502 lyx_view_->setBusy(false);
503 need_resize_ = false;
507 void GuiWorkArea::showCursor()
513 bool l_shape = false;
514 Font const & realfont = buffer_view_->cursor().real_current_font;
515 BufferParams const & bp = buffer_view_->buffer().params();
516 bool const samelang = realfont.language() == bp.language;
517 bool const isrtl = realfont.isVisibleRightToLeft();
519 if (!samelang || isrtl != bp.language->rightToLeft())
522 // The ERT language hack needs fixing up
523 if (realfont.language() == latex_language)
526 Font const font = buffer_view_->cursor().getFont();
527 FontMetrics const & fm = theFontMetrics(font);
528 int const asc = fm.maxAscent();
529 int const des = fm.maxDescent();
533 Cursor & cur = buffer_view_->cursor();
537 // if it doesn't touch the screen, don't try to show it
538 bool cursorInView = true;
539 if (y + h < 0 || y >= viewport()->height())
540 cursorInView = false;
542 // show cursor on screen
543 bool completable = cur.inset().showCompletionCursor()
544 && completer_->completionAvailable()
545 && !completer_->popupVisible()
546 && !completer_->inlineVisible();
548 cursor_visible_ = true;
549 showCursor(x, y, h, l_shape, isrtl, completable);
554 void GuiWorkArea::hideCursor()
556 if (!cursor_visible_)
559 cursor_visible_ = false;
564 void GuiWorkArea::toggleCursor()
573 void GuiWorkArea::updateScrollbar()
575 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
576 // WARNING: don't touch at the scrollbar value like this:
577 // verticalScrollBar()->setValue(scroll_.position);
578 // because this would cause a recursive signal/slot calling with
579 // GuiWorkArea::scrollTo
580 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
581 verticalScrollBar()->setPageStep(scroll_.page_step);
582 verticalScrollBar()->setSingleStep(scroll_.single_step);
583 verticalScrollBar()->setSliderPosition(scroll_.position);
587 void GuiWorkArea::scrollTo(int value)
589 stopBlinkingCursor();
590 buffer_view_->scrollDocView(value);
592 if (lyxrc.cursor_follows_scrollbar) {
593 buffer_view_->setCursorFromScrollbar();
594 lyx_view_->updateLayoutList();
596 // Show the cursor immediately after any operation.
597 startBlinkingCursor();
598 QApplication::syncX();
602 bool GuiWorkArea::event(QEvent * e)
605 case QEvent::ToolTip: {
606 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
607 if (lyxrc.use_tooltip) {
608 QPoint pos = helpEvent->pos();
609 if (pos.x() < viewport()->width()) {
610 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
611 QToolTip::showText(helpEvent->globalPos(), s);
614 QToolTip::hideText();
616 // Don't forget to accept the event!
621 case QEvent::ShortcutOverride: {
622 // We catch this event in order to catch the Tab or Shift+Tab key press
623 // which are otherwise reserved to focus switching between controls
625 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
626 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
627 || ke->modifiers() & Qt::ControlModifier)
628 return QAbstractScrollArea::event(e);
634 return QAbstractScrollArea::event(e);
640 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
642 QPoint pos = e->pos();
643 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
645 QAbstractScrollArea::contextMenuEvent(e);
648 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
650 QAbstractScrollArea::contextMenuEvent(e);
653 // Position the menu to the right.
654 // FIXME: menu position should be different for RTL text.
655 menu->exec(e->globalPos());
660 void GuiWorkArea::focusInEvent(QFocusEvent * e)
662 if (lyx_view_->currentWorkArea() != this)
663 lyx_view_->setCurrentWorkArea(this);
665 startBlinkingCursor();
666 QAbstractScrollArea::focusInEvent(e);
670 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
672 stopBlinkingCursor();
673 QAbstractScrollArea::focusOutEvent(e);
677 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
679 if (dc_event_.active && dc_event_ == *e) {
680 dc_event_.active = false;
681 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
682 q_button_state(e->button()));
688 inputContext()->reset();
690 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
691 q_button_state(e->button()));
692 dispatch(cmd, q_key_state(e->modifiers()));
697 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
699 if (synthetic_mouse_event_.timeout.running())
700 synthetic_mouse_event_.timeout.stop();
702 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
703 q_button_state(e->button()));
709 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
711 // we kill the triple click if we move
712 doubleClickTimeout();
713 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
714 q_motion_state(e->buttons()));
718 // If we're above or below the work area...
719 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
720 // Make sure only a synthetic event can cause a page scroll,
721 // so they come at a steady rate:
723 // _Force_ a scroll up:
726 cmd.y = viewport()->height();
727 // Store the event, to be handled when the timeout expires.
728 synthetic_mouse_event_.cmd = cmd;
730 if (synthetic_mouse_event_.timeout.running())
731 // Discard the event. Note that it _may_ be handled
732 // when the timeout expires if
733 // synthetic_mouse_event_.cmd has not been overwritten.
734 // Ie, when the timeout expires, we handle the
735 // most recent event but discard all others that
736 // occurred after the one used to start the timeout
737 // in the first place.
740 synthetic_mouse_event_.restart_timeout = true;
741 synthetic_mouse_event_.timeout.start();
742 // Fall through to handle this event...
744 } else if (synthetic_mouse_event_.timeout.running()) {
745 // Store the event, to be possibly handled when the timeout
747 // Once the timeout has expired, normal control is returned
748 // to mouseMoveEvent (restart_timeout = false).
749 // This results in a much smoother 'feel' when moving the
750 // mouse back into the work area.
751 synthetic_mouse_event_.cmd = cmd;
752 synthetic_mouse_event_.restart_timeout = false;
756 // Has anything changed on-screen since the last QMouseEvent
758 double const scrollbar_value = verticalScrollBar()->value();
759 if (e->x() == synthetic_mouse_event_.x_old
760 && e->y() == synthetic_mouse_event_.y_old
761 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
762 // Nothing changed on-screen since the last QMouseEvent.
766 // Yes something has changed. Store the params used to check this.
767 synthetic_mouse_event_.x_old = e->x();
768 synthetic_mouse_event_.y_old = e->y();
769 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
771 // ... and dispatch the event to the LyX core.
776 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
778 // Wheel rotation by one notch results in a delta() of 120 (see
779 // documentation of QWheelEvent)
780 int const delta = ev->delta() / 120;
781 if (ev->modifiers() & Qt::ControlModifier) {
782 lyxrc.zoom += 5 * delta;
785 // The global QPixmapCache is used in GuiPainter to cache text
786 // painting so we must reset it.
787 QPixmapCache::clear();
788 guiApp->fontLoader().update();
790 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
794 // Take into account the desktop wide settings.
795 int const lines = qApp->wheelScrollLines();
796 int const page_step = verticalScrollBar()->pageStep();
797 // Test if the wheel mouse is set to one screen at a time.
798 int scroll_value = lines > page_step
799 ? page_step : lines * verticalScrollBar()->singleStep();
801 // Take into account the rotation.
802 scroll_value *= delta;
804 // Take into account user preference.
805 scroll_value *= lyxrc.mouse_wheel_speed;
806 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
807 << " delta = " << delta << " scroll_value = " << scroll_value
808 << " page_step = " << page_step);
810 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
816 void GuiWorkArea::generateSyntheticMouseEvent()
818 // Set things off to generate the _next_ 'pseudo' event.
819 if (synthetic_mouse_event_.restart_timeout)
820 synthetic_mouse_event_.timeout.start();
822 // Has anything changed on-screen since the last timeout signal
824 double const scrollbar_value = verticalScrollBar()->value();
825 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
826 // Yes it has. Store the params used to check this.
827 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
829 // ... and dispatch the event to the LyX core.
830 dispatch(synthetic_mouse_event_.cmd);
835 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
837 // intercept some keys if completion popup is visible
838 if (completer_->popupVisible()) {
842 completer_->activate();
848 // intercept keys for the completion
849 if (ev->key() == Qt::Key_Tab) {
855 if (completer_->popupVisible() && ev->key() == Qt::Key_Escape) {
856 completer_->hidePopup();
861 if (completer_->inlineVisible() && ev->key() == Qt::Key_Escape) {
862 completer_->hideInline();
867 // do nothing if there are other events
868 // (the auto repeated events come too fast)
869 // \todo FIXME: remove hard coded Qt keys, process the key binding
871 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
872 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
873 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
879 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
880 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
883 setKeySymbol(&sym, ev);
884 processKeySym(sym, q_key_state(ev->modifiers()));
889 void GuiWorkArea::doubleClickTimeout()
891 dc_event_.active = false;
895 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
897 dc_event_ = DoubleClick(ev);
898 QTimer::singleShot(QApplication::doubleClickInterval(), this,
899 SLOT(doubleClickTimeout()));
900 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
902 q_button_state(ev->button()));
908 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
910 QAbstractScrollArea::resizeEvent(ev);
916 void GuiWorkArea::update(int x, int y, int w, int h)
918 viewport()->repaint(x, y, w, h);
922 void GuiWorkArea::paintEvent(QPaintEvent * ev)
924 QRect const rc = ev->rect();
925 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
926 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
929 screen_ = QPixmap(viewport()->width(), viewport()->height());
935 QPainter pain(viewport());
936 pain.drawPixmap(rc, screen_, rc);
942 void GuiWorkArea::updateScreen()
944 GuiPainter pain(&screen_);
945 buffer_view_->draw(pain);
949 void GuiWorkArea::showCursor(int x, int y, int h,
950 bool l_shape, bool rtl, bool completable)
952 if (schedule_redraw_) {
953 // This happens when a graphic conversion is finished. As we don't know
954 // the size of the new graphics, it's better the update everything.
955 // We can't use redraw() here because this would trigger a infinite
956 // recursive loop with showCursor().
957 buffer_view_->resize(viewport()->width(), viewport()->height());
960 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
961 schedule_redraw_ = false;
962 // Show the cursor immediately after the update.
968 cursor_->update(x, y, h, l_shape, rtl, completable);
970 viewport()->update(cursor_->rect());
974 void GuiWorkArea::removeCursor()
977 //if (!qApp->focusWidget())
978 viewport()->update(cursor_->rect());
982 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
984 QString const & commit_string = e->commitString();
985 docstring const & preedit_string
986 = qstring_to_ucs4(e->preeditString());
988 if (!commit_string.isEmpty()) {
990 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
991 << " commitString: " << e->commitString());
995 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
996 for (int i = 0; i != commit_string.size(); ++i) {
997 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1002 // Hide the cursor during the kana-kanji transformation.
1003 if (preedit_string.empty())
1004 startBlinkingCursor();
1006 stopBlinkingCursor();
1008 // last_width : for checking if last preedit string was/wasn't empty.
1009 static bool last_width = false;
1010 if (!last_width && preedit_string.empty()) {
1011 // if last_width is last length of preedit string.
1016 GuiPainter pain(&screen_);
1017 buffer_view_->updateMetrics();
1018 buffer_view_->draw(pain);
1019 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1020 FontMetrics const & fm = theFontMetrics(font);
1021 int height = fm.maxHeight();
1022 int cur_x = cursor_->rect().left();
1023 int cur_y = cursor_->rect().bottom();
1025 // redraw area of preedit string.
1026 update(0, cur_y - height, viewport()->width(),
1027 (height + 1) * preedit_lines_);
1029 if (preedit_string.empty()) {
1037 // att : stores an IM attribute.
1038 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1040 // get attributes of input method cursor.
1041 // cursor_pos : cursor position in preedit string.
1042 size_t cursor_pos = 0;
1043 bool cursor_is_visible = false;
1044 for (int i = 0; i != att.size(); ++i) {
1045 if (att.at(i).type == QInputMethodEvent::Cursor) {
1046 cursor_pos = att.at(i).start;
1047 cursor_is_visible = att.at(i).length != 0;
1052 size_t preedit_length = preedit_string.length();
1054 // get position of selection in input method.
1055 // FIXME: isn't there a way to do this simplier?
1056 // rStart : cursor position in selected string in IM.
1058 // rLength : selected string length in IM.
1060 if (cursor_pos < preedit_length) {
1061 for (int i = 0; i != att.size(); ++i) {
1062 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1063 if (att.at(i).start <= int(cursor_pos)
1064 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1065 rStart = att.at(i).start;
1066 rLength = att.at(i).length;
1067 if (!cursor_is_visible)
1068 cursor_pos += rLength;
1075 rStart = cursor_pos;
1079 int const right_margin = buffer_view_->rightMargin();
1080 Painter::preedit_style ps;
1081 // Most often there would be only one line:
1083 for (size_t pos = 0; pos != preedit_length; ++pos) {
1084 char_type const typed_char = preedit_string[pos];
1085 // reset preedit string style
1086 ps = Painter::preedit_default;
1088 // if we reached the right extremity of the screen, go to next line.
1089 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1090 cur_x = right_margin;
1091 cur_y += height + 1;
1094 // preedit strings are displayed with dashed underline
1095 // and partial strings are displayed white on black indicating
1096 // that we are in selecting mode in the input method.
1097 // FIXME: rLength == preedit_length is not a changing condition
1098 // FIXME: should be put out of the loop.
1100 && pos < rStart + rLength
1101 && !(cursor_pos < rLength && rLength == preedit_length))
1102 ps = Painter::preedit_selecting;
1104 if (pos == cursor_pos
1105 && (cursor_pos < rLength && rLength == preedit_length))
1106 ps = Painter::preedit_cursor;
1108 // draw one character and update cur_x.
1109 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1112 // update the preedit string screen area.
1113 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1114 (height + 1) * preedit_lines_);
1116 // Don't forget to accept the event!
1121 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1123 QRect cur_r(0,0,0,0);
1125 // this is the CJK-specific composition window position.
1126 case Qt::ImMicroFocus:
1127 cur_r = cursor_->rect();
1128 if (preedit_lines_ != 1)
1130 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1131 // return lower right of cursor in LyX.
1134 return QWidget::inputMethodQuery(query);
1139 void GuiWorkArea::updateWindowTitle()
1141 docstring maximize_title;
1142 docstring minimize_title;
1144 Buffer & buf = buffer_view_->buffer();
1145 FileName const fileName = buf.fileName();
1146 if (!fileName.empty()) {
1147 maximize_title = fileName.displayName(30);
1148 minimize_title = from_utf8(fileName.onlyFileName());
1149 if (!buf.isClean()) {
1150 maximize_title += _(" (changed)");
1151 minimize_title += char_type('*');
1153 if (buf.isReadonly())
1154 maximize_title += _(" (read only)");
1157 QString title = windowTitle();
1158 QString new_title = toqstr(maximize_title);
1159 if (title == new_title)
1162 QWidget::setWindowTitle(new_title);
1163 QWidget::setWindowIconText(toqstr(minimize_title));
1168 void GuiWorkArea::setReadOnly(bool)
1170 updateWindowTitle();
1171 if (this == lyx_view_->currentWorkArea())
1172 lyx_view_->updateDialogs();
1176 bool GuiWorkArea::isFullScreen()
1178 return lyx_view_ && lyx_view_->isFullScreen();
1182 ////////////////////////////////////////////////////////////////////
1186 ////////////////////////////////////////////////////////////////////
1189 class NoTabFrameMacStyle : public QMacStyle {
1192 QRect subElementRect(SubElement element, const QStyleOption * option,
1193 const QWidget * widget = 0) const
1195 QRect rect = QMacStyle::subElementRect(element, option, widget);
1196 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1198 // The Qt Mac style puts the contents into a 3 pixel wide box
1199 // which looks very ugly and not like other Mac applications.
1200 // Hence we remove this here, and moreover the 16 pixel round
1201 // frame above if the tab bar is hidden.
1202 if (element == QStyle::SE_TabWidgetTabContents) {
1203 rect.adjust(- rect.left(), 0, rect.left(), 0);
1212 NoTabFrameMacStyle noTabFrameMacStyle;
1216 TabWorkArea::TabWorkArea(QWidget * parent)
1217 : QTabWidget(parent), clicked_tab_(-1)
1220 setStyle(&noTabFrameMacStyle);
1223 QPalette pal = palette();
1224 pal.setColor(QPalette::Active, QPalette::Button,
1225 pal.color(QPalette::Active, QPalette::Window));
1226 pal.setColor(QPalette::Disabled, QPalette::Button,
1227 pal.color(QPalette::Disabled, QPalette::Window));
1228 pal.setColor(QPalette::Inactive, QPalette::Button,
1229 pal.color(QPalette::Inactive, QPalette::Window));
1231 QObject::connect(this, SIGNAL(currentChanged(int)),
1232 this, SLOT(on_currentTabChanged(int)));
1234 QToolButton * closeBufferButton = new QToolButton(this);
1235 closeBufferButton->setPalette(pal);
1236 // FIXME: rename the icon to closebuffer.png
1237 closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1238 closeBufferButton->setText("Close File");
1239 closeBufferButton->setAutoRaise(true);
1240 closeBufferButton->setCursor(Qt::ArrowCursor);
1241 closeBufferButton->setToolTip(qt_("Close File"));
1242 closeBufferButton->setEnabled(true);
1243 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1244 this, SLOT(closeCurrentBuffer()));
1245 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1247 // setup drag'n'drop
1248 QTabBar* tb = new DragTabBar;
1249 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1250 this, SLOT(moveTab(int, int)));
1251 tb->setElideMode(Qt::ElideNone);
1254 // make us responsible for the context menu of the tabbar
1255 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1256 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1257 this, SLOT(showContextMenu(const QPoint &)));
1259 setUsesScrollButtons(true);
1263 void TabWorkArea::setFullScreen(bool full_screen)
1265 for (int i = 0; i != count(); ++i) {
1266 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1267 wa->setFullScreen(full_screen);
1270 if (lyxrc.full_screen_tabbar)
1271 showBar(!full_screen && count()>1);
1275 void TabWorkArea::showBar(bool show)
1277 tabBar()->setEnabled(show);
1278 tabBar()->setVisible(show);
1282 GuiWorkArea * TabWorkArea::currentWorkArea()
1287 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1293 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1295 for (int i = 0; i != count(); ++i) {
1296 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1297 LASSERT(wa, return 0);
1298 if (&wa->bufferView().buffer() == &buffer)
1305 void TabWorkArea::closeAll()
1308 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1316 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1318 LASSERT(work_area, /**/);
1319 int index = indexOf(work_area);
1323 if (index == currentIndex())
1324 // Make sure the work area is up to date.
1325 on_currentTabChanged(index);
1327 // Switch to the work area.
1328 setCurrentIndex(index);
1329 work_area->setFocus();
1335 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1337 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1338 wa->setUpdatesEnabled(false);
1339 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1340 // when hiding it again below).
1341 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1342 showBar(count() > 0);
1343 addTab(wa, wa->windowTitle());
1344 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1345 this, SLOT(updateTabTexts()));
1346 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1347 setFullScreen(true);
1349 // Hide tabbar if there's only one tab.
1350 showBar(count() > 1);
1358 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1360 LASSERT(work_area, return false);
1361 int index = indexOf(work_area);
1365 work_area->setUpdatesEnabled(false);
1370 // make sure the next work area is enabled.
1371 currentWidget()->setUpdatesEnabled(true);
1372 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1373 setFullScreen(true);
1375 // Hide tabbar if there's only one tab.
1376 showBar(count() > 1);
1378 lastWorkAreaRemoved();
1387 void TabWorkArea::on_currentTabChanged(int i)
1389 // returns e.g. on application destruction
1392 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1393 LASSERT(wa, return);
1394 BufferView & bv = wa->bufferView();
1395 bv.cursor().fixIfBroken();
1397 wa->setUpdatesEnabled(true);
1401 currentWorkAreaChanged(wa);
1403 LYXERR(Debug::GUI, "currentTabChanged " << i
1404 << "File" << bv.buffer().absFileName());
1408 void TabWorkArea::closeCurrentBuffer()
1410 if (clicked_tab_ != -1)
1411 setCurrentIndex(clicked_tab_);
1413 lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1417 void TabWorkArea::closeCurrentTab()
1419 if (clicked_tab_ == -1)
1420 removeWorkArea(currentWorkArea());
1422 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1431 /// make vector happy
1434 DisplayPath(int tab, FileName const & filename)
1437 filename_ = toqstr(filename.onlyFileNameWithoutExt());
1438 postfix_ = toqstr(filename.absoluteFilePath()).
1439 split("/", QString::SkipEmptyParts);
1440 postfix_.pop_back();
1441 abs_ = toqstr(filename.absoluteFilePath());
1442 dottedPrefix_ = false;
1445 /// Absolute path for debugging.
1450 /// Add the first segment from the postfix or three dots to the prefix.
1451 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1452 /// when really needed.
1453 void shiftPathSegment(bool dotted)
1455 if (postfix_.count() <= 0)
1459 if (dottedPrefix_ && !prefix_.isEmpty())
1461 prefix_ += postfix_.front() + "/";
1463 dottedPrefix_ = dotted && !prefix_.isEmpty();
1464 postfix_.pop_front();
1467 QString displayString() const
1469 if (prefix_.isEmpty())
1472 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1473 return prefix_ + (dots ? ".../" : "") + filename_;
1476 QString forecastPathString() const
1478 if (postfix_.count() == 0)
1479 return displayString();
1482 + (dottedPrefix_ ? ".../" : "")
1483 + postfix_.front() + "/";
1486 bool final() const { return postfix_.empty(); }
1488 int tab() const { return tab_; }
1494 QStringList postfix_;
1507 bool operator<(DisplayPath const & a, DisplayPath const & b)
1509 return a.displayString() < b.displayString();
1513 bool operator==(DisplayPath const & a, DisplayPath const & b)
1515 return a.displayString() == b.displayString();
1519 void TabWorkArea::updateTabTexts()
1524 std::list<DisplayPath> paths;
1525 typedef std::list<DisplayPath>::iterator It;
1527 // collect full names first: path into postfix, empty prefix and
1528 // filename without extension
1529 for (size_t i = 0; i < n; ++i) {
1530 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(i));
1531 FileName const fn = i_wa->bufferView().buffer().fileName();
1532 paths.push_back(DisplayPath(i, fn));
1535 // go through path segments and see if it helps to make the path more unique
1536 bool somethingChanged = true;
1537 bool allFinal = false;
1538 while (somethingChanged && !allFinal) {
1539 // adding path segments changes order
1542 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1543 somethingChanged = false;
1546 // find segments which are not unique (i.e. non-atomic)
1547 It it = paths.begin();
1549 QString segString = it->displayString();
1550 for (; it != paths.end(); ++it) {
1551 // look to the next item
1556 allFinal = allFinal && it->final();
1558 LYXERR(Debug::GUI, "it = " << it->abs()
1559 << " => " << it->displayString());
1561 // still the same segment?
1563 if ((next != paths.end()
1564 && (nextString = next->displayString()) == segString))
1566 LYXERR(Debug::GUI, "segment ended");
1568 // only a trivial one with one element?
1569 if (it == segStart) {
1570 // start new segment
1572 segString = nextString;
1576 // we found a non-atomic segment segStart <= sit <= it < next.
1577 // Shift path segments and hope for the best
1578 // that it makes the path more unique.
1579 somethingChanged = true;
1581 QString dspString = sit->forecastPathString();
1582 LYXERR(Debug::GUI, "first forecast found for "
1583 << sit->abs() << " => " << dspString);
1585 bool moreUnique = false;
1586 for (; sit != next; ++sit) {
1587 if (sit->forecastPathString() != dspString) {
1588 LYXERR(Debug::GUI, "different forecast found for "
1589 << sit->abs() << " => " << sit->forecastPathString());
1593 LYXERR(Debug::GUI, "same forecast found for "
1594 << sit->abs() << " => " << dspString);
1597 // if the path segment helped, add it. Otherwise add dots
1598 bool dots = !moreUnique;
1599 LYXERR(Debug::GUI, "using dots = " << dots);
1600 for (sit = segStart; sit != next; ++sit) {
1601 sit->shiftPathSegment(dots);
1602 LYXERR(Debug::GUI, "shifting "
1603 << sit->abs() << " => " << sit->displayString());
1606 // start new segment
1608 segString = nextString;
1612 // set new tab titles
1613 for (It it = paths.begin(); it != paths.end(); ++it) {
1614 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(it->tab()));
1615 Buffer & buf = i_wa->bufferView().buffer();
1616 if (!buf.fileName().empty() && !buf.isClean())
1617 setTabText(it->tab(), it->displayString() + "*");
1619 setTabText(it->tab(), it->displayString());
1624 void TabWorkArea::showContextMenu(const QPoint & pos)
1627 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1628 if (clicked_tab_ == -1)
1633 popup.addAction(QIcon(":/images/hidetab.png"),
1634 qt_("Hide tab"), this, SLOT(closeCurrentTab()));
1635 popup.addAction(QIcon(":/images/closetab.png"),
1636 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1637 popup.exec(tabBar()->mapToGlobal(pos));
1643 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1645 QWidget * w = widget(fromIndex);
1646 QIcon icon = tabIcon(fromIndex);
1647 QString text = tabText(fromIndex);
1649 setCurrentIndex(fromIndex);
1650 removeTab(fromIndex);
1651 insertTab(toIndex, w, icon, text);
1652 setCurrentIndex(toIndex);
1656 DragTabBar::DragTabBar(QWidget* parent)
1659 setAcceptDrops(true);
1663 #if QT_VERSION < 0x040300
1664 int DragTabBar::tabAt(QPoint const & position) const
1666 const int max = count();
1667 for (int i = 0; i < max; ++i) {
1668 if (tabRect(i).contains(position))
1676 void DragTabBar::mousePressEvent(QMouseEvent * event)
1678 if (event->button() == Qt::LeftButton)
1679 dragStartPos_ = event->pos();
1680 QTabBar::mousePressEvent(event);
1684 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1686 // If the left button isn't pressed anymore then return
1687 if (!(event->buttons() & Qt::LeftButton))
1690 // If the distance is too small then return
1691 if ((event->pos() - dragStartPos_).manhattanLength()
1692 < QApplication::startDragDistance())
1695 // did we hit something after all?
1696 int tab = tabAt(dragStartPos_);
1700 // simulate button release to remove highlight from button
1701 int i = currentIndex();
1702 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1703 event->button(), event->buttons(), 0);
1704 QTabBar::mouseReleaseEvent(&me);
1708 QDrag * drag = new QDrag(this);
1709 QMimeData * mimeData = new QMimeData;
1710 // a crude way to distinguish tab-reodering drops from other ones
1711 mimeData->setData("action", "tab-reordering") ;
1712 drag->setMimeData(mimeData);
1714 #if QT_VERSION >= 0x040300
1715 // get tab pixmap as cursor
1716 QRect r = tabRect(tab);
1717 QPixmap pixmap(r.size());
1718 render(&pixmap, - r.topLeft());
1719 drag->setPixmap(pixmap);
1722 drag->start(Qt::MoveAction);
1728 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1730 // Only accept if it's an tab-reordering request
1731 QMimeData const * m = event->mimeData();
1732 QStringList formats = m->formats();
1733 if (formats.contains("action")
1734 && m->data("action") == "tab-reordering")
1735 event->acceptProposedAction();
1739 void DragTabBar::dropEvent(QDropEvent * event)
1741 int fromIndex = tabAt(dragStartPos_);
1742 int toIndex = tabAt(event->pos());
1744 // Tell interested objects that
1745 if (fromIndex != toIndex)
1746 tabMoveRequested(fromIndex, toIndex);
1747 event->acceptProposedAction();
1751 } // namespace frontend
1754 #include "GuiWorkArea_moc.cpp"