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;
119 class CursorWidget : public QWidget {
121 CursorWidget(QWidget * parent)
124 resize(CursorWidth, 20);
127 void paintEvent(QPaintEvent *)
129 QColor const & col = guiApp->colorCache().get(LColor::cursor);
135 switch (cursor_shape_) {
137 // FIXME the cursor width shouldn't be hard-coded!
139 lshape_cursor_ = false;
142 cursor_w_ = cursor_h_ / 3;
143 lshape_cursor_ = true;
145 case REVERSED_L_SHAPE:
146 cursor_w_ = cursor_h_ / 3;
147 //cursor_x_ -= cursor_w_ - 1;
148 lshape_cursor_ = true;
153 // We cache two pixmaps:
154 // 1 the vertical line of the cursor.
155 // 2 the horizontal line of the L-shaped cursor (if necessary).
157 // Draw the new (vertical) cursor.
159 pain.fillRect(rect(), col);
161 // Draw the new (horizontal) cursor if necessary.
162 if (lshape_cursor_) {
163 hcursor_ = QPixmap(cursor_w_, 1);
165 show_hcursor_ = true;
178 QColor cursor_color_;
182 // This is a 'heartbeat' generating synthetic mouse move events when the
183 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
184 SyntheticMouseEvent::SyntheticMouseEvent()
185 : timeout(200), restart_timeout(true),
186 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
190 GuiWorkArea::GuiWorkArea(int w, int h, int id, LyXView & lyx_view)
191 : WorkArea(id, lyx_view)
193 cursor_ = new frontend::CursorWidget(this);
196 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
197 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
198 setAcceptDrops(true);
199 setMinimumSize(100, 70);
201 //viewport()->setAutoFillBackground(false);
202 //viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
203 setFocusPolicy(Qt::WheelFocus);
205 viewport()->setCursor(Qt::IBeamCursor);
209 synthetic_mouse_event_.timeout.timeout.connect(
210 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
213 // Initialize the vertical Scroll Bar
214 QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
215 this, SLOT(adjustViewWithScrollBar(int)));
217 // PageStep only depends on the viewport height.
218 verticalScrollBar()->setPageStep(viewport()->height());
220 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
221 << "\n Area width\t" << width()
222 << "\n Area height\t" << height()
223 << "\n viewport width\t" << viewport()->width()
224 << "\n viewport height\t" << viewport()->height()
227 if (USE_EVENT_PRUNING) {
228 // This is the keyboard buffering stuff...
229 // I don't see any need for this under windows. The keyboard is reactive
232 if ( !QObject::connect(&step_timer_, SIGNAL(timeout()),
233 this, SLOT(keyeventTimeout())) )
234 lyxerr[Debug::GUI] << "ERROR: keyeventTimeout cannot connect!" << endl;
236 // Start the timer, one-shot.
237 step_timer_.setSingleShot(true);
238 step_timer_.start(50);
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 verticalScrollBar()->setTracking(false);
251 // do what cursor movement does (some grey)
253 int scroll_max_ = std::max(0, h - height());
255 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
256 verticalScrollBar()->setRange(0, scroll_max_);
257 verticalScrollBar()->setSliderPosition(scroll_pos);
258 verticalScrollBar()->setSingleStep(scroll_line_step);
259 verticalScrollBar()->setValue(scroll_pos);
261 verticalScrollBar()->setTracking(true);
265 void GuiWorkArea::adjustViewWithScrollBar(int)
267 scrollBufferView(verticalScrollBar()->sliderPosition());
271 void GuiWorkArea::dragEnterEvent(QDragEnterEvent * event)
273 if (event->mimeData()->hasUrls())
275 /// \todo Ask lyx-devel is this is enough:
276 /// if (event->mimeData()->hasFormat("text/plain"))
277 /// event->acceptProposedAction();
281 void GuiWorkArea::dropEvent(QDropEvent* event)
283 QList<QUrl> files = event->mimeData()->urls();
287 lyxerr[Debug::GUI] << "GuiWorkArea::dropEvent: got URIs!" << endl;
288 for (int i = 0; i!=files.size(); ++i) {
289 string const file = os::internal_path(fromqstr(files.at(i).toLocalFile()));
291 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
296 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
298 // FIXME: it would be better to send a signal "newBuffer()"
299 // in BufferList that could be connected to the different tabbar.
300 lyx_view_.updateTab();
301 startBlinkingCursor();
303 //FIXME: Use case: Two windows share the same buffer.
304 // The first window is resize. This modify the inner Buffer
305 // structure because Paragraph has a notion of line break and
306 // thus line width (this is very bad!).
307 // When switching to the other window which does not have the
308 // same size, LyX crashes because the line break is not adapted
309 // the this BufferView width.
310 // The following line fix the crash by resizing the BufferView
311 // on a focusInEvent(). That is not a good fix but it is a fix
312 // nevertheless. The bad side effect is that when the two
313 // BufferViews show the same portion of the Buffer, the second
314 // BufferView will show the same line breaks as the first one;
315 // even though those line breaks are not adapted to the second
316 // BufferView width... such is life!
321 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
323 stopBlinkingCursor();
327 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
329 if (dc_event_.active && dc_event_ == *e) {
330 dc_event_.active = false;
331 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
332 dc_event_.x, dc_event_.y,
333 q_button_state(dc_event_.state));
338 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
339 q_button_state(e->button()));
344 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
346 if (synthetic_mouse_event_.timeout.running())
347 synthetic_mouse_event_.timeout.stop();
349 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
350 q_button_state(e->button()));
355 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
357 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
358 q_motion_state(e->buttons()));
360 // If we're above or below the work area...
361 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
362 // Make sure only a synthetic event can cause a page scroll,
363 // so they come at a steady rate:
365 // _Force_ a scroll up:
368 cmd.y = viewport()->height();
369 // Store the event, to be handled when the timeout expires.
370 synthetic_mouse_event_.cmd = cmd;
372 if (synthetic_mouse_event_.timeout.running())
373 // Discard the event. Note that it _may_ be handled
374 // when the timeout expires if
375 // synthetic_mouse_event_.cmd has not been overwritten.
376 // Ie, when the timeout expires, we handle the
377 // most recent event but discard all others that
378 // occurred after the one used to start the timeout
379 // in the first place.
382 synthetic_mouse_event_.restart_timeout = true;
383 synthetic_mouse_event_.timeout.start();
384 // Fall through to handle this event...
387 } else if (synthetic_mouse_event_.timeout.running()) {
388 // Store the event, to be possibly handled when the timeout
390 // Once the timeout has expired, normal control is returned
391 // to mouseMoveEvent (restart_timeout = false).
392 // This results in a much smoother 'feel' when moving the
393 // mouse back into the work area.
394 synthetic_mouse_event_.cmd = cmd;
395 synthetic_mouse_event_.restart_timeout = false;
399 // Has anything changed on-screen since the last QMouseEvent
401 double const scrollbar_value = verticalScrollBar()->value();
402 if (e->x() != synthetic_mouse_event_.x_old ||
403 e->y() != synthetic_mouse_event_.y_old ||
404 scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
405 // Yes it has. Store the params used to check this.
406 synthetic_mouse_event_.x_old = e->x();
407 synthetic_mouse_event_.y_old = e->y();
408 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
410 // ... and dispatch the event to the LyX core.
416 void GuiWorkArea::wheelEvent(QWheelEvent * e)
418 // Wheel rotation by one notch results in a delta() of 120 (see
419 // documentation of QWheelEvent)
420 int const lines = qApp->wheelScrollLines() * e->delta() / 120;
421 verticalScrollBar()->setValue(verticalScrollBar()->value() -
422 lines * verticalScrollBar()->singleStep());
423 adjustViewWithScrollBar();
427 void GuiWorkArea::generateSyntheticMouseEvent()
429 // Set things off to generate the _next_ 'pseudo' event.
430 if (synthetic_mouse_event_.restart_timeout)
431 synthetic_mouse_event_.timeout.start();
433 // Has anything changed on-screen since the last timeout signal
435 double const scrollbar_value = verticalScrollBar()->value();
436 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
437 // Yes it has. Store the params used to check this.
438 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
440 // ... and dispatch the event to the LyX core.
441 dispatch(synthetic_mouse_event_.cmd);
446 void GuiWorkArea::keyPressEvent(QKeyEvent * e)
448 lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
449 << " count=" << e->count()
450 << " text=" << fromqstr(e->text())
451 << " isAutoRepeat=" << e->isAutoRepeat()
452 << " key=" << e->key()
455 if (USE_EVENT_PRUNING) {
456 keyeventQueue_.push(boost::shared_ptr<QKeyEvent>(new QKeyEvent(*e)));
459 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
461 processKeySym(sym, q_key_state(e->modifiers()));
466 // This is used only if USE_EVENT_PRUNING is defined...
467 void GuiWorkArea::keyeventTimeout()
469 bool handle_autos = true;
471 while (!keyeventQueue_.empty()) {
472 boost::shared_ptr<QKeyEvent> ev = keyeventQueue_.front();
474 // We never handle more than one auto repeated
475 // char in a list of queued up events.
476 if (!handle_autos && ev->isAutoRepeat()) {
477 keyeventQueue_.pop();
481 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
484 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
485 << " count=" << ev->count()
486 << " text=" << fromqstr(ev->text())
487 << " isAutoRepeat=" << ev->isAutoRepeat()
488 << " key=" << ev->key()
491 processKeySym(sym, q_key_state(ev->modifiers()));
492 keyeventQueue_.pop();
494 handle_autos = false;
497 // Restart the timer.
498 step_timer_.setSingleShot(true);
499 step_timer_.start(25);
503 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
505 dc_event_ = double_click(e);
507 if (!dc_event_.active)
510 dc_event_.active = false;
512 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
513 dc_event_.x, dc_event_.y,
514 q_button_state(dc_event_.state));
519 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
522 screen_ = QPixmap(ev->size().width(), ev->size().height());
523 verticalScrollBar()->setPageStep(viewport()->height());
524 QAbstractScrollArea::resizeEvent(ev);
529 void GuiWorkArea::update(int x, int y, int w, int h)
531 viewport()->update(x, y, w, h);
535 void GuiWorkArea::doGreyOut(QLPainter & pain)
538 pain.fillRectangle(0, 0, width(), height(),
541 //if (!lyxrc.show_banner)
543 lyxerr << "show banner: " << lyxrc.show_banner << endl;
544 /// The text to be written on top of the pixmap
545 string const text = lyx_version ? lyx_version : "unknown";
546 string const file = support::libFileSearch("images", "banner", "ppm");
550 QPixmap pm(toqstr(file));
552 lyxerr << "could not load splash screen: '" << file << "'" << endl;
557 // The font used to display the version info
558 font.setStyleHint(QFont::SansSerif);
559 font.setWeight(QFont::Bold);
560 font.setPointSize(LyXFont::SIZE_NORMAL);
562 int const w = pm.width();
563 int const h = pm.height();
565 int x = (width() - w) / 2;
566 int y = (height() - h) / 2;
568 pain.drawPixmap(x, y, pm);
573 pain.setPen(QColor(255, 255, 0));
575 pain.drawText(x, y, toqstr(text));
579 void GuiWorkArea::paintEvent(QPaintEvent * ev)
581 QRect const rc = ev->rect();
582 lyxerr[Debug::PAINTING] << "paintEvent begin: x: " << rc.x()
584 << " w: " << rc.width()
585 << " h: " << rc.height() << endl;
587 QPainter pain(viewport());
588 pain.drawPixmap(rc, screen_, rc);
593 void GuiWorkArea::expose(int x, int y, int w, int h)
595 QLPainter pain(&screen_);
597 if (w == 3) { // FIXME HACK
598 // Assume splash screen drawing is requested when
600 lyxerr << "splash screen requested" << endl;
603 else if (!buffer_view_->buffer()) {
604 lyxerr << "no buffer: " << endl;
609 paintText(*buffer_view_, pain);
616 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
618 cursor_->setGeometry(x, y, CursorWidth, h);
619 cursor_->shape_ = shape;
624 void GuiWorkArea::removeCursor()
626 if (!qApp->focusWidget())
632 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
634 QString const & text = e->commitString();
635 if (!text.isEmpty()) {
637 lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
638 << " preeditString =" << fromqstr(e->preeditString())
639 << " commitString =" << fromqstr(e->commitString())
643 // needed to make math superscript work on some systems
644 // ideally, such special coding should not be necessary
646 key = Qt::Key_AsciiCircum;
647 // FIXME: Needs for investigation, this key is not really used,
648 // the ctor below just check if key is different from 0.
649 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, text);
655 } // namespace frontend
658 #include "GuiWorkArea_moc.cpp"