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;
64 using support::FileName;
66 /// return the LyX key state from Qt's
67 static key_modifier::state q_key_state(Qt::KeyboardModifiers state)
69 key_modifier::state k = key_modifier::none;
70 if (state & Qt::ControlModifier)
71 k |= key_modifier::ctrl;
72 if (state & Qt::ShiftModifier)
73 k |= key_modifier::shift;
74 if (state & Qt::AltModifier || state & Qt::MetaModifier)
75 k |= key_modifier::alt;
80 /// return the LyX mouse button state from Qt's
81 static mouse_button::state q_button_state(Qt::MouseButton button)
83 mouse_button::state b = mouse_button::none;
86 b = mouse_button::button1;
89 b = mouse_button::button2;
92 b = mouse_button::button3;
101 /// return the LyX mouse button state from Qt's
102 mouse_button::state q_motion_state(Qt::MouseButtons state)
104 mouse_button::state b = mouse_button::none;
105 if (state & Qt::LeftButton)
106 b |= mouse_button::button1;
107 if (state & Qt::MidButton)
108 b |= mouse_button::button2;
109 if (state & Qt::RightButton)
110 b |= mouse_button::button3;
121 void draw(QPainter & painter)
123 if (show_ && rect_.isValid()) {
126 painter.fillRect(rect_.x(), rect_.y(), CursorWidth, rect_.height(), color_);
127 painter.setPen(color_);
128 painter.drawLine(rect_.bottomLeft().x() + CursorWidth, rect_.bottomLeft().y(),
129 rect_.bottomRight().x(), rect_.bottomLeft().y());
132 case REVERSED_L_SHAPE:
133 painter.fillRect(rect_.x() + rect_.height() / 3, rect_.y(), CursorWidth, rect_.height(), color_);
134 painter.setPen(color_);
135 painter.drawLine(rect_.bottomRight().x() - CursorWidth, rect_.bottomLeft().y(),
136 rect_.bottomLeft().x(), rect_.bottomLeft().y());
140 painter.fillRect(rect_, color_);
146 void update(int x, int y, int h, CursorShape shape)
148 color_ = guiApp->colorCache().get(Color::cursor);
152 rect_ = QRect(x, y, CursorWidth + h / 3, h);
154 case REVERSED_L_SHAPE:
155 rect_ = QRect(x - h / 3, y, CursorWidth + h / 3, h);
158 rect_ = QRect(x, y, CursorWidth, h);
163 void show(bool set_show = true) { show_ = set_show; }
164 void hide() { show_ = false; }
166 QRect const & rect() { return rect_; }
180 // This is a 'heartbeat' generating synthetic mouse move events when the
181 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
182 SyntheticMouseEvent::SyntheticMouseEvent()
183 : timeout(200), restart_timeout(true),
184 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
188 GuiWorkArea::GuiWorkArea(int w, int h, int id, LyXView & lyx_view)
189 : WorkArea(id, lyx_view), need_resize_(false), schedule_redraw_(false),
192 screen_ = QPixmap(viewport()->width(), viewport()->height());
193 cursor_ = new frontend::CursorWidget();
196 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
197 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
198 setAcceptDrops(true);
199 setMouseTracking(true);
200 setMinimumSize(100, 70);
202 viewport()->setAutoFillBackground(false);
203 // We don't need double-buffering nor SystemBackground on
204 // the viewport because we have our own backing pixmap.
205 viewport()->setAttribute(Qt::WA_NoSystemBackground);
207 setFocusPolicy(Qt::WheelFocus);
209 viewport()->setCursor(Qt::IBeamCursor);
213 synthetic_mouse_event_.timeout.timeout.connect(
214 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
217 // Initialize the vertical Scroll Bar
218 QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
219 this, SLOT(adjustViewWithScrollBar(int)));
221 // disable context menu for the scrollbar
222 verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu);
224 // PageStep only depends on the viewport height.
225 verticalScrollBar()->setPageStep(viewport()->height());
227 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
228 << "\n Area width\t" << width()
229 << "\n Area height\t" << height()
230 << "\n viewport width\t" << viewport()->width()
231 << "\n viewport height\t" << viewport()->height()
234 // Enables input methods for asian languages.
235 // Must be set when creating custom text editing widgets.
236 setAttribute(Qt::WA_InputMethodEnabled, true);
240 void GuiWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
242 if (verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOn)
243 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
245 verticalScrollBar()->setTracking(false);
247 // do what cursor movement does (some grey)
249 int scroll_max_ = std::max(0, h - height());
251 verticalScrollBar()->setRange(0, scroll_max_);
252 verticalScrollBar()->setSliderPosition(scroll_pos);
253 verticalScrollBar()->setSingleStep(scroll_line_step);
254 verticalScrollBar()->setValue(scroll_pos);
256 verticalScrollBar()->setTracking(true);
260 void GuiWorkArea::adjustViewWithScrollBar(int)
262 scrollBufferView(verticalScrollBar()->sliderPosition());
263 QApplication::syncX();
267 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
269 // No need to do anything if we didn't change views...
270 // if (theApp() == 0 || &lyx_view_ == theApp()->currentView())
273 theApp()->setCurrentView(lyx_view_);
275 // Repaint the whole screen.
276 // Note: this is different from redraw() as only the backing pixmap
277 // will be redrawn, which is cheap.
278 viewport()->repaint();
280 // FIXME: it would be better to send a signal "newBuffer()"
281 // in BufferList that could be connected to the different tabbars.
282 lyx_view_.updateTab();
284 startBlinkingCursor();
288 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
290 stopBlinkingCursor();
294 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
296 if (dc_event_.active && dc_event_ == *e) {
297 dc_event_.active = false;
298 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
300 q_button_state(e->button()));
305 inputContext()->reset();
307 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
308 q_button_state(e->button()));
309 dispatch(cmd, q_key_state(e->modifiers()));
313 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
315 if (synthetic_mouse_event_.timeout.running())
316 synthetic_mouse_event_.timeout.stop();
318 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
319 q_button_state(e->button()));
324 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
326 // we kill the triple click if we move
327 doubleClickTimeout();
328 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
329 q_motion_state(e->buttons()));
331 // If we're above or below the work area...
332 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
333 // Make sure only a synthetic event can cause a page scroll,
334 // so they come at a steady rate:
336 // _Force_ a scroll up:
339 cmd.y = viewport()->height();
340 // Store the event, to be handled when the timeout expires.
341 synthetic_mouse_event_.cmd = cmd;
343 if (synthetic_mouse_event_.timeout.running())
344 // Discard the event. Note that it _may_ be handled
345 // when the timeout expires if
346 // synthetic_mouse_event_.cmd has not been overwritten.
347 // Ie, when the timeout expires, we handle the
348 // most recent event but discard all others that
349 // occurred after the one used to start the timeout
350 // in the first place.
353 synthetic_mouse_event_.restart_timeout = true;
354 synthetic_mouse_event_.timeout.start();
355 // Fall through to handle this event...
358 } else if (synthetic_mouse_event_.timeout.running()) {
359 // Store the event, to be possibly handled when the timeout
361 // Once the timeout has expired, normal control is returned
362 // to mouseMoveEvent (restart_timeout = false).
363 // This results in a much smoother 'feel' when moving the
364 // mouse back into the work area.
365 synthetic_mouse_event_.cmd = cmd;
366 synthetic_mouse_event_.restart_timeout = false;
370 // Has anything changed on-screen since the last QMouseEvent
372 double const scrollbar_value = verticalScrollBar()->value();
373 if (e->x() != synthetic_mouse_event_.x_old ||
374 e->y() != synthetic_mouse_event_.y_old ||
375 scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
376 // Yes it has. Store the params used to check this.
377 synthetic_mouse_event_.x_old = e->x();
378 synthetic_mouse_event_.y_old = e->y();
379 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
381 // ... and dispatch the event to the LyX core.
387 void GuiWorkArea::wheelEvent(QWheelEvent * e)
389 // Wheel rotation by one notch results in a delta() of 120 (see
390 // documentation of QWheelEvent)
391 int const lines = qApp->wheelScrollLines() * e->delta() / 120;
392 verticalScrollBar()->setValue(verticalScrollBar()->value() -
393 lines * verticalScrollBar()->singleStep());
394 adjustViewWithScrollBar();
398 void GuiWorkArea::generateSyntheticMouseEvent()
400 // Set things off to generate the _next_ 'pseudo' event.
401 if (synthetic_mouse_event_.restart_timeout)
402 synthetic_mouse_event_.timeout.start();
404 // Has anything changed on-screen since the last timeout signal
406 double const scrollbar_value = verticalScrollBar()->value();
407 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
408 // Yes it has. Store the params used to check this.
409 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
411 // ... and dispatch the event to the LyX core.
412 dispatch(synthetic_mouse_event_.cmd);
417 void GuiWorkArea::keyPressEvent(QKeyEvent * e)
419 // do nothing if there are other events
420 // (the auto repeated events come too fast)
421 // \todo FIXME: remove hard coded Qt keys, process the key binding
423 if (XEventsQueued(QX11Info::display(), 0) > 1 && e->isAutoRepeat()
424 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
426 << BOOST_CURRENT_FUNCTION << endl
427 << "system is busy: scroll key event ignored" << endl;
433 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
434 << " count=" << e->count()
435 << " text=" << fromqstr(e->text())
436 << " isAutoRepeat=" << e->isAutoRepeat()
437 << " key=" << e->key()
440 boost::shared_ptr<QKeySymbol> sym(new QKeySymbol);
442 processKeySym(sym, q_key_state(e->modifiers()));
445 void GuiWorkArea::doubleClickTimeout() {
446 dc_event_.active = false;
449 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
451 dc_event_ = double_click(e);
452 QTimer::singleShot(QApplication::doubleClickInterval(), this,
453 SLOT(doubleClickTimeout()));
454 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
456 q_button_state(e->button()));
461 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
463 QAbstractScrollArea::resizeEvent(ev);
468 void GuiWorkArea::update(int x, int y, int w, int h)
470 viewport()->repaint(x, y, w, h);
474 void GuiWorkArea::doGreyOut(QLPainter & pain)
476 pain.fillRectangle(0, 0, width(), height(),
479 //if (!lyxrc.show_banner)
481 LYXERR(Debug::GUI) << "show banner: " << lyxrc.show_banner << endl;
482 /// The text to be written on top of the pixmap
483 QString const text = lyx_version ? QString(lyx_version) : qt_("unknown version");
484 FileName const file = support::libFileSearch("images", "banner", "png");
488 QPixmap pm(toqstr(file.absFilename()));
490 lyxerr << "could not load splash screen: '" << file << "'" << endl;
495 // The font used to display the version info
496 font.setStyleHint(QFont::SansSerif);
497 font.setWeight(QFont::Bold);
498 font.setPointSize(convert<int>(lyxrc.font_sizes[Font::SIZE_LARGE]));
500 int const w = pm.width();
501 int const h = pm.height();
503 int x = (width() - w) / 2;
504 int y = (height() - h) / 2;
506 pain.drawPixmap(x, y, pm);
511 pain.setPen(QColor(255, 255, 0));
513 pain.drawText(x, y, text);
517 void GuiWorkArea::paintEvent(QPaintEvent * ev)
519 QRect const rc = ev->rect();
521 LYXERR(Debug::PAINTING) << "paintEvent begin: x: " << rc.x()
523 << " w: " << rc.width()
524 << " h: " << rc.height() << endl;
528 verticalScrollBar()->setPageStep(viewport()->height());
529 screen_ = QPixmap(viewport()->width(), viewport()->height());
532 WorkArea::hideCursor();
533 WorkArea::showCursor();
534 need_resize_ = false;
537 QPainter pain(viewport());
538 pain.drawPixmap(rc, screen_, rc);
543 void GuiWorkArea::expose(int x, int y, int w, int h)
550 void GuiWorkArea::updateScreen()
552 QLPainter pain(&screen_);
555 LYXERR(Debug::GUI) << "splash screen requested" << endl;
556 verticalScrollBar()->hide();
561 verticalScrollBar()->show();
562 paintText(*buffer_view_, pain);
566 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
568 if (schedule_redraw_) {
569 if (buffer_view_ && buffer_view_->buffer()) {
570 buffer_view_->update(Update::Force);
572 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
574 schedule_redraw_ = false;
575 // Show the cursor immediately after the update.
581 cursor_->update(x, y, h, shape);
583 viewport()->update(cursor_->rect());
587 void GuiWorkArea::removeCursor()
590 //if (!qApp->focusWidget())
591 viewport()->update(cursor_->rect());
595 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
597 QString const & commit_string = e->commitString();
598 docstring const & preedit_string
599 = qstring_to_ucs4(e->preeditString());
606 if (!commit_string.isEmpty()) {
608 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
609 << " preeditString =" << fromqstr(e->preeditString())
610 << " commitString =" << fromqstr(e->commitString())
615 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
616 for (int i = 0; i < commit_string.size(); ++i) {
617 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
622 // Hide the cursor during the kana-kanji transformation.
623 if (preedit_string.empty())
624 startBlinkingCursor();
626 stopBlinkingCursor();
628 // last_width : for checking if last preedit string was/wasn't empty.
629 static bool last_width = false;
630 if (!last_width && preedit_string.empty()) {
631 // if last_width is last length of preedit string.
636 QLPainter pain(&screen_);
637 buffer_view_->updateMetrics(false);
638 paintText(*buffer_view_, pain);
639 Font font = buffer_view_->cursor().getFont();
640 FontMetrics const & fm = theFontMetrics(font);
641 int height = fm.maxHeight();
642 int cur_x = cursor_->rect().left();
643 int cur_y = cursor_->rect().bottom();
645 // redraw area of preedit string.
646 update(0, cur_y - height, GuiWorkArea::width(),
647 (height + 1) * preedit_lines_);
649 if (preedit_string.empty()) {
657 // att : stores an IM attribute.
658 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
660 // get attributes of input method cursor.
661 // cursor_pos : cursor position in preedit string.
662 size_t cursor_pos = 0;
663 bool cursor_is_visible = false;
664 for (int i = 0; i < att.size(); ++i) {
665 if (att.at(i).type == QInputMethodEvent::Cursor) {
666 cursor_pos = att.at(i).start;
667 cursor_is_visible = att.at(i).length != 0;
672 size_t preedit_length = preedit_string.length();
674 // get position of selection in input method.
675 // FIXME: isn't there a way to do this simplier?
676 // rStart : cursor position in selected string in IM.
678 // rLength : selected string length in IM.
680 if (cursor_pos < preedit_length) {
681 for (int i = 0; i < att.size(); ++i) {
682 if (att.at(i).type == QInputMethodEvent::TextFormat) {
683 if (att.at(i).start <= int(cursor_pos)
684 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
685 rStart = att.at(i).start;
686 rLength = att.at(i).length;
687 if (!cursor_is_visible)
688 cursor_pos += rLength;
699 int const right_margin = rightMargin();
700 Painter::preedit_style ps;
701 // Most often there would be only one line:
703 for (size_t pos = 0; pos != preedit_length; ++pos) {
704 char_type const typed_char = preedit_string[pos];
705 // reset preedit string style
706 ps = Painter::preedit_default;
708 // if we reached the right extremity of the screen, go to next line.
709 if (cur_x + fm.width(typed_char) > GuiWorkArea::width() - right_margin) {
710 cur_x = right_margin;
714 // preedit strings are displayed with dashed underline
715 // and partial strings are displayed white on black indicating
716 // that we are in selecting mode in the input method.
717 // FIXME: rLength == preedit_length is not a changing condition
718 // FIXME: should be put out of the loop.
720 && pos < rStart + rLength
721 && !(cursor_pos < rLength && rLength == preedit_length))
722 ps = Painter::preedit_selecting;
724 if (pos == cursor_pos
725 && (cursor_pos < rLength && rLength == preedit_length))
726 ps = Painter::preedit_cursor;
728 // draw one character and update cur_x.
729 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
732 // update the preedit string screen area.
733 update(0, cur_y - preedit_lines_*height, GuiWorkArea::width(),
734 (height + 1) * preedit_lines_);
736 // Don't forget to accept the event!
741 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
743 QRect cur_r(0,0,0,0);
745 // this is the CJK-specific composition window position.
746 case Qt::ImMicroFocus:
747 cur_r = cursor_->rect();
748 if (preedit_lines_ != 1)
750 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
751 // return lower right of cursor in LyX.
754 return QWidget::inputMethodQuery(query);
758 } // namespace frontend
761 #include "GuiWorkArea_moc.cpp"