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 "QLyXKeySym.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>
52 int const CursorWidth = 2;
54 int const CursorWidth = 1;
61 namespace os = lyx::support::os;
66 using support::FileName;
68 /// return the LyX key state from Qt's
69 static key_modifier::state q_key_state(Qt::KeyboardModifiers state)
71 key_modifier::state k = key_modifier::none;
72 if (state & Qt::ControlModifier)
73 k |= key_modifier::ctrl;
74 if (state & Qt::ShiftModifier)
75 k |= key_modifier::shift;
76 if (state & Qt::AltModifier || state & Qt::MetaModifier)
77 k |= key_modifier::alt;
82 /// return the LyX mouse button state from Qt's
83 static mouse_button::state q_button_state(Qt::MouseButton button)
85 mouse_button::state b = mouse_button::none;
88 b = mouse_button::button1;
91 b = mouse_button::button2;
94 b = mouse_button::button3;
103 /// return the LyX mouse button state from Qt's
104 mouse_button::state q_motion_state(Qt::MouseButtons state)
106 mouse_button::state b = mouse_button::none;
107 if (state & Qt::LeftButton)
108 b |= mouse_button::button1;
109 if (state & Qt::MidButton)
110 b |= mouse_button::button2;
111 if (state & Qt::RightButton)
112 b |= mouse_button::button3;
123 void draw(QPainter & painter)
125 // FIXME: do something depending on the cursor shape.
126 if (show_ && rect_.isValid())
127 painter.fillRect(rect_, color_);
130 void update(int x, int y, int h, CursorShape shape)
132 color_ = guiApp->colorCache().get(LColor::cursor);
133 rect_ = QRect(x, y, CursorWidth, h);
137 void show(bool set_show = true) { show_ = set_show; }
138 void hide() { show_ = false; }
140 QRect const & rect() { return rect_; }
154 // This is a 'heartbeat' generating synthetic mouse move events when the
155 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
156 SyntheticMouseEvent::SyntheticMouseEvent()
157 : timeout(200), restart_timeout(true),
158 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
162 GuiWorkArea::GuiWorkArea(int w, int h, int id, LyXView & lyx_view)
163 : WorkArea(id, lyx_view), need_resize_(false), schedule_redraw_(false),
166 screen_ = QPixmap(viewport()->width(), viewport()->height());
167 cursor_ = new frontend::CursorWidget();
170 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
171 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
172 setAcceptDrops(true);
173 setMouseTracking(true);
174 setMinimumSize(100, 70);
176 viewport()->setAutoFillBackground(false);
177 // We don't need double-buffering nor SystemBackground on
178 // the viewport because we have our own backing pixmap.
179 viewport()->setAttribute(Qt::WA_NoSystemBackground);
181 setFocusPolicy(Qt::WheelFocus);
183 viewport()->setCursor(Qt::IBeamCursor);
187 synthetic_mouse_event_.timeout.timeout.connect(
188 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
191 // Initialize the vertical Scroll Bar
192 QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
193 this, SLOT(adjustViewWithScrollBar(int)));
195 // disable context menu for the scrollbar
196 verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu);
198 // PageStep only depends on the viewport height.
199 verticalScrollBar()->setPageStep(viewport()->height());
201 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
202 << "\n Area width\t" << width()
203 << "\n Area height\t" << height()
204 << "\n viewport width\t" << viewport()->width()
205 << "\n viewport height\t" << viewport()->height()
208 // Enables input methods for asian languages.
209 // Must be set when creating custom text editing widgets.
210 setAttribute(Qt::WA_InputMethodEnabled, true);
214 void GuiWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
216 if (verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOn)
217 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
219 verticalScrollBar()->setTracking(false);
221 // do what cursor movement does (some grey)
223 int scroll_max_ = std::max(0, h - height());
225 verticalScrollBar()->setRange(0, scroll_max_);
226 verticalScrollBar()->setSliderPosition(scroll_pos);
227 verticalScrollBar()->setSingleStep(scroll_line_step);
228 verticalScrollBar()->setValue(scroll_pos);
230 verticalScrollBar()->setTracking(true);
234 void GuiWorkArea::adjustViewWithScrollBar(int)
236 scrollBufferView(verticalScrollBar()->sliderPosition());
240 void GuiWorkArea::dragEnterEvent(QDragEnterEvent * event)
242 if (event->mimeData()->hasUrls())
244 /// \todo Ask lyx-devel is this is enough:
245 /// if (event->mimeData()->hasFormat("text/plain"))
246 /// event->acceptProposedAction();
250 void GuiWorkArea::dropEvent(QDropEvent* event)
252 QList<QUrl> files = event->mimeData()->urls();
256 LYXERR(Debug::GUI) << "GuiWorkArea::dropEvent: got URIs!" << endl;
257 for (int i = 0; i!=files.size(); ++i) {
258 string const file = os::internal_path(fromqstr(files.at(i).toLocalFile()));
260 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
265 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
267 // No need to do anything if we didn't change views...
268 // if (theApp() == 0 || &lyx_view_ == theApp()->currentView())
271 theApp()->setCurrentView(lyx_view_);
273 // Repaint the whole screen.
274 // Note: this is different from redraw() as only the backing pixmap
275 // will be redrawn, which is cheap.
276 viewport()->repaint();
278 // FIXME: it would be better to send a signal "newBuffer()"
279 // in BufferList that could be connected to the different tabbars.
280 lyx_view_.updateTab();
282 startBlinkingCursor();
286 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
288 stopBlinkingCursor();
292 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
294 if (dc_event_.active && dc_event_ == *e) {
295 dc_event_.active = false;
296 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
298 q_button_state(e->button()));
303 inputContext()->reset();
305 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
306 q_button_state(e->button()));
307 dispatch(cmd, q_key_state(e->modifiers()));
311 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
313 if (synthetic_mouse_event_.timeout.running())
314 synthetic_mouse_event_.timeout.stop();
316 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
317 q_button_state(e->button()));
322 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
324 // we kill the triple click if we move
325 doubleClickTimeout();
326 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
327 q_motion_state(e->buttons()));
329 // If we're above or below the work area...
330 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
331 // Make sure only a synthetic event can cause a page scroll,
332 // so they come at a steady rate:
334 // _Force_ a scroll up:
337 cmd.y = viewport()->height();
338 // Store the event, to be handled when the timeout expires.
339 synthetic_mouse_event_.cmd = cmd;
341 if (synthetic_mouse_event_.timeout.running())
342 // Discard the event. Note that it _may_ be handled
343 // when the timeout expires if
344 // synthetic_mouse_event_.cmd has not been overwritten.
345 // Ie, when the timeout expires, we handle the
346 // most recent event but discard all others that
347 // occurred after the one used to start the timeout
348 // in the first place.
351 synthetic_mouse_event_.restart_timeout = true;
352 synthetic_mouse_event_.timeout.start();
353 // Fall through to handle this event...
356 } else if (synthetic_mouse_event_.timeout.running()) {
357 // Store the event, to be possibly handled when the timeout
359 // Once the timeout has expired, normal control is returned
360 // to mouseMoveEvent (restart_timeout = false).
361 // This results in a much smoother 'feel' when moving the
362 // mouse back into the work area.
363 synthetic_mouse_event_.cmd = cmd;
364 synthetic_mouse_event_.restart_timeout = false;
368 // Has anything changed on-screen since the last QMouseEvent
370 double const scrollbar_value = verticalScrollBar()->value();
371 if (e->x() != synthetic_mouse_event_.x_old ||
372 e->y() != synthetic_mouse_event_.y_old ||
373 scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
374 // Yes it has. Store the params used to check this.
375 synthetic_mouse_event_.x_old = e->x();
376 synthetic_mouse_event_.y_old = e->y();
377 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
379 // ... and dispatch the event to the LyX core.
385 void GuiWorkArea::wheelEvent(QWheelEvent * e)
387 // Wheel rotation by one notch results in a delta() of 120 (see
388 // documentation of QWheelEvent)
389 int const lines = qApp->wheelScrollLines() * e->delta() / 120;
390 verticalScrollBar()->setValue(verticalScrollBar()->value() -
391 lines * verticalScrollBar()->singleStep());
392 adjustViewWithScrollBar();
396 void GuiWorkArea::generateSyntheticMouseEvent()
398 // Set things off to generate the _next_ 'pseudo' event.
399 if (synthetic_mouse_event_.restart_timeout)
400 synthetic_mouse_event_.timeout.start();
402 // Has anything changed on-screen since the last timeout signal
404 double const scrollbar_value = verticalScrollBar()->value();
405 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
406 // Yes it has. Store the params used to check this.
407 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
409 // ... and dispatch the event to the LyX core.
410 dispatch(synthetic_mouse_event_.cmd);
415 void GuiWorkArea::keyPressEvent(QKeyEvent * e)
417 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
418 << " count=" << e->count()
419 << " text=" << fromqstr(e->text())
420 << " isAutoRepeat=" << e->isAutoRepeat()
421 << " key=" << e->key()
424 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
426 processKeySym(sym, q_key_state(e->modifiers()));
429 void GuiWorkArea::doubleClickTimeout() {
430 dc_event_.active = false;
433 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
435 dc_event_ = double_click(e);
436 QTimer::singleShot(QApplication::doubleClickInterval(), this,
437 SLOT(doubleClickTimeout()));
438 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
440 q_button_state(e->button()));
445 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
447 QAbstractScrollArea::resizeEvent(ev);
452 void GuiWorkArea::update(int x, int y, int w, int h)
454 viewport()->repaint(x, y, w, h);
458 void GuiWorkArea::doGreyOut(QLPainter & pain)
460 pain.fillRectangle(0, 0, width(), height(),
463 //if (!lyxrc.show_banner)
465 LYXERR(Debug::GUI) << "show banner: " << lyxrc.show_banner << endl;
466 /// The text to be written on top of the pixmap
467 QString const text = lyx_version ? QString(lyx_version) : qt_("unknown version");
468 FileName const file = support::libFileSearch("images", "banner", "png");
472 QPixmap pm(toqstr(file.absFilename()));
474 lyxerr << "could not load splash screen: '" << file << "'" << endl;
479 // The font used to display the version info
480 font.setStyleHint(QFont::SansSerif);
481 font.setWeight(QFont::Bold);
482 font.setPointSize(convert<int>(lyxrc.font_sizes[LyXFont::SIZE_LARGE]));
484 int const w = pm.width();
485 int const h = pm.height();
487 int x = (width() - w) / 2;
488 int y = (height() - h) / 2;
490 pain.drawPixmap(x, y, pm);
495 pain.setPen(QColor(255, 255, 0));
497 pain.drawText(x, y, text);
501 void GuiWorkArea::paintEvent(QPaintEvent * ev)
503 QRect const rc = ev->rect();
505 LYXERR(Debug::PAINTING) << "paintEvent begin: x: " << rc.x()
507 << " w: " << rc.width()
508 << " h: " << rc.height() << endl;
512 verticalScrollBar()->setPageStep(viewport()->height());
513 screen_ = QPixmap(viewport()->width(), viewport()->height());
516 need_resize_ = false;
519 QPainter pain(viewport());
520 pain.drawPixmap(rc, screen_, rc);
525 void GuiWorkArea::expose(int x, int y, int w, int h)
532 void GuiWorkArea::updateScreen()
534 QLPainter pain(&screen_);
537 LYXERR(Debug::GUI) << "splash screen requested" << endl;
538 verticalScrollBar()->hide();
543 verticalScrollBar()->show();
544 paintText(*buffer_view_, pain);
548 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
550 if (schedule_redraw_) {
551 if (buffer_view_ && buffer_view_->buffer()) {
552 buffer_view_->update(Update::Force);
554 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
556 schedule_redraw_ = false;
557 // Show the cursor immediately after the update.
563 cursor_->update(x, y, h, shape);
565 viewport()->update(cursor_->rect());
569 void GuiWorkArea::removeCursor()
572 //if (!qApp->focusWidget())
573 viewport()->update(cursor_->rect());
577 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
579 QString const & commit_string = e->commitString();
580 docstring const & preedit_string
581 = qstring_to_ucs4(e->preeditString());
588 if (!commit_string.isEmpty()) {
590 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
591 << " preeditString =" << fromqstr(e->preeditString())
592 << " commitString =" << fromqstr(e->commitString())
597 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
598 for (int i = 0; i < commit_string.size(); ++i) {
599 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
604 // Hide the cursor during the kana-kanji transformation.
605 if (preedit_string.empty())
606 startBlinkingCursor();
608 stopBlinkingCursor();
610 // last_width : for checking if last preedit string was/wasn't empty.
611 static bool last_width = false;
612 if (!last_width && preedit_string.empty()) {
613 // if last_width is last length of preedit string.
618 QLPainter pain(&screen_);
619 buffer_view_->updateMetrics(false);
620 paintText(*buffer_view_, pain);
621 LyXFont font = buffer_view_->cursor().getFont();
622 FontMetrics const & fm = theFontMetrics(font);
623 int height = fm.maxHeight();
624 int cur_x = cursor_->rect().left();
625 int cur_y = cursor_->rect().bottom();
627 // redraw area of preedit string.
628 update(0, cur_y - height, GuiWorkArea::width(),
629 (height + 1) * preedit_lines_);
631 if (preedit_string.empty()) {
639 // att : stores an IM attribute.
640 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
642 // get attributes of input method cursor.
643 // cursor_pos : cursor position in preedit string.
644 size_t cursor_pos = 0;
645 bool cursor_is_visible = false;
646 for (int i = 0; i < att.size(); ++i) {
647 if (att.at(i).type == QInputMethodEvent::Cursor) {
648 cursor_pos = att.at(i).start;
649 cursor_is_visible = att.at(i).length != 0;
654 size_t preedit_length = preedit_string.length();
656 // get position of selection in input method.
657 // FIXME: isn't there a way to do this simplier?
658 // rStart : cursor position in selected string in IM.
660 // rLength : selected string length in IM.
662 if (cursor_pos < preedit_length) {
663 for (int i = 0; i < att.size(); ++i) {
664 if (att.at(i).type == QInputMethodEvent::TextFormat) {
665 if (att.at(i).start <= int(cursor_pos)
666 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
667 rStart = att.at(i).start;
668 rLength = att.at(i).length;
669 if (!cursor_is_visible)
670 cursor_pos += rLength;
681 int const right_margin = lyx::rightMargin();
682 Painter::preedit_style ps;
683 // Most often there would be only one line:
685 for (size_t pos = 0; pos != preedit_length; ++pos) {
686 char_type const typed_char = preedit_string[pos];
687 // reset preedit string style
688 ps = Painter::preedit_default;
690 // if we reached the right extremity of the screen, go to next line.
691 if (cur_x + fm.width(typed_char) > GuiWorkArea::width() - right_margin) {
692 cur_x = right_margin;
696 // preedit strings are displayed with dashed underline
697 // and partial strings are displayed white on black indicating
698 // that we are in selecting mode in the input method.
699 // FIXME: rLength == preedit_length is not a changing condition
700 // FIXME: should be put out of the loop.
702 && pos < rStart + rLength
703 && !(cursor_pos < rLength && rLength == preedit_length))
704 ps = Painter::preedit_selecting;
706 if (pos == cursor_pos
707 && (cursor_pos < rLength && rLength == preedit_length))
708 ps = Painter::preedit_cursor;
710 // draw one character and update cur_x.
711 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
714 // update the preedit string screen area.
715 update(0, cur_y - preedit_lines_*height, GuiWorkArea::width(),
716 (height + 1) * preedit_lines_);
718 // Don't forget to accept the event!
723 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
725 QRect cur_r(0,0,0,0);
727 // this is the CJK-specific composition window position.
728 case Qt::ImMicroFocus:
729 cur_r = cursor_->rect();
730 if (preedit_lines_ != 1)
732 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
733 // return lower right of cursor in LyX.
736 return QWidget::inputMethodQuery(query);
740 } // namespace frontend
743 #include "GuiWorkArea_moc.cpp"