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 cursorInView = false;
573 // show cursor on screen
574 bool completable = cur.inset().showCompletionCursor()
575 && completer_->completionAvailable()
576 && !completer_->popupVisible()
577 && !completer_->inlineVisible();
579 cursor_visible_ = true;
580 showCursor(x, y, h, l_shape, isrtl, completable);
585 void GuiWorkArea::hideCursor()
587 if (!cursor_visible_)
590 cursor_visible_ = false;
595 void GuiWorkArea::toggleCursor()
604 void GuiWorkArea::updateScrollbar()
606 ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
607 // WARNING: don't touch at the scrollbar value like this:
608 // verticalScrollBar()->setValue(scroll_.position);
609 // because this would cause a recursive signal/slot calling with
610 // GuiWorkArea::scrollTo
611 verticalScrollBar()->setRange(scroll_.min, scroll_.max);
612 verticalScrollBar()->setPageStep(scroll_.page_step);
613 verticalScrollBar()->setSingleStep(scroll_.single_step);
614 verticalScrollBar()->setSliderPosition(scroll_.position);
618 void GuiWorkArea::scrollTo(int value)
620 stopBlinkingCursor();
621 buffer_view_->scrollDocView(value);
623 if (lyxrc.cursor_follows_scrollbar) {
624 buffer_view_->setCursorFromScrollbar();
625 lyx_view_->updateLayoutList();
627 // Show the cursor immediately after any operation.
628 startBlinkingCursor();
629 QApplication::syncX();
633 bool GuiWorkArea::event(QEvent * e)
636 case QEvent::ToolTip: {
637 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
638 if (lyxrc.use_tooltip) {
639 QPoint pos = helpEvent->pos();
640 if (pos.x() < viewport()->width()) {
641 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
642 QToolTip::showText(helpEvent->globalPos(), s);
645 QToolTip::hideText();
647 // Don't forget to accept the event!
652 case QEvent::ShortcutOverride: {
653 // We catch this event in order to catch the Tab or Shift+Tab key press
654 // which are otherwise reserved to focus switching between controls
656 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
657 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
658 || ke->modifiers() & Qt::ControlModifier)
659 return QAbstractScrollArea::event(e);
665 return QAbstractScrollArea::event(e);
671 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
673 QPoint pos = e->pos();
674 docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
676 QAbstractScrollArea::contextMenuEvent(e);
679 QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
681 QAbstractScrollArea::contextMenuEvent(e);
684 // Position the menu to the right.
685 // FIXME: menu position should be different for RTL text.
686 menu->exec(e->globalPos());
691 void GuiWorkArea::focusInEvent(QFocusEvent * e)
694 LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << std::endl);
695 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
697 old_gwa->stopBlinkingCursor();
698 lyx_view_->setCurrentWorkArea(this);
701 if (lyx_view_->currentWorkArea() != this)
702 lyx_view_->setCurrentWorkArea(this);
704 startBlinkingCursor();
705 QAbstractScrollArea::focusInEvent(e);
709 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
711 LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << std::endl);
712 stopBlinkingCursor();
713 QAbstractScrollArea::focusOutEvent(e);
717 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
719 if (dc_event_.active && dc_event_ == *e) {
720 dc_event_.active = false;
721 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
722 q_button_state(e->button()));
728 inputContext()->reset();
730 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
731 q_button_state(e->button()));
732 dispatch(cmd, q_key_state(e->modifiers()));
737 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
739 if (synthetic_mouse_event_.timeout.running())
740 synthetic_mouse_event_.timeout.stop();
742 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
743 q_button_state(e->button()));
749 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
751 // we kill the triple click if we move
752 doubleClickTimeout();
753 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
754 q_motion_state(e->buttons()));
758 // If we're above or below the work area...
759 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
760 // Make sure only a synthetic event can cause a page scroll,
761 // so they come at a steady rate:
763 // _Force_ a scroll up:
766 cmd.y = viewport()->height();
767 // Store the event, to be handled when the timeout expires.
768 synthetic_mouse_event_.cmd = cmd;
770 if (synthetic_mouse_event_.timeout.running())
771 // Discard the event. Note that it _may_ be handled
772 // when the timeout expires if
773 // synthetic_mouse_event_.cmd has not been overwritten.
774 // Ie, when the timeout expires, we handle the
775 // most recent event but discard all others that
776 // occurred after the one used to start the timeout
777 // in the first place.
780 synthetic_mouse_event_.restart_timeout = true;
781 synthetic_mouse_event_.timeout.start();
782 // Fall through to handle this event...
784 } else if (synthetic_mouse_event_.timeout.running()) {
785 // Store the event, to be possibly handled when the timeout
787 // Once the timeout has expired, normal control is returned
788 // to mouseMoveEvent (restart_timeout = false).
789 // This results in a much smoother 'feel' when moving the
790 // mouse back into the work area.
791 synthetic_mouse_event_.cmd = cmd;
792 synthetic_mouse_event_.restart_timeout = false;
796 // Has anything changed on-screen since the last QMouseEvent
798 double const scrollbar_value = verticalScrollBar()->value();
799 if (e->x() == synthetic_mouse_event_.x_old
800 && e->y() == synthetic_mouse_event_.y_old
801 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
802 // Nothing changed on-screen since the last QMouseEvent.
806 // Yes something has changed. Store the params used to check this.
807 synthetic_mouse_event_.x_old = e->x();
808 synthetic_mouse_event_.y_old = e->y();
809 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
811 // ... and dispatch the event to the LyX core.
816 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
818 // Wheel rotation by one notch results in a delta() of 120 (see
819 // documentation of QWheelEvent)
820 int const delta = ev->delta() / 120;
821 if (ev->modifiers() & Qt::ControlModifier) {
822 lyxrc.zoom += 5 * delta;
825 // The global QPixmapCache is used in GuiPainter to cache text
826 // painting so we must reset it.
827 QPixmapCache::clear();
828 guiApp->fontLoader().update();
830 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
834 // Take into account the desktop wide settings.
835 int const lines = qApp->wheelScrollLines();
836 int const page_step = verticalScrollBar()->pageStep();
837 // Test if the wheel mouse is set to one screen at a time.
838 int scroll_value = lines > page_step
839 ? page_step : lines * verticalScrollBar()->singleStep();
841 // Take into account the rotation.
842 scroll_value *= delta;
844 // Take into account user preference.
845 scroll_value *= lyxrc.mouse_wheel_speed;
846 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
847 << " delta = " << delta << " scroll_value = " << scroll_value
848 << " page_step = " << page_step);
850 verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
856 void GuiWorkArea::generateSyntheticMouseEvent()
858 // Set things off to generate the _next_ 'pseudo' event.
859 if (synthetic_mouse_event_.restart_timeout)
860 synthetic_mouse_event_.timeout.start();
862 // Has anything changed on-screen since the last timeout signal
864 double const scrollbar_value = verticalScrollBar()->value();
865 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
866 // Yes it has. Store the params used to check this.
867 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
869 // ... and dispatch the event to the LyX core.
870 dispatch(synthetic_mouse_event_.cmd);
875 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
877 // Do not process here some keys if dialog_mode_ is set
879 && (ev->modifiers() == Qt::NoModifier
880 || ev->modifiers() == Qt::ShiftModifier)
881 && (ev->key() == Qt::Key_Escape
882 || ev->key() == Qt::Key_Enter
883 || ev->key() == Qt::Key_Return)
889 // intercept some keys if completion popup is visible
890 if (completer_->popupVisible()) {
894 completer_->activate();
900 // do nothing if there are other events
901 // (the auto repeated events come too fast)
902 // \todo FIXME: remove hard coded Qt keys, process the key binding
904 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
905 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
906 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
912 LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
913 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
916 setKeySymbol(&sym, ev);
917 processKeySym(sym, q_key_state(ev->modifiers()));
922 void GuiWorkArea::doubleClickTimeout()
924 dc_event_.active = false;
928 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
930 dc_event_ = DoubleClick(ev);
931 QTimer::singleShot(QApplication::doubleClickInterval(), this,
932 SLOT(doubleClickTimeout()));
933 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
935 q_button_state(ev->button()));
941 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
943 QAbstractScrollArea::resizeEvent(ev);
949 void GuiWorkArea::update(int x, int y, int w, int h)
951 viewport()->repaint(x, y, w, h);
955 void GuiWorkArea::paintEvent(QPaintEvent * ev)
957 QRect const rc = ev->rect();
958 // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
959 // << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
962 screen_ = QPixmap(viewport()->width(), viewport()->height());
968 QPainter pain(viewport());
969 pain.drawPixmap(rc, screen_, rc);
975 void GuiWorkArea::updateScreen()
977 GuiPainter pain(&screen_);
978 buffer_view_->draw(pain);
982 void GuiWorkArea::showCursor(int x, int y, int h,
983 bool l_shape, bool rtl, bool completable)
985 if (schedule_redraw_) {
986 // This happens when a graphic conversion is finished. As we don't know
987 // the size of the new graphics, it's better the update everything.
988 // We can't use redraw() here because this would trigger a infinite
989 // recursive loop with showCursor().
990 buffer_view_->resize(viewport()->width(), viewport()->height());
993 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
994 schedule_redraw_ = false;
995 // Show the cursor immediately after the update.
1001 cursor_->update(x, y, h, l_shape, rtl, completable);
1003 viewport()->update(cursor_->rect());
1007 void GuiWorkArea::removeCursor()
1010 //if (!qApp->focusWidget())
1011 viewport()->update(cursor_->rect());
1015 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1017 QString const & commit_string = e->commitString();
1018 docstring const & preedit_string
1019 = qstring_to_ucs4(e->preeditString());
1021 if (!commit_string.isEmpty()) {
1023 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1024 << " commitString: " << e->commitString());
1028 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1029 for (int i = 0; i != commit_string.size(); ++i) {
1030 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1035 // Hide the cursor during the kana-kanji transformation.
1036 if (preedit_string.empty())
1037 startBlinkingCursor();
1039 stopBlinkingCursor();
1041 // last_width : for checking if last preedit string was/wasn't empty.
1042 static bool last_width = false;
1043 if (!last_width && preedit_string.empty()) {
1044 // if last_width is last length of preedit string.
1049 GuiPainter pain(&screen_);
1050 buffer_view_->updateMetrics();
1051 buffer_view_->draw(pain);
1052 FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1053 FontMetrics const & fm = theFontMetrics(font);
1054 int height = fm.maxHeight();
1055 int cur_x = cursor_->rect().left();
1056 int cur_y = cursor_->rect().bottom();
1058 // redraw area of preedit string.
1059 update(0, cur_y - height, viewport()->width(),
1060 (height + 1) * preedit_lines_);
1062 if (preedit_string.empty()) {
1070 // att : stores an IM attribute.
1071 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1073 // get attributes of input method cursor.
1074 // cursor_pos : cursor position in preedit string.
1075 size_t cursor_pos = 0;
1076 bool cursor_is_visible = false;
1077 for (int i = 0; i != att.size(); ++i) {
1078 if (att.at(i).type == QInputMethodEvent::Cursor) {
1079 cursor_pos = att.at(i).start;
1080 cursor_is_visible = att.at(i).length != 0;
1085 size_t preedit_length = preedit_string.length();
1087 // get position of selection in input method.
1088 // FIXME: isn't there a way to do this simplier?
1089 // rStart : cursor position in selected string in IM.
1091 // rLength : selected string length in IM.
1093 if (cursor_pos < preedit_length) {
1094 for (int i = 0; i != att.size(); ++i) {
1095 if (att.at(i).type == QInputMethodEvent::TextFormat) {
1096 if (att.at(i).start <= int(cursor_pos)
1097 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1098 rStart = att.at(i).start;
1099 rLength = att.at(i).length;
1100 if (!cursor_is_visible)
1101 cursor_pos += rLength;
1108 rStart = cursor_pos;
1112 int const right_margin = buffer_view_->rightMargin();
1113 Painter::preedit_style ps;
1114 // Most often there would be only one line:
1116 for (size_t pos = 0; pos != preedit_length; ++pos) {
1117 char_type const typed_char = preedit_string[pos];
1118 // reset preedit string style
1119 ps = Painter::preedit_default;
1121 // if we reached the right extremity of the screen, go to next line.
1122 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1123 cur_x = right_margin;
1124 cur_y += height + 1;
1127 // preedit strings are displayed with dashed underline
1128 // and partial strings are displayed white on black indicating
1129 // that we are in selecting mode in the input method.
1130 // FIXME: rLength == preedit_length is not a changing condition
1131 // FIXME: should be put out of the loop.
1133 && pos < rStart + rLength
1134 && !(cursor_pos < rLength && rLength == preedit_length))
1135 ps = Painter::preedit_selecting;
1137 if (pos == cursor_pos
1138 && (cursor_pos < rLength && rLength == preedit_length))
1139 ps = Painter::preedit_cursor;
1141 // draw one character and update cur_x.
1142 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1145 // update the preedit string screen area.
1146 update(0, cur_y - preedit_lines_*height, viewport()->width(),
1147 (height + 1) * preedit_lines_);
1149 // Don't forget to accept the event!
1154 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1156 QRect cur_r(0, 0, 0, 0);
1158 // this is the CJK-specific composition window position.
1159 case Qt::ImMicroFocus:
1160 cur_r = cursor_->rect();
1161 if (preedit_lines_ != 1)
1163 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1164 // return lower right of cursor in LyX.
1167 return QWidget::inputMethodQuery(query);
1172 void GuiWorkArea::updateWindowTitle()
1174 docstring maximize_title;
1175 docstring minimize_title;
1177 Buffer & buf = buffer_view_->buffer();
1178 FileName const fileName = buf.fileName();
1179 if (!fileName.empty()) {
1180 maximize_title = fileName.displayName(30);
1181 minimize_title = from_utf8(fileName.onlyFileName());
1182 if (buf.lyxvc().inUse())
1183 maximize_title += _(" (version control)");
1184 if (!buf.isClean()) {
1185 maximize_title += _(" (changed)");
1186 minimize_title += char_type('*');
1188 if (buf.isReadonly())
1189 maximize_title += _(" (read only)");
1192 QString title = windowTitle();
1193 QString new_title = toqstr(maximize_title);
1194 if (title == new_title)
1197 QWidget::setWindowTitle(new_title);
1198 QWidget::setWindowIconText(toqstr(minimize_title));
1203 void GuiWorkArea::setReadOnly(bool)
1205 updateWindowTitle();
1206 if (this == lyx_view_->currentWorkArea())
1207 lyx_view_->updateDialogs();
1211 bool GuiWorkArea::isFullScreen()
1213 return lyx_view_ && lyx_view_->isFullScreen();
1217 ////////////////////////////////////////////////////////////////////
1221 ////////////////////////////////////////////////////////////////////
1224 class NoTabFrameMacStyle : public QMacStyle {
1227 QRect subElementRect(SubElement element, const QStyleOption * option,
1228 const QWidget * widget = 0) const
1230 QRect rect = QMacStyle::subElementRect(element, option, widget);
1231 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1233 // The Qt Mac style puts the contents into a 3 pixel wide box
1234 // which looks very ugly and not like other Mac applications.
1235 // Hence we remove this here, and moreover the 16 pixel round
1236 // frame above if the tab bar is hidden.
1237 if (element == QStyle::SE_TabWidgetTabContents) {
1238 rect.adjust(- rect.left(), 0, rect.left(), 0);
1247 NoTabFrameMacStyle noTabFrameMacStyle;
1251 TabWorkArea::TabWorkArea(QWidget * parent)
1252 : QTabWidget(parent), clicked_tab_(-1)
1255 setStyle(&noTabFrameMacStyle);
1258 QPalette pal = palette();
1259 pal.setColor(QPalette::Active, QPalette::Button,
1260 pal.color(QPalette::Active, QPalette::Window));
1261 pal.setColor(QPalette::Disabled, QPalette::Button,
1262 pal.color(QPalette::Disabled, QPalette::Window));
1263 pal.setColor(QPalette::Inactive, QPalette::Button,
1264 pal.color(QPalette::Inactive, QPalette::Window));
1266 QObject::connect(this, SIGNAL(currentChanged(int)),
1267 this, SLOT(on_currentTabChanged(int)));
1269 QToolButton * closeBufferButton = new QToolButton(this);
1270 closeBufferButton->setPalette(pal);
1271 // FIXME: rename the icon to closebuffer.png
1272 closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1273 closeBufferButton->setText("Close File");
1274 closeBufferButton->setAutoRaise(true);
1275 closeBufferButton->setCursor(Qt::ArrowCursor);
1276 closeBufferButton->setToolTip(qt_("Close File"));
1277 closeBufferButton->setEnabled(true);
1278 QObject::connect(closeBufferButton, SIGNAL(clicked()),
1279 this, SLOT(closeCurrentBuffer()));
1280 setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1282 // setup drag'n'drop
1283 QTabBar* tb = new DragTabBar;
1284 connect(tb, SIGNAL(tabMoveRequested(int, int)),
1285 this, SLOT(moveTab(int, int)));
1286 tb->setElideMode(Qt::ElideNone);
1289 // make us responsible for the context menu of the tabbar
1290 tb->setContextMenuPolicy(Qt::CustomContextMenu);
1291 connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1292 this, SLOT(showContextMenu(const QPoint &)));
1294 setUsesScrollButtons(true);
1298 void TabWorkArea::setFullScreen(bool full_screen)
1300 for (int i = 0; i != count(); ++i) {
1301 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1302 wa->setFullScreen(full_screen);
1305 if (lyxrc.full_screen_tabbar)
1306 showBar(!full_screen && count()>1);
1310 void TabWorkArea::showBar(bool show)
1312 tabBar()->setEnabled(show);
1313 tabBar()->setVisible(show);
1317 GuiWorkArea * TabWorkArea::currentWorkArea()
1322 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1328 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1330 for (int i = 0; i != count(); ++i) {
1331 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1332 LASSERT(wa, return 0);
1333 if (&wa->bufferView().buffer() == &buffer)
1340 void TabWorkArea::closeAll()
1343 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1351 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1353 LASSERT(work_area, /**/);
1354 int index = indexOf(work_area);
1358 if (index == currentIndex())
1359 // Make sure the work area is up to date.
1360 on_currentTabChanged(index);
1362 // Switch to the work area.
1363 setCurrentIndex(index);
1364 work_area->setFocus();
1370 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1372 GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1373 wa->setUpdatesEnabled(false);
1374 // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1375 // when hiding it again below).
1376 if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1377 showBar(count() > 0);
1378 addTab(wa, wa->windowTitle());
1379 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1380 this, SLOT(updateTabTexts()));
1381 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1382 setFullScreen(true);
1384 // Hide tabbar if there's only one tab.
1385 showBar(count() > 1);
1393 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1395 LASSERT(work_area, return false);
1396 int index = indexOf(work_area);
1400 work_area->setUpdatesEnabled(false);
1405 // make sure the next work area is enabled.
1406 currentWidget()->setUpdatesEnabled(true);
1407 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1408 setFullScreen(true);
1410 // Hide tabbar if there's only one tab.
1411 showBar(count() > 1);
1413 lastWorkAreaRemoved();
1422 void TabWorkArea::on_currentTabChanged(int i)
1424 // returns e.g. on application destruction
1427 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1428 LASSERT(wa, return);
1429 BufferView & bv = wa->bufferView();
1430 bv.cursor().fixIfBroken();
1432 wa->setUpdatesEnabled(true);
1436 currentWorkAreaChanged(wa);
1438 LYXERR(Debug::GUI, "currentTabChanged " << i
1439 << "File" << bv.buffer().absFileName());
1443 void TabWorkArea::closeCurrentBuffer()
1445 if (clicked_tab_ != -1)
1446 setCurrentIndex(clicked_tab_);
1448 lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1452 void TabWorkArea::closeCurrentTab()
1454 if (clicked_tab_ == -1)
1455 removeWorkArea(currentWorkArea());
1457 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1466 /// make vector happy
1469 DisplayPath(int tab, FileName const & filename)
1472 filename_ = toqstr(filename.onlyFileNameWithoutExt());
1473 postfix_ = toqstr(filename.absoluteFilePath()).
1474 split("/", QString::SkipEmptyParts);
1475 postfix_.pop_back();
1476 abs_ = toqstr(filename.absoluteFilePath());
1477 dottedPrefix_ = false;
1480 /// Absolute path for debugging.
1485 /// Add the first segment from the postfix or three dots to the prefix.
1486 /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1487 /// when really needed.
1488 void shiftPathSegment(bool dotted)
1490 if (postfix_.count() <= 0)
1494 if (dottedPrefix_ && !prefix_.isEmpty())
1496 prefix_ += postfix_.front() + "/";
1498 dottedPrefix_ = dotted && !prefix_.isEmpty();
1499 postfix_.pop_front();
1502 QString displayString() const
1504 if (prefix_.isEmpty())
1507 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1508 return prefix_ + (dots ? ".../" : "") + filename_;
1511 QString forecastPathString() const
1513 if (postfix_.count() == 0)
1514 return displayString();
1517 + (dottedPrefix_ ? ".../" : "")
1518 + postfix_.front() + "/";
1521 bool final() const { return postfix_.empty(); }
1523 int tab() const { return tab_; }
1529 QStringList postfix_;
1542 bool operator<(DisplayPath const & a, DisplayPath const & b)
1544 return a.displayString() < b.displayString();
1548 bool operator==(DisplayPath const & a, DisplayPath const & b)
1550 return a.displayString() == b.displayString();
1554 void TabWorkArea::updateTabTexts()
1559 std::list<DisplayPath> paths;
1560 typedef std::list<DisplayPath>::iterator It;
1562 // collect full names first: path into postfix, empty prefix and
1563 // filename without extension
1564 for (size_t i = 0; i < n; ++i) {
1565 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(i));
1566 FileName const fn = i_wa->bufferView().buffer().fileName();
1567 paths.push_back(DisplayPath(i, fn));
1570 // go through path segments and see if it helps to make the path more unique
1571 bool somethingChanged = true;
1572 bool allFinal = false;
1573 while (somethingChanged && !allFinal) {
1574 // adding path segments changes order
1577 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1578 somethingChanged = false;
1581 // find segments which are not unique (i.e. non-atomic)
1582 It it = paths.begin();
1584 QString segString = it->displayString();
1585 for (; it != paths.end(); ++it) {
1586 // look to the next item
1591 allFinal = allFinal && it->final();
1593 LYXERR(Debug::GUI, "it = " << it->abs()
1594 << " => " << it->displayString());
1596 // still the same segment?
1598 if ((next != paths.end()
1599 && (nextString = next->displayString()) == segString))
1601 LYXERR(Debug::GUI, "segment ended");
1603 // only a trivial one with one element?
1604 if (it == segStart) {
1605 // start new segment
1607 segString = nextString;
1611 // we found a non-atomic segment segStart <= sit <= it < next.
1612 // Shift path segments and hope for the best
1613 // that it makes the path more unique.
1614 somethingChanged = true;
1616 QString dspString = sit->forecastPathString();
1617 LYXERR(Debug::GUI, "first forecast found for "
1618 << sit->abs() << " => " << dspString);
1620 bool moreUnique = false;
1621 for (; sit != next; ++sit) {
1622 if (sit->forecastPathString() != dspString) {
1623 LYXERR(Debug::GUI, "different forecast found for "
1624 << sit->abs() << " => " << sit->forecastPathString());
1628 LYXERR(Debug::GUI, "same forecast found for "
1629 << sit->abs() << " => " << dspString);
1632 // if the path segment helped, add it. Otherwise add dots
1633 bool dots = !moreUnique;
1634 LYXERR(Debug::GUI, "using dots = " << dots);
1635 for (sit = segStart; sit != next; ++sit) {
1636 sit->shiftPathSegment(dots);
1637 LYXERR(Debug::GUI, "shifting "
1638 << sit->abs() << " => " << sit->displayString());
1641 // start new segment
1643 segString = nextString;
1647 // set new tab titles
1648 for (It it = paths.begin(); it != paths.end(); ++it) {
1649 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(it->tab()));
1650 Buffer & buf = i_wa->bufferView().buffer();
1651 if (!buf.fileName().empty() && !buf.isClean())
1652 setTabText(it->tab(), it->displayString() + "*");
1654 setTabText(it->tab(), it->displayString());
1659 void TabWorkArea::showContextMenu(const QPoint & pos)
1662 clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1663 if (clicked_tab_ == -1)
1668 popup.addAction(QIcon(":/images/hidetab.png"),
1669 qt_("Hide tab"), this, SLOT(closeCurrentTab()));
1670 popup.addAction(QIcon(":/images/closetab.png"),
1671 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1672 popup.exec(tabBar()->mapToGlobal(pos));
1678 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1680 QWidget * w = widget(fromIndex);
1681 QIcon icon = tabIcon(fromIndex);
1682 QString text = tabText(fromIndex);
1684 setCurrentIndex(fromIndex);
1685 removeTab(fromIndex);
1686 insertTab(toIndex, w, icon, text);
1687 setCurrentIndex(toIndex);
1691 DragTabBar::DragTabBar(QWidget* parent)
1694 setAcceptDrops(true);
1698 #if QT_VERSION < 0x040300
1699 int DragTabBar::tabAt(QPoint const & position) const
1701 const int max = count();
1702 for (int i = 0; i < max; ++i) {
1703 if (tabRect(i).contains(position))
1711 void DragTabBar::mousePressEvent(QMouseEvent * event)
1713 if (event->button() == Qt::LeftButton)
1714 dragStartPos_ = event->pos();
1715 QTabBar::mousePressEvent(event);
1719 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1721 // If the left button isn't pressed anymore then return
1722 if (!(event->buttons() & Qt::LeftButton))
1725 // If the distance is too small then return
1726 if ((event->pos() - dragStartPos_).manhattanLength()
1727 < QApplication::startDragDistance())
1730 // did we hit something after all?
1731 int tab = tabAt(dragStartPos_);
1735 // simulate button release to remove highlight from button
1736 int i = currentIndex();
1737 QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1738 event->button(), event->buttons(), 0);
1739 QTabBar::mouseReleaseEvent(&me);
1743 QDrag * drag = new QDrag(this);
1744 QMimeData * mimeData = new QMimeData;
1745 // a crude way to distinguish tab-reodering drops from other ones
1746 mimeData->setData("action", "tab-reordering") ;
1747 drag->setMimeData(mimeData);
1749 #if QT_VERSION >= 0x040300
1750 // get tab pixmap as cursor
1751 QRect r = tabRect(tab);
1752 QPixmap pixmap(r.size());
1753 render(&pixmap, - r.topLeft());
1754 drag->setPixmap(pixmap);
1757 drag->start(Qt::MoveAction);
1763 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1765 // Only accept if it's an tab-reordering request
1766 QMimeData const * m = event->mimeData();
1767 QStringList formats = m->formats();
1768 if (formats.contains("action")
1769 && m->data("action") == "tab-reordering")
1770 event->acceptProposedAction();
1774 void DragTabBar::dropEvent(QDropEvent * event)
1776 int fromIndex = tabAt(dragStartPos_);
1777 int toIndex = tabAt(event->pos());
1779 // Tell interested objects that
1780 if (fromIndex != toIndex)
1781 tabMoveRequested(fromIndex, toIndex);
1782 event->acceptProposedAction();
1786 } // namespace frontend
1789 #include "moc_GuiWorkArea.cpp"