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 "QLPainter.h"
18 #include "QKeySymbol.h"
19 #include "qt_helpers.h"
21 #include "frontends/LyXView.h"
23 #include "BufferView.h"
26 #include "FuncRequest.h"
28 #include "rowpainter.h"
31 #include "support/filetools.h" // LibFileSearch
32 #include "support/convert.h"
34 #include "graphics/GraphicsImage.h"
35 #include "graphics/GraphicsLoader.h"
37 #include <QInputContext>
39 #include <QMainWindow>
44 #include <boost/bind.hpp>
45 #include <boost/current_function.hpp>
49 extern "C" int XEventsQueued(Display *display, int mode);
53 int const CursorWidth = 2;
55 int const CursorWidth = 1;
66 using support::FileName;
68 /// return the LyX mouse button state from Qt's
69 static mouse_button::state q_button_state(Qt::MouseButton button)
71 mouse_button::state b = mouse_button::none;
74 b = mouse_button::button1;
77 b = mouse_button::button2;
80 b = mouse_button::button3;
89 /// return the LyX mouse button state from Qt's
90 mouse_button::state q_motion_state(Qt::MouseButtons state)
92 mouse_button::state b = mouse_button::none;
93 if (state & Qt::LeftButton)
94 b |= mouse_button::button1;
95 if (state & Qt::MidButton)
96 b |= mouse_button::button2;
97 if (state & Qt::RightButton)
98 b |= mouse_button::button3;
109 void draw(QPainter & painter)
111 if (show_ && rect_.isValid()) {
114 painter.fillRect(rect_.x(), rect_.y(), CursorWidth, rect_.height(), color_);
115 painter.setPen(color_);
116 painter.drawLine(rect_.bottomLeft().x() + CursorWidth, rect_.bottomLeft().y(),
117 rect_.bottomRight().x(), rect_.bottomLeft().y());
120 case REVERSED_L_SHAPE:
121 painter.fillRect(rect_.x() + rect_.height() / 3, rect_.y(), CursorWidth, rect_.height(), color_);
122 painter.setPen(color_);
123 painter.drawLine(rect_.bottomRight().x() - CursorWidth, rect_.bottomLeft().y(),
124 rect_.bottomLeft().x(), rect_.bottomLeft().y());
128 painter.fillRect(rect_, color_);
134 void update(int x, int y, int h, CursorShape shape)
136 color_ = guiApp->colorCache().get(Color::cursor);
140 rect_ = QRect(x, y, CursorWidth + h / 3, h);
142 case REVERSED_L_SHAPE:
143 rect_ = QRect(x - h / 3, y, CursorWidth + h / 3, h);
146 rect_ = QRect(x, y, CursorWidth, h);
151 void show(bool set_show = true) { show_ = set_show; }
152 void hide() { show_ = false; }
154 QRect const & rect() { return rect_; }
168 // This is a 'heartbeat' generating synthetic mouse move events when the
169 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
170 SyntheticMouseEvent::SyntheticMouseEvent()
171 : timeout(200), restart_timeout(true),
172 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
176 GuiWorkArea::GuiWorkArea(Buffer & buf, LyXView & lv)
177 : WorkArea(buf, lv), need_resize_(false), schedule_redraw_(false),
180 screen_ = QPixmap(viewport()->width(), viewport()->height());
181 cursor_ = new frontend::CursorWidget();
184 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
185 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
186 setAcceptDrops(true);
187 setMouseTracking(true);
188 setMinimumSize(100, 70);
190 viewport()->setAutoFillBackground(false);
191 // We don't need double-buffering nor SystemBackground on
192 // the viewport because we have our own backing pixmap.
193 viewport()->setAttribute(Qt::WA_NoSystemBackground);
195 setFocusPolicy(Qt::WheelFocus);
197 viewport()->setCursor(Qt::IBeamCursor);
199 synthetic_mouse_event_.timeout.timeout.connect(
200 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
203 // Initialize the vertical Scroll Bar
204 QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
205 this, SLOT(adjustViewWithScrollBar(int)));
207 // disable context menu for the scrollbar
208 verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu);
210 // PageStep only depends on the viewport height.
211 verticalScrollBar()->setPageStep(viewport()->height());
213 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
214 << "\n Area width\t" << width()
215 << "\n Area height\t" << height()
216 << "\n viewport width\t" << viewport()->width()
217 << "\n viewport height\t" << viewport()->height()
220 // Enables input methods for asian languages.
221 // Must be set when creating custom text editing widgets.
222 setAttribute(Qt::WA_InputMethodEnabled, true);
226 void GuiWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
228 if (verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOn)
229 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
231 verticalScrollBar()->setTracking(false);
233 // do what cursor movement does (some grey)
235 int scroll_max_ = std::max(0, h - height());
237 verticalScrollBar()->setRange(0, scroll_max_);
238 verticalScrollBar()->setSliderPosition(scroll_pos);
239 verticalScrollBar()->setSingleStep(scroll_line_step);
240 verticalScrollBar()->setValue(scroll_pos);
242 verticalScrollBar()->setTracking(true);
246 void GuiWorkArea::adjustViewWithScrollBar(int)
248 scrollBufferView(verticalScrollBar()->sliderPosition());
249 QApplication::syncX();
253 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
255 // No need to do anything if we didn't change views...
256 // if (theApp() == 0 || &lyx_view_ == theApp()->currentView())
259 theApp()->setCurrentView(*lyx_view_);
261 // Repaint the whole screen.
262 // Note: this is different from redraw() as only the backing pixmap
263 // will be redrawn, which is cheap.
264 viewport()->repaint();
266 startBlinkingCursor();
270 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
272 stopBlinkingCursor();
276 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
278 if (dc_event_.active && dc_event_ == *e) {
279 dc_event_.active = false;
280 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
282 q_button_state(e->button()));
287 inputContext()->reset();
289 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
290 q_button_state(e->button()));
291 dispatch(cmd, q_key_state(e->modifiers()));
295 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
297 if (synthetic_mouse_event_.timeout.running())
298 synthetic_mouse_event_.timeout.stop();
300 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
301 q_button_state(e->button()));
306 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
308 // we kill the triple click if we move
309 doubleClickTimeout();
310 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
311 q_motion_state(e->buttons()));
313 // If we're above or below the work area...
314 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
315 // Make sure only a synthetic event can cause a page scroll,
316 // so they come at a steady rate:
318 // _Force_ a scroll up:
321 cmd.y = viewport()->height();
322 // Store the event, to be handled when the timeout expires.
323 synthetic_mouse_event_.cmd = cmd;
325 if (synthetic_mouse_event_.timeout.running())
326 // Discard the event. Note that it _may_ be handled
327 // when the timeout expires if
328 // synthetic_mouse_event_.cmd has not been overwritten.
329 // Ie, when the timeout expires, we handle the
330 // most recent event but discard all others that
331 // occurred after the one used to start the timeout
332 // in the first place.
335 synthetic_mouse_event_.restart_timeout = true;
336 synthetic_mouse_event_.timeout.start();
337 // Fall through to handle this event...
340 } else if (synthetic_mouse_event_.timeout.running()) {
341 // Store the event, to be possibly handled when the timeout
343 // Once the timeout has expired, normal control is returned
344 // to mouseMoveEvent (restart_timeout = false).
345 // This results in a much smoother 'feel' when moving the
346 // mouse back into the work area.
347 synthetic_mouse_event_.cmd = cmd;
348 synthetic_mouse_event_.restart_timeout = false;
352 // Has anything changed on-screen since the last QMouseEvent
354 double const scrollbar_value = verticalScrollBar()->value();
355 if (e->x() != synthetic_mouse_event_.x_old ||
356 e->y() != synthetic_mouse_event_.y_old ||
357 scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
358 // Yes it has. Store the params used to check this.
359 synthetic_mouse_event_.x_old = e->x();
360 synthetic_mouse_event_.y_old = e->y();
361 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
363 // ... and dispatch the event to the LyX core.
369 void GuiWorkArea::wheelEvent(QWheelEvent * e)
371 // Wheel rotation by one notch results in a delta() of 120 (see
372 // documentation of QWheelEvent)
373 int const lines = qApp->wheelScrollLines() * e->delta() / 120;
374 verticalScrollBar()->setValue(verticalScrollBar()->value() -
375 lines * verticalScrollBar()->singleStep());
376 adjustViewWithScrollBar();
380 void GuiWorkArea::generateSyntheticMouseEvent()
382 // Set things off to generate the _next_ 'pseudo' event.
383 if (synthetic_mouse_event_.restart_timeout)
384 synthetic_mouse_event_.timeout.start();
386 // Has anything changed on-screen since the last timeout signal
388 double const scrollbar_value = verticalScrollBar()->value();
389 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
390 // Yes it has. Store the params used to check this.
391 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
393 // ... and dispatch the event to the LyX core.
394 dispatch(synthetic_mouse_event_.cmd);
399 void GuiWorkArea::keyPressEvent(QKeyEvent * e)
401 // do nothing if there are other events
402 // (the auto repeated events come too fast)
403 // \todo FIXME: remove hard coded Qt keys, process the key binding
405 if (XEventsQueued(QX11Info::display(), 0) > 1 && e->isAutoRepeat()
406 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
408 << BOOST_CURRENT_FUNCTION << endl
409 << "system is busy: scroll key event ignored" << endl;
415 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
416 << " count=" << e->count()
417 << " text=" << fromqstr(e->text())
418 << " isAutoRepeat=" << e->isAutoRepeat()
419 << " key=" << e->key()
422 boost::shared_ptr<QKeySymbol> sym(new QKeySymbol);
424 processKeySym(sym, q_key_state(e->modifiers()));
427 void GuiWorkArea::doubleClickTimeout() {
428 dc_event_.active = false;
431 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
433 dc_event_ = double_click(e);
434 QTimer::singleShot(QApplication::doubleClickInterval(), this,
435 SLOT(doubleClickTimeout()));
436 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
438 q_button_state(e->button()));
443 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
445 QAbstractScrollArea::resizeEvent(ev);
450 void GuiWorkArea::update(int x, int y, int w, int h)
452 viewport()->repaint(x, y, w, h);
456 void GuiWorkArea::paintEvent(QPaintEvent * ev)
458 QRect const rc = ev->rect();
460 LYXERR(Debug::PAINTING) << "paintEvent begin: x: " << rc.x()
462 << " w: " << rc.width()
463 << " h: " << rc.height() << endl;
467 verticalScrollBar()->setPageStep(viewport()->height());
468 screen_ = QPixmap(viewport()->width(), viewport()->height());
471 WorkArea::hideCursor();
472 WorkArea::showCursor();
473 need_resize_ = false;
476 QPainter pain(viewport());
477 pain.drawPixmap(rc, screen_, rc);
482 void GuiWorkArea::expose(int x, int y, int w, int h)
489 void GuiWorkArea::updateScreen()
491 QLPainter pain(&screen_);
492 verticalScrollBar()->show();
493 paintText(*buffer_view_, pain);
497 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
499 if (schedule_redraw_) {
500 buffer_view_->update(Update::Force);
502 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
503 schedule_redraw_ = false;
504 // Show the cursor immediately after the update.
510 cursor_->update(x, y, h, shape);
512 viewport()->update(cursor_->rect());
516 void GuiWorkArea::removeCursor()
519 //if (!qApp->focusWidget())
520 viewport()->update(cursor_->rect());
524 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
526 QString const & commit_string = e->commitString();
527 docstring const & preedit_string
528 = qstring_to_ucs4(e->preeditString());
530 if (!commit_string.isEmpty()) {
532 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
533 << " preeditString =" << fromqstr(e->preeditString())
534 << " commitString =" << fromqstr(e->commitString())
539 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
540 for (int i = 0; i < commit_string.size(); ++i) {
541 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
546 // Hide the cursor during the kana-kanji transformation.
547 if (preedit_string.empty())
548 startBlinkingCursor();
550 stopBlinkingCursor();
552 // last_width : for checking if last preedit string was/wasn't empty.
553 static bool last_width = false;
554 if (!last_width && preedit_string.empty()) {
555 // if last_width is last length of preedit string.
560 QLPainter pain(&screen_);
561 buffer_view_->updateMetrics(false);
562 paintText(*buffer_view_, pain);
563 Font font = buffer_view_->cursor().getFont();
564 FontMetrics const & fm = theFontMetrics(font);
565 int height = fm.maxHeight();
566 int cur_x = cursor_->rect().left();
567 int cur_y = cursor_->rect().bottom();
569 // redraw area of preedit string.
570 update(0, cur_y - height, GuiWorkArea::width(),
571 (height + 1) * preedit_lines_);
573 if (preedit_string.empty()) {
581 // att : stores an IM attribute.
582 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
584 // get attributes of input method cursor.
585 // cursor_pos : cursor position in preedit string.
586 size_t cursor_pos = 0;
587 bool cursor_is_visible = false;
588 for (int i = 0; i < att.size(); ++i) {
589 if (att.at(i).type == QInputMethodEvent::Cursor) {
590 cursor_pos = att.at(i).start;
591 cursor_is_visible = att.at(i).length != 0;
596 size_t preedit_length = preedit_string.length();
598 // get position of selection in input method.
599 // FIXME: isn't there a way to do this simplier?
600 // rStart : cursor position in selected string in IM.
602 // rLength : selected string length in IM.
604 if (cursor_pos < preedit_length) {
605 for (int i = 0; i < att.size(); ++i) {
606 if (att.at(i).type == QInputMethodEvent::TextFormat) {
607 if (att.at(i).start <= int(cursor_pos)
608 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
609 rStart = att.at(i).start;
610 rLength = att.at(i).length;
611 if (!cursor_is_visible)
612 cursor_pos += rLength;
623 int const right_margin = rightMargin();
624 Painter::preedit_style ps;
625 // Most often there would be only one line:
627 for (size_t pos = 0; pos != preedit_length; ++pos) {
628 char_type const typed_char = preedit_string[pos];
629 // reset preedit string style
630 ps = Painter::preedit_default;
632 // if we reached the right extremity of the screen, go to next line.
633 if (cur_x + fm.width(typed_char) > GuiWorkArea::width() - right_margin) {
634 cur_x = right_margin;
638 // preedit strings are displayed with dashed underline
639 // and partial strings are displayed white on black indicating
640 // that we are in selecting mode in the input method.
641 // FIXME: rLength == preedit_length is not a changing condition
642 // FIXME: should be put out of the loop.
644 && pos < rStart + rLength
645 && !(cursor_pos < rLength && rLength == preedit_length))
646 ps = Painter::preedit_selecting;
648 if (pos == cursor_pos
649 && (cursor_pos < rLength && rLength == preedit_length))
650 ps = Painter::preedit_cursor;
652 // draw one character and update cur_x.
653 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
656 // update the preedit string screen area.
657 update(0, cur_y - preedit_lines_*height, GuiWorkArea::width(),
658 (height + 1) * preedit_lines_);
660 // Don't forget to accept the event!
665 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
667 QRect cur_r(0,0,0,0);
669 // this is the CJK-specific composition window position.
670 case Qt::ImMicroFocus:
671 cur_r = cursor_->rect();
672 if (preedit_lines_ != 1)
674 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
675 // return lower right of cursor in LyX.
678 return QWidget::inputMethodQuery(query);
682 } // namespace frontend
685 #include "GuiWorkArea_moc.cpp"