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"
34 #include "graphics/GraphicsImage.h"
35 #include "graphics/GraphicsLoader.h"
38 #include <QMainWindow>
41 #include <QDragEnterEvent>
45 #include <boost/bind.hpp>
46 #include <boost/current_function.hpp>
48 // Abdel (26/06/2006):
49 // On windows-XP the UserGuide PageDown scroll test is faster without event pruning (16 s)
50 // than with it (23 s).
52 int const CursorWidth = 2;
53 #define USE_EVENT_PRUNING 0
55 int const CursorWidth = 1;
56 #define USE_EVENT_PRUNING 0
63 namespace os = lyx::support::os;
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)
165 cursor_ = new frontend::CursorWidget();
168 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
169 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
170 setAcceptDrops(true);
171 setMinimumSize(100, 70);
173 //viewport()->setAutoFillBackground(false);
174 //viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
175 setFocusPolicy(Qt::WheelFocus);
177 viewport()->setCursor(Qt::IBeamCursor);
181 synthetic_mouse_event_.timeout.timeout.connect(
182 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
185 // Initialize the vertical Scroll Bar
186 QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
187 this, SLOT(adjustViewWithScrollBar(int)));
189 // PageStep only depends on the viewport height.
190 verticalScrollBar()->setPageStep(viewport()->height());
192 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
193 << "\n Area width\t" << width()
194 << "\n Area height\t" << height()
195 << "\n viewport width\t" << viewport()->width()
196 << "\n viewport height\t" << viewport()->height()
199 if (USE_EVENT_PRUNING) {
200 // This is the keyboard buffering stuff...
201 // I don't see any need for this under windows. The keyboard is reactive
204 if ( !QObject::connect(&step_timer_, SIGNAL(timeout()),
205 this, SLOT(keyeventTimeout())) )
206 lyxerr[Debug::GUI] << "ERROR: keyeventTimeout cannot connect!" << endl;
208 // Start the timer, one-shot.
209 step_timer_.setSingleShot(true);
210 step_timer_.start(50);
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 verticalScrollBar()->setTracking(false);
223 // do what cursor movement does (some grey)
225 int scroll_max_ = std::max(0, h - height());
227 verticalScrollBar()->setRange(0, scroll_max_);
228 verticalScrollBar()->setSliderPosition(scroll_pos);
229 verticalScrollBar()->setSingleStep(scroll_line_step);
230 verticalScrollBar()->setValue(scroll_pos);
232 verticalScrollBar()->setTracking(true);
236 void GuiWorkArea::adjustViewWithScrollBar(int)
238 scrollBufferView(verticalScrollBar()->sliderPosition());
242 void GuiWorkArea::dragEnterEvent(QDragEnterEvent * event)
244 if (event->mimeData()->hasUrls())
246 /// \todo Ask lyx-devel is this is enough:
247 /// if (event->mimeData()->hasFormat("text/plain"))
248 /// event->acceptProposedAction();
252 void GuiWorkArea::dropEvent(QDropEvent* event)
254 QList<QUrl> files = event->mimeData()->urls();
258 lyxerr[Debug::GUI] << "GuiWorkArea::dropEvent: got URIs!" << endl;
259 for (int i = 0; i!=files.size(); ++i) {
260 string const file = os::internal_path(fromqstr(files.at(i).toLocalFile()));
262 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
267 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
269 // No need to do anything if we didn't change views...
270 if (&lyx_view_ == &theApp->currentView())
273 theApp->setCurrentView(lyx_view_);
275 // FIXME: it would be better to send a signal "newBuffer()"
276 // in BufferList that could be connected to the different tabbars.
277 lyx_view_.updateTab();
279 startBlinkingCursor();
281 //FIXME: Use case: Two windows share the same buffer.
282 // The first window is resize. This modify the inner Buffer
283 // structure because Paragraph has a notion of line break and
284 // thus line width (this is very bad!).
285 // When switching to the other window which does not have the
286 // same size, LyX crashes because the line break is not adapted
287 // the this BufferView width.
288 // The following line fix the crash by resizing the BufferView
289 // on a focusInEvent(). That is not a good fix but it is a fix
290 // nevertheless. The bad side effect is that when the two
291 // BufferViews show the same portion of the Buffer, the second
292 // BufferView will show the same line breaks as the first one;
293 // even though those line breaks are not adapted to the second
294 // BufferView width... such is life!
299 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
301 // No need to do anything if we didn't change views...
302 if (&lyx_view_ == &theApp->currentView())
305 stopBlinkingCursor();
309 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
311 if (dc_event_.active && dc_event_ == *e) {
312 dc_event_.active = false;
313 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
314 dc_event_.x, dc_event_.y,
315 q_button_state(dc_event_.state));
320 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
321 q_button_state(e->button()));
326 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
328 if (synthetic_mouse_event_.timeout.running())
329 synthetic_mouse_event_.timeout.stop();
331 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
332 q_button_state(e->button()));
337 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
339 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
340 q_motion_state(e->buttons()));
342 // If we're above or below the work area...
343 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
344 // Make sure only a synthetic event can cause a page scroll,
345 // so they come at a steady rate:
347 // _Force_ a scroll up:
350 cmd.y = viewport()->height();
351 // Store the event, to be handled when the timeout expires.
352 synthetic_mouse_event_.cmd = cmd;
354 if (synthetic_mouse_event_.timeout.running())
355 // Discard the event. Note that it _may_ be handled
356 // when the timeout expires if
357 // synthetic_mouse_event_.cmd has not been overwritten.
358 // Ie, when the timeout expires, we handle the
359 // most recent event but discard all others that
360 // occurred after the one used to start the timeout
361 // in the first place.
364 synthetic_mouse_event_.restart_timeout = true;
365 synthetic_mouse_event_.timeout.start();
366 // Fall through to handle this event...
369 } else if (synthetic_mouse_event_.timeout.running()) {
370 // Store the event, to be possibly handled when the timeout
372 // Once the timeout has expired, normal control is returned
373 // to mouseMoveEvent (restart_timeout = false).
374 // This results in a much smoother 'feel' when moving the
375 // mouse back into the work area.
376 synthetic_mouse_event_.cmd = cmd;
377 synthetic_mouse_event_.restart_timeout = false;
381 // Has anything changed on-screen since the last QMouseEvent
383 double const scrollbar_value = verticalScrollBar()->value();
384 if (e->x() != synthetic_mouse_event_.x_old ||
385 e->y() != synthetic_mouse_event_.y_old ||
386 scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
387 // Yes it has. Store the params used to check this.
388 synthetic_mouse_event_.x_old = e->x();
389 synthetic_mouse_event_.y_old = e->y();
390 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
392 // ... and dispatch the event to the LyX core.
398 void GuiWorkArea::wheelEvent(QWheelEvent * e)
400 // Wheel rotation by one notch results in a delta() of 120 (see
401 // documentation of QWheelEvent)
402 int const lines = qApp->wheelScrollLines() * e->delta() / 120;
403 verticalScrollBar()->setValue(verticalScrollBar()->value() -
404 lines * verticalScrollBar()->singleStep());
405 adjustViewWithScrollBar();
409 void GuiWorkArea::generateSyntheticMouseEvent()
411 // Set things off to generate the _next_ 'pseudo' event.
412 if (synthetic_mouse_event_.restart_timeout)
413 synthetic_mouse_event_.timeout.start();
415 // Has anything changed on-screen since the last timeout signal
417 double const scrollbar_value = verticalScrollBar()->value();
418 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
419 // Yes it has. Store the params used to check this.
420 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
422 // ... and dispatch the event to the LyX core.
423 dispatch(synthetic_mouse_event_.cmd);
428 void GuiWorkArea::keyPressEvent(QKeyEvent * e)
430 lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
431 << " count=" << e->count()
432 << " text=" << fromqstr(e->text())
433 << " isAutoRepeat=" << e->isAutoRepeat()
434 << " key=" << e->key()
437 if (USE_EVENT_PRUNING) {
438 keyeventQueue_.push(boost::shared_ptr<QKeyEvent>(new QKeyEvent(*e)));
441 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
443 processKeySym(sym, q_key_state(e->modifiers()));
448 // This is used only if USE_EVENT_PRUNING is defined...
449 void GuiWorkArea::keyeventTimeout()
451 bool handle_autos = true;
453 while (!keyeventQueue_.empty()) {
454 boost::shared_ptr<QKeyEvent> ev = keyeventQueue_.front();
456 // We never handle more than one auto repeated
457 // char in a list of queued up events.
458 if (!handle_autos && ev->isAutoRepeat()) {
459 keyeventQueue_.pop();
463 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
466 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
467 << " count=" << ev->count()
468 << " text=" << fromqstr(ev->text())
469 << " isAutoRepeat=" << ev->isAutoRepeat()
470 << " key=" << ev->key()
473 processKeySym(sym, q_key_state(ev->modifiers()));
474 keyeventQueue_.pop();
476 handle_autos = false;
479 // Restart the timer.
480 step_timer_.setSingleShot(true);
481 step_timer_.start(25);
485 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
487 dc_event_ = double_click(e);
489 if (!dc_event_.active)
492 dc_event_.active = false;
494 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
495 dc_event_.x, dc_event_.y,
496 q_button_state(dc_event_.state));
501 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
503 stopBlinkingCursor();
504 screen_ = QPixmap(ev->size().width(), ev->size().height());
505 verticalScrollBar()->setPageStep(viewport()->height());
506 QAbstractScrollArea::resizeEvent(ev);
508 startBlinkingCursor();
512 void GuiWorkArea::update(int x, int y, int w, int h)
514 viewport()->update(x, y, w, h);
518 void GuiWorkArea::doGreyOut(QLPainter & pain)
520 pain.fillRectangle(0, 0, width(), height(),
523 //if (!lyxrc.show_banner)
525 lyxerr << "show banner: " << lyxrc.show_banner << endl;
526 /// The text to be written on top of the pixmap
527 string const text = lyx_version ? lyx_version : "unknown";
528 string const file = support::libFileSearch("images", "banner", "ppm");
532 QPixmap pm(toqstr(file));
534 lyxerr << "could not load splash screen: '" << file << "'" << endl;
539 // The font used to display the version info
540 font.setStyleHint(QFont::SansSerif);
541 font.setWeight(QFont::Bold);
542 font.setPointSize(LyXFont::SIZE_NORMAL);
544 int const w = pm.width();
545 int const h = pm.height();
547 int x = (width() - w) / 2;
548 int y = (height() - h) / 2;
550 pain.drawPixmap(x, y, pm);
555 pain.setPen(QColor(255, 255, 0));
557 pain.drawText(x, y, toqstr(text));
561 void GuiWorkArea::paintEvent(QPaintEvent * ev)
563 QRect const rc = ev->rect();
564 lyxerr[Debug::PAINTING] << "paintEvent begin: x: " << rc.x()
566 << " w: " << rc.width()
567 << " h: " << rc.height() << endl;
569 QPainter pain(viewport());
570 pain.drawPixmap(rc, screen_, rc);
575 void GuiWorkArea::expose(int x, int y, int w, int h)
577 QLPainter pain(&screen_);
580 lyxerr << "splash screen requested" << endl;
582 verticalScrollBar()->hide();
583 update(0, 0, width(), height());
587 verticalScrollBar()->show();
588 paintText(*buffer_view_, pain);
593 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
595 cursor_->update(x, y, h, shape);
597 viewport()->update(cursor_->rect());
601 void GuiWorkArea::removeCursor()
604 //if (!qApp->focusWidget())
605 viewport()->update(cursor_->rect());
609 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
611 QString const & text = e->commitString();
612 if (!text.isEmpty()) {
614 lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
615 << " preeditString =" << fromqstr(e->preeditString())
616 << " commitString =" << fromqstr(e->commitString())
620 // needed to make math superscript work on some systems
621 // ideally, such special coding should not be necessary
623 key = Qt::Key_AsciiCircum;
624 // FIXME: Needs for investigation, this key is not really used,
625 // the ctor below just check if key is different from 0.
626 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, text);
632 } // namespace frontend
635 #include "GuiWorkArea_moc.cpp"