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"
23 #include "BufferView.h"
24 #include "rowpainter.h"
26 #include "FuncRequest.h"
31 #include "support/filetools.h" // LibFileSearch
32 #include "support/os.h"
33 #include "support/convert.h"
35 #include "graphics/GraphicsImage.h"
36 #include "graphics/GraphicsLoader.h"
39 #include <QMainWindow>
42 #include <QDragEnterEvent>
46 #include <QInputContext>
48 #include <boost/bind.hpp>
49 #include <boost/current_function.hpp>
53 extern "C" int XEventsQueued(Display *display, int mode);
57 int const CursorWidth = 2;
59 int const CursorWidth = 1;
66 namespace os = lyx::support::os;
71 using support::FileName;
73 /// return the LyX key state from Qt's
74 static key_modifier::state q_key_state(Qt::KeyboardModifiers state)
76 key_modifier::state k = key_modifier::none;
77 if (state & Qt::ControlModifier)
78 k |= key_modifier::ctrl;
79 if (state & Qt::ShiftModifier)
80 k |= key_modifier::shift;
81 if (state & Qt::AltModifier || state & Qt::MetaModifier)
82 k |= key_modifier::alt;
87 /// return the LyX mouse button state from Qt's
88 static mouse_button::state q_button_state(Qt::MouseButton button)
90 mouse_button::state b = mouse_button::none;
93 b = mouse_button::button1;
96 b = mouse_button::button2;
99 b = mouse_button::button3;
108 /// return the LyX mouse button state from Qt's
109 mouse_button::state q_motion_state(Qt::MouseButtons state)
111 mouse_button::state b = mouse_button::none;
112 if (state & Qt::LeftButton)
113 b |= mouse_button::button1;
114 if (state & Qt::MidButton)
115 b |= mouse_button::button2;
116 if (state & Qt::RightButton)
117 b |= mouse_button::button3;
128 void draw(QPainter & painter)
130 // FIXME: do something depending on the cursor shape.
131 if (show_ && rect_.isValid())
132 painter.fillRect(rect_, color_);
135 void update(int x, int y, int h, CursorShape shape)
137 color_ = guiApp->colorCache().get(Color::cursor);
138 rect_ = QRect(x, y, CursorWidth, h);
142 void show(bool set_show = true) { show_ = set_show; }
143 void hide() { show_ = false; }
145 QRect const & rect() { return rect_; }
159 // This is a 'heartbeat' generating synthetic mouse move events when the
160 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
161 SyntheticMouseEvent::SyntheticMouseEvent()
162 : timeout(200), restart_timeout(true),
163 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
167 GuiWorkArea::GuiWorkArea(int w, int h, int id, LyXView & lyx_view)
168 : WorkArea(id, lyx_view), need_resize_(false), schedule_redraw_(false),
171 screen_ = QPixmap(viewport()->width(), viewport()->height());
172 cursor_ = new frontend::CursorWidget();
175 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
176 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
177 setAcceptDrops(true);
178 setMouseTracking(true);
179 setMinimumSize(100, 70);
181 viewport()->setAutoFillBackground(false);
182 // We don't need double-buffering nor SystemBackground on
183 // the viewport because we have our own backing pixmap.
184 viewport()->setAttribute(Qt::WA_NoSystemBackground);
186 setFocusPolicy(Qt::WheelFocus);
188 viewport()->setCursor(Qt::IBeamCursor);
192 synthetic_mouse_event_.timeout.timeout.connect(
193 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
196 // Initialize the vertical Scroll Bar
197 QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
198 this, SLOT(adjustViewWithScrollBar(int)));
200 // disable context menu for the scrollbar
201 verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu);
203 // PageStep only depends on the viewport height.
204 verticalScrollBar()->setPageStep(viewport()->height());
206 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
207 << "\n Area width\t" << width()
208 << "\n Area height\t" << height()
209 << "\n viewport width\t" << viewport()->width()
210 << "\n viewport height\t" << viewport()->height()
213 // Enables input methods for asian languages.
214 // Must be set when creating custom text editing widgets.
215 setAttribute(Qt::WA_InputMethodEnabled, true);
219 void GuiWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
221 if (verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOn)
222 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
224 verticalScrollBar()->setTracking(false);
226 // do what cursor movement does (some grey)
228 int scroll_max_ = std::max(0, h - height());
230 verticalScrollBar()->setRange(0, scroll_max_);
231 verticalScrollBar()->setSliderPosition(scroll_pos);
232 verticalScrollBar()->setSingleStep(scroll_line_step);
233 verticalScrollBar()->setValue(scroll_pos);
235 verticalScrollBar()->setTracking(true);
239 void GuiWorkArea::adjustViewWithScrollBar(int)
241 scrollBufferView(verticalScrollBar()->sliderPosition());
242 QApplication::syncX();
246 void GuiWorkArea::dragEnterEvent(QDragEnterEvent * event)
248 if (event->mimeData()->hasUrls())
250 /// \todo Ask lyx-devel is this is enough:
251 /// if (event->mimeData()->hasFormat("text/plain"))
252 /// event->acceptProposedAction();
256 void GuiWorkArea::dropEvent(QDropEvent* event)
258 QList<QUrl> files = event->mimeData()->urls();
262 LYXERR(Debug::GUI) << "GuiWorkArea::dropEvent: got URIs!" << endl;
263 for (int i = 0; i!=files.size(); ++i) {
264 string const file = os::internal_path(fromqstr(files.at(i).toLocalFile()));
266 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
271 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
273 // No need to do anything if we didn't change views...
274 // if (theApp() == 0 || &lyx_view_ == theApp()->currentView())
277 theApp()->setCurrentView(lyx_view_);
279 // Repaint the whole screen.
280 // Note: this is different from redraw() as only the backing pixmap
281 // will be redrawn, which is cheap.
282 viewport()->repaint();
284 // FIXME: it would be better to send a signal "newBuffer()"
285 // in BufferList that could be connected to the different tabbars.
286 lyx_view_.updateTab();
288 startBlinkingCursor();
292 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
294 stopBlinkingCursor();
298 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
300 if (dc_event_.active && dc_event_ == *e) {
301 dc_event_.active = false;
302 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
304 q_button_state(e->button()));
309 inputContext()->reset();
311 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
312 q_button_state(e->button()));
313 dispatch(cmd, q_key_state(e->modifiers()));
317 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
319 if (synthetic_mouse_event_.timeout.running())
320 synthetic_mouse_event_.timeout.stop();
322 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
323 q_button_state(e->button()));
328 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
330 // we kill the triple click if we move
331 doubleClickTimeout();
332 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
333 q_motion_state(e->buttons()));
335 // If we're above or below the work area...
336 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
337 // Make sure only a synthetic event can cause a page scroll,
338 // so they come at a steady rate:
340 // _Force_ a scroll up:
343 cmd.y = viewport()->height();
344 // Store the event, to be handled when the timeout expires.
345 synthetic_mouse_event_.cmd = cmd;
347 if (synthetic_mouse_event_.timeout.running())
348 // Discard the event. Note that it _may_ be handled
349 // when the timeout expires if
350 // synthetic_mouse_event_.cmd has not been overwritten.
351 // Ie, when the timeout expires, we handle the
352 // most recent event but discard all others that
353 // occurred after the one used to start the timeout
354 // in the first place.
357 synthetic_mouse_event_.restart_timeout = true;
358 synthetic_mouse_event_.timeout.start();
359 // Fall through to handle this event...
362 } else if (synthetic_mouse_event_.timeout.running()) {
363 // Store the event, to be possibly handled when the timeout
365 // Once the timeout has expired, normal control is returned
366 // to mouseMoveEvent (restart_timeout = false).
367 // This results in a much smoother 'feel' when moving the
368 // mouse back into the work area.
369 synthetic_mouse_event_.cmd = cmd;
370 synthetic_mouse_event_.restart_timeout = false;
374 // Has anything changed on-screen since the last QMouseEvent
376 double const scrollbar_value = verticalScrollBar()->value();
377 if (e->x() != synthetic_mouse_event_.x_old ||
378 e->y() != synthetic_mouse_event_.y_old ||
379 scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
380 // Yes it has. Store the params used to check this.
381 synthetic_mouse_event_.x_old = e->x();
382 synthetic_mouse_event_.y_old = e->y();
383 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
385 // ... and dispatch the event to the LyX core.
391 void GuiWorkArea::wheelEvent(QWheelEvent * e)
393 // Wheel rotation by one notch results in a delta() of 120 (see
394 // documentation of QWheelEvent)
395 int const lines = qApp->wheelScrollLines() * e->delta() / 120;
396 verticalScrollBar()->setValue(verticalScrollBar()->value() -
397 lines * verticalScrollBar()->singleStep());
398 adjustViewWithScrollBar();
402 void GuiWorkArea::generateSyntheticMouseEvent()
404 // Set things off to generate the _next_ 'pseudo' event.
405 if (synthetic_mouse_event_.restart_timeout)
406 synthetic_mouse_event_.timeout.start();
408 // Has anything changed on-screen since the last timeout signal
410 double const scrollbar_value = verticalScrollBar()->value();
411 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
412 // Yes it has. Store the params used to check this.
413 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
415 // ... and dispatch the event to the LyX core.
416 dispatch(synthetic_mouse_event_.cmd);
421 void GuiWorkArea::keyPressEvent(QKeyEvent * e)
423 // do nothing if there are other events
424 // (the auto repeated events come too fast)
425 // \todo FIXME: remove hard coded Qt keysprocess the key binding
427 if (XEventsQueued(QX11Info::display(), 0) > 1 && e->isAutoRepeat()
428 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
430 << BOOST_CURRENT_FUNCTION << endl
431 << "sysstem is busy: scroll key event ignored" << endl;
437 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
438 << " count=" << e->count()
439 << " text=" << fromqstr(e->text())
440 << " isAutoRepeat=" << e->isAutoRepeat()
441 << " key=" << e->key()
444 boost::shared_ptr<QKeySymbol> sym(new QKeySymbol);
446 processKeySym(sym, q_key_state(e->modifiers()));
449 void GuiWorkArea::doubleClickTimeout() {
450 dc_event_.active = false;
453 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
455 dc_event_ = double_click(e);
456 QTimer::singleShot(QApplication::doubleClickInterval(), this,
457 SLOT(doubleClickTimeout()));
458 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
460 q_button_state(e->button()));
465 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
467 QAbstractScrollArea::resizeEvent(ev);
472 void GuiWorkArea::update(int x, int y, int w, int h)
474 viewport()->repaint(x, y, w, h);
478 void GuiWorkArea::doGreyOut(QLPainter & pain)
480 pain.fillRectangle(0, 0, width(), height(),
483 //if (!lyxrc.show_banner)
485 LYXERR(Debug::GUI) << "show banner: " << lyxrc.show_banner << endl;
486 /// The text to be written on top of the pixmap
487 QString const text = lyx_version ? QString(lyx_version) : qt_("unknown version");
488 FileName const file = support::libFileSearch("images", "banner", "png");
492 QPixmap pm(toqstr(file.absFilename()));
494 lyxerr << "could not load splash screen: '" << file << "'" << endl;
499 // The font used to display the version info
500 font.setStyleHint(QFont::SansSerif);
501 font.setWeight(QFont::Bold);
502 font.setPointSize(convert<int>(lyxrc.font_sizes[Font::SIZE_LARGE]));
504 int const w = pm.width();
505 int const h = pm.height();
507 int x = (width() - w) / 2;
508 int y = (height() - h) / 2;
510 pain.drawPixmap(x, y, pm);
515 pain.setPen(QColor(255, 255, 0));
517 pain.drawText(x, y, text);
521 void GuiWorkArea::paintEvent(QPaintEvent * ev)
523 QRect const rc = ev->rect();
525 LYXERR(Debug::PAINTING) << "paintEvent begin: x: " << rc.x()
527 << " w: " << rc.width()
528 << " h: " << rc.height() << endl;
532 verticalScrollBar()->setPageStep(viewport()->height());
533 screen_ = QPixmap(viewport()->width(), viewport()->height());
536 need_resize_ = false;
539 QPainter pain(viewport());
540 pain.drawPixmap(rc, screen_, rc);
545 void GuiWorkArea::expose(int x, int y, int w, int h)
552 void GuiWorkArea::updateScreen()
554 QLPainter pain(&screen_);
557 LYXERR(Debug::GUI) << "splash screen requested" << endl;
558 verticalScrollBar()->hide();
563 verticalScrollBar()->show();
564 paintText(*buffer_view_, pain);
568 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
570 if (schedule_redraw_) {
571 if (buffer_view_ && buffer_view_->buffer()) {
572 buffer_view_->update(Update::Force);
574 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
576 schedule_redraw_ = false;
577 // Show the cursor immediately after the update.
583 cursor_->update(x, y, h, shape);
585 viewport()->update(cursor_->rect());
589 void GuiWorkArea::removeCursor()
592 //if (!qApp->focusWidget())
593 viewport()->update(cursor_->rect());
597 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
599 QString const & commit_string = e->commitString();
600 docstring const & preedit_string
601 = qstring_to_ucs4(e->preeditString());
608 if (!commit_string.isEmpty()) {
610 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
611 << " preeditString =" << fromqstr(e->preeditString())
612 << " commitString =" << fromqstr(e->commitString())
617 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
618 for (int i = 0; i < commit_string.size(); ++i) {
619 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
624 // Hide the cursor during the kana-kanji transformation.
625 if (preedit_string.empty())
626 startBlinkingCursor();
628 stopBlinkingCursor();
630 // last_width : for checking if last preedit string was/wasn't empty.
631 static bool last_width = false;
632 if (!last_width && preedit_string.empty()) {
633 // if last_width is last length of preedit string.
638 QLPainter pain(&screen_);
639 buffer_view_->updateMetrics(false);
640 paintText(*buffer_view_, pain);
641 Font font = buffer_view_->cursor().getFont();
642 FontMetrics const & fm = theFontMetrics(font);
643 int height = fm.maxHeight();
644 int cur_x = cursor_->rect().left();
645 int cur_y = cursor_->rect().bottom();
647 // redraw area of preedit string.
648 update(0, cur_y - height, GuiWorkArea::width(),
649 (height + 1) * preedit_lines_);
651 if (preedit_string.empty()) {
659 // att : stores an IM attribute.
660 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
662 // get attributes of input method cursor.
663 // cursor_pos : cursor position in preedit string.
664 size_t cursor_pos = 0;
665 bool cursor_is_visible = false;
666 for (int i = 0; i < att.size(); ++i) {
667 if (att.at(i).type == QInputMethodEvent::Cursor) {
668 cursor_pos = att.at(i).start;
669 cursor_is_visible = att.at(i).length != 0;
674 size_t preedit_length = preedit_string.length();
676 // get position of selection in input method.
677 // FIXME: isn't there a way to do this simplier?
678 // rStart : cursor position in selected string in IM.
680 // rLength : selected string length in IM.
682 if (cursor_pos < preedit_length) {
683 for (int i = 0; i < att.size(); ++i) {
684 if (att.at(i).type == QInputMethodEvent::TextFormat) {
685 if (att.at(i).start <= int(cursor_pos)
686 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
687 rStart = att.at(i).start;
688 rLength = att.at(i).length;
689 if (!cursor_is_visible)
690 cursor_pos += rLength;
701 int const right_margin = rightMargin();
702 Painter::preedit_style ps;
703 // Most often there would be only one line:
705 for (size_t pos = 0; pos != preedit_length; ++pos) {
706 char_type const typed_char = preedit_string[pos];
707 // reset preedit string style
708 ps = Painter::preedit_default;
710 // if we reached the right extremity of the screen, go to next line.
711 if (cur_x + fm.width(typed_char) > GuiWorkArea::width() - right_margin) {
712 cur_x = right_margin;
716 // preedit strings are displayed with dashed underline
717 // and partial strings are displayed white on black indicating
718 // that we are in selecting mode in the input method.
719 // FIXME: rLength == preedit_length is not a changing condition
720 // FIXME: should be put out of the loop.
722 && pos < rStart + rLength
723 && !(cursor_pos < rLength && rLength == preedit_length))
724 ps = Painter::preedit_selecting;
726 if (pos == cursor_pos
727 && (cursor_pos < rLength && rLength == preedit_length))
728 ps = Painter::preedit_cursor;
730 // draw one character and update cur_x.
731 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
734 // update the preedit string screen area.
735 update(0, cur_y - preedit_lines_*height, GuiWorkArea::width(),
736 (height + 1) * preedit_lines_);
738 // Don't forget to accept the event!
743 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
745 QRect cur_r(0,0,0,0);
747 // this is the CJK-specific composition window position.
748 case Qt::ImMicroFocus:
749 cur_r = cursor_->rect();
750 if (preedit_lines_ != 1)
752 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
753 // return lower right of cursor in LyX.
756 return QWidget::inputMethodQuery(query);
760 } // namespace frontend
763 #include "GuiWorkArea_moc.cpp"