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"
24 #include "funcrequest.h"
26 #include "support/os.h"
28 #include <QApplication>
31 #include <QMainWindow>
33 #include <QDragEnterEvent>
38 #include <boost/bind.hpp>
40 ///////////////////////////////////////////////////////////////
47 #include <Carbon/Carbon.h>
48 #include <support/lstrings.h>
49 using lyx::support::subst;
52 // You can find other qt-immodule, X11 and MACX specific stuff
53 // at the end of this file...
54 ///////////////////////////////////////////////////////////////
59 namespace os = lyx::support::os;
63 QWorkArea const * wa_ptr = 0;
65 /// return the LyX key state from Qt's
66 key_modifier::state q_key_state(Qt::ButtonState state)
68 key_modifier::state k = key_modifier::none;
69 if (state & Qt::ControlModifier)
70 k |= key_modifier::ctrl;
71 if (state & Qt::ShiftModifier)
72 k |= key_modifier::shift;
73 if (state & Qt::AltModifier)
74 k |= key_modifier::alt;
79 /// return the LyX mouse button state from Qt's
80 mouse_button::state q_button_state(Qt::ButtonState button)
82 mouse_button::state b = mouse_button::none;
85 b = mouse_button::button1;
88 b = mouse_button::button2;
91 b = mouse_button::button3;
100 /// return the LyX mouse button state from Qt's
101 mouse_button::state q_motion_state(Qt::ButtonState state)
103 mouse_button::state b = mouse_button::none;
104 if (state & Qt::LeftButton)
105 b |= mouse_button::button1;
106 if (state & Qt::MidButton)
107 b |= mouse_button::button2;
108 if (state & Qt::RightButton)
109 b |= mouse_button::button3;
115 // This is a 'heartbeat' generating synthetic mouse move events when the
116 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
117 SyntheticMouseEvent::SyntheticMouseEvent()
118 : timeout(200), restart_timeout(true),
119 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
123 QWorkArea::QWorkArea(LyXView &, int w, int h)
124 : QAbstractScrollArea(qApp->mainWidget()), WorkArea(), painter_(this)
126 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
127 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
129 (static_cast<QMainWindow*>(qApp->mainWidget()))->setCentralWidget(this);
131 setAcceptDrops(true);
133 setMinimumSize(100, 70);
135 viewport()->setAutoFillBackground(false);
136 viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
138 viewport()->setFocusPolicy(Qt::WheelFocus);
139 viewport()->setFocus();
140 setFocusPolicy(Qt::WheelFocus);
142 viewport()->setCursor(Qt::IBeamCursor);
149 synthetic_mouse_event_.timeout.timeout.connect(
150 boost::bind(&QWorkArea::generateSyntheticMouseEvent,
153 // Initialize the vertical Scroll Bar
154 QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
155 this, SLOT(adjustViewWithScrollBar(int)));
157 // PageStep only depends on the viewport height.
158 verticalScrollBar()->setPageStep(workHeight_);
160 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
161 << "\n Area width\t" << width()
162 << "\n Area height\t" << height()
163 << "\n viewport width\t" << viewport()->width()
164 << "\n viewport height\t" << viewport()->height()
168 // This is the keyboard buffering stuff...
169 // I don't see any need for this under windows. The keyboard is reactive
172 if ( !QObject::connect(&step_timer_, SIGNAL(timeout()),
173 this, SLOT(keyeventTimeout())) )
174 lyxerr[Debug::GUI] << "ERROR: keyeventTimeout cannot connect!" << endl;
176 // Start the timer, one-shot.
177 step_timer_.start(50, true);
180 ///////////////////////////////////////////////////////////////////////
181 // Specific stuff goes here...
183 #if USE_INPUT_METHODS
184 // to make qt-immodule work
185 setInputMethodEnabled(true);
189 // doubleClickInterval() is 400 ms on X11 witch is just too long.
190 // On Windows and Mac OS X, the operating system's value is used.
191 // On Microsoft Windows, calling this function sets the double
192 // click interval for all applications. So we don't!
193 QApplication::setDoubleClickInterval(300);
201 QWorkArea::~QWorkArea()
205 void QWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
207 // do what cursor movement does (some grey)
209 int scroll_max_ = std::max(0, h - height());
211 verticalScrollBar()->setRange(0, scroll_max_);
212 verticalScrollBar()->setSliderPosition(scroll_pos);
213 verticalScrollBar()->setLineStep(scroll_line_step);
216 void QWorkArea::adjustViewWithScrollBar(int action)
218 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
219 << " verticalScrollBar val=" << verticalScrollBar()->value()
220 << " verticalScrollBar pos=" << verticalScrollBar()->sliderPosition()
221 << " min=" << verticalScrollBar()->minimum()
222 << " max=" << verticalScrollBar()->maximum()
223 << " pagestep=" << verticalScrollBar()->pageStep()
224 << " linestep=" << verticalScrollBar()->lineStep()
227 this->scrollDocView(verticalScrollBar()->sliderPosition());
231 void QWorkArea::haveSelection(bool own) const
235 if (!QApplication::clipboard()->supportsSelection())
239 QApplication::clipboard()->setText(QString(), QClipboard::Selection);
241 // We don't need to do anything if own = false, as this case is
246 string const QWorkArea::getClipboard() const
248 QString str = QApplication::clipboard()->text(QClipboard::Selection);
249 lyxerr[Debug::ACTION] << "getClipboard: " << (const char*) str << endl;
253 // The MAC clipboard uses \r for lineendings, and we use \n
254 return subst(fromqstr(str), '\r', '\n');
256 return fromqstr(str);
261 void QWorkArea::putClipboard(string const & str) const
264 // The MAC clipboard uses \r for lineendings, and we use \n
265 QApplication::clipboard()->setText(toqstr(subst(str, '\n', '\r')),
266 QClipboard::Selection);
268 QApplication::clipboard()->setText(toqstr(str), QClipboard::Selection);
270 lyxerr[Debug::ACTION] << "putClipboard: " << str << endl;
274 void QWorkArea::dragEnterEvent(QDragEnterEvent * event)
276 event->accept(Q3UriDrag::canDecode(event));
278 /// \todo Ask lyx-devel is this is enough:
279 /// if (event->mimeData()->hasFormat("text/plain"))
280 /// event->acceptProposedAction();
285 void QWorkArea::dropEvent(QDropEvent* event)
289 if (Q3UriDrag::decodeLocalFiles(event, files)) {
290 lyxerr[Debug::GUI] << "QWorkArea::dropEvent: got URIs!"
292 for (QStringList::Iterator i = files.begin();
293 i!=files.end(); ++i) {
294 string const file = os::internal_path(fromqstr(*i));
295 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
301 void QWorkArea::mousePressEvent(QMouseEvent * e)
303 if (dc_event_.active && dc_event_ == *e) {
304 dc_event_.active = false;
305 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
306 dc_event_.x, dc_event_.y,
307 q_button_state(dc_event_.state));
312 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
313 q_button_state(e->button()));
318 void QWorkArea::mouseReleaseEvent(QMouseEvent * e)
320 if (synthetic_mouse_event_.timeout.running())
321 synthetic_mouse_event_.timeout.stop();
323 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
324 q_button_state(e->button()));
329 void QWorkArea::mouseMoveEvent(QMouseEvent * e)
331 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
332 q_motion_state(e->state()));
334 // If we're above or below the work area...
335 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
336 // Make sure only a synthetic event can cause a page scroll,
337 // so they come at a steady rate:
339 // _Force_ a scroll up:
342 cmd.y = viewport()->height();
343 // Store the event, to be handled when the timeout expires.
344 synthetic_mouse_event_.cmd = cmd;
346 if (synthetic_mouse_event_.timeout.running())
347 // Discard the event. Note that it _may_ be handled
348 // when the timeout expires if
349 // synthetic_mouse_event_.cmd has not been overwritten.
350 // Ie, when the timeout expires, we handle the
351 // most recent event but discard all others that
352 // occurred after the one used to start the timeout
353 // in the first place.
356 synthetic_mouse_event_.restart_timeout = true;
357 synthetic_mouse_event_.timeout.start();
358 // Fall through to handle this event...
361 } else if (synthetic_mouse_event_.timeout.running()) {
362 // Store the event, to be possibly handled when the timeout
364 // Once the timeout has expired, normal control is returned
365 // to mouseMoveEvent (restart_timeout = false).
366 // This results in a much smoother 'feel' when moving the
367 // mouse back into the work area.
368 synthetic_mouse_event_.cmd = cmd;
369 synthetic_mouse_event_.restart_timeout = false;
373 // Has anything changed on-screen since the last QMouseEvent
375 double const scrollbar_value = verticalScrollBar()->value();
376 if (e->x() != synthetic_mouse_event_.x_old ||
377 e->y() != synthetic_mouse_event_.y_old ||
378 scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
379 // Yes it has. Store the params used to check this.
380 synthetic_mouse_event_.x_old = e->x();
381 synthetic_mouse_event_.y_old = e->y();
382 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
384 // ... and dispatch the event to the LyX core.
390 void QWorkArea::wheelEvent(QWheelEvent * e)
392 // Wheel rotation by one notch results in a delta() of 120 (see
393 // documentation of QWheelEvent)
394 int const lines = QApplication::wheelScrollLines() * e->delta() / 120;
395 verticalScrollBar()->setValue(verticalScrollBar()->value() -
396 lines * verticalScrollBar()->lineStep());
397 adjustViewWithScrollBar();
401 void QWorkArea::generateSyntheticMouseEvent()
403 // Set things off to generate the _next_ 'pseudo' event.
404 if (synthetic_mouse_event_.restart_timeout)
405 synthetic_mouse_event_.timeout.start();
407 // Has anything changed on-screen since the last timeout signal
409 double const scrollbar_value = verticalScrollBar()->value();
410 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
411 // Yes it has. Store the params used to check this.
412 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
414 // ... and dispatch the event to the LyX core.
415 this->dispatch(synthetic_mouse_event_.cmd);
419 void QWorkArea::keyPressEvent(QKeyEvent * e)
421 lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
422 << " count=" << e->count()
423 << " text=" << (const char *) e->text()
424 << " isAutoRepeat=" << e->isAutoRepeat()
425 << " key=" << e->key()
428 // keyeventQueue_.push(boost::shared_ptr<QKeyEvent>(new QKeyEvent(*e)));
430 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
432 this->workAreaKeyPress(sym, q_key_state(e->state()));
436 // This is not used for now...
437 void QWorkArea::keyeventTimeout()
439 bool handle_autos = true;
441 while (!keyeventQueue_.empty()) {
442 boost::shared_ptr<QKeyEvent> ev = keyeventQueue_.front();
444 // We never handle more than one auto repeated
445 // char in a list of queued up events.
446 if (!handle_autos && ev->isAutoRepeat()) {
447 keyeventQueue_.pop();
451 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
454 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
455 << " count=" << ev->count()
456 << " text=" << (const char *) ev->text()
457 << " isAutoRepeat=" << ev->isAutoRepeat()
458 << " key=" << ev->key()
461 this->workAreaKeyPress(sym, q_key_state(ev->state()));
462 keyeventQueue_.pop();
464 handle_autos = false;
467 // Restart the timer.
468 step_timer_.start(25, true);
472 void QWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
474 dc_event_ = double_click(e);
476 if (!dc_event_.active)
479 dc_event_.active = false;
481 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
482 dc_event_.x, dc_event_.y,
483 q_button_state(dc_event_.state));
488 void QWorkArea::resizeEvent(QResizeEvent * resizeEvent)
490 workWidth_ = viewport()->width();
491 workHeight_ = viewport()->height();
493 verticalScrollBar()->setPageStep(viewport()->height());
495 screen_device_ = QPixmap(viewport()->width(), viewport()->height());
496 paint_device_ = QImage(viewport()->width(), viewport()->height(), QImage::Format_RGB32);
498 this->workAreaResize();
501 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
502 << "\n QWidget width\t" << this->QWidget::width()
503 << "\n QWidget height\t" << this->QWidget::height()
504 << "\n viewport width\t" << viewport()->width()
505 << "\n viewport height\t" << viewport()->height()
506 << "\n QResizeEvent rect left\t" << rect().left()
507 << "\n QResizeEvent rect right\t" << rect().right()
512 void QWorkArea::update(int x, int y, int w, int h)
514 //screen_device_.fromImage(paint_device_);
515 QPainter q(&screen_device_);
516 q.drawImage(x, y, paint_device_.copy(x, y, w, h));
518 viewport()->update(x, y, w, h);
521 void QWorkArea::paintEvent(QPaintEvent * e)
524 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
525 << "\n QWidget width\t" << this->width()
526 << "\n QWidget height\t" << this->height()
527 << "\n viewport width\t" << viewport()->width()
528 << "\n viewport height\t" << viewport()->height()
529 << "\n pixmap width\t" << pixmap_->width()
530 << "\n pixmap height\t" << pixmap_->height()
531 << "\n QPaintEvent x\t" << e->rect().x()
532 << "\n QPaintEvent y\t" << e->rect().y()
533 << "\n QPaintEvent w\t" << e->rect().width()
534 << "\n QPaintEvent h\t" << e->rect().height()
537 QPainter q(viewport());
538 q.drawPixmap(e->rect(), screen_device_, e->rect());
541 QPixmap QWorkArea::copyScreen(int x, int y, int w, int h) const
543 return screen_device_.copy(x, y, w, h);
546 void QWorkArea::drawScreen(int x, int y, QPixmap pixmap)
548 QPainter q(&screen_device_);
549 q.drawPixmap(x, y, pixmap);
550 viewport()->update(x, y, pixmap.width(), pixmap.height());
554 ///////////////////////////////////////////////////////////////
555 ///////////////////////////////////////////////////////////////
558 ////////////////////////////////////////////////////////////////////////
559 // qt-immodule specific stuff goes here...
561 #if USE_INPUT_METHODS
562 // to make qt-immodule work
564 void QWorkArea::inputMethodEvent(QInputMethodEvent * e)
566 QString const text = e->text();
567 if (!text.isEmpty()) {
569 // needed to make math superscript work on some systems
570 // ideally, such special coding should not be necessary
572 key = Qt::Key_AsciiCircum;
573 QKeyEvent ev(QEvent::KeyPress, key, *text.ascii(), 0, text);
581 ////////////////////////////////////////////////////////////////////////
582 // X11 specific stuff goes here...
585 bool lyxX11EventFilter(XEvent * xev)
588 case SelectionRequest:
589 lyxerr[Debug::GUI] << "X requested selection." << endl;
591 wa_ptr->selectionRequested();
594 lyxerr[Debug::GUI] << "Lost selection." << endl;
596 wa_ptr->selectionLost();
604 ////////////////////////////////////////////////////////////////////////
605 // Mac OSX specific stuff goes here...
609 OSErr checkAppleEventForMissingParams(const AppleEvent& theAppleEvent)
611 DescType returnedType;
613 OSErr err = AEGetAttributePtr(&theAppleEvent, keyMissedKeywordAttr,
614 typeWildCard, &returnedType, nil, 0,
617 case errAEDescNotFound:
620 return errAEEventNotHandled;
627 pascal OSErr handleOpenDocuments(const AppleEvent* inEvent,
628 AppleEvent* /*reply*/, long /*refCon*/)
631 AEDescList documentList;
632 OSErr err = AEGetParamDesc(inEvent, keyDirectObject, typeAEList,
637 err = checkAppleEventForMissingParams(*inEvent);
640 err = AECountItems(&documentList, &documentCount);
641 for (long documentIndex = 1;
642 err == noErr && documentIndex <= documentCount;
644 DescType returnedType;
649 err = AESizeOfNthItem(&documentList, documentIndex,
650 &returnedType, &actualSize);
652 err = AEGetNthPtr(&documentList, documentIndex,
654 &returnedType, (Ptr)&ref,
655 sizeof(FSRef), &actualSize);
657 FSRefMakePath(&ref, (UInt8*)qstr_buf,
659 s_arg=QString::fromUtf8(qstr_buf);
661 FuncRequest(LFUN_FILE_OPEN,
668 AEDisposeDesc(&documentList);