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 <boost/current_function.hpp>
16 #include "QWorkArea.h"
17 #include "QLPainter.h"
18 #include "QLyXKeySym.h"
20 #include "lcolorcache.h"
21 #include "qt_helpers.h"
22 #include "BufferView.h"
24 #include "funcrequest.h"
26 #include "support/os.h"
28 #include <QApplication>
31 #include <QMainWindow>
34 #include <QDragEnterEvent>
39 #include <boost/bind.hpp>
41 ///////////////////////////////////////////////////////////////
48 #include <Carbon/Carbon.h>
49 #include <support/lstrings.h>
50 using lyx::support::subst;
53 // You can find other qt-immodule, X11 and MACX specific stuff
54 // at the end of this file...
55 ///////////////////////////////////////////////////////////////
60 namespace os = lyx::support::os;
64 QWorkArea * wa_ptr = 0;
66 /// return the LyX key state from Qt's
67 key_modifier::state q_key_state(Qt::ButtonState state)
69 key_modifier::state k = key_modifier::none;
70 if (state & Qt::ControlModifier)
71 k |= key_modifier::ctrl;
72 if (state & Qt::ShiftModifier)
73 k |= key_modifier::shift;
74 if (state & Qt::AltModifier)
75 k |= key_modifier::alt;
80 /// return the LyX mouse button state from Qt's
81 mouse_button::state q_button_state(Qt::ButtonState button)
83 mouse_button::state b = mouse_button::none;
86 b = mouse_button::button1;
89 b = mouse_button::button2;
92 b = mouse_button::button3;
101 /// return the LyX mouse button state from Qt's
102 mouse_button::state q_motion_state(Qt::ButtonState state)
104 mouse_button::state b = mouse_button::none;
105 if (state & Qt::LeftButton)
106 b |= mouse_button::button1;
107 if (state & Qt::MidButton)
108 b |= mouse_button::button2;
109 if (state & Qt::RightButton)
110 b |= mouse_button::button3;
116 // This is a 'heartbeat' generating synthetic mouse move events when the
117 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
118 SyntheticMouseEvent::SyntheticMouseEvent()
119 : timeout(200), restart_timeout(true),
120 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
124 QWorkArea::QWorkArea(LyXView & owner, int w, int h)
125 : QAbstractScrollArea(qApp->mainWidget()), WorkArea(), view_(owner), painter_(this)
127 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
128 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
130 (static_cast<QMainWindow*>(qApp->mainWidget()))->setCentralWidget(this);
132 setAcceptDrops(true);
134 setMinimumSize(100, 70);
136 viewport()->setAutoFillBackground(false);
137 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
139 viewport()->setFocusPolicy(Qt::WheelFocus);
140 viewport()->setFocus();
141 setFocusPolicy(Qt::WheelFocus);
143 viewport()->setCursor(Qt::IBeamCursor);
150 synthetic_mouse_event_.timeout.timeout.connect(
151 boost::bind(&QWorkArea::generateSyntheticMouseEvent,
154 // Initialize the vertical Scroll Bar
155 QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
156 this, SLOT(adjustViewWithScrollBar(int)));
158 // PageStep only depends on the viewport height.
159 verticalScrollBar()->setPageStep(workHeight_);
161 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
162 << "\n Area width\t" << width()
163 << "\n Area height\t" << height()
164 << "\n viewport width\t" << viewport()->width()
165 << "\n viewport height\t" << viewport()->height()
169 // This is the keyboard buffering stuff...
170 // I don't see any need for this under windows. The keyboard is reactive
173 if ( !QObject::connect(&step_timer_, SIGNAL(timeout()),
174 this, SLOT(keyeventTimeout())) )
175 lyxerr[Debug::GUI] << "ERROR: keyeventTimeout cannot connect!" << endl;
177 // Start the timer, one-shot.
178 step_timer_.start(50, true);
181 ///////////////////////////////////////////////////////////////////////
182 // Specific stuff goes here...
184 #if USE_INPUT_METHODS
185 // to make qt-immodule work
186 setInputMethodEnabled(true);
190 // doubleClickInterval() is 400 ms on X11 witch is just too long.
191 // On Windows and Mac OS X, the operating system's value is used.
192 // On Microsoft Windows, calling this function sets the double
193 // click interval for all applications. So we don't!
194 QApplication::setDoubleClickInterval(300);
202 QWorkArea::~QWorkArea()
206 void QWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
208 // do what cursor movement does (some grey)
210 int scroll_max_ = std::max(0, h - height());
212 verticalScrollBar()->setRange(0, scroll_max_);
213 verticalScrollBar()->setSliderPosition(scroll_pos);
214 verticalScrollBar()->setLineStep(scroll_line_step);
217 void QWorkArea::adjustViewWithScrollBar(int action)
219 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
220 << " verticalScrollBar val=" << verticalScrollBar()->value()
221 << " verticalScrollBar pos=" << verticalScrollBar()->sliderPosition()
222 << " min=" << verticalScrollBar()->minimum()
223 << " max=" << verticalScrollBar()->maximum()
224 << " pagestep=" << verticalScrollBar()->pageStep()
225 << " linestep=" << verticalScrollBar()->lineStep()
228 view_.view()->scrollDocView(verticalScrollBar()->sliderPosition());
232 void QWorkArea::haveSelection(bool own) const
234 /// \todo ask X11 and MAC devels why this wa_ptr is useful.
235 wa_ptr = const_cast<QWorkArea*>(this);
237 if (!QApplication::clipboard()->supportsSelection())
241 QApplication::clipboard()->setText(QString(), QClipboard::Selection);
243 // We don't need to do anything if own = false, as this case is
248 string const QWorkArea::getClipboard() const
250 QString str = QApplication::clipboard()->text(QClipboard::Selection);
251 lyxerr[Debug::ACTION] << "getClipboard: " << (const char*) str << endl;
255 // The MAC clipboard uses \r for lineendings, and we use \n
256 return subst(fromqstr(str), '\r', '\n');
258 return fromqstr(str);
263 void QWorkArea::putClipboard(string const & str) const
266 // The MAC clipboard uses \r for lineendings, and we use \n
267 QApplication::clipboard()->setText(toqstr(subst(str, '\n', '\r')),
268 QClipboard::Selection);
270 QApplication::clipboard()->setText(toqstr(str), QClipboard::Selection);
272 lyxerr[Debug::ACTION] << "putClipboard: " << str << endl;
276 void QWorkArea::dragEnterEvent(QDragEnterEvent * event)
278 if (event->mimeData()->hasUrls())
280 /// \todo Ask lyx-devel is this is enough:
281 /// if (event->mimeData()->hasFormat("text/plain"))
282 /// event->acceptProposedAction();
287 void QWorkArea::dropEvent(QDropEvent* event)
289 QList<QUrl> files = event->mimeData()->urls();
293 lyxerr[Debug::GUI] << "QWorkArea::dropEvent: got URIs!" << endl;
294 for (int i = 0; i!=files.size(); ++i) {
295 string const file = os::internal_path(fromqstr(files.at(i).toString()));
297 view_.view()->workAreaDispatch(FuncRequest(LFUN_FILE_OPEN, file));
302 void QWorkArea::mousePressEvent(QMouseEvent * e)
304 if (dc_event_.active && dc_event_ == *e) {
305 dc_event_.active = false;
306 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
307 dc_event_.x, dc_event_.y,
308 q_button_state(dc_event_.state));
309 view_.view()->workAreaDispatch(cmd);
313 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
314 q_button_state(e->button()));
315 view_.view()->workAreaDispatch(cmd);
319 void QWorkArea::mouseReleaseEvent(QMouseEvent * e)
321 if (synthetic_mouse_event_.timeout.running())
322 synthetic_mouse_event_.timeout.stop();
324 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
325 q_button_state(e->button()));
326 view_.view()->workAreaDispatch(cmd);
330 void QWorkArea::mouseMoveEvent(QMouseEvent * e)
332 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
333 q_motion_state(e->state()));
335 // If we're above or below the work area...
336 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
337 // Make sure only a synthetic event can cause a page scroll,
338 // so they come at a steady rate:
340 // _Force_ a scroll up:
343 cmd.y = viewport()->height();
344 // Store the event, to be handled when the timeout expires.
345 synthetic_mouse_event_.cmd = cmd;
347 if (synthetic_mouse_event_.timeout.running())
348 // Discard the event. Note that it _may_ be handled
349 // when the timeout expires if
350 // synthetic_mouse_event_.cmd has not been overwritten.
351 // Ie, when the timeout expires, we handle the
352 // most recent event but discard all others that
353 // occurred after the one used to start the timeout
354 // in the first place.
357 synthetic_mouse_event_.restart_timeout = true;
358 synthetic_mouse_event_.timeout.start();
359 // Fall through to handle this event...
362 } else if (synthetic_mouse_event_.timeout.running()) {
363 // Store the event, to be possibly handled when the timeout
365 // Once the timeout has expired, normal control is returned
366 // to mouseMoveEvent (restart_timeout = false).
367 // This results in a much smoother 'feel' when moving the
368 // mouse back into the work area.
369 synthetic_mouse_event_.cmd = cmd;
370 synthetic_mouse_event_.restart_timeout = false;
374 // Has anything changed on-screen since the last QMouseEvent
376 double const scrollbar_value = verticalScrollBar()->value();
377 if (e->x() != synthetic_mouse_event_.x_old ||
378 e->y() != synthetic_mouse_event_.y_old ||
379 scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
380 // Yes it has. Store the params used to check this.
381 synthetic_mouse_event_.x_old = e->x();
382 synthetic_mouse_event_.y_old = e->y();
383 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
385 // ... and dispatch the event to the LyX core.
386 view_.view()->workAreaDispatch(cmd);
391 void QWorkArea::wheelEvent(QWheelEvent * e)
393 // Wheel rotation by one notch results in a delta() of 120 (see
394 // documentation of QWheelEvent)
395 int const lines = QApplication::wheelScrollLines() * e->delta() / 120;
396 verticalScrollBar()->setValue(verticalScrollBar()->value() -
397 lines * verticalScrollBar()->lineStep());
398 adjustViewWithScrollBar();
402 void QWorkArea::generateSyntheticMouseEvent()
404 // Set things off to generate the _next_ 'pseudo' event.
405 if (synthetic_mouse_event_.restart_timeout)
406 synthetic_mouse_event_.timeout.start();
408 // Has anything changed on-screen since the last timeout signal
410 double const scrollbar_value = verticalScrollBar()->value();
411 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
412 // Yes it has. Store the params used to check this.
413 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
415 // ... and dispatch the event to the LyX core.
416 view_.view()->workAreaDispatch(synthetic_mouse_event_.cmd);
420 void QWorkArea::keyPressEvent(QKeyEvent * e)
422 lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
423 << " count=" << e->count()
424 << " text=" << (const char *) e->text()
425 << " isAutoRepeat=" << e->isAutoRepeat()
426 << " key=" << e->key()
429 // keyeventQueue_.push(boost::shared_ptr<QKeyEvent>(new QKeyEvent(*e)));
431 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
433 view_.view()->workAreaKeyPress(sym, q_key_state(e->state()));
437 // This is not used for now...
438 void QWorkArea::keyeventTimeout()
440 bool handle_autos = true;
442 while (!keyeventQueue_.empty()) {
443 boost::shared_ptr<QKeyEvent> ev = keyeventQueue_.front();
445 // We never handle more than one auto repeated
446 // char in a list of queued up events.
447 if (!handle_autos && ev->isAutoRepeat()) {
448 keyeventQueue_.pop();
452 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
455 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
456 << " count=" << ev->count()
457 << " text=" << (const char *) ev->text()
458 << " isAutoRepeat=" << ev->isAutoRepeat()
459 << " key=" << ev->key()
462 view_.view()->workAreaKeyPress(sym, q_key_state(ev->state()));
463 keyeventQueue_.pop();
465 handle_autos = false;
468 // Restart the timer.
469 step_timer_.start(25, true);
473 void QWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
475 dc_event_ = double_click(e);
477 if (!dc_event_.active)
480 dc_event_.active = false;
482 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
483 dc_event_.x, dc_event_.y,
484 q_button_state(dc_event_.state));
485 view_.view()->workAreaDispatch(cmd);
489 void QWorkArea::resizeEvent(QResizeEvent * resizeEvent)
491 workWidth_ = viewport()->width();
492 workHeight_ = viewport()->height();
494 verticalScrollBar()->setPageStep(viewport()->height());
496 // screen_device_ = QPixmap(viewport()->width(), viewport()->height());
497 // paint_device_ = QImage(viewport()->width(), viewport()->height(), QImage::Format_RGB32);
498 paint_device_ = QPixmap(viewport()->width(), viewport()->height());
500 view_.view()->workAreaResize();
503 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
504 << "\n QWidget width\t" << this->QWidget::width()
505 << "\n QWidget height\t" << this->QWidget::height()
506 << "\n viewport width\t" << viewport()->width()
507 << "\n viewport height\t" << viewport()->height()
508 << "\n QResizeEvent rect left\t" << rect().left()
509 << "\n QResizeEvent rect right\t" << rect().right()
514 void QWorkArea::update(int x, int y, int w, int h)
516 //screen_device_.fromImage(paint_device_);
517 //QPainter q(&screen_device_);
518 //q.drawImage(x, y, paint_device_.copy(x, y, w, h));
520 viewport()->update(x, y, w, h);
523 void QWorkArea::paintEvent(QPaintEvent * e)
526 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
527 << "\n QWidget width\t" << this->width()
528 << "\n QWidget height\t" << this->height()
529 << "\n viewport width\t" << viewport()->width()
530 << "\n viewport height\t" << viewport()->height()
531 << "\n pixmap width\t" << pixmap_->width()
532 << "\n pixmap height\t" << pixmap_->height()
533 << "\n QPaintEvent x\t" << e->rect().x()
534 << "\n QPaintEvent y\t" << e->rect().y()
535 << "\n QPaintEvent w\t" << e->rect().width()
536 << "\n QPaintEvent h\t" << e->rect().height()
539 QPainter q(viewport());
540 q.drawPixmap(e->rect(), paint_device_, e->rect());
544 QPixmap QWorkArea::copyScreen(int x, int y, int w, int h) const
546 return paint_device_.copy(x, y, w, h);
549 void QWorkArea::drawScreen(int x, int y, QPixmap pixmap)
551 QPainter q(&paint_device_);
552 q.drawPixmap(x, y, pixmap);
553 viewport()->update(x, y, pixmap.width(), pixmap.height());
557 ///////////////////////////////////////////////////////////////
558 ///////////////////////////////////////////////////////////////
561 ////////////////////////////////////////////////////////////////////////
562 // qt-immodule specific stuff goes here...
564 #if USE_INPUT_METHODS
565 // to make qt-immodule work
567 void QWorkArea::inputMethodEvent(QInputMethodEvent * e)
569 QString const text = e->text();
570 if (!text.isEmpty()) {
572 // needed to make math superscript work on some systems
573 // ideally, such special coding should not be necessary
575 key = Qt::Key_AsciiCircum;
576 QKeyEvent ev(QEvent::KeyPress, key, *text.ascii(), 0, text);
584 ////////////////////////////////////////////////////////////////////////
585 // X11 specific stuff goes here...
588 bool lyxX11EventFilter(XEvent * xev)
591 case SelectionRequest:
592 lyxerr[Debug::GUI] << "X requested selection." << endl;
594 wa_ptr->view().view()->selectionRequested();
597 lyxerr[Debug::GUI] << "Lost selection." << endl;
599 wa_ptr->view().view()->selectionLost();
607 ////////////////////////////////////////////////////////////////////////
608 // Mac OSX specific stuff goes here...
612 OSErr checkAppleEventForMissingParams(const AppleEvent& theAppleEvent)
614 DescType returnedType;
616 OSErr err = AEGetAttributePtr(&theAppleEvent, keyMissedKeywordAttr,
617 typeWildCard, &returnedType, nil, 0,
620 case errAEDescNotFound:
623 return errAEEventNotHandled;
630 pascal OSErr handleOpenDocuments(const AppleEvent* inEvent,
631 AppleEvent* /*reply*/, long /*refCon*/)
634 AEDescList documentList;
635 OSErr err = AEGetParamDesc(inEvent, keyDirectObject, typeAEList,
640 err = checkAppleEventForMissingParams(*inEvent);
643 err = AECountItems(&documentList, &documentCount);
644 for (long documentIndex = 1;
645 err == noErr && documentIndex <= documentCount;
647 DescType returnedType;
652 err = AESizeOfNthItem(&documentList, documentIndex,
653 &returnedType, &actualSize);
655 err = AEGetNthPtr(&documentList, documentIndex,
657 &returnedType, (Ptr)&ref,
658 sizeof(FSRef), &actualSize);
660 FSRefMakePath(&ref, (UInt8*)qstr_buf,
662 s_arg=QString::fromUtf8(qstr_buf);
663 wa_ptr->view().view()->workAreaDispatch(
664 FuncRequest(LFUN_FILE_OPEN,
671 AEDisposeDesc(&documentList);
676 #include "QWorkArea_moc.cpp"