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 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(int w, int h, int id, LyXView & lyx_view)
175 : WorkArea(id, lyx_view), 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);
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 // FIXME: it would be better to send a signal "newBuffer()"
267 // in BufferList that could be connected to the different tabbars.
268 lyx_view_.updateTab();
270 startBlinkingCursor();
274 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
276 stopBlinkingCursor();
280 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
282 if (dc_event_.active && dc_event_ == *e) {
283 dc_event_.active = false;
284 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
286 q_button_state(e->button()));
291 inputContext()->reset();
293 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
294 q_button_state(e->button()));
295 dispatch(cmd, q_key_state(e->modifiers()));
299 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
301 if (synthetic_mouse_event_.timeout.running())
302 synthetic_mouse_event_.timeout.stop();
304 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
305 q_button_state(e->button()));
310 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
312 // we kill the triple click if we move
313 doubleClickTimeout();
314 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
315 q_motion_state(e->buttons()));
317 // If we're above or below the work area...
318 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
319 // Make sure only a synthetic event can cause a page scroll,
320 // so they come at a steady rate:
322 // _Force_ a scroll up:
325 cmd.y = viewport()->height();
326 // Store the event, to be handled when the timeout expires.
327 synthetic_mouse_event_.cmd = cmd;
329 if (synthetic_mouse_event_.timeout.running())
330 // Discard the event. Note that it _may_ be handled
331 // when the timeout expires if
332 // synthetic_mouse_event_.cmd has not been overwritten.
333 // Ie, when the timeout expires, we handle the
334 // most recent event but discard all others that
335 // occurred after the one used to start the timeout
336 // in the first place.
339 synthetic_mouse_event_.restart_timeout = true;
340 synthetic_mouse_event_.timeout.start();
341 // Fall through to handle this event...
344 } else if (synthetic_mouse_event_.timeout.running()) {
345 // Store the event, to be possibly handled when the timeout
347 // Once the timeout has expired, normal control is returned
348 // to mouseMoveEvent (restart_timeout = false).
349 // This results in a much smoother 'feel' when moving the
350 // mouse back into the work area.
351 synthetic_mouse_event_.cmd = cmd;
352 synthetic_mouse_event_.restart_timeout = false;
356 // Has anything changed on-screen since the last QMouseEvent
358 double const scrollbar_value = verticalScrollBar()->value();
359 if (e->x() != synthetic_mouse_event_.x_old ||
360 e->y() != synthetic_mouse_event_.y_old ||
361 scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
362 // Yes it has. Store the params used to check this.
363 synthetic_mouse_event_.x_old = e->x();
364 synthetic_mouse_event_.y_old = e->y();
365 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
367 // ... and dispatch the event to the LyX core.
373 void GuiWorkArea::wheelEvent(QWheelEvent * e)
375 // Wheel rotation by one notch results in a delta() of 120 (see
376 // documentation of QWheelEvent)
377 int const lines = qApp->wheelScrollLines() * e->delta() / 120;
378 verticalScrollBar()->setValue(verticalScrollBar()->value() -
379 lines * verticalScrollBar()->singleStep());
380 adjustViewWithScrollBar();
384 void GuiWorkArea::generateSyntheticMouseEvent()
386 // Set things off to generate the _next_ 'pseudo' event.
387 if (synthetic_mouse_event_.restart_timeout)
388 synthetic_mouse_event_.timeout.start();
390 // Has anything changed on-screen since the last timeout signal
392 double const scrollbar_value = verticalScrollBar()->value();
393 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
394 // Yes it has. Store the params used to check this.
395 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
397 // ... and dispatch the event to the LyX core.
398 dispatch(synthetic_mouse_event_.cmd);
403 void GuiWorkArea::keyPressEvent(QKeyEvent * e)
405 // do nothing if there are other events
406 // (the auto repeated events come too fast)
407 // \todo FIXME: remove hard coded Qt keys, process the key binding
409 if (XEventsQueued(QX11Info::display(), 0) > 1 && e->isAutoRepeat()
410 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
412 << BOOST_CURRENT_FUNCTION << endl
413 << "system is busy: scroll key event ignored" << endl;
419 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
420 << " count=" << e->count()
421 << " text=" << fromqstr(e->text())
422 << " isAutoRepeat=" << e->isAutoRepeat()
423 << " key=" << e->key()
426 boost::shared_ptr<QKeySymbol> sym(new QKeySymbol);
428 processKeySym(sym, q_key_state(e->modifiers()));
431 void GuiWorkArea::doubleClickTimeout() {
432 dc_event_.active = false;
435 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
437 dc_event_ = double_click(e);
438 QTimer::singleShot(QApplication::doubleClickInterval(), this,
439 SLOT(doubleClickTimeout()));
440 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
442 q_button_state(e->button()));
447 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
449 QAbstractScrollArea::resizeEvent(ev);
454 void GuiWorkArea::update(int x, int y, int w, int h)
456 viewport()->repaint(x, y, w, h);
460 void GuiWorkArea::doGreyOut(QLPainter & pain)
462 pain.fillRectangle(0, 0, width(), height(),
465 //if (!lyxrc.show_banner)
467 LYXERR(Debug::GUI) << "show banner: " << lyxrc.show_banner << endl;
468 /// The text to be written on top of the pixmap
469 QString const text = lyx_version ? QString(lyx_version) : qt_("unknown version");
470 FileName const file = support::libFileSearch("images", "banner", "png");
474 QPixmap pm(toqstr(file.absFilename()));
476 lyxerr << "could not load splash screen: '" << file << "'" << endl;
481 // The font used to display the version info
482 font.setStyleHint(QFont::SansSerif);
483 font.setWeight(QFont::Bold);
484 font.setPointSize(convert<int>(lyxrc.font_sizes[Font::SIZE_LARGE]));
486 int const w = pm.width();
487 int const h = pm.height();
489 int x = (width() - w) / 2;
490 int y = (height() - h) / 2;
492 pain.drawPixmap(x, y, pm);
497 pain.setPen(QColor(255, 255, 0));
499 pain.drawText(x, y, text);
503 void GuiWorkArea::paintEvent(QPaintEvent * ev)
505 QRect const rc = ev->rect();
507 LYXERR(Debug::PAINTING) << "paintEvent begin: x: " << rc.x()
509 << " w: " << rc.width()
510 << " h: " << rc.height() << endl;
514 verticalScrollBar()->setPageStep(viewport()->height());
515 screen_ = QPixmap(viewport()->width(), viewport()->height());
518 WorkArea::hideCursor();
519 WorkArea::showCursor();
520 need_resize_ = false;
523 QPainter pain(viewport());
524 pain.drawPixmap(rc, screen_, rc);
529 void GuiWorkArea::expose(int x, int y, int w, int h)
536 void GuiWorkArea::updateScreen()
538 QLPainter pain(&screen_);
541 LYXERR(Debug::GUI) << "splash screen requested" << endl;
542 verticalScrollBar()->hide();
547 verticalScrollBar()->show();
548 paintText(*buffer_view_, pain);
552 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
554 if (schedule_redraw_) {
555 if (buffer_view_ && buffer_view_->buffer()) {
556 buffer_view_->update(Update::Force);
558 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
560 schedule_redraw_ = false;
561 // Show the cursor immediately after the update.
567 cursor_->update(x, y, h, shape);
569 viewport()->update(cursor_->rect());
573 void GuiWorkArea::removeCursor()
576 //if (!qApp->focusWidget())
577 viewport()->update(cursor_->rect());
581 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
583 QString const & commit_string = e->commitString();
584 docstring const & preedit_string
585 = qstring_to_ucs4(e->preeditString());
592 if (!commit_string.isEmpty()) {
594 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
595 << " preeditString =" << fromqstr(e->preeditString())
596 << " commitString =" << fromqstr(e->commitString())
601 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
602 for (int i = 0; i < commit_string.size(); ++i) {
603 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
608 // Hide the cursor during the kana-kanji transformation.
609 if (preedit_string.empty())
610 startBlinkingCursor();
612 stopBlinkingCursor();
614 // last_width : for checking if last preedit string was/wasn't empty.
615 static bool last_width = false;
616 if (!last_width && preedit_string.empty()) {
617 // if last_width is last length of preedit string.
622 QLPainter pain(&screen_);
623 buffer_view_->updateMetrics(false);
624 paintText(*buffer_view_, pain);
625 Font font = buffer_view_->cursor().getFont();
626 FontMetrics const & fm = theFontMetrics(font);
627 int height = fm.maxHeight();
628 int cur_x = cursor_->rect().left();
629 int cur_y = cursor_->rect().bottom();
631 // redraw area of preedit string.
632 update(0, cur_y - height, GuiWorkArea::width(),
633 (height + 1) * preedit_lines_);
635 if (preedit_string.empty()) {
643 // att : stores an IM attribute.
644 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
646 // get attributes of input method cursor.
647 // cursor_pos : cursor position in preedit string.
648 size_t cursor_pos = 0;
649 bool cursor_is_visible = false;
650 for (int i = 0; i < att.size(); ++i) {
651 if (att.at(i).type == QInputMethodEvent::Cursor) {
652 cursor_pos = att.at(i).start;
653 cursor_is_visible = att.at(i).length != 0;
658 size_t preedit_length = preedit_string.length();
660 // get position of selection in input method.
661 // FIXME: isn't there a way to do this simplier?
662 // rStart : cursor position in selected string in IM.
664 // rLength : selected string length in IM.
666 if (cursor_pos < preedit_length) {
667 for (int i = 0; i < att.size(); ++i) {
668 if (att.at(i).type == QInputMethodEvent::TextFormat) {
669 if (att.at(i).start <= int(cursor_pos)
670 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
671 rStart = att.at(i).start;
672 rLength = att.at(i).length;
673 if (!cursor_is_visible)
674 cursor_pos += rLength;
685 int const right_margin = rightMargin();
686 Painter::preedit_style ps;
687 // Most often there would be only one line:
689 for (size_t pos = 0; pos != preedit_length; ++pos) {
690 char_type const typed_char = preedit_string[pos];
691 // reset preedit string style
692 ps = Painter::preedit_default;
694 // if we reached the right extremity of the screen, go to next line.
695 if (cur_x + fm.width(typed_char) > GuiWorkArea::width() - right_margin) {
696 cur_x = right_margin;
700 // preedit strings are displayed with dashed underline
701 // and partial strings are displayed white on black indicating
702 // that we are in selecting mode in the input method.
703 // FIXME: rLength == preedit_length is not a changing condition
704 // FIXME: should be put out of the loop.
706 && pos < rStart + rLength
707 && !(cursor_pos < rLength && rLength == preedit_length))
708 ps = Painter::preedit_selecting;
710 if (pos == cursor_pos
711 && (cursor_pos < rLength && rLength == preedit_length))
712 ps = Painter::preedit_cursor;
714 // draw one character and update cur_x.
715 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
718 // update the preedit string screen area.
719 update(0, cur_y - preedit_lines_*height, GuiWorkArea::width(),
720 (height + 1) * preedit_lines_);
722 // Don't forget to accept the event!
727 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
729 QRect cur_r(0,0,0,0);
731 // this is the CJK-specific composition window position.
732 case Qt::ImMicroFocus:
733 cur_r = cursor_->rect();
734 if (preedit_lines_ != 1)
736 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
737 // return lower right of cursor in LyX.
740 return QWidget::inputMethodQuery(query);
744 } // namespace frontend
747 #include "GuiWorkArea_moc.cpp"