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::ScrollBarAsNeeded);
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 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());
245 void GuiWorkArea::dragEnterEvent(QDragEnterEvent * event)
247 if (event->mimeData()->hasUrls())
249 /// \todo Ask lyx-devel is this is enough:
250 /// if (event->mimeData()->hasFormat("text/plain"))
251 /// event->acceptProposedAction();
255 void GuiWorkArea::dropEvent(QDropEvent* event)
257 QList<QUrl> files = event->mimeData()->urls();
261 lyxerr[Debug::GUI] << "GuiWorkArea::dropEvent: got URIs!" << endl;
262 for (int i = 0; i!=files.size(); ++i) {
263 string const file = os::internal_path(fromqstr(files.at(i).toLocalFile()));
265 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
270 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
272 // No need to do anything if we didn't change views...
273 if (&lyx_view_ == &theApp->currentView())
276 theApp->setCurrentView(lyx_view_);
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();
284 //FIXME: Use case: Two windows share the same buffer.
285 // The first window is resize. This modify the inner Buffer
286 // structure because Paragraph has a notion of line break and
287 // thus line width (this is very bad!).
288 // When switching to the other window which does not have the
289 // same size, LyX crashes because the line break is not adapted
290 // the this BufferView width.
291 // The following line fix the crash by resizing the BufferView
292 // on a focusInEvent(). That is not a good fix but it is a fix
293 // nevertheless. The bad side effect is that when the two
294 // BufferViews show the same portion of the Buffer, the second
295 // BufferView will show the same line breaks as the first one;
296 // even though those line breaks are not adapted to the second
297 // BufferView width... such is life!
302 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
304 // No need to do anything if we didn't change views...
305 if (&lyx_view_ == &theApp->currentView())
308 stopBlinkingCursor();
312 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
314 if (dc_event_.active && dc_event_ == *e) {
315 dc_event_.active = false;
316 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
317 dc_event_.x, dc_event_.y,
318 q_button_state(dc_event_.state));
323 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
324 q_button_state(e->button()));
329 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
331 if (synthetic_mouse_event_.timeout.running())
332 synthetic_mouse_event_.timeout.stop();
334 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
335 q_button_state(e->button()));
340 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
342 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
343 q_motion_state(e->buttons()));
345 // If we're above or below the work area...
346 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
347 // Make sure only a synthetic event can cause a page scroll,
348 // so they come at a steady rate:
350 // _Force_ a scroll up:
353 cmd.y = viewport()->height();
354 // Store the event, to be handled when the timeout expires.
355 synthetic_mouse_event_.cmd = cmd;
357 if (synthetic_mouse_event_.timeout.running())
358 // Discard the event. Note that it _may_ be handled
359 // when the timeout expires if
360 // synthetic_mouse_event_.cmd has not been overwritten.
361 // Ie, when the timeout expires, we handle the
362 // most recent event but discard all others that
363 // occurred after the one used to start the timeout
364 // in the first place.
367 synthetic_mouse_event_.restart_timeout = true;
368 synthetic_mouse_event_.timeout.start();
369 // Fall through to handle this event...
372 } else if (synthetic_mouse_event_.timeout.running()) {
373 // Store the event, to be possibly handled when the timeout
375 // Once the timeout has expired, normal control is returned
376 // to mouseMoveEvent (restart_timeout = false).
377 // This results in a much smoother 'feel' when moving the
378 // mouse back into the work area.
379 synthetic_mouse_event_.cmd = cmd;
380 synthetic_mouse_event_.restart_timeout = false;
384 // Has anything changed on-screen since the last QMouseEvent
386 double const scrollbar_value = verticalScrollBar()->value();
387 if (e->x() != synthetic_mouse_event_.x_old ||
388 e->y() != synthetic_mouse_event_.y_old ||
389 scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
390 // Yes it has. Store the params used to check this.
391 synthetic_mouse_event_.x_old = e->x();
392 synthetic_mouse_event_.y_old = e->y();
393 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
395 // ... and dispatch the event to the LyX core.
401 void GuiWorkArea::wheelEvent(QWheelEvent * e)
403 // Wheel rotation by one notch results in a delta() of 120 (see
404 // documentation of QWheelEvent)
405 int const lines = qApp->wheelScrollLines() * e->delta() / 120;
406 verticalScrollBar()->setValue(verticalScrollBar()->value() -
407 lines * verticalScrollBar()->singleStep());
408 adjustViewWithScrollBar();
412 void GuiWorkArea::generateSyntheticMouseEvent()
414 // Set things off to generate the _next_ 'pseudo' event.
415 if (synthetic_mouse_event_.restart_timeout)
416 synthetic_mouse_event_.timeout.start();
418 // Has anything changed on-screen since the last timeout signal
420 double const scrollbar_value = verticalScrollBar()->value();
421 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
422 // Yes it has. Store the params used to check this.
423 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
425 // ... and dispatch the event to the LyX core.
426 dispatch(synthetic_mouse_event_.cmd);
431 void GuiWorkArea::keyPressEvent(QKeyEvent * e)
433 lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
434 << " count=" << e->count()
435 << " text=" << fromqstr(e->text())
436 << " isAutoRepeat=" << e->isAutoRepeat()
437 << " key=" << e->key()
440 if (USE_EVENT_PRUNING) {
441 keyeventQueue_.push(boost::shared_ptr<QKeyEvent>(new QKeyEvent(*e)));
444 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
446 processKeySym(sym, q_key_state(e->modifiers()));
451 // This is used only if USE_EVENT_PRUNING is defined...
452 void GuiWorkArea::keyeventTimeout()
454 bool handle_autos = true;
456 while (!keyeventQueue_.empty()) {
457 boost::shared_ptr<QKeyEvent> ev = keyeventQueue_.front();
459 // We never handle more than one auto repeated
460 // char in a list of queued up events.
461 if (!handle_autos && ev->isAutoRepeat()) {
462 keyeventQueue_.pop();
466 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
469 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
470 << " count=" << ev->count()
471 << " text=" << fromqstr(ev->text())
472 << " isAutoRepeat=" << ev->isAutoRepeat()
473 << " key=" << ev->key()
476 processKeySym(sym, q_key_state(ev->modifiers()));
477 keyeventQueue_.pop();
479 handle_autos = false;
482 // Restart the timer.
483 step_timer_.setSingleShot(true);
484 step_timer_.start(25);
488 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
490 dc_event_ = double_click(e);
492 if (!dc_event_.active)
495 dc_event_.active = false;
497 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
498 dc_event_.x, dc_event_.y,
499 q_button_state(dc_event_.state));
504 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
506 stopBlinkingCursor();
507 screen_ = QPixmap(ev->size().width(), ev->size().height());
508 verticalScrollBar()->setPageStep(viewport()->height());
509 QAbstractScrollArea::resizeEvent(ev);
511 startBlinkingCursor();
515 void GuiWorkArea::update(int x, int y, int w, int h)
517 viewport()->update(x, y, w, h);
521 void GuiWorkArea::doGreyOut(QLPainter & pain)
523 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
525 pain.fillRectangle(0, 0, width(), height(),
528 //if (!lyxrc.show_banner)
530 lyxerr << "show banner: " << lyxrc.show_banner << endl;
531 /// The text to be written on top of the pixmap
532 string const text = lyx_version ? lyx_version : "unknown";
533 string const file = support::libFileSearch("images", "banner", "ppm");
537 QPixmap pm(toqstr(file));
539 lyxerr << "could not load splash screen: '" << file << "'" << endl;
544 // The font used to display the version info
545 font.setStyleHint(QFont::SansSerif);
546 font.setWeight(QFont::Bold);
547 font.setPointSize(LyXFont::SIZE_NORMAL);
549 int const w = pm.width();
550 int const h = pm.height();
552 int x = (width() - w) / 2;
553 int y = (height() - h) / 2;
555 pain.drawPixmap(x, y, pm);
560 pain.setPen(QColor(255, 255, 0));
562 pain.drawText(x, y, toqstr(text));
566 void GuiWorkArea::paintEvent(QPaintEvent * ev)
568 QRect const rc = ev->rect();
569 lyxerr[Debug::PAINTING] << "paintEvent begin: x: " << rc.x()
571 << " w: " << rc.width()
572 << " h: " << rc.height() << endl;
574 QPainter pain(viewport());
575 pain.drawPixmap(rc, screen_, rc);
580 void GuiWorkArea::expose(int x, int y, int w, int h)
582 QLPainter pain(&screen_);
585 lyxerr << "splash screen requested" << endl;
587 verticalScrollBar()->hide();
588 update(0, 0, width(), height());
592 verticalScrollBar()->show();
593 paintText(*buffer_view_, pain);
598 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
600 cursor_->update(x, y, h, shape);
602 viewport()->update(cursor_->rect());
606 void GuiWorkArea::removeCursor()
609 //if (!qApp->focusWidget())
610 viewport()->update(cursor_->rect());
614 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
616 QString const & text = e->commitString();
617 if (!text.isEmpty()) {
619 lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
620 << " preeditString =" << fromqstr(e->preeditString())
621 << " commitString =" << fromqstr(e->commitString())
625 // needed to make math superscript work on some systems
626 // ideally, such special coding should not be necessary
628 key = Qt::Key_AsciiCircum;
629 // FIXME: Needs for investigation, this key is not really used,
630 // the ctor below just check if key is different from 0.
631 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, text);
637 } // namespace frontend
640 #include "GuiWorkArea_moc.cpp"