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"
23 #include "BufferView.h"
26 #include "FuncRequest.h"
30 #include "support/filetools.h" // LibFileSearch
32 #include "graphics/GraphicsImage.h"
33 #include "graphics/GraphicsLoader.h"
35 #include <QInputContext>
37 #include <QMainWindow>
42 #include <boost/bind.hpp>
43 #include <boost/current_function.hpp>
47 extern "C" int XEventsQueued(Display *display, int mode);
51 int const CursorWidth = 2;
53 int const CursorWidth = 1;
64 using support::FileName;
66 /// return the LyX mouse button state from Qt's
67 static mouse_button::state q_button_state(Qt::MouseButton button)
69 mouse_button::state b = mouse_button::none;
72 b = mouse_button::button1;
75 b = mouse_button::button2;
78 b = mouse_button::button3;
87 /// return the LyX mouse button state from Qt's
88 mouse_button::state q_motion_state(Qt::MouseButtons state)
90 mouse_button::state b = mouse_button::none;
91 if (state & Qt::LeftButton)
92 b |= mouse_button::button1;
93 if (state & Qt::MidButton)
94 b |= mouse_button::button2;
95 if (state & Qt::RightButton)
96 b |= mouse_button::button3;
107 void draw(QPainter & painter)
109 if (show_ && rect_.isValid()) {
112 painter.fillRect(rect_.x(), rect_.y(), CursorWidth, rect_.height(), color_);
113 painter.setPen(color_);
114 painter.drawLine(rect_.bottomLeft().x() + CursorWidth, rect_.bottomLeft().y(),
115 rect_.bottomRight().x(), rect_.bottomLeft().y());
118 case REVERSED_L_SHAPE:
119 painter.fillRect(rect_.x() + rect_.height() / 3, rect_.y(), CursorWidth, rect_.height(), color_);
120 painter.setPen(color_);
121 painter.drawLine(rect_.bottomRight().x() - CursorWidth, rect_.bottomLeft().y(),
122 rect_.bottomLeft().x(), rect_.bottomLeft().y());
126 painter.fillRect(rect_, color_);
132 void update(int x, int y, int h, CursorShape shape)
134 color_ = guiApp->colorCache().get(Color::cursor);
138 rect_ = QRect(x, y, CursorWidth + h / 3, h);
140 case REVERSED_L_SHAPE:
141 rect_ = QRect(x - h / 3, y, CursorWidth + h / 3, h);
144 rect_ = QRect(x, y, CursorWidth, h);
149 void show(bool set_show = true) { show_ = set_show; }
150 void hide() { show_ = false; }
152 QRect const & rect() { return rect_; }
166 // This is a 'heartbeat' generating synthetic mouse move events when the
167 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
168 SyntheticMouseEvent::SyntheticMouseEvent()
169 : timeout(200), restart_timeout(true),
170 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
174 GuiWorkArea::GuiWorkArea(Buffer & buf, LyXView & lv)
175 : WorkArea(buf, lv), need_resize_(false), schedule_redraw_(false),
178 screen_ = QPixmap(viewport()->width(), viewport()->height());
179 cursor_ = new frontend::CursorWidget();
182 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
183 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
184 setAcceptDrops(true);
185 setMouseTracking(true);
186 setMinimumSize(100, 70);
188 viewport()->setAutoFillBackground(false);
189 // We don't need double-buffering nor SystemBackground on
190 // the viewport because we have our own backing pixmap.
191 viewport()->setAttribute(Qt::WA_NoSystemBackground);
193 setFocusPolicy(Qt::WheelFocus);
195 viewport()->setCursor(Qt::IBeamCursor);
197 synthetic_mouse_event_.timeout.timeout.connect(
198 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
201 // Initialize the vertical Scroll Bar
202 QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
203 this, SLOT(adjustViewWithScrollBar(int)));
205 // disable context menu for the scrollbar
206 verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu);
208 // PageStep only depends on the viewport height.
209 verticalScrollBar()->setPageStep(viewport()->height());
211 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
212 << "\n Area width\t" << width()
213 << "\n Area height\t" << height()
214 << "\n viewport width\t" << viewport()->width()
215 << "\n viewport height\t" << viewport()->height()
218 // Enables input methods for asian languages.
219 // Must be set when creating custom text editing widgets.
220 setAttribute(Qt::WA_InputMethodEnabled, true);
224 void GuiWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
226 if (verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOn)
227 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
229 verticalScrollBar()->setTracking(false);
231 // do what cursor movement does (some grey)
233 int scroll_max_ = std::max(0, h - height());
235 verticalScrollBar()->setRange(0, scroll_max_);
236 verticalScrollBar()->setSliderPosition(scroll_pos);
237 verticalScrollBar()->setSingleStep(scroll_line_step);
238 verticalScrollBar()->setValue(scroll_pos);
240 verticalScrollBar()->setTracking(true);
244 void GuiWorkArea::adjustViewWithScrollBar(int action)
246 stopBlinkingCursor();
247 if (action == QAbstractSlider::SliderPageStepAdd)
248 buffer_view_->scrollDown(viewport()->height());
249 else if (action == QAbstractSlider::SliderPageStepSub)
250 buffer_view_->scrollUp(viewport()->height());
252 buffer_view_->scrollDocView(verticalScrollBar()->sliderPosition());
254 if (lyxrc.cursor_follows_scrollbar) {
255 buffer_view_->setCursorFromScrollbar();
256 lyx_view_->updateLayoutChoice();
258 // Show the cursor immediately after any operation.
259 startBlinkingCursor();
260 QApplication::syncX();
264 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
266 // Repaint the whole screen.
267 // Note: this is different from redraw() as only the backing pixmap
268 // will be redrawn, which is cheap.
269 viewport()->repaint();
271 startBlinkingCursor();
275 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
277 stopBlinkingCursor();
281 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
283 if (dc_event_.active && dc_event_ == *e) {
284 dc_event_.active = false;
285 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
287 q_button_state(e->button()));
292 inputContext()->reset();
294 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
295 q_button_state(e->button()));
296 dispatch(cmd, q_key_state(e->modifiers()));
300 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
302 if (synthetic_mouse_event_.timeout.running())
303 synthetic_mouse_event_.timeout.stop();
305 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
306 q_button_state(e->button()));
311 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
313 // we kill the triple click if we move
314 doubleClickTimeout();
315 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
316 q_motion_state(e->buttons()));
318 // If we're above or below the work area...
319 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
320 // Make sure only a synthetic event can cause a page scroll,
321 // so they come at a steady rate:
323 // _Force_ a scroll up:
326 cmd.y = viewport()->height();
327 // Store the event, to be handled when the timeout expires.
328 synthetic_mouse_event_.cmd = cmd;
330 if (synthetic_mouse_event_.timeout.running())
331 // Discard the event. Note that it _may_ be handled
332 // when the timeout expires if
333 // synthetic_mouse_event_.cmd has not been overwritten.
334 // Ie, when the timeout expires, we handle the
335 // most recent event but discard all others that
336 // occurred after the one used to start the timeout
337 // in the first place.
340 synthetic_mouse_event_.restart_timeout = true;
341 synthetic_mouse_event_.timeout.start();
342 // Fall through to handle this event...
345 } else if (synthetic_mouse_event_.timeout.running()) {
346 // Store the event, to be possibly handled when the timeout
348 // Once the timeout has expired, normal control is returned
349 // to mouseMoveEvent (restart_timeout = false).
350 // This results in a much smoother 'feel' when moving the
351 // mouse back into the work area.
352 synthetic_mouse_event_.cmd = cmd;
353 synthetic_mouse_event_.restart_timeout = false;
357 // Has anything changed on-screen since the last QMouseEvent
359 double const scrollbar_value = verticalScrollBar()->value();
360 if (e->x() != synthetic_mouse_event_.x_old ||
361 e->y() != synthetic_mouse_event_.y_old ||
362 scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
363 // Yes it has. Store the params used to check this.
364 synthetic_mouse_event_.x_old = e->x();
365 synthetic_mouse_event_.y_old = e->y();
366 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
368 // ... and dispatch the event to the LyX core.
374 void GuiWorkArea::wheelEvent(QWheelEvent * e)
376 // Wheel rotation by one notch results in a delta() of 120 (see
377 // documentation of QWheelEvent)
378 int const lines = qApp->wheelScrollLines() * e->delta() / 120;
379 verticalScrollBar()->setValue(verticalScrollBar()->value() -
380 lines * verticalScrollBar()->singleStep());
381 adjustViewWithScrollBar();
385 void GuiWorkArea::generateSyntheticMouseEvent()
387 // Set things off to generate the _next_ 'pseudo' event.
388 if (synthetic_mouse_event_.restart_timeout)
389 synthetic_mouse_event_.timeout.start();
391 // Has anything changed on-screen since the last timeout signal
393 double const scrollbar_value = verticalScrollBar()->value();
394 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
395 // Yes it has. Store the params used to check this.
396 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
398 // ... and dispatch the event to the LyX core.
399 dispatch(synthetic_mouse_event_.cmd);
404 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
406 // do nothing if there are other events
407 // (the auto repeated events come too fast)
408 // \todo FIXME: remove hard coded Qt keys, process the key binding
410 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
411 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
413 << BOOST_CURRENT_FUNCTION << endl
414 << "system is busy: scroll key event ignored" << endl;
420 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
421 << " count=" << ev->count()
422 << " text=" << fromqstr(ev->text())
423 << " isAutoRepeat=" << ev->isAutoRepeat()
424 << " key=" << ev->key()
428 setKeySymbol(&sym, ev);
429 processKeySym(sym, q_key_state(ev->modifiers()));
433 void GuiWorkArea::doubleClickTimeout()
435 dc_event_.active = false;
439 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
441 dc_event_ = double_click(ev);
442 QTimer::singleShot(QApplication::doubleClickInterval(), this,
443 SLOT(doubleClickTimeout()));
444 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
446 q_button_state(ev->button()));
451 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
453 QAbstractScrollArea::resizeEvent(ev);
458 void GuiWorkArea::update(int x, int y, int w, int h)
460 viewport()->repaint(x, y, w, h);
464 void GuiWorkArea::paintEvent(QPaintEvent * ev)
466 QRect const rc = ev->rect();
468 LYXERR(Debug::PAINTING) << "paintEvent begin: x: " << rc.x()
470 << " w: " << rc.width()
471 << " h: " << rc.height() << endl;
475 verticalScrollBar()->setPageStep(viewport()->height());
476 screen_ = QPixmap(viewport()->width(), viewport()->height());
479 WorkArea::hideCursor();
480 WorkArea::showCursor();
481 need_resize_ = false;
484 QPainter pain(viewport());
485 pain.drawPixmap(rc, screen_, rc);
490 void GuiWorkArea::expose(int x, int y, int w, int h)
497 void GuiWorkArea::updateScreen()
499 GuiPainter pain(&screen_);
500 verticalScrollBar()->show();
501 buffer_view_->draw(pain);
505 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
507 if (schedule_redraw_) {
508 buffer_view_->update(Update::Force);
510 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
511 schedule_redraw_ = false;
512 // Show the cursor immediately after the update.
518 cursor_->update(x, y, h, shape);
520 viewport()->update(cursor_->rect());
524 void GuiWorkArea::removeCursor()
527 //if (!qApp->focusWidget())
528 viewport()->update(cursor_->rect());
532 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
534 QString const & commit_string = e->commitString();
535 docstring const & preedit_string
536 = qstring_to_ucs4(e->preeditString());
538 if (!commit_string.isEmpty()) {
540 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
541 << " preeditString =" << fromqstr(e->preeditString())
542 << " commitString =" << fromqstr(e->commitString())
547 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
548 for (int i = 0; i < commit_string.size(); ++i) {
549 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
554 // Hide the cursor during the kana-kanji transformation.
555 if (preedit_string.empty())
556 startBlinkingCursor();
558 stopBlinkingCursor();
560 // last_width : for checking if last preedit string was/wasn't empty.
561 static bool last_width = false;
562 if (!last_width && preedit_string.empty()) {
563 // if last_width is last length of preedit string.
568 GuiPainter pain(&screen_);
569 buffer_view_->updateMetrics(false);
570 buffer_view_->draw(pain);
571 Font font = buffer_view_->cursor().getFont();
572 FontMetrics const & fm = theFontMetrics(font);
573 int height = fm.maxHeight();
574 int cur_x = cursor_->rect().left();
575 int cur_y = cursor_->rect().bottom();
577 // redraw area of preedit string.
578 update(0, cur_y - height, GuiWorkArea::width(),
579 (height + 1) * preedit_lines_);
581 if (preedit_string.empty()) {
589 // att : stores an IM attribute.
590 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
592 // get attributes of input method cursor.
593 // cursor_pos : cursor position in preedit string.
594 size_t cursor_pos = 0;
595 bool cursor_is_visible = false;
596 for (int i = 0; i < att.size(); ++i) {
597 if (att.at(i).type == QInputMethodEvent::Cursor) {
598 cursor_pos = att.at(i).start;
599 cursor_is_visible = att.at(i).length != 0;
604 size_t preedit_length = preedit_string.length();
606 // get position of selection in input method.
607 // FIXME: isn't there a way to do this simplier?
608 // rStart : cursor position in selected string in IM.
610 // rLength : selected string length in IM.
612 if (cursor_pos < preedit_length) {
613 for (int i = 0; i < att.size(); ++i) {
614 if (att.at(i).type == QInputMethodEvent::TextFormat) {
615 if (att.at(i).start <= int(cursor_pos)
616 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
617 rStart = att.at(i).start;
618 rLength = att.at(i).length;
619 if (!cursor_is_visible)
620 cursor_pos += rLength;
631 int const right_margin = rightMargin();
632 Painter::preedit_style ps;
633 // Most often there would be only one line:
635 for (size_t pos = 0; pos != preedit_length; ++pos) {
636 char_type const typed_char = preedit_string[pos];
637 // reset preedit string style
638 ps = Painter::preedit_default;
640 // if we reached the right extremity of the screen, go to next line.
641 if (cur_x + fm.width(typed_char) > GuiWorkArea::width() - right_margin) {
642 cur_x = right_margin;
646 // preedit strings are displayed with dashed underline
647 // and partial strings are displayed white on black indicating
648 // that we are in selecting mode in the input method.
649 // FIXME: rLength == preedit_length is not a changing condition
650 // FIXME: should be put out of the loop.
652 && pos < rStart + rLength
653 && !(cursor_pos < rLength && rLength == preedit_length))
654 ps = Painter::preedit_selecting;
656 if (pos == cursor_pos
657 && (cursor_pos < rLength && rLength == preedit_length))
658 ps = Painter::preedit_cursor;
660 // draw one character and update cur_x.
661 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
664 // update the preedit string screen area.
665 update(0, cur_y - preedit_lines_*height, GuiWorkArea::width(),
666 (height + 1) * preedit_lines_);
668 // Don't forget to accept the event!
673 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
675 QRect cur_r(0,0,0,0);
677 // this is the CJK-specific composition window position.
678 case Qt::ImMicroFocus:
679 cur_r = cursor_->rect();
680 if (preedit_lines_ != 1)
682 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
683 // return lower right of cursor in LyX.
686 return QWidget::inputMethodQuery(query);
690 } // namespace frontend
693 #include "GuiWorkArea_moc.cpp"