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"
37 #include "MetricsInfo.h"
38 #include "qt_helpers.h"
42 #include "graphics/GraphicsImage.h"
43 #include "graphics/GraphicsLoader.h"
45 #include "support/debug.h"
46 #include "support/gettext.h"
47 #include "support/FileName.h"
49 #include "frontends/Application.h"
50 #include "frontends/FontMetrics.h"
51 #include "frontends/WorkAreaManager.h"
53 #include <QContextMenuEvent>
54 #include <QInputContext>
59 #include <QMainWindow>
63 #include <QPixmapCache>
66 #include <QToolButton>
70 #include <boost/bind.hpp>
76 extern "C" int XEventsQueued(Display *display, int mode);
80 int const CursorWidth = 2;
82 int const CursorWidth = 1;
84 int const TabIndicatorWidth = 3;
90 using namespace lyx::support;
95 /// return the LyX mouse button state from Qt's
96 static mouse_button::state q_button_state(Qt::MouseButton button)
98 mouse_button::state b = mouse_button::none;
101 b = mouse_button::button1;
104 b = mouse_button::button2;
106 case Qt::RightButton:
107 b = mouse_button::button3;
116 /// return the LyX mouse button state from Qt's
117 mouse_button::state q_motion_state(Qt::MouseButtons state)
119 mouse_button::state b = mouse_button::none;
120 if (state & Qt::LeftButton)
121 b |= mouse_button::button1;
122 if (state & Qt::MidButton)
123 b |= mouse_button::button2;
124 if (state & Qt::RightButton)
125 b |= mouse_button::button3;
136 void draw(QPainter & painter)
138 if (!show_ || !rect_.isValid())
142 int l = x_ - rect_.left();
143 int r = rect_.right() - x_;
144 int bot = rect_.bottom();
146 // draw vertica linel
147 painter.fillRect(x_, y, CursorWidth, rect_.height(), color_);
149 // draw RTL/LTR indication
150 painter.setPen(color_);
153 painter.drawLine(x_, bot, x_ - l, bot);
155 painter.drawLine(x_, bot, x_ + CursorWidth + r, bot);
158 // draw completion triangle
160 int m = y + rect_.height() / 2;
161 int d = TabIndicatorWidth - 1;
163 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
164 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
166 painter.drawLine(x_ + CursorWidth, m - d, x_ + CursorWidth + d, m);
167 painter.drawLine(x_ + CursorWidth, m + d, x_ + CursorWidth + d, m);
172 void update(int x, int y, int h, bool l_shape,
173 bool rtl, bool completable)
175 color_ = guiApp->colorCache().get(Color_cursor);
178 completable_ = completable;
181 // extension to left and right
185 // RTL/LTR indication
193 // completion triangle
196 l = max(l, TabIndicatorWidth);
198 r = max(r, TabIndicatorWidth);
201 // compute overall rectangle
202 rect_ = QRect(x - l, y, CursorWidth + r + l, h);
205 void show(bool set_show = true) { show_ = set_show; }
206 void hide() { show_ = false; }
208 QRect const & rect() { return rect_; }
211 /// cursor is in RTL or LTR text
213 /// indication for RTL or LTR
215 /// triangle to show that a completion is available
221 /// rectangle, possibly with l_shape and completion triangle
223 /// x position (were the vertical line is drawn)
228 // This is a 'heartbeat' generating synthetic mouse move events when the
229 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
230 SyntheticMouseEvent::SyntheticMouseEvent()
231 : timeout(200), restart_timeout(true),
232 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
236 GuiWorkArea::GuiWorkArea(QWidget *)
237 : buffer_view_(0), lyx_view_(0),
238 cursor_visible_(false),
239 need_resize_(false), schedule_redraw_(false),
240 preedit_lines_(1), completer_(new GuiCompleter(this))
245 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
246 : buffer_view_(0), lyx_view_(0),
247 cursor_visible_(false),
248 need_resize_(false), schedule_redraw_(false),
249 preedit_lines_(1), completer_(new GuiCompleter(this))
256 void GuiWorkArea::init()
259 connect(&cursor_timeout_, SIGNAL(timeout()),
260 this, SLOT(toggleCursor()));
262 int const time = QApplication::cursorFlashTime() / 2;
264 cursor_timeout_.setInterval(time);
265 cursor_timeout_.start();
267 // let's initialize this just to be safe
268 cursor_timeout_.setInterval(500);
271 screen_ = QPixmap(viewport()->width(), viewport()->height());
272 cursor_ = new frontend::CursorWidget();
275 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
276 setAcceptDrops(true);
277 setMouseTracking(true);
278 setMinimumSize(100, 70);
280 setFrameStyle(QFrame::NoFrame);
282 setFrameStyle(QFrame::Box);
286 viewport()->setAutoFillBackground(false);
287 // We don't need double-buffering nor SystemBackground on
288 // the viewport because we have our own backing pixmap.
289 viewport()->setAttribute(Qt::WA_NoSystemBackground);
291 setFocusPolicy(Qt::StrongFocus);
293 viewport()->setCursor(Qt::IBeamCursor);
295 synthetic_mouse_event_.timeout.timeout.connect(
296 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
299 // Initialize the vertical Scroll Bar
300 QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
301 this, SLOT(scrollTo(int)));
303 LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
304 << " viewport height: " << viewport()->height());
306 // Enables input methods for asian languages.
307 // Must be set when creating custom text editing widgets.
308 setAttribute(Qt::WA_InputMethodEnabled, true);
310 dialog_mode_ = false;
314 GuiWorkArea::~GuiWorkArea()
316 buffer_view_->buffer().workAreaManager().remove(this);
319 // Completer has a QObject parent and is thus automatically destroyed.
320 // delete completer_;
324 void GuiWorkArea::setGuiView(GuiView & gv)
330 void GuiWorkArea::setBuffer(Buffer & buffer)
333 buffer_view_ = new BufferView(buffer),
334 buffer.workAreaManager().add(this);
336 // HACK: Prevents an additional redraw when the scrollbar pops up
337 // which regularily happens on documents with more than one page.
338 // The policy should be set to "Qt::ScrollBarAsNeeded" soon.
339 // Since we have no geometry information yet, we assume that
340 // a document needs a scrollbar if there is more then four
341 // paragraph in the outermost text.
342 if (buffer.text().paragraphs().size() > 4)
343 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
344 QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
349 void GuiWorkArea::fixVerticalScrollBar()
352 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
356 void GuiWorkArea::close()
358 lyx_view_->removeWorkArea(this);
362 void GuiWorkArea::setFullScreen(bool full_screen)
364 buffer_view_->setFullScreen(full_screen);
366 setFrameStyle(QFrame::NoFrame);
367 if (lyxrc.full_screen_scrollbar)
368 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
371 setFrameStyle(QFrame::NoFrame);
373 setFrameStyle(QFrame::Box);
375 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
380 BufferView & GuiWorkArea::bufferView()
382 return *buffer_view_;
386 BufferView const & GuiWorkArea::bufferView() const
388 return *buffer_view_;
392 void GuiWorkArea::stopBlinkingCursor()
394 cursor_timeout_.stop();
399 void GuiWorkArea::startBlinkingCursor()
402 //we're not supposed to cache this value.
403 int const time = QApplication::cursorFlashTime() / 2;
406 cursor_timeout_.setInterval(time);
407 cursor_timeout_.start();
411 void GuiWorkArea::redraw()
414 // No need to redraw in this case.
417 // No need to do anything if this is the current view. The BufferView
418 // metrics are already up to date.
419 if (lyx_view_ != guiApp->currentView()
420 || lyx_view_->currentWorkArea() != this) {
421 // FIXME: it would be nice to optimize for the off-screen case.
422 buffer_view_->updateMetrics();
423 buffer_view_->cursor().fixIfBroken();
426 // update cursor position, because otherwise it has to wait until
427 // the blinking interval is over
428 if (cursor_visible_) {
433 LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
435 update(0, 0, viewport()->width(), viewport()->height());
437 /// \warning: scrollbar updating *must* be done after the BufferView is drawn
438 /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
440 lyx_view_->updateStatusBar();
442 if (lyxerr.debugging(Debug::WORKAREA))
443 buffer_view_->coordCache().dump();
447 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
449 if (lyx_view_->isFullScreen() && lyx_view_->menuBar()->isVisible()) {
450 // FIXME HACK: we should not have to do this here. See related comment
451 // in GuiView::event() (QEvent::ShortcutOverride)
452 lyx_view_->menuBar()->hide();
455 // In order to avoid bad surprise in the middle of an operation,
456 // we better stop the blinking cursor...
457 // the cursor gets restarted in GuiView::restartCursor()
458 stopBlinkingCursor();
460 theLyXFunc().setLyXView(lyx_view_);
461 theLyXFunc().processKeySym(key, mod);
465 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
468 if (cmd0.action == LFUN_FILE_OPEN) {
469 lyx_view_->dispatch(cmd0);
473 theLyXFunc().setLyXView(lyx_view_);
477 if (cmd0.action == LFUN_MOUSE_PRESS) {
478 if (mod == ShiftModifier)
479 cmd = FuncRequest(cmd0, "region-select");
480 else if (mod == ControlModifier)
481 cmd = FuncRequest(cmd0, "paragraph-select");
488 bool const notJustMovingTheMouse =
489 cmd.action != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
491 // In order to avoid bad surprise in the middle of an operation, we better stop
492 // the blinking cursor.
493 if (notJustMovingTheMouse)
494 stopBlinkingCursor();
496 buffer_view_->mouseEventDispatch(cmd);
498 // Skip these when selecting
499 if (cmd.action != LFUN_MOUSE_MOTION) {
500 completer_->updateVisibility(false, false);
501 lyx_view_->updateDialogs();
502 lyx_view_->updateStatusBar();
505 // GUI tweaks except with mouse motion with no button pressed.
506 if (notJustMovingTheMouse) {
507 // Slight hack: this is only called currently when we
508 // clicked somewhere, so we force through the display
509 // of the new status here.
510 lyx_view_->clearMessage();
512 // Show the cursor immediately after any operation
513 startBlinkingCursor();
518 void GuiWorkArea::resizeBufferView()
520 // WARNING: Please don't put any code that will trigger a repaint here!
521 // We are already inside a paint event.
522 lyx_view_->setBusy(true);
523 buffer_view_->resize(viewport()->width(), viewport()->height());
526 // Update scrollbars which might have changed due different
527 // BufferView dimension. This is especially important when the
528 // BufferView goes from zero-size to the real-size for the first time,
529 // as the scrollbar paramters are then set for the first time.
532 lyx_view_->updateLayoutList();
533 lyx_view_->setBusy(false);
534 need_resize_ = false;
538 void GuiWorkArea::showCursor()
544 bool l_shape = false;
545 Font const & realfont = buffer_view_->cursor().real_current_font;
546 BufferParams const & bp = buffer_view_->buffer().params();
547 bool const samelang = realfont.language() == bp.language;
548 bool const isrtl = realfont.isVisibleRightToLeft();
550 if (!samelang || isrtl != bp.language->rightToLeft())
553 // The ERT language hack needs fixing up
554 if (realfont.language() == latex_language)
557 Font const font = buffer_view_->cursor().getFont();
558 FontMetrics const & fm = theFontMetrics(font);
559 int const asc = fm.maxAscent();
560 int const des = fm.maxDescent();
564 Cursor & cur = buffer_view_->cursor();
568 // if it doesn't touch the screen, don't try to show it
569 bool cursorInView = true;
570 if (y + h < 0 || y >= viewport()->height()
571 || !cur.bv().paragraphVisible(cur))
572 cursorInView = false;
574 // show cursor on screen
575 bool completable = cur.inset().showCompletionCursor()
576 && completer_->completionAvailable()
577 && !completer_->popupVisible()
578 && !completer_->inlineVisible();
580 cursor_visible_ = true;
581 showCursor(x, y, h, l_shape, isrtl, completable);
586 void GuiWorkArea::hideCursor()
588 if (!cursor_visible_)
591 cursor_visible_ = false;
596 void GuiWorkArea::toggleCursor()
605 void GuiWorkArea::updateScrollbar()
607 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
608 // WARNING: don't touch at the scrollbar value like this:
609 // verticalScrollBar()->setValue(scroll_.position);
610 // because this would cause a recursive signal/slot calling with
611 // GuiWorkArea::scrollTo
612 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
613 verticalScrollBar()->setPageStep(scroll_.page_step);
614 verticalScrollBar()->setSingleStep(scroll_.single_step);
615 verticalScrollBar()->setSliderPosition(scroll_.position);
619 void GuiWorkArea::scrollTo(int value)
621 stopBlinkingCursor();
622 buffer_view_->scrollDocView(value);
624 if (lyxrc.cursor_follows_scrollbar) {
625 buffer_view_->setCursorFromScrollbar();
626 lyx_view_->updateLayoutList();
628 // Show the cursor immediately after any operation.
629 startBlinkingCursor();
630 QApplication::syncX();
634 bool GuiWorkArea::event(QEvent * e)
637 case QEvent::ToolTip: {
638 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
639 if (lyxrc.use_tooltip) {
640 QPoint pos = helpEvent->pos();
641 if (pos.x() < viewport()->width()) {
642 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
643 QToolTip::showText(helpEvent->globalPos(), s);
646 QToolTip::hideText();
648 // Don't forget to accept the event!
653 case QEvent::ShortcutOverride: {
654 // We catch this event in order to catch the Tab or Shift+Tab key press
655 // which are otherwise reserved to focus switching between controls
657 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
658 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
659 || ke->modifiers() & Qt::ControlModifier)
660 return QAbstractScrollArea::event(e);
666 return QAbstractScrollArea::event(e);
672 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
674 QPoint pos = e->pos();
675 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
677 QAbstractScrollArea::contextMenuEvent(e);
680 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
682 QAbstractScrollArea::contextMenuEvent(e);
685 // Position the menu to the right.
686 // FIXME: menu position should be different for RTL text.
687 menu->exec(e->globalPos());
692 void GuiWorkArea::focusInEvent(QFocusEvent * e)
695 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << std::endl);
696 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
698 old_gwa->stopBlinkingCursor();
699 lyx_view_->setCurrentWorkArea(this);
702 if (lyx_view_->currentWorkArea() != this)
703 lyx_view_->setCurrentWorkArea(this);
705 startBlinkingCursor();
706 QAbstractScrollArea::focusInEvent(e);
710 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
712 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << std::endl);
713 stopBlinkingCursor();
714 QAbstractScrollArea::focusOutEvent(e);
718 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
720 if (dc_event_.active && dc_event_ == *e) {
721 dc_event_.active = false;
722 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
723 q_button_state(e->button()));
729 inputContext()->reset();
731 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
732 q_button_state(e->button()));
733 dispatch(cmd, q_key_state(e->modifiers()));
738 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
740 if (synthetic_mouse_event_.timeout.running())
741 synthetic_mouse_event_.timeout.stop();
743 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
744 q_button_state(e->button()));
750 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
752 // we kill the triple click if we move
753 doubleClickTimeout();
754 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
755 q_motion_state(e->buttons()));
759 // If we're above or below the work area...
760 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
761 // Make sure only a synthetic event can cause a page scroll,
762 // so they come at a steady rate:
764 // _Force_ a scroll up:
767 cmd.y = viewport()->height();
768 // Store the event, to be handled when the timeout expires.
769 synthetic_mouse_event_.cmd = cmd;
771 if (synthetic_mouse_event_.timeout.running())
772 // Discard the event. Note that it _may_ be handled
773 // when the timeout expires if
774 // synthetic_mouse_event_.cmd has not been overwritten.
775 // Ie, when the timeout expires, we handle the
776 // most recent event but discard all others that
777 // occurred after the one used to start the timeout
778 // in the first place.
781 synthetic_mouse_event_.restart_timeout = true;
782 synthetic_mouse_event_.timeout.start();
783 // Fall through to handle this event...
785 } else if (synthetic_mouse_event_.timeout.running()) {
786 // Store the event, to be possibly handled when the timeout
788 // Once the timeout has expired, normal control is returned
789 // to mouseMoveEvent (restart_timeout = false).
790 // This results in a much smoother 'feel' when moving the
791 // mouse back into the work area.
792 synthetic_mouse_event_.cmd = cmd;
793 synthetic_mouse_event_.restart_timeout = false;
797 // Has anything changed on-screen since the last QMouseEvent
799 double const scrollbar_value = verticalScrollBar()->value();
800 if (e->x() == synthetic_mouse_event_.x_old
801 && e->y() == synthetic_mouse_event_.y_old
802 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
803 // Nothing changed on-screen since the last QMouseEvent.
807 // Yes something has changed. Store the params used to check this.
808 synthetic_mouse_event_.x_old = e->x();
809 synthetic_mouse_event_.y_old = e->y();
810 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
812 // ... and dispatch the event to the LyX core.
817 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
819 // Wheel rotation by one notch results in a delta() of 120 (see
820 // documentation of QWheelEvent)
821 int const delta = ev->delta() / 120;
822 if (ev->modifiers() & Qt::ControlModifier) {
823 lyxrc.zoom += 5 * delta;
826 // The global QPixmapCache is used in GuiPainter to cache text
827 // painting so we must reset it.
828 QPixmapCache::clear();
829 guiApp->fontLoader().update();
831 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
835 // Take into account the desktop wide settings.
836 int const lines = qApp->wheelScrollLines();
837 int const page_step = verticalScrollBar()->pageStep();
838 // Test if the wheel mouse is set to one screen at a time.
839 int scroll_value = lines > page_step
840 ? page_step : lines * verticalScrollBar()->singleStep();
842 // Take into account the rotation.
843 scroll_value *= delta;
845 // Take into account user preference.
846 scroll_value *= lyxrc.mouse_wheel_speed;
847 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
848 << " delta = " << delta << " scroll_value = " << scroll_value
849 << " page_step = " << page_step);
851 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
857 void GuiWorkArea::generateSyntheticMouseEvent()
859 // Set things off to generate the _next_ 'pseudo' event.
860 if (synthetic_mouse_event_.restart_timeout)
861 synthetic_mouse_event_.timeout.start();
863 // Has anything changed on-screen since the last timeout signal
865 double const scrollbar_value = verticalScrollBar()->value();
866 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
867 // Yes it has. Store the params used to check this.
868 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
870 // ... and dispatch the event to the LyX core.
871 dispatch(synthetic_mouse_event_.cmd);
876 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
878 // Do not process here some keys if dialog_mode_ is set
880 && (ev->modifiers() == Qt::NoModifier
881 || ev->modifiers() == Qt::ShiftModifier)
882 && (ev->key() == Qt::Key_Escape
883 || ev->key() == Qt::Key_Enter
884 || ev->key() == Qt::Key_Return)
890 // intercept some keys if completion popup is visible
891 if (completer_->popupVisible()) {
895 completer_->activate();
901 // do nothing if there are other events
902 // (the auto repeated events come too fast)
903 // \todo FIXME: remove hard coded Qt keys, process the key binding
905 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
906 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
907 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
913 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
914 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
917 setKeySymbol(&sym, ev);
918 processKeySym(sym, q_key_state(ev->modifiers()));
923 void GuiWorkArea::doubleClickTimeout()
925 dc_event_.active = false;
929 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
931 dc_event_ = DoubleClick(ev);
932 QTimer::singleShot(QApplication::doubleClickInterval(), this,
933 SLOT(doubleClickTimeout()));
934 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
936 q_button_state(ev->button()));
942 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
944 QAbstractScrollArea::resizeEvent(ev);
950 void GuiWorkArea::update(int x, int y, int w, int h)
952 viewport()->repaint(x, y, w, h);
956 void GuiWorkArea::paintEvent(QPaintEvent * ev)
958 QRect const rc = ev->rect();
959 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
960 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
963 screen_ = QPixmap(viewport()->width(), viewport()->height());
969 QPainter pain(viewport());
970 pain.drawPixmap(rc, screen_, rc);
976 void GuiWorkArea::updateScreen()
978 GuiPainter pain(&screen_);
979 buffer_view_->draw(pain);
983 void GuiWorkArea::showCursor(int x, int y, int h,
984 bool l_shape, bool rtl, bool completable)
986 if (schedule_redraw_) {
987 // This happens when a graphic conversion is finished. As we don't know
988 // the size of the new graphics, it's better the update everything.
989 // We can't use redraw() here because this would trigger a infinite
990 // recursive loop with showCursor().
991 buffer_view_->resize(viewport()->width(), viewport()->height());
994 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
995 schedule_redraw_ = false;
996 // Show the cursor immediately after the update.
1002 cursor_->update(x, y, h, l_shape, rtl, completable);
1004 viewport()->update(cursor_->rect());
1008 void GuiWorkArea::removeCursor()
1011 //if (!qApp->focusWidget())
1012 viewport()->update(cursor_->rect());
1016 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1018 QString const & commit_string = e->commitString();
1019 docstring const & preedit_string
1020 = qstring_to_ucs4(e->preeditString());
1022 if (!commit_string.isEmpty()) {
1024 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1025 << " commitString: " << e->commitString());
1029 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1030 for (int i = 0; i != commit_string.size(); ++i) {
1031 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1036 // Hide the cursor during the kana-kanji transformation.
1037 if (preedit_string.empty())
1038 startBlinkingCursor();
1040 stopBlinkingCursor();
1042 // last_width : for checking if last preedit string was/wasn't empty.
1043 static bool last_width = false;
1044 if (!last_width && preedit_string.empty()) {
1045 // if last_width is last length of preedit string.
1050 GuiPainter pain(&screen_);
1051 buffer_view_->updateMetrics();
1052 buffer_view_->draw(pain);
1053 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1054 FontMetrics const & fm = theFontMetrics(font);
1055 int height = fm.maxHeight();
1056 int cur_x = cursor_->rect().left();
1057 int cur_y = cursor_->rect().bottom();
1059 // redraw area of preedit string.
1060 update(0, cur_y - height, viewport()->width(),
1061 (height + 1) * preedit_lines_);
1063 if (preedit_string.empty()) {
1071 // att : stores an IM attribute.
1072 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1074 // get attributes of input method cursor.
1075 // cursor_pos : cursor position in preedit string.
1076 size_t cursor_pos = 0;
1077 bool cursor_is_visible = false;
1078 for (int i = 0; i != att.size(); ++i) {
1079 if (att.at(i).type == QInputMethodEvent::Cursor) {
1080 cursor_pos = att.at(i).start;
1081 cursor_is_visible = att.at(i).length != 0;
1086 size_t preedit_length = preedit_string.length();
1088 // get position of selection in input method.
1089 // FIXME: isn't there a way to do this simplier?
1090 // rStart : cursor position in selected string in IM.
1092 // rLength : selected string length in IM.
1094 if (cursor_pos < preedit_length) {
1095 for (int i = 0; i != att.size(); ++i) {
1096 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1097 if (att.at(i).start <= int(cursor_pos)
1098 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1099 rStart = att.at(i).start;
1100 rLength = att.at(i).length;
1101 if (!cursor_is_visible)
1102 cursor_pos += rLength;
1109 rStart = cursor_pos;
1113 int const right_margin = buffer_view_->rightMargin();
1114 Painter::preedit_style ps;
1115 // Most often there would be only one line:
1117 for (size_t pos = 0; pos != preedit_length; ++pos) {
1118 char_type const typed_char = preedit_string[pos];
1119 // reset preedit string style
1120 ps = Painter::preedit_default;
1122 // if we reached the right extremity of the screen, go to next line.
1123 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1124 cur_x = right_margin;
1125 cur_y += height + 1;
1128 // preedit strings are displayed with dashed underline
1129 // and partial strings are displayed white on black indicating
1130 // that we are in selecting mode in the input method.
1131 // FIXME: rLength == preedit_length is not a changing condition
1132 // FIXME: should be put out of the loop.
1134 && pos < rStart + rLength
1135 && !(cursor_pos < rLength && rLength == preedit_length))
1136 ps = Painter::preedit_selecting;
1138 if (pos == cursor_pos
1139 && (cursor_pos < rLength && rLength == preedit_length))
1140 ps = Painter::preedit_cursor;
1142 // draw one character and update cur_x.
1143 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1146 // update the preedit string screen area.
1147 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1148 (height + 1) * preedit_lines_);
1150 // Don't forget to accept the event!
1155 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1157 QRect cur_r(0, 0, 0, 0);
1159 // this is the CJK-specific composition window position.
1160 case Qt::ImMicroFocus:
1161 cur_r = cursor_->rect();
1162 if (preedit_lines_ != 1)
1164 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1165 // return lower right of cursor in LyX.
1168 return QWidget::inputMethodQuery(query);
1173 void GuiWorkArea::updateWindowTitle()
1175 docstring maximize_title;
1176 docstring minimize_title;
1178 Buffer & buf = buffer_view_->buffer();
1179 FileName const fileName = buf.fileName();
1180 if (!fileName.empty()) {
1181 maximize_title = fileName.displayName(30);
1182 minimize_title = from_utf8(fileName.onlyFileName());
1183 if (buf.lyxvc().inUse())
1184 maximize_title += _(" (version control)");
1185 if (!buf.isClean()) {
1186 maximize_title += _(" (changed)");
1187 minimize_title += char_type('*');
1189 if (buf.isReadonly())
1190 maximize_title += _(" (read only)");
1193 QString title = windowTitle();
1194 QString new_title = toqstr(maximize_title);
1195 if (title == new_title)
1198 QWidget::setWindowTitle(new_title);
1199 QWidget::setWindowIconText(toqstr(minimize_title));
1204 void GuiWorkArea::setReadOnly(bool)
1206 updateWindowTitle();
1207 if (this == lyx_view_->currentWorkArea())
1208 lyx_view_->updateDialogs();
1212 bool GuiWorkArea::isFullScreen()
1214 return lyx_view_ && lyx_view_->isFullScreen();
1218 ////////////////////////////////////////////////////////////////////
1222 ////////////////////////////////////////////////////////////////////
1225 class NoTabFrameMacStyle : public QMacStyle {
1228 QRect subElementRect(SubElement element, const QStyleOption * option,
1229 const QWidget * widget = 0) const
1231 QRect rect = QMacStyle::subElementRect(element, option, widget);
1232 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1234 // The Qt Mac style puts the contents into a 3 pixel wide box
1235 // which looks very ugly and not like other Mac applications.
1236 // Hence we remove this here, and moreover the 16 pixel round
1237 // frame above if the tab bar is hidden.
1238 if (element == QStyle::SE_TabWidgetTabContents) {
1239 rect.adjust(- rect.left(), 0, rect.left(), 0);
1248 NoTabFrameMacStyle noTabFrameMacStyle;
1252 TabWorkArea::TabWorkArea(QWidget * parent)
1253 : QTabWidget(parent), clicked_tab_(-1)
1256 setStyle(&noTabFrameMacStyle);
1259 QPalette pal = palette();
1260 pal.setColor(QPalette::Active, QPalette::Button,
1261 pal.color(QPalette::Active, QPalette::Window));
1262 pal.setColor(QPalette::Disabled, QPalette::Button,
1263 pal.color(QPalette::Disabled, QPalette::Window));
1264 pal.setColor(QPalette::Inactive, QPalette::Button,
1265 pal.color(QPalette::Inactive, QPalette::Window));
1267 QObject::connect(this, SIGNAL(currentChanged(int)),
1268 this, SLOT(on_currentTabChanged(int)));
1270 QToolButton * closeBufferButton = new QToolButton(this);
1271 closeBufferButton->setPalette(pal);
1272 // FIXME: rename the icon to closebuffer.png
1273 closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1274 closeBufferButton->setText("Close File");
1275 closeBufferButton->setAutoRaise(true);
1276 closeBufferButton->setCursor(Qt::ArrowCursor);
1277 closeBufferButton->setToolTip(qt_("Close File"));
1278 closeBufferButton->setEnabled(true);
1279 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1280 this, SLOT(closeCurrentBuffer()));
1281 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1283 // setup drag'n'drop
1284 QTabBar* tb = new DragTabBar;
1285 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1286 this, SLOT(moveTab(int, int)));
1287 tb->setElideMode(Qt::ElideNone);
1290 // make us responsible for the context menu of the tabbar
1291 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1292 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1293 this, SLOT(showContextMenu(const QPoint &)));
1295 setUsesScrollButtons(true);
1299 void TabWorkArea::setFullScreen(bool full_screen)
1301 for (int i = 0; i != count(); ++i) {
1302 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1303 wa->setFullScreen(full_screen);
1306 if (lyxrc.full_screen_tabbar)
1307 showBar(!full_screen && count()>1);
1311 void TabWorkArea::showBar(bool show)
1313 tabBar()->setEnabled(show);
1314 tabBar()->setVisible(show);
1318 GuiWorkArea * TabWorkArea::currentWorkArea()
1323 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1329 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1331 for (int i = 0; i != count(); ++i) {
1332 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1333 LASSERT(wa, return 0);
1334 if (&wa->bufferView().buffer() == &buffer)
1341 void TabWorkArea::closeAll()
1344 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1352 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1354 LASSERT(work_area, /**/);
1355 int index = indexOf(work_area);
1359 if (index == currentIndex())
1360 // Make sure the work area is up to date.
1361 on_currentTabChanged(index);
1363 // Switch to the work area.
1364 setCurrentIndex(index);
1365 work_area->setFocus();
1371 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1373 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1374 wa->setUpdatesEnabled(false);
1375 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1376 // when hiding it again below).
1377 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1378 showBar(count() > 0);
1379 addTab(wa, wa->windowTitle());
1380 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1381 this, SLOT(updateTabTexts()));
1382 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1383 setFullScreen(true);
1385 // Hide tabbar if there's only one tab.
1386 showBar(count() > 1);
1394 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1396 LASSERT(work_area, return false);
1397 int index = indexOf(work_area);
1401 work_area->setUpdatesEnabled(false);
1406 // make sure the next work area is enabled.
1407 currentWidget()->setUpdatesEnabled(true);
1408 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1409 setFullScreen(true);
1411 // Hide tabbar if there's only one tab.
1412 showBar(count() > 1);
1414 lastWorkAreaRemoved();
1423 void TabWorkArea::on_currentTabChanged(int i)
1425 // returns e.g. on application destruction
1428 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1429 LASSERT(wa, return);
1430 BufferView & bv = wa->bufferView();
1431 bv.cursor().fixIfBroken();
1433 wa->setUpdatesEnabled(true);
1437 currentWorkAreaChanged(wa);
1439 LYXERR(Debug::GUI, "currentTabChanged " << i
1440 << "File" << bv.buffer().absFileName());
1444 void TabWorkArea::closeCurrentBuffer()
1446 if (clicked_tab_ != -1)
1447 setCurrentIndex(clicked_tab_);
1449 lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1453 void TabWorkArea::closeCurrentTab()
1455 if (clicked_tab_ == -1)
1456 removeWorkArea(currentWorkArea());
1458 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1467 /// make vector happy
1470 DisplayPath(int tab, FileName const & filename)
1473 filename_ = toqstr(filename.onlyFileNameWithoutExt());
1474 postfix_ = toqstr(filename.absoluteFilePath()).
1475 split("/", QString::SkipEmptyParts);
1476 postfix_.pop_back();
1477 abs_ = toqstr(filename.absoluteFilePath());
1478 dottedPrefix_ = false;
1481 /// Absolute path for debugging.
1486 /// Add the first segment from the postfix or three dots to the prefix.
1487 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1488 /// when really needed.
1489 void shiftPathSegment(bool dotted)
1491 if (postfix_.count() <= 0)
1495 if (dottedPrefix_ && !prefix_.isEmpty())
1497 prefix_ += postfix_.front() + "/";
1499 dottedPrefix_ = dotted && !prefix_.isEmpty();
1500 postfix_.pop_front();
1503 QString displayString() const
1505 if (prefix_.isEmpty())
1508 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1509 return prefix_ + (dots ? ".../" : "") + filename_;
1512 QString forecastPathString() const
1514 if (postfix_.count() == 0)
1515 return displayString();
1518 + (dottedPrefix_ ? ".../" : "")
1519 + postfix_.front() + "/";
1522 bool final() const { return postfix_.empty(); }
1524 int tab() const { return tab_; }
1530 QStringList postfix_;
1543 bool operator<(DisplayPath const & a, DisplayPath const & b)
1545 return a.displayString() < b.displayString();
1549 bool operator==(DisplayPath const & a, DisplayPath const & b)
1551 return a.displayString() == b.displayString();
1555 void TabWorkArea::updateTabTexts()
1560 std::list<DisplayPath> paths;
1561 typedef std::list<DisplayPath>::iterator It;
1563 // collect full names first: path into postfix, empty prefix and
1564 // filename without extension
1565 for (size_t i = 0; i < n; ++i) {
1566 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(i));
1567 FileName const fn = i_wa->bufferView().buffer().fileName();
1568 paths.push_back(DisplayPath(i, fn));
1571 // go through path segments and see if it helps to make the path more unique
1572 bool somethingChanged = true;
1573 bool allFinal = false;
1574 while (somethingChanged && !allFinal) {
1575 // adding path segments changes order
1578 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1579 somethingChanged = false;
1582 // find segments which are not unique (i.e. non-atomic)
1583 It it = paths.begin();
1585 QString segString = it->displayString();
1586 for (; it != paths.end(); ++it) {
1587 // look to the next item
1592 allFinal = allFinal && it->final();
1594 LYXERR(Debug::GUI, "it = " << it->abs()
1595 << " => " << it->displayString());
1597 // still the same segment?
1599 if ((next != paths.end()
1600 && (nextString = next->displayString()) == segString))
1602 LYXERR(Debug::GUI, "segment ended");
1604 // only a trivial one with one element?
1605 if (it == segStart) {
1606 // start new segment
1608 segString = nextString;
1612 // we found a non-atomic segment segStart <= sit <= it < next.
1613 // Shift path segments and hope for the best
1614 // that it makes the path more unique.
1615 somethingChanged = true;
1617 QString dspString = sit->forecastPathString();
1618 LYXERR(Debug::GUI, "first forecast found for "
1619 << sit->abs() << " => " << dspString);
1621 bool moreUnique = false;
1622 for (; sit != next; ++sit) {
1623 if (sit->forecastPathString() != dspString) {
1624 LYXERR(Debug::GUI, "different forecast found for "
1625 << sit->abs() << " => " << sit->forecastPathString());
1629 LYXERR(Debug::GUI, "same forecast found for "
1630 << sit->abs() << " => " << dspString);
1633 // if the path segment helped, add it. Otherwise add dots
1634 bool dots = !moreUnique;
1635 LYXERR(Debug::GUI, "using dots = " << dots);
1636 for (sit = segStart; sit != next; ++sit) {
1637 sit->shiftPathSegment(dots);
1638 LYXERR(Debug::GUI, "shifting "
1639 << sit->abs() << " => " << sit->displayString());
1642 // start new segment
1644 segString = nextString;
1648 // set new tab titles
1649 for (It it = paths.begin(); it != paths.end(); ++it) {
1650 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(it->tab()));
1651 Buffer & buf = i_wa->bufferView().buffer();
1652 if (!buf.fileName().empty() && !buf.isClean())
1653 setTabText(it->tab(), it->displayString() + "*");
1655 setTabText(it->tab(), it->displayString());
1660 void TabWorkArea::showContextMenu(const QPoint & pos)
1663 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1664 if (clicked_tab_ == -1)
1669 popup.addAction(QIcon(":/images/hidetab.png"),
1670 qt_("Hide tab"), this, SLOT(closeCurrentTab()));
1671 popup.addAction(QIcon(":/images/closetab.png"),
1672 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1673 popup.exec(tabBar()->mapToGlobal(pos));
1679 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1681 QWidget * w = widget(fromIndex);
1682 QIcon icon = tabIcon(fromIndex);
1683 QString text = tabText(fromIndex);
1685 setCurrentIndex(fromIndex);
1686 removeTab(fromIndex);
1687 insertTab(toIndex, w, icon, text);
1688 setCurrentIndex(toIndex);
1692 DragTabBar::DragTabBar(QWidget* parent)
1695 setAcceptDrops(true);
1699 #if QT_VERSION < 0x040300
1700 int DragTabBar::tabAt(QPoint const & position) const
1702 const int max = count();
1703 for (int i = 0; i < max; ++i) {
1704 if (tabRect(i).contains(position))
1712 void DragTabBar::mousePressEvent(QMouseEvent * event)
1714 if (event->button() == Qt::LeftButton)
1715 dragStartPos_ = event->pos();
1716 QTabBar::mousePressEvent(event);
1720 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1722 // If the left button isn't pressed anymore then return
1723 if (!(event->buttons() & Qt::LeftButton))
1726 // If the distance is too small then return
1727 if ((event->pos() - dragStartPos_).manhattanLength()
1728 < QApplication::startDragDistance())
1731 // did we hit something after all?
1732 int tab = tabAt(dragStartPos_);
1736 // simulate button release to remove highlight from button
1737 int i = currentIndex();
1738 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1739 event->button(), event->buttons(), 0);
1740 QTabBar::mouseReleaseEvent(&me);
1744 QDrag * drag = new QDrag(this);
1745 QMimeData * mimeData = new QMimeData;
1746 // a crude way to distinguish tab-reodering drops from other ones
1747 mimeData->setData("action", "tab-reordering") ;
1748 drag->setMimeData(mimeData);
1750 #if QT_VERSION >= 0x040300
1751 // get tab pixmap as cursor
1752 QRect r = tabRect(tab);
1753 QPixmap pixmap(r.size());
1754 render(&pixmap, - r.topLeft());
1755 drag->setPixmap(pixmap);
1758 drag->start(Qt::MoveAction);
1764 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1766 // Only accept if it's an tab-reordering request
1767 QMimeData const * m = event->mimeData();
1768 QStringList formats = m->formats();
1769 if (formats.contains("action")
1770 && m->data("action") == "tab-reordering")
1771 event->acceptProposedAction();
1775 void DragTabBar::dropEvent(QDropEvent * event)
1777 int fromIndex = tabAt(dragStartPos_);
1778 int toIndex = tabAt(event->pos());
1780 // Tell interested objects that
1781 if (fromIndex != toIndex)
1782 tabMoveRequested(fromIndex, toIndex);
1783 event->acceptProposedAction();
1787 } // namespace frontend
1790 #include "moc_GuiWorkArea.cpp"