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 "GuiApplication.h"
17 #include "GuiPainter.h"
18 #include "GuiKeySymbol.h"
19 #include "qt_helpers.h"
21 #include "frontends/LyXView.h"
24 #include "BufferView.h"
27 #include "FuncRequest.h"
32 #include "support/filetools.h" // LibFileSearch
34 #include "graphics/GraphicsImage.h"
35 #include "graphics/GraphicsLoader.h"
37 #include <QInputContext>
39 #include <QMainWindow>
41 #include <QPushButton>
46 #include <boost/bind.hpp>
47 #include <boost/current_function.hpp>
51 extern "C" int XEventsQueued(Display *display, int mode);
55 int const CursorWidth = 2;
57 int const CursorWidth = 1;
68 using support::FileName;
70 /// return the LyX mouse button state from Qt's
71 static mouse_button::state q_button_state(Qt::MouseButton button)
73 mouse_button::state b = mouse_button::none;
76 b = mouse_button::button1;
79 b = mouse_button::button2;
82 b = mouse_button::button3;
91 /// return the LyX mouse button state from Qt's
92 mouse_button::state q_motion_state(Qt::MouseButtons state)
94 mouse_button::state b = mouse_button::none;
95 if (state & Qt::LeftButton)
96 b |= mouse_button::button1;
97 if (state & Qt::MidButton)
98 b |= mouse_button::button2;
99 if (state & Qt::RightButton)
100 b |= mouse_button::button3;
111 void draw(QPainter & painter)
113 if (show_ && rect_.isValid()) {
116 painter.fillRect(rect_.x(), rect_.y(), CursorWidth, rect_.height(), color_);
117 painter.setPen(color_);
118 painter.drawLine(rect_.bottomLeft().x() + CursorWidth, rect_.bottomLeft().y(),
119 rect_.bottomRight().x(), rect_.bottomLeft().y());
122 case REVERSED_L_SHAPE:
123 painter.fillRect(rect_.x() + rect_.height() / 3, rect_.y(), CursorWidth, rect_.height(), color_);
124 painter.setPen(color_);
125 painter.drawLine(rect_.bottomRight().x() - CursorWidth, rect_.bottomLeft().y(),
126 rect_.bottomLeft().x(), rect_.bottomLeft().y());
130 painter.fillRect(rect_, color_);
136 void update(int x, int y, int h, CursorShape shape)
138 color_ = guiApp->colorCache().get(Color::cursor);
142 rect_ = QRect(x, y, CursorWidth + h / 3, h);
144 case REVERSED_L_SHAPE:
145 rect_ = QRect(x - h / 3, y, CursorWidth + h / 3, h);
148 rect_ = QRect(x, y, CursorWidth, h);
153 void show(bool set_show = true) { show_ = set_show; }
154 void hide() { show_ = false; }
156 QRect const & rect() { return rect_; }
170 // This is a 'heartbeat' generating synthetic mouse move events when the
171 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
172 SyntheticMouseEvent::SyntheticMouseEvent()
173 : timeout(200), restart_timeout(true),
174 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
178 GuiWorkArea::GuiWorkArea(Buffer & buf, LyXView & lv)
179 : WorkArea(buf, lv), need_resize_(false), schedule_redraw_(false),
182 screen_ = QPixmap(viewport()->width(), viewport()->height());
183 cursor_ = new frontend::CursorWidget();
186 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
187 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
188 setAcceptDrops(true);
189 setMouseTracking(true);
190 setMinimumSize(100, 70);
192 viewport()->setAutoFillBackground(false);
193 // We don't need double-buffering nor SystemBackground on
194 // the viewport because we have our own backing pixmap.
195 viewport()->setAttribute(Qt::WA_NoSystemBackground);
197 setFocusPolicy(Qt::WheelFocus);
199 viewport()->setCursor(Qt::IBeamCursor);
201 synthetic_mouse_event_.timeout.timeout.connect(
202 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
205 // Initialize the vertical Scroll Bar
206 QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
207 this, SLOT(adjustViewWithScrollBar(int)));
209 // disable context menu for the scrollbar
210 verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu);
212 // PageStep only depends on the viewport height.
213 verticalScrollBar()->setPageStep(viewport()->height());
215 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
216 << "\n Area width\t" << width()
217 << "\n Area height\t" << height()
218 << "\n viewport width\t" << viewport()->width()
219 << "\n viewport height\t" << viewport()->height()
222 // Enables input methods for asian languages.
223 // Must be set when creating custom text editing widgets.
224 setAttribute(Qt::WA_InputMethodEnabled, true);
228 void GuiWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
230 if (verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOn)
231 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
233 verticalScrollBar()->setTracking(false);
235 // do what cursor movement does (some grey)
237 int scroll_max_ = std::max(0, h - height());
239 verticalScrollBar()->setRange(0, scroll_max_);
240 verticalScrollBar()->setSliderPosition(scroll_pos);
241 verticalScrollBar()->setSingleStep(scroll_line_step);
242 verticalScrollBar()->setValue(scroll_pos);
244 verticalScrollBar()->setTracking(true);
248 void GuiWorkArea::adjustViewWithScrollBar(int action)
250 stopBlinkingCursor();
251 if (action == QAbstractSlider::SliderPageStepAdd)
252 buffer_view_->scrollDown(viewport()->height());
253 else if (action == QAbstractSlider::SliderPageStepSub)
254 buffer_view_->scrollUp(viewport()->height());
256 buffer_view_->scrollDocView(verticalScrollBar()->sliderPosition());
258 if (lyxrc.cursor_follows_scrollbar) {
259 buffer_view_->setCursorFromScrollbar();
260 lyx_view_->updateLayoutChoice();
262 // Show the cursor immediately after any operation.
263 startBlinkingCursor();
264 QApplication::syncX();
268 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
270 // Repaint the whole screen.
271 // Note: this is different from redraw() as only the backing pixmap
272 // will be redrawn, which is cheap.
273 viewport()->repaint();
275 startBlinkingCursor();
279 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
281 stopBlinkingCursor();
285 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
287 if (dc_event_.active && dc_event_ == *e) {
288 dc_event_.active = false;
289 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
291 q_button_state(e->button()));
296 inputContext()->reset();
298 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
299 q_button_state(e->button()));
300 dispatch(cmd, q_key_state(e->modifiers()));
304 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
306 if (synthetic_mouse_event_.timeout.running())
307 synthetic_mouse_event_.timeout.stop();
309 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
310 q_button_state(e->button()));
315 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
317 // we kill the triple click if we move
318 doubleClickTimeout();
319 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
320 q_motion_state(e->buttons()));
322 // If we're above or below the work area...
323 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
324 // Make sure only a synthetic event can cause a page scroll,
325 // so they come at a steady rate:
327 // _Force_ a scroll up:
330 cmd.y = viewport()->height();
331 // Store the event, to be handled when the timeout expires.
332 synthetic_mouse_event_.cmd = cmd;
334 if (synthetic_mouse_event_.timeout.running())
335 // Discard the event. Note that it _may_ be handled
336 // when the timeout expires if
337 // synthetic_mouse_event_.cmd has not been overwritten.
338 // Ie, when the timeout expires, we handle the
339 // most recent event but discard all others that
340 // occurred after the one used to start the timeout
341 // in the first place.
344 synthetic_mouse_event_.restart_timeout = true;
345 synthetic_mouse_event_.timeout.start();
346 // Fall through to handle this event...
349 } else if (synthetic_mouse_event_.timeout.running()) {
350 // Store the event, to be possibly handled when the timeout
352 // Once the timeout has expired, normal control is returned
353 // to mouseMoveEvent (restart_timeout = false).
354 // This results in a much smoother 'feel' when moving the
355 // mouse back into the work area.
356 synthetic_mouse_event_.cmd = cmd;
357 synthetic_mouse_event_.restart_timeout = false;
361 // Has anything changed on-screen since the last QMouseEvent
363 double const scrollbar_value = verticalScrollBar()->value();
364 if (e->x() != synthetic_mouse_event_.x_old ||
365 e->y() != synthetic_mouse_event_.y_old ||
366 scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
367 // Yes it has. Store the params used to check this.
368 synthetic_mouse_event_.x_old = e->x();
369 synthetic_mouse_event_.y_old = e->y();
370 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
372 // ... and dispatch the event to the LyX core.
378 void GuiWorkArea::wheelEvent(QWheelEvent * e)
380 // Wheel rotation by one notch results in a delta() of 120 (see
381 // documentation of QWheelEvent)
382 int const lines = qApp->wheelScrollLines() * e->delta() / 120;
383 verticalScrollBar()->setValue(verticalScrollBar()->value() -
384 lines * verticalScrollBar()->singleStep());
385 adjustViewWithScrollBar();
389 void GuiWorkArea::generateSyntheticMouseEvent()
391 // Set things off to generate the _next_ 'pseudo' event.
392 if (synthetic_mouse_event_.restart_timeout)
393 synthetic_mouse_event_.timeout.start();
395 // Has anything changed on-screen since the last timeout signal
397 double const scrollbar_value = verticalScrollBar()->value();
398 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
399 // Yes it has. Store the params used to check this.
400 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
402 // ... and dispatch the event to the LyX core.
403 dispatch(synthetic_mouse_event_.cmd);
408 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
410 // do nothing if there are other events
411 // (the auto repeated events come too fast)
412 // \todo FIXME: remove hard coded Qt keys, process the key binding
414 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
415 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
417 << BOOST_CURRENT_FUNCTION << endl
418 << "system is busy: scroll key event ignored" << endl;
424 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
425 << " count=" << ev->count()
426 << " text=" << fromqstr(ev->text())
427 << " isAutoRepeat=" << ev->isAutoRepeat()
428 << " key=" << ev->key()
432 setKeySymbol(&sym, ev);
433 processKeySym(sym, q_key_state(ev->modifiers()));
437 void GuiWorkArea::doubleClickTimeout()
439 dc_event_.active = false;
443 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
445 dc_event_ = double_click(ev);
446 QTimer::singleShot(QApplication::doubleClickInterval(), this,
447 SLOT(doubleClickTimeout()));
448 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
450 q_button_state(ev->button()));
455 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
457 QAbstractScrollArea::resizeEvent(ev);
462 void GuiWorkArea::update(int x, int y, int w, int h)
464 viewport()->repaint(x, y, w, h);
468 void GuiWorkArea::paintEvent(QPaintEvent * ev)
470 QRect const rc = ev->rect();
472 LYXERR(Debug::PAINTING) << "paintEvent begin: x: " << rc.x()
474 << " w: " << rc.width()
475 << " h: " << rc.height() << endl;
479 verticalScrollBar()->setPageStep(viewport()->height());
480 screen_ = QPixmap(viewport()->width(), viewport()->height());
483 WorkArea::hideCursor();
484 WorkArea::showCursor();
485 need_resize_ = false;
488 QPainter pain(viewport());
489 pain.drawPixmap(rc, screen_, rc);
494 void GuiWorkArea::expose(int x, int y, int w, int h)
501 void GuiWorkArea::updateScreen()
503 GuiPainter pain(&screen_);
504 verticalScrollBar()->show();
505 buffer_view_->draw(pain);
509 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
511 if (schedule_redraw_) {
512 buffer_view_->updateMetrics(false);
514 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
515 schedule_redraw_ = false;
516 // Show the cursor immediately after the update.
522 cursor_->update(x, y, h, shape);
524 viewport()->update(cursor_->rect());
528 void GuiWorkArea::removeCursor()
531 //if (!qApp->focusWidget())
532 viewport()->update(cursor_->rect());
536 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
538 QString const & commit_string = e->commitString();
539 docstring const & preedit_string
540 = qstring_to_ucs4(e->preeditString());
542 if (!commit_string.isEmpty()) {
544 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
545 << " preeditString =" << fromqstr(e->preeditString())
546 << " commitString =" << fromqstr(e->commitString())
551 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
552 for (int i = 0; i < commit_string.size(); ++i) {
553 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
558 // Hide the cursor during the kana-kanji transformation.
559 if (preedit_string.empty())
560 startBlinkingCursor();
562 stopBlinkingCursor();
564 // last_width : for checking if last preedit string was/wasn't empty.
565 static bool last_width = false;
566 if (!last_width && preedit_string.empty()) {
567 // if last_width is last length of preedit string.
572 GuiPainter pain(&screen_);
573 buffer_view_->updateMetrics(false);
574 buffer_view_->draw(pain);
575 Font font = buffer_view_->cursor().getFont();
576 FontMetrics const & fm = theFontMetrics(font);
577 int height = fm.maxHeight();
578 int cur_x = cursor_->rect().left();
579 int cur_y = cursor_->rect().bottom();
581 // redraw area of preedit string.
582 update(0, cur_y - height, GuiWorkArea::width(),
583 (height + 1) * preedit_lines_);
585 if (preedit_string.empty()) {
593 // att : stores an IM attribute.
594 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
596 // get attributes of input method cursor.
597 // cursor_pos : cursor position in preedit string.
598 size_t cursor_pos = 0;
599 bool cursor_is_visible = false;
600 for (int i = 0; i < att.size(); ++i) {
601 if (att.at(i).type == QInputMethodEvent::Cursor) {
602 cursor_pos = att.at(i).start;
603 cursor_is_visible = att.at(i).length != 0;
608 size_t preedit_length = preedit_string.length();
610 // get position of selection in input method.
611 // FIXME: isn't there a way to do this simplier?
612 // rStart : cursor position in selected string in IM.
614 // rLength : selected string length in IM.
616 if (cursor_pos < preedit_length) {
617 for (int i = 0; i < att.size(); ++i) {
618 if (att.at(i).type == QInputMethodEvent::TextFormat) {
619 if (att.at(i).start <= int(cursor_pos)
620 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
621 rStart = att.at(i).start;
622 rLength = att.at(i).length;
623 if (!cursor_is_visible)
624 cursor_pos += rLength;
635 int const right_margin = rightMargin();
636 Painter::preedit_style ps;
637 // Most often there would be only one line:
639 for (size_t pos = 0; pos != preedit_length; ++pos) {
640 char_type const typed_char = preedit_string[pos];
641 // reset preedit string style
642 ps = Painter::preedit_default;
644 // if we reached the right extremity of the screen, go to next line.
645 if (cur_x + fm.width(typed_char) > GuiWorkArea::width() - right_margin) {
646 cur_x = right_margin;
650 // preedit strings are displayed with dashed underline
651 // and partial strings are displayed white on black indicating
652 // that we are in selecting mode in the input method.
653 // FIXME: rLength == preedit_length is not a changing condition
654 // FIXME: should be put out of the loop.
656 && pos < rStart + rLength
657 && !(cursor_pos < rLength && rLength == preedit_length))
658 ps = Painter::preedit_selecting;
660 if (pos == cursor_pos
661 && (cursor_pos < rLength && rLength == preedit_length))
662 ps = Painter::preedit_cursor;
664 // draw one character and update cur_x.
665 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
668 // update the preedit string screen area.
669 update(0, cur_y - preedit_lines_*height, GuiWorkArea::width(),
670 (height + 1) * preedit_lines_);
672 // Don't forget to accept the event!
677 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
679 QRect cur_r(0,0,0,0);
681 // this is the CJK-specific composition window position.
682 case Qt::ImMicroFocus:
683 cur_r = cursor_->rect();
684 if (preedit_lines_ != 1)
686 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
687 // return lower right of cursor in LyX.
690 return QWidget::inputMethodQuery(query);
694 ////////////////////////////////////////////////////////////////////
695 // TabWorkArea implementation.
696 ////////////////////////////////////////////////////////////////////
697 TabWorkArea::TabWorkArea(QWidget * parent): QTabWidget(parent)
699 QPushButton * closeTabButton = new QPushButton(this);
700 FileName const file = support::libFileSearch("images", "closetab", "png");
702 QPixmap pm(toqstr(file.absFilename()));
703 closeTabButton->setIcon(QIcon(pm));
704 closeTabButton->setMaximumSize(pm.size());
705 closeTabButton->setFlat(true);
707 closeTabButton->setText("Close");
709 closeTabButton->setCursor(Qt::ArrowCursor);
710 closeTabButton->setToolTip(tr("Close tab"));
711 closeTabButton->setEnabled(true);
713 QObject::connect(this, SIGNAL(currentChanged(int)),
714 this, SLOT(on_currentTabChanged(int)));
715 QObject::connect(closeTabButton, SIGNAL(clicked()),
716 this, SLOT(closeCurrentTab()));
718 setCornerWidget(closeTabButton);
719 #if QT_VERSION >= 0x040200
720 setUsesScrollButtons(true);
725 void TabWorkArea::showBar(bool show)
727 tabBar()->setVisible(show);
731 void TabWorkArea::closeAll()
734 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
742 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
744 BOOST_ASSERT(work_area);
745 int index = indexOf(work_area);
749 if (index == currentIndex())
750 // Make sure the work area is up to date.
751 on_currentTabChanged(index);
753 // Switch to the work area.
754 setCurrentIndex(index);
755 work_area->setFocus();
761 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
763 BOOST_ASSERT(work_area);
764 int index = indexOf(work_area);
768 work_area->setUpdatesEnabled(false);
773 // make sure the next work area is enabled.
774 currentWidget()->setUpdatesEnabled(true);
775 // Hide tabbar if there's only one tab.
776 showBar(count() > 1);
782 void TabWorkArea::on_currentTabChanged(int i)
784 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
786 BufferView & bv = wa->bufferView();
787 bv.updateMetrics(false);
788 bv.cursor().fixIfBroken();
789 wa->setUpdatesEnabled(true);
793 currentWorkAreaChanged(wa);
795 LYXERR(Debug::GUI) << "currentTabChanged " << i
796 << "File" << bv.buffer().fileName() << endl;
800 void TabWorkArea::closeCurrentTab()
802 lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
805 } // namespace frontend
808 #include "GuiWorkArea_moc.cpp"