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 = false) { show_ = set_show; }
138 void hide() { show_ = false; }
152 // This is a 'heartbeat' generating synthetic mouse move events when the
153 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
154 SyntheticMouseEvent::SyntheticMouseEvent()
155 : timeout(200), restart_timeout(true),
156 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
160 GuiWorkArea::GuiWorkArea(int w, int h, int id, LyXView & lyx_view)
161 : WorkArea(id, lyx_view)
163 cursor_ = new frontend::CursorWidget();
166 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
167 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
168 setAcceptDrops(true);
169 setMinimumSize(100, 70);
171 //viewport()->setAutoFillBackground(false);
172 //viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
173 setFocusPolicy(Qt::WheelFocus);
175 viewport()->setCursor(Qt::IBeamCursor);
179 synthetic_mouse_event_.timeout.timeout.connect(
180 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
183 // Initialize the vertical Scroll Bar
184 QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
185 this, SLOT(adjustViewWithScrollBar(int)));
187 // PageStep only depends on the viewport height.
188 verticalScrollBar()->setPageStep(viewport()->height());
190 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
191 << "\n Area width\t" << width()
192 << "\n Area height\t" << height()
193 << "\n viewport width\t" << viewport()->width()
194 << "\n viewport height\t" << viewport()->height()
197 if (USE_EVENT_PRUNING) {
198 // This is the keyboard buffering stuff...
199 // I don't see any need for this under windows. The keyboard is reactive
202 if ( !QObject::connect(&step_timer_, SIGNAL(timeout()),
203 this, SLOT(keyeventTimeout())) )
204 lyxerr[Debug::GUI] << "ERROR: keyeventTimeout cannot connect!" << endl;
206 // Start the timer, one-shot.
207 step_timer_.setSingleShot(true);
208 step_timer_.start(50);
211 // Enables input methods for asian languages.
212 // Must be set when creating custom text editing widgets.
213 setAttribute(Qt::WA_InputMethodEnabled, true);
217 void GuiWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
219 verticalScrollBar()->setTracking(false);
221 // do what cursor movement does (some grey)
223 int scroll_max_ = std::max(0, h - height());
225 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
226 verticalScrollBar()->setRange(0, scroll_max_);
227 verticalScrollBar()->setSliderPosition(scroll_pos);
228 verticalScrollBar()->setSingleStep(scroll_line_step);
229 verticalScrollBar()->setValue(scroll_pos);
231 verticalScrollBar()->setTracking(true);
235 void GuiWorkArea::adjustViewWithScrollBar(int)
237 scrollBufferView(verticalScrollBar()->sliderPosition());
241 void GuiWorkArea::dragEnterEvent(QDragEnterEvent * event)
243 if (event->mimeData()->hasUrls())
245 /// \todo Ask lyx-devel is this is enough:
246 /// if (event->mimeData()->hasFormat("text/plain"))
247 /// event->acceptProposedAction();
251 void GuiWorkArea::dropEvent(QDropEvent* event)
253 QList<QUrl> files = event->mimeData()->urls();
257 lyxerr[Debug::GUI] << "GuiWorkArea::dropEvent: got URIs!" << endl;
258 for (int i = 0; i!=files.size(); ++i) {
259 string const file = os::internal_path(fromqstr(files.at(i).toLocalFile()));
261 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
266 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
268 // No need to do anything if we didn't change views...
269 if (&lyx_view_ == &theApp->currentView())
272 theApp->setCurrentView(lyx_view_);
274 // FIXME: it would be better to send a signal "newBuffer()"
275 // in BufferList that could be connected to the different tabbars.
276 lyx_view_.updateTab();
278 startBlinkingCursor();
280 //FIXME: Use case: Two windows share the same buffer.
281 // The first window is resize. This modify the inner Buffer
282 // structure because Paragraph has a notion of line break and
283 // thus line width (this is very bad!).
284 // When switching to the other window which does not have the
285 // same size, LyX crashes because the line break is not adapted
286 // the this BufferView width.
287 // The following line fix the crash by resizing the BufferView
288 // on a focusInEvent(). That is not a good fix but it is a fix
289 // nevertheless. The bad side effect is that when the two
290 // BufferViews show the same portion of the Buffer, the second
291 // BufferView will show the same line breaks as the first one;
292 // even though those line breaks are not adapted to the second
293 // BufferView width... such is life!
298 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
300 // No need to do anything if we didn't change views...
301 if (&lyx_view_ == &theApp->currentView())
304 stopBlinkingCursor();
308 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
310 if (dc_event_.active && dc_event_ == *e) {
311 dc_event_.active = false;
312 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
313 dc_event_.x, dc_event_.y,
314 q_button_state(dc_event_.state));
319 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
320 q_button_state(e->button()));
325 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
327 if (synthetic_mouse_event_.timeout.running())
328 synthetic_mouse_event_.timeout.stop();
330 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
331 q_button_state(e->button()));
336 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
338 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
339 q_motion_state(e->buttons()));
341 // If we're above or below the work area...
342 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
343 // Make sure only a synthetic event can cause a page scroll,
344 // so they come at a steady rate:
346 // _Force_ a scroll up:
349 cmd.y = viewport()->height();
350 // Store the event, to be handled when the timeout expires.
351 synthetic_mouse_event_.cmd = cmd;
353 if (synthetic_mouse_event_.timeout.running())
354 // Discard the event. Note that it _may_ be handled
355 // when the timeout expires if
356 // synthetic_mouse_event_.cmd has not been overwritten.
357 // Ie, when the timeout expires, we handle the
358 // most recent event but discard all others that
359 // occurred after the one used to start the timeout
360 // in the first place.
363 synthetic_mouse_event_.restart_timeout = true;
364 synthetic_mouse_event_.timeout.start();
365 // Fall through to handle this event...
368 } else if (synthetic_mouse_event_.timeout.running()) {
369 // Store the event, to be possibly handled when the timeout
371 // Once the timeout has expired, normal control is returned
372 // to mouseMoveEvent (restart_timeout = false).
373 // This results in a much smoother 'feel' when moving the
374 // mouse back into the work area.
375 synthetic_mouse_event_.cmd = cmd;
376 synthetic_mouse_event_.restart_timeout = false;
380 // Has anything changed on-screen since the last QMouseEvent
382 double const scrollbar_value = verticalScrollBar()->value();
383 if (e->x() != synthetic_mouse_event_.x_old ||
384 e->y() != synthetic_mouse_event_.y_old ||
385 scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
386 // Yes it has. Store the params used to check this.
387 synthetic_mouse_event_.x_old = e->x();
388 synthetic_mouse_event_.y_old = e->y();
389 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
391 // ... and dispatch the event to the LyX core.
397 void GuiWorkArea::wheelEvent(QWheelEvent * e)
399 // Wheel rotation by one notch results in a delta() of 120 (see
400 // documentation of QWheelEvent)
401 int const lines = qApp->wheelScrollLines() * e->delta() / 120;
402 verticalScrollBar()->setValue(verticalScrollBar()->value() -
403 lines * verticalScrollBar()->singleStep());
404 adjustViewWithScrollBar();
408 void GuiWorkArea::generateSyntheticMouseEvent()
410 // Set things off to generate the _next_ 'pseudo' event.
411 if (synthetic_mouse_event_.restart_timeout)
412 synthetic_mouse_event_.timeout.start();
414 // Has anything changed on-screen since the last timeout signal
416 double const scrollbar_value = verticalScrollBar()->value();
417 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
418 // Yes it has. Store the params used to check this.
419 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
421 // ... and dispatch the event to the LyX core.
422 dispatch(synthetic_mouse_event_.cmd);
427 void GuiWorkArea::keyPressEvent(QKeyEvent * e)
429 lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
430 << " count=" << e->count()
431 << " text=" << fromqstr(e->text())
432 << " isAutoRepeat=" << e->isAutoRepeat()
433 << " key=" << e->key()
436 if (USE_EVENT_PRUNING) {
437 keyeventQueue_.push(boost::shared_ptr<QKeyEvent>(new QKeyEvent(*e)));
440 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
442 processKeySym(sym, q_key_state(e->modifiers()));
447 // This is used only if USE_EVENT_PRUNING is defined...
448 void GuiWorkArea::keyeventTimeout()
450 bool handle_autos = true;
452 while (!keyeventQueue_.empty()) {
453 boost::shared_ptr<QKeyEvent> ev = keyeventQueue_.front();
455 // We never handle more than one auto repeated
456 // char in a list of queued up events.
457 if (!handle_autos && ev->isAutoRepeat()) {
458 keyeventQueue_.pop();
462 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
465 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
466 << " count=" << ev->count()
467 << " text=" << fromqstr(ev->text())
468 << " isAutoRepeat=" << ev->isAutoRepeat()
469 << " key=" << ev->key()
472 processKeySym(sym, q_key_state(ev->modifiers()));
473 keyeventQueue_.pop();
475 handle_autos = false;
478 // Restart the timer.
479 step_timer_.setSingleShot(true);
480 step_timer_.start(25);
484 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
486 dc_event_ = double_click(e);
488 if (!dc_event_.active)
491 dc_event_.active = false;
493 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
494 dc_event_.x, dc_event_.y,
495 q_button_state(dc_event_.state));
500 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
503 screen_ = QPixmap(ev->size().width(), ev->size().height());
504 verticalScrollBar()->setPageStep(viewport()->height());
505 QAbstractScrollArea::resizeEvent(ev);
510 void GuiWorkArea::update(int x, int y, int w, int h)
512 viewport()->update(x, y, w, h);
516 void GuiWorkArea::doGreyOut(QLPainter & pain)
518 pain.fillRectangle(0, 0, width(), height(),
521 //if (!lyxrc.show_banner)
523 lyxerr << "show banner: " << lyxrc.show_banner << endl;
524 /// The text to be written on top of the pixmap
525 string const text = lyx_version ? lyx_version : "unknown";
526 string const file = support::libFileSearch("images", "banner", "ppm");
530 QPixmap pm(toqstr(file));
532 lyxerr << "could not load splash screen: '" << file << "'" << endl;
537 // The font used to display the version info
538 font.setStyleHint(QFont::SansSerif);
539 font.setWeight(QFont::Bold);
540 font.setPointSize(LyXFont::SIZE_NORMAL);
542 int const w = pm.width();
543 int const h = pm.height();
545 int x = (width() - w) / 2;
546 int y = (height() - h) / 2;
548 pain.drawPixmap(x, y, pm);
553 pain.setPen(QColor(255, 255, 0));
555 pain.drawText(x, y, toqstr(text));
559 void GuiWorkArea::paintEvent(QPaintEvent * ev)
561 QRect const rc = ev->rect();
562 lyxerr[Debug::PAINTING] << "paintEvent begin: x: " << rc.x()
564 << " w: " << rc.width()
565 << " h: " << rc.height() << endl;
567 QPainter pain(viewport());
568 pain.drawPixmap(rc, screen_, rc);
573 void GuiWorkArea::expose(int x, int y, int w, int h)
575 QLPainter pain(&screen_);
578 lyxerr << "splash screen requested" << endl;
580 verticalScrollBar()->hide();
581 update(0, 0, width(), height());
585 verticalScrollBar()->show();
586 paintText(*buffer_view_, pain);
591 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
593 cursor_->update(x, y, h, shape);
598 void GuiWorkArea::removeCursor()
600 if (!qApp->focusWidget())
606 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
608 QString const & text = e->commitString();
609 if (!text.isEmpty()) {
611 lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
612 << " preeditString =" << fromqstr(e->preeditString())
613 << " commitString =" << fromqstr(e->commitString())
617 // needed to make math superscript work on some systems
618 // ideally, such special coding should not be necessary
620 key = Qt::Key_AsciiCircum;
621 // FIXME: Needs for investigation, this key is not really used,
622 // the ctor below just check if key is different from 0.
623 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, text);
629 } // namespace frontend
632 #include "GuiWorkArea_moc.cpp"