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(int w, int h, int id, LyXView & lyx_view)
177 : WorkArea(id, lyx_view), 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);
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)
250 scrollBufferView(verticalScrollBar()->sliderPosition());
251 QApplication::syncX();
255 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
257 // No need to do anything if we didn't change views...
258 // if (theApp() == 0 || &lyx_view_ == theApp()->currentView())
261 theApp()->setCurrentView(lyx_view_);
263 // Repaint the whole screen.
264 // Note: this is different from redraw() as only the backing pixmap
265 // will be redrawn, which is cheap.
266 viewport()->repaint();
268 // FIXME: it would be better to send a signal "newBuffer()"
269 // in BufferList that could be connected to the different tabbars.
270 lyx_view_.updateTab();
272 startBlinkingCursor();
276 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
278 stopBlinkingCursor();
282 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
284 if (dc_event_.active && dc_event_ == *e) {
285 dc_event_.active = false;
286 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
288 q_button_state(e->button()));
293 inputContext()->reset();
295 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
296 q_button_state(e->button()));
297 dispatch(cmd, q_key_state(e->modifiers()));
301 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
303 if (synthetic_mouse_event_.timeout.running())
304 synthetic_mouse_event_.timeout.stop();
306 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
307 q_button_state(e->button()));
312 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
314 // we kill the triple click if we move
315 doubleClickTimeout();
316 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
317 q_motion_state(e->buttons()));
319 // If we're above or below the work area...
320 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
321 // Make sure only a synthetic event can cause a page scroll,
322 // so they come at a steady rate:
324 // _Force_ a scroll up:
327 cmd.y = viewport()->height();
328 // Store the event, to be handled when the timeout expires.
329 synthetic_mouse_event_.cmd = cmd;
331 if (synthetic_mouse_event_.timeout.running())
332 // Discard the event. Note that it _may_ be handled
333 // when the timeout expires if
334 // synthetic_mouse_event_.cmd has not been overwritten.
335 // Ie, when the timeout expires, we handle the
336 // most recent event but discard all others that
337 // occurred after the one used to start the timeout
338 // in the first place.
341 synthetic_mouse_event_.restart_timeout = true;
342 synthetic_mouse_event_.timeout.start();
343 // Fall through to handle this event...
346 } else if (synthetic_mouse_event_.timeout.running()) {
347 // Store the event, to be possibly handled when the timeout
349 // Once the timeout has expired, normal control is returned
350 // to mouseMoveEvent (restart_timeout = false).
351 // This results in a much smoother 'feel' when moving the
352 // mouse back into the work area.
353 synthetic_mouse_event_.cmd = cmd;
354 synthetic_mouse_event_.restart_timeout = false;
358 // Has anything changed on-screen since the last QMouseEvent
360 double const scrollbar_value = verticalScrollBar()->value();
361 if (e->x() != synthetic_mouse_event_.x_old ||
362 e->y() != synthetic_mouse_event_.y_old ||
363 scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
364 // Yes it has. Store the params used to check this.
365 synthetic_mouse_event_.x_old = e->x();
366 synthetic_mouse_event_.y_old = e->y();
367 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
369 // ... and dispatch the event to the LyX core.
375 void GuiWorkArea::wheelEvent(QWheelEvent * e)
377 // Wheel rotation by one notch results in a delta() of 120 (see
378 // documentation of QWheelEvent)
379 int const lines = qApp->wheelScrollLines() * e->delta() / 120;
380 verticalScrollBar()->setValue(verticalScrollBar()->value() -
381 lines * verticalScrollBar()->singleStep());
382 adjustViewWithScrollBar();
386 void GuiWorkArea::generateSyntheticMouseEvent()
388 // Set things off to generate the _next_ 'pseudo' event.
389 if (synthetic_mouse_event_.restart_timeout)
390 synthetic_mouse_event_.timeout.start();
392 // Has anything changed on-screen since the last timeout signal
394 double const scrollbar_value = verticalScrollBar()->value();
395 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
396 // Yes it has. Store the params used to check this.
397 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
399 // ... and dispatch the event to the LyX core.
400 dispatch(synthetic_mouse_event_.cmd);
405 void GuiWorkArea::keyPressEvent(QKeyEvent * e)
407 // do nothing if there are other events
408 // (the auto repeated events come too fast)
409 // \todo FIXME: remove hard coded Qt keys, process the key binding
411 if (XEventsQueued(QX11Info::display(), 0) > 1 && e->isAutoRepeat()
412 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
414 << BOOST_CURRENT_FUNCTION << endl
415 << "system is busy: scroll key event ignored" << endl;
421 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
422 << " count=" << e->count()
423 << " text=" << fromqstr(e->text())
424 << " isAutoRepeat=" << e->isAutoRepeat()
425 << " key=" << e->key()
428 boost::shared_ptr<QKeySymbol> sym(new QKeySymbol);
430 processKeySym(sym, q_key_state(e->modifiers()));
433 void GuiWorkArea::doubleClickTimeout() {
434 dc_event_.active = false;
437 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
439 dc_event_ = double_click(e);
440 QTimer::singleShot(QApplication::doubleClickInterval(), this,
441 SLOT(doubleClickTimeout()));
442 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
444 q_button_state(e->button()));
449 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
451 QAbstractScrollArea::resizeEvent(ev);
456 void GuiWorkArea::update(int x, int y, int w, int h)
458 viewport()->repaint(x, y, w, h);
462 void GuiWorkArea::doGreyOut(QLPainter & pain)
464 pain.fillRectangle(0, 0, width(), height(),
467 //if (!lyxrc.show_banner)
469 LYXERR(Debug::GUI) << "show banner: " << lyxrc.show_banner << endl;
470 /// The text to be written on top of the pixmap
471 QString const text = lyx_version ? QString(lyx_version) : qt_("unknown version");
472 FileName const file = support::libFileSearch("images", "banner", "png");
476 QPixmap pm(toqstr(file.absFilename()));
478 lyxerr << "could not load splash screen: '" << file << "'" << endl;
483 // The font used to display the version info
484 font.setStyleHint(QFont::SansSerif);
485 font.setWeight(QFont::Bold);
486 font.setPointSize(convert<int>(lyxrc.font_sizes[Font::SIZE_LARGE]));
488 int const w = pm.width();
489 int const h = pm.height();
491 int x = (width() - w) / 2;
492 int y = (height() - h) / 2;
494 pain.drawPixmap(x, y, pm);
499 pain.setPen(QColor(255, 255, 0));
501 pain.drawText(x, y, text);
505 void GuiWorkArea::paintEvent(QPaintEvent * ev)
507 QRect const rc = ev->rect();
509 LYXERR(Debug::PAINTING) << "paintEvent begin: x: " << rc.x()
511 << " w: " << rc.width()
512 << " h: " << rc.height() << endl;
516 verticalScrollBar()->setPageStep(viewport()->height());
517 screen_ = QPixmap(viewport()->width(), viewport()->height());
520 WorkArea::hideCursor();
521 WorkArea::showCursor();
522 need_resize_ = false;
525 QPainter pain(viewport());
526 pain.drawPixmap(rc, screen_, rc);
531 void GuiWorkArea::expose(int x, int y, int w, int h)
538 void GuiWorkArea::updateScreen()
540 QLPainter pain(&screen_);
543 LYXERR(Debug::GUI) << "splash screen requested" << endl;
544 verticalScrollBar()->hide();
549 verticalScrollBar()->show();
550 paintText(*buffer_view_, pain);
554 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
556 if (schedule_redraw_) {
557 if (buffer_view_ && buffer_view_->buffer()) {
558 buffer_view_->update(Update::Force);
560 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
562 schedule_redraw_ = false;
563 // Show the cursor immediately after the update.
569 cursor_->update(x, y, h, shape);
571 viewport()->update(cursor_->rect());
575 void GuiWorkArea::removeCursor()
578 //if (!qApp->focusWidget())
579 viewport()->update(cursor_->rect());
583 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
585 QString const & commit_string = e->commitString();
586 docstring const & preedit_string
587 = qstring_to_ucs4(e->preeditString());
594 if (!commit_string.isEmpty()) {
596 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
597 << " preeditString =" << fromqstr(e->preeditString())
598 << " commitString =" << fromqstr(e->commitString())
603 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
604 for (int i = 0; i < commit_string.size(); ++i) {
605 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
610 // Hide the cursor during the kana-kanji transformation.
611 if (preedit_string.empty())
612 startBlinkingCursor();
614 stopBlinkingCursor();
616 // last_width : for checking if last preedit string was/wasn't empty.
617 static bool last_width = false;
618 if (!last_width && preedit_string.empty()) {
619 // if last_width is last length of preedit string.
624 QLPainter pain(&screen_);
625 buffer_view_->updateMetrics(false);
626 paintText(*buffer_view_, pain);
627 Font font = buffer_view_->cursor().getFont();
628 FontMetrics const & fm = theFontMetrics(font);
629 int height = fm.maxHeight();
630 int cur_x = cursor_->rect().left();
631 int cur_y = cursor_->rect().bottom();
633 // redraw area of preedit string.
634 update(0, cur_y - height, GuiWorkArea::width(),
635 (height + 1) * preedit_lines_);
637 if (preedit_string.empty()) {
645 // att : stores an IM attribute.
646 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
648 // get attributes of input method cursor.
649 // cursor_pos : cursor position in preedit string.
650 size_t cursor_pos = 0;
651 bool cursor_is_visible = false;
652 for (int i = 0; i < att.size(); ++i) {
653 if (att.at(i).type == QInputMethodEvent::Cursor) {
654 cursor_pos = att.at(i).start;
655 cursor_is_visible = att.at(i).length != 0;
660 size_t preedit_length = preedit_string.length();
662 // get position of selection in input method.
663 // FIXME: isn't there a way to do this simplier?
664 // rStart : cursor position in selected string in IM.
666 // rLength : selected string length in IM.
668 if (cursor_pos < preedit_length) {
669 for (int i = 0; i < att.size(); ++i) {
670 if (att.at(i).type == QInputMethodEvent::TextFormat) {
671 if (att.at(i).start <= int(cursor_pos)
672 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
673 rStart = att.at(i).start;
674 rLength = att.at(i).length;
675 if (!cursor_is_visible)
676 cursor_pos += rLength;
687 int const right_margin = rightMargin();
688 Painter::preedit_style ps;
689 // Most often there would be only one line:
691 for (size_t pos = 0; pos != preedit_length; ++pos) {
692 char_type const typed_char = preedit_string[pos];
693 // reset preedit string style
694 ps = Painter::preedit_default;
696 // if we reached the right extremity of the screen, go to next line.
697 if (cur_x + fm.width(typed_char) > GuiWorkArea::width() - right_margin) {
698 cur_x = right_margin;
702 // preedit strings are displayed with dashed underline
703 // and partial strings are displayed white on black indicating
704 // that we are in selecting mode in the input method.
705 // FIXME: rLength == preedit_length is not a changing condition
706 // FIXME: should be put out of the loop.
708 && pos < rStart + rLength
709 && !(cursor_pos < rLength && rLength == preedit_length))
710 ps = Painter::preedit_selecting;
712 if (pos == cursor_pos
713 && (cursor_pos < rLength && rLength == preedit_length))
714 ps = Painter::preedit_cursor;
716 // draw one character and update cur_x.
717 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
720 // update the preedit string screen area.
721 update(0, cur_y - preedit_lines_*height, GuiWorkArea::width(),
722 (height + 1) * preedit_lines_);
724 // Don't forget to accept the event!
729 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
731 QRect cur_r(0,0,0,0);
733 // this is the CJK-specific composition window position.
734 case Qt::ImMicroFocus:
735 cur_r = cursor_->rect();
736 if (preedit_lines_ != 1)
738 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
739 // return lower right of cursor in LyX.
742 return QWidget::inputMethodQuery(query);
746 } // namespace frontend
749 #include "GuiWorkArea_moc.cpp"