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 if (show_ && rect_.isValid()) {
133 painter.fillRect(rect_.x(), rect_.y(), CursorWidth, rect_.height(), color_);
134 painter.setPen(color_);
135 painter.drawLine(rect_.bottomLeft().x() + CursorWidth, rect_.bottomLeft().y(),
136 rect_.bottomRight().x(), rect_.bottomLeft().y());
139 case REVERSED_L_SHAPE:
140 painter.fillRect(rect_.x() + rect_.height() / 3, rect_.y(), CursorWidth, rect_.height(), color_);
141 painter.setPen(color_);
142 painter.drawLine(rect_.bottomRight().x() - CursorWidth, rect_.bottomLeft().y(),
143 rect_.bottomLeft().x(), rect_.bottomLeft().y());
147 painter.fillRect(rect_, color_);
153 void update(int x, int y, int h, CursorShape shape)
155 color_ = guiApp->colorCache().get(Color::cursor);
159 rect_ = QRect(x, y, CursorWidth + h / 3, h);
161 case REVERSED_L_SHAPE:
162 rect_ = QRect(x - h / 3, y, CursorWidth + h / 3, h);
165 rect_ = QRect(x, y, CursorWidth, h);
170 void show(bool set_show = true) { show_ = set_show; }
171 void hide() { show_ = false; }
173 QRect const & rect() { return rect_; }
187 // This is a 'heartbeat' generating synthetic mouse move events when the
188 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
189 SyntheticMouseEvent::SyntheticMouseEvent()
190 : timeout(200), restart_timeout(true),
191 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
195 GuiWorkArea::GuiWorkArea(int w, int h, int id, LyXView & lyx_view)
196 : WorkArea(id, lyx_view), need_resize_(false), schedule_redraw_(false),
199 screen_ = QPixmap(viewport()->width(), viewport()->height());
200 cursor_ = new frontend::CursorWidget();
203 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
204 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
205 setAcceptDrops(true);
206 setMouseTracking(true);
207 setMinimumSize(100, 70);
209 viewport()->setAutoFillBackground(false);
210 // We don't need double-buffering nor SystemBackground on
211 // the viewport because we have our own backing pixmap.
212 viewport()->setAttribute(Qt::WA_NoSystemBackground);
214 setFocusPolicy(Qt::WheelFocus);
216 viewport()->setCursor(Qt::IBeamCursor);
220 synthetic_mouse_event_.timeout.timeout.connect(
221 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
224 // Initialize the vertical Scroll Bar
225 QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
226 this, SLOT(adjustViewWithScrollBar(int)));
228 // disable context menu for the scrollbar
229 verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu);
231 // PageStep only depends on the viewport height.
232 verticalScrollBar()->setPageStep(viewport()->height());
234 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
235 << "\n Area width\t" << width()
236 << "\n Area height\t" << height()
237 << "\n viewport width\t" << viewport()->width()
238 << "\n viewport height\t" << viewport()->height()
241 // Enables input methods for asian languages.
242 // Must be set when creating custom text editing widgets.
243 setAttribute(Qt::WA_InputMethodEnabled, true);
247 void GuiWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
249 if (verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOn)
250 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
252 verticalScrollBar()->setTracking(false);
254 // do what cursor movement does (some grey)
256 int scroll_max_ = std::max(0, h - height());
258 verticalScrollBar()->setRange(0, scroll_max_);
259 verticalScrollBar()->setSliderPosition(scroll_pos);
260 verticalScrollBar()->setSingleStep(scroll_line_step);
261 verticalScrollBar()->setValue(scroll_pos);
263 verticalScrollBar()->setTracking(true);
267 void GuiWorkArea::adjustViewWithScrollBar(int)
269 scrollBufferView(verticalScrollBar()->sliderPosition());
270 QApplication::syncX();
274 void GuiWorkArea::dragEnterEvent(QDragEnterEvent * event)
276 if (event->mimeData()->hasUrls())
278 /// \todo Ask lyx-devel is this is enough:
279 /// if (event->mimeData()->hasFormat("text/plain"))
280 /// event->acceptProposedAction();
284 void GuiWorkArea::dropEvent(QDropEvent* event)
286 QList<QUrl> files = event->mimeData()->urls();
290 LYXERR(Debug::GUI) << "GuiWorkArea::dropEvent: got URIs!" << endl;
291 for (int i = 0; i!=files.size(); ++i) {
292 string const file = os::internal_path(fromqstr(files.at(i).toLocalFile()));
294 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
299 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
301 // No need to do anything if we didn't change views...
302 // if (theApp() == 0 || &lyx_view_ == theApp()->currentView())
305 theApp()->setCurrentView(lyx_view_);
307 // Repaint the whole screen.
308 // Note: this is different from redraw() as only the backing pixmap
309 // will be redrawn, which is cheap.
310 viewport()->repaint();
312 // FIXME: it would be better to send a signal "newBuffer()"
313 // in BufferList that could be connected to the different tabbars.
314 lyx_view_.updateTab();
316 startBlinkingCursor();
320 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
322 stopBlinkingCursor();
326 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
328 if (dc_event_.active && dc_event_ == *e) {
329 dc_event_.active = false;
330 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
332 q_button_state(e->button()));
337 inputContext()->reset();
339 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
340 q_button_state(e->button()));
341 dispatch(cmd, q_key_state(e->modifiers()));
345 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
347 if (synthetic_mouse_event_.timeout.running())
348 synthetic_mouse_event_.timeout.stop();
350 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
351 q_button_state(e->button()));
356 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
358 // we kill the triple click if we move
359 doubleClickTimeout();
360 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
361 q_motion_state(e->buttons()));
363 // If we're above or below the work area...
364 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
365 // Make sure only a synthetic event can cause a page scroll,
366 // so they come at a steady rate:
368 // _Force_ a scroll up:
371 cmd.y = viewport()->height();
372 // Store the event, to be handled when the timeout expires.
373 synthetic_mouse_event_.cmd = cmd;
375 if (synthetic_mouse_event_.timeout.running())
376 // Discard the event. Note that it _may_ be handled
377 // when the timeout expires if
378 // synthetic_mouse_event_.cmd has not been overwritten.
379 // Ie, when the timeout expires, we handle the
380 // most recent event but discard all others that
381 // occurred after the one used to start the timeout
382 // in the first place.
385 synthetic_mouse_event_.restart_timeout = true;
386 synthetic_mouse_event_.timeout.start();
387 // Fall through to handle this event...
390 } else if (synthetic_mouse_event_.timeout.running()) {
391 // Store the event, to be possibly handled when the timeout
393 // Once the timeout has expired, normal control is returned
394 // to mouseMoveEvent (restart_timeout = false).
395 // This results in a much smoother 'feel' when moving the
396 // mouse back into the work area.
397 synthetic_mouse_event_.cmd = cmd;
398 synthetic_mouse_event_.restart_timeout = false;
402 // Has anything changed on-screen since the last QMouseEvent
404 double const scrollbar_value = verticalScrollBar()->value();
405 if (e->x() != synthetic_mouse_event_.x_old ||
406 e->y() != synthetic_mouse_event_.y_old ||
407 scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
408 // Yes it has. Store the params used to check this.
409 synthetic_mouse_event_.x_old = e->x();
410 synthetic_mouse_event_.y_old = e->y();
411 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
413 // ... and dispatch the event to the LyX core.
419 void GuiWorkArea::wheelEvent(QWheelEvent * e)
421 // Wheel rotation by one notch results in a delta() of 120 (see
422 // documentation of QWheelEvent)
423 int const lines = qApp->wheelScrollLines() * e->delta() / 120;
424 verticalScrollBar()->setValue(verticalScrollBar()->value() -
425 lines * verticalScrollBar()->singleStep());
426 adjustViewWithScrollBar();
430 void GuiWorkArea::generateSyntheticMouseEvent()
432 // Set things off to generate the _next_ 'pseudo' event.
433 if (synthetic_mouse_event_.restart_timeout)
434 synthetic_mouse_event_.timeout.start();
436 // Has anything changed on-screen since the last timeout signal
438 double const scrollbar_value = verticalScrollBar()->value();
439 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
440 // Yes it has. Store the params used to check this.
441 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
443 // ... and dispatch the event to the LyX core.
444 dispatch(synthetic_mouse_event_.cmd);
449 void GuiWorkArea::keyPressEvent(QKeyEvent * e)
451 // do nothing if there are other events
452 // (the auto repeated events come too fast)
453 // \todo FIXME: remove hard coded Qt keys, process the key binding
455 if (XEventsQueued(QX11Info::display(), 0) > 1 && e->isAutoRepeat()
456 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
458 << BOOST_CURRENT_FUNCTION << endl
459 << "system is busy: scroll key event ignored" << endl;
465 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
466 << " count=" << e->count()
467 << " text=" << fromqstr(e->text())
468 << " isAutoRepeat=" << e->isAutoRepeat()
469 << " key=" << e->key()
472 boost::shared_ptr<QKeySymbol> sym(new QKeySymbol);
474 processKeySym(sym, q_key_state(e->modifiers()));
477 void GuiWorkArea::doubleClickTimeout() {
478 dc_event_.active = false;
481 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
483 dc_event_ = double_click(e);
484 QTimer::singleShot(QApplication::doubleClickInterval(), this,
485 SLOT(doubleClickTimeout()));
486 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
488 q_button_state(e->button()));
493 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
495 QAbstractScrollArea::resizeEvent(ev);
500 void GuiWorkArea::update(int x, int y, int w, int h)
502 viewport()->repaint(x, y, w, h);
506 void GuiWorkArea::doGreyOut(QLPainter & pain)
508 pain.fillRectangle(0, 0, width(), height(),
511 //if (!lyxrc.show_banner)
513 LYXERR(Debug::GUI) << "show banner: " << lyxrc.show_banner << endl;
514 /// The text to be written on top of the pixmap
515 QString const text = lyx_version ? QString(lyx_version) : qt_("unknown version");
516 FileName const file = support::libFileSearch("images", "banner", "png");
520 QPixmap pm(toqstr(file.absFilename()));
522 lyxerr << "could not load splash screen: '" << file << "'" << endl;
527 // The font used to display the version info
528 font.setStyleHint(QFont::SansSerif);
529 font.setWeight(QFont::Bold);
530 font.setPointSize(convert<int>(lyxrc.font_sizes[Font::SIZE_LARGE]));
532 int const w = pm.width();
533 int const h = pm.height();
535 int x = (width() - w) / 2;
536 int y = (height() - h) / 2;
538 pain.drawPixmap(x, y, pm);
543 pain.setPen(QColor(255, 255, 0));
545 pain.drawText(x, y, text);
549 void GuiWorkArea::paintEvent(QPaintEvent * ev)
551 QRect const rc = ev->rect();
553 LYXERR(Debug::PAINTING) << "paintEvent begin: x: " << rc.x()
555 << " w: " << rc.width()
556 << " h: " << rc.height() << endl;
560 verticalScrollBar()->setPageStep(viewport()->height());
561 screen_ = QPixmap(viewport()->width(), viewport()->height());
564 need_resize_ = false;
567 QPainter pain(viewport());
568 pain.drawPixmap(rc, screen_, rc);
573 void GuiWorkArea::expose(int x, int y, int w, int h)
580 void GuiWorkArea::updateScreen()
582 QLPainter pain(&screen_);
585 LYXERR(Debug::GUI) << "splash screen requested" << endl;
586 verticalScrollBar()->hide();
591 verticalScrollBar()->show();
592 paintText(*buffer_view_, pain);
596 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
598 if (schedule_redraw_) {
599 if (buffer_view_ && buffer_view_->buffer()) {
600 buffer_view_->update(Update::Force);
602 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
604 schedule_redraw_ = false;
605 // Show the cursor immediately after the update.
611 cursor_->update(x, y, h, shape);
613 viewport()->update(cursor_->rect());
617 void GuiWorkArea::removeCursor()
620 //if (!qApp->focusWidget())
621 viewport()->update(cursor_->rect());
625 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
627 QString const & commit_string = e->commitString();
628 docstring const & preedit_string
629 = qstring_to_ucs4(e->preeditString());
636 if (!commit_string.isEmpty()) {
638 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
639 << " preeditString =" << fromqstr(e->preeditString())
640 << " commitString =" << fromqstr(e->commitString())
645 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
646 for (int i = 0; i < commit_string.size(); ++i) {
647 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
652 // Hide the cursor during the kana-kanji transformation.
653 if (preedit_string.empty())
654 startBlinkingCursor();
656 stopBlinkingCursor();
658 // last_width : for checking if last preedit string was/wasn't empty.
659 static bool last_width = false;
660 if (!last_width && preedit_string.empty()) {
661 // if last_width is last length of preedit string.
666 QLPainter pain(&screen_);
667 buffer_view_->updateMetrics(false);
668 paintText(*buffer_view_, pain);
669 Font font = buffer_view_->cursor().getFont();
670 FontMetrics const & fm = theFontMetrics(font);
671 int height = fm.maxHeight();
672 int cur_x = cursor_->rect().left();
673 int cur_y = cursor_->rect().bottom();
675 // redraw area of preedit string.
676 update(0, cur_y - height, GuiWorkArea::width(),
677 (height + 1) * preedit_lines_);
679 if (preedit_string.empty()) {
687 // att : stores an IM attribute.
688 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
690 // get attributes of input method cursor.
691 // cursor_pos : cursor position in preedit string.
692 size_t cursor_pos = 0;
693 bool cursor_is_visible = false;
694 for (int i = 0; i < att.size(); ++i) {
695 if (att.at(i).type == QInputMethodEvent::Cursor) {
696 cursor_pos = att.at(i).start;
697 cursor_is_visible = att.at(i).length != 0;
702 size_t preedit_length = preedit_string.length();
704 // get position of selection in input method.
705 // FIXME: isn't there a way to do this simplier?
706 // rStart : cursor position in selected string in IM.
708 // rLength : selected string length in IM.
710 if (cursor_pos < preedit_length) {
711 for (int i = 0; i < att.size(); ++i) {
712 if (att.at(i).type == QInputMethodEvent::TextFormat) {
713 if (att.at(i).start <= int(cursor_pos)
714 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
715 rStart = att.at(i).start;
716 rLength = att.at(i).length;
717 if (!cursor_is_visible)
718 cursor_pos += rLength;
729 int const right_margin = rightMargin();
730 Painter::preedit_style ps;
731 // Most often there would be only one line:
733 for (size_t pos = 0; pos != preedit_length; ++pos) {
734 char_type const typed_char = preedit_string[pos];
735 // reset preedit string style
736 ps = Painter::preedit_default;
738 // if we reached the right extremity of the screen, go to next line.
739 if (cur_x + fm.width(typed_char) > GuiWorkArea::width() - right_margin) {
740 cur_x = right_margin;
744 // preedit strings are displayed with dashed underline
745 // and partial strings are displayed white on black indicating
746 // that we are in selecting mode in the input method.
747 // FIXME: rLength == preedit_length is not a changing condition
748 // FIXME: should be put out of the loop.
750 && pos < rStart + rLength
751 && !(cursor_pos < rLength && rLength == preedit_length))
752 ps = Painter::preedit_selecting;
754 if (pos == cursor_pos
755 && (cursor_pos < rLength && rLength == preedit_length))
756 ps = Painter::preedit_cursor;
758 // draw one character and update cur_x.
759 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
762 // update the preedit string screen area.
763 update(0, cur_y - preedit_lines_*height, GuiWorkArea::width(),
764 (height + 1) * preedit_lines_);
766 // Don't forget to accept the event!
771 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
773 QRect cur_r(0,0,0,0);
775 // this is the CJK-specific composition window position.
776 case Qt::ImMicroFocus:
777 cur_r = cursor_->rect();
778 if (preedit_lines_ != 1)
780 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
781 // return lower right of cursor in LyX.
784 return QWidget::inputMethodQuery(query);
788 } // namespace frontend
791 #include "GuiWorkArea_moc.cpp"