]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/QWorkArea.C
QWorkArea.[Ch]: Wheel one-liner mouse fix
[lyx.git] / src / frontends / qt4 / QWorkArea.C
1 /**
2  * \file QWorkArea.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  * \author Abdelrazak Younes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include <boost/current_function.hpp>
15
16 #include "QWorkArea.h"
17 #include "QLPainter.h"
18 #include "QLyXKeySym.h"
19
20 #include "lcolorcache.h"
21 #include "qt_helpers.h"
22
23 #include "debug.h"
24 #include "funcrequest.h"
25 #include "LColor.h"
26 #include "support/os.h"
27
28 #include <QApplication>
29 #include <QClipboard>
30 #include <QLayout>
31 #include <QMainWindow>
32 #include <Q3UriDrag>
33 #include <QDragEnterEvent>
34 #include <QPixmap>
35 #include <QPainter>
36 #include <QScrollBar>
37
38 #include <boost/bind.hpp>
39
40 ///////////////////////////////////////////////////////////////
41 // Specific stuff
42 #ifdef Q_WS_X11
43 #include <X11/Xlib.h>
44 #endif
45
46 #ifdef Q_WS_MACX
47 #include <Carbon/Carbon.h>
48 #include <support/lstrings.h>
49 using lyx::support::subst;
50 #endif
51
52 // You can find other qt-immodule, X11 and MACX specific stuff 
53 // at the end of this file...
54 ///////////////////////////////////////////////////////////////
55
56 using std::endl;
57 using std::string;
58
59 namespace os = lyx::support::os;
60
61 namespace {
62
63 QWorkArea const * wa_ptr = 0;
64
65 /// return the LyX key state from Qt's
66 key_modifier::state q_key_state(Qt::ButtonState state)
67 {
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;
75         return k;
76 }
77
78
79 /// return the LyX mouse button state from Qt's
80 mouse_button::state q_button_state(Qt::ButtonState button)
81 {
82         mouse_button::state b = mouse_button::none;
83         switch (button) {
84                 case Qt::LeftButton:
85                         b = mouse_button::button1;
86                         break;
87                 case Qt::MidButton:
88                         b = mouse_button::button2;
89                         break;
90                 case Qt::RightButton:
91                         b = mouse_button::button3;
92                         break;
93                 default:
94                         break;
95         }
96         return b;
97 }
98
99
100 /// return the LyX mouse button state from Qt's
101 mouse_button::state q_motion_state(Qt::ButtonState state)
102 {
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;
110         return b;
111 }
112
113 } // namespace anon
114
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)
120 {}
121
122
123 QWorkArea::QWorkArea(LyXView &, int w, int h)
124         : QAbstractScrollArea(qApp->mainWidget()), WorkArea(), painter_(this)
125 {
126         setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
127         setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
128
129         (static_cast<QMainWindow*>(qApp->mainWidget()))->setCentralWidget(this);
130
131         setAcceptDrops(true);
132
133         setMinimumSize(100, 70);
134
135         viewport()->setAutoFillBackground(false);
136         viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
137
138         viewport()->setFocusPolicy(Qt::WheelFocus);
139         viewport()->setFocus();
140         setFocusPolicy(Qt::WheelFocus);
141
142         viewport()->setCursor(Qt::IBeamCursor);
143
144         resize(w, h);
145         show();
146         workWidth_ = w;
147         workHeight_ = h;
148
149         synthetic_mouse_event_.timeout.timeout.connect(
150                 boost::bind(&QWorkArea::generateSyntheticMouseEvent,
151                             this));
152         
153         // Initialize the vertical Scroll Bar
154         QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
155                 this, SLOT(adjustViewWithScrollBar(int)));
156
157         // PageStep only depends on the viewport height.
158         verticalScrollBar()->setPageStep(workHeight_);  
159
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()
165                 << endl;
166
167 /*
168         // This is the keyboard buffering stuff...
169         // I don't see any need for this under windows. The keyboard is reactive
170     // enough...
171
172         if ( !QObject::connect(&step_timer_, SIGNAL(timeout()),
173                 this, SLOT(keyeventTimeout())) )
174                         lyxerr[Debug::GUI] << "ERROR: keyeventTimeout cannot connect!" << endl;
175
176         // Start the timer, one-shot.
177         step_timer_.start(50, true);
178 */
179
180         ///////////////////////////////////////////////////////////////////////
181         // Specific stuff goes here...
182
183 #if USE_INPUT_METHODS
184         // to make qt-immodule work
185         setInputMethodEnabled(true);
186 #endif
187
188 #ifdef Q_WS_X11
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);
194 #endif
195
196 #ifdef Q_WS_MACX
197         wa_ptr = this;
198 #endif
199 }
200
201 QWorkArea::~QWorkArea()
202 {
203 }
204
205 void QWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
206 {
207         // do what cursor movement does (some grey)
208         h += height() / 4;
209         int scroll_max_ = std::max(0, h - height());
210
211         verticalScrollBar()->setRange(0, scroll_max_);
212         verticalScrollBar()->setSliderPosition(scroll_pos);
213         verticalScrollBar()->setLineStep(scroll_line_step);
214 }
215
216 void QWorkArea::adjustViewWithScrollBar(int action)
217 {
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()
225                 << endl;
226
227         this->scrollDocView(verticalScrollBar()->sliderPosition());
228 }
229
230
231 void QWorkArea::haveSelection(bool own) const
232 {
233         wa_ptr = this;
234
235         if (!QApplication::clipboard()->supportsSelection())
236                 return;
237
238         if (own) {
239                 QApplication::clipboard()->setText(QString(), QClipboard::Selection);
240         }
241         // We don't need to do anything if own = false, as this case is
242         // handled by QT.
243 }
244
245
246 string const QWorkArea::getClipboard() const
247 {
248         QString str = QApplication::clipboard()->text(QClipboard::Selection);
249         lyxerr[Debug::ACTION] << "getClipboard: " << (const char*) str << endl;
250         if (str.isNull())
251                 return string();
252 #ifdef Q_WS_MACX
253         // The MAC clipboard uses \r for lineendings, and we use \n
254         return subst(fromqstr(str), '\r', '\n');
255 #else
256         return fromqstr(str);
257 #endif
258 }
259
260
261 void QWorkArea::putClipboard(string const & str) const
262 {
263 #ifdef Q_WS_MACX
264         // The MAC clipboard uses \r for lineendings, and we use \n
265         QApplication::clipboard()->setText(toqstr(subst(str, '\n', '\r')),
266                                            QClipboard::Selection);
267 #else
268         QApplication::clipboard()->setText(toqstr(str), QClipboard::Selection);
269 #endif
270         lyxerr[Debug::ACTION] << "putClipboard: " << str << endl;
271 }
272
273
274 void QWorkArea::dragEnterEvent(QDragEnterEvent * event)
275 {
276         event->accept(Q3UriDrag::canDecode(event));
277
278         /// \todo Ask lyx-devel is this is enough:
279         /// if (event->mimeData()->hasFormat("text/plain"))
280         ///     event->acceptProposedAction();
281
282 }
283
284
285 void QWorkArea::dropEvent(QDropEvent* event)
286 {
287         QStringList files;
288
289         if (Q3UriDrag::decodeLocalFiles(event, files)) {
290                 lyxerr[Debug::GUI] << "QWorkArea::dropEvent: got URIs!"
291                                    << endl;
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));
296                 }
297         }
298 }
299
300
301 void QWorkArea::mousePressEvent(QMouseEvent * e)
302 {
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));
308                 this->dispatch(cmd);
309                 return;
310         }
311
312         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
313                               q_button_state(e->button()));
314         this->dispatch(cmd);
315 }
316
317
318 void QWorkArea::mouseReleaseEvent(QMouseEvent * e)
319 {
320         if (synthetic_mouse_event_.timeout.running())
321                 synthetic_mouse_event_.timeout.stop();
322
323         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
324                               q_button_state(e->button()));
325         this->dispatch(cmd);
326 }
327
328
329 void QWorkArea::mouseMoveEvent(QMouseEvent * e)
330 {
331         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
332                               q_motion_state(e->state()));
333
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:
338                 if (e->y() <= 20)
339                         // _Force_ a scroll up:
340                         cmd.y = -40;
341                 else
342                         cmd.y = viewport()->height();
343                 // Store the event, to be handled when the timeout expires.
344                 synthetic_mouse_event_.cmd = cmd;
345
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.
354                         return;
355                 else {
356                         synthetic_mouse_event_.restart_timeout = true;
357                         synthetic_mouse_event_.timeout.start();
358                         // Fall through to handle this event...
359                 }
360
361         } else if (synthetic_mouse_event_.timeout.running()) {
362                 // Store the event, to be possibly handled when the timeout
363                 // expires.
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;
370                 return;
371         }
372
373         // Has anything changed on-screen since the last QMouseEvent
374         // was received?
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;
383
384                 // ... and dispatch the event to the LyX core.
385                 this->dispatch(cmd);
386         }
387 }
388
389
390 void QWorkArea::wheelEvent(QWheelEvent * e)
391 {
392         verticalScrollBar()->setValue(verticalScrollBar()->value() - e->delta());
393         adjustViewWithScrollBar();\r
394 }
395
396 void QWorkArea::generateSyntheticMouseEvent()
397 {
398         // Set things off to generate the _next_ 'pseudo' event.
399         if (synthetic_mouse_event_.restart_timeout)
400                 synthetic_mouse_event_.timeout.start();
401
402         // Has anything changed on-screen since the last timeout signal
403         // was received?
404         double const scrollbar_value = verticalScrollBar()->value();
405         if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
406                 // Yes it has. Store the params used to check this.
407                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
408
409                 // ... and dispatch the event to the LyX core.
410                 this->dispatch(synthetic_mouse_event_.cmd);
411         }
412 }
413
414 void QWorkArea::keyPressEvent(QKeyEvent * e)
415 {
416         lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
417                 << " count=" << e->count()
418                 << " text=" << (const char *) e->text()
419                 << " isAutoRepeat=" << e->isAutoRepeat()
420                 << " key=" << e->key()
421                 << endl;
422
423 //      keyeventQueue_.push(boost::shared_ptr<QKeyEvent>(new QKeyEvent(*e)));
424
425     boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
426     sym->set(e);
427     this->workAreaKeyPress(sym, q_key_state(e->state()));        
428  
429 }
430
431 // This is not used for now...
432 void QWorkArea::keyeventTimeout()
433 {
434         bool handle_autos = true;
435
436         while (!keyeventQueue_.empty()) {
437                 boost::shared_ptr<QKeyEvent> ev = keyeventQueue_.front();
438
439                 // We never handle more than one auto repeated
440                 // char in a list of queued up events.
441                 if (!handle_autos && ev->isAutoRepeat()) {
442                         keyeventQueue_.pop();
443                         continue;
444                 }
445
446         boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
447                 sym->set(ev.get());
448
449         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
450                 << " count=" << ev->count()
451                 << " text=" << (const char *) ev->text()
452                 << " isAutoRepeat=" << ev->isAutoRepeat()
453                 << " key=" << ev->key()
454                 << endl;
455
456                 this->workAreaKeyPress(sym, q_key_state(ev->state()));
457                 keyeventQueue_.pop();
458
459                 handle_autos = false;
460         }
461
462         // Restart the timer.
463         step_timer_.start(25, true);
464 }
465
466
467 void QWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
468 {
469         dc_event_ = double_click(e);
470
471         if (!dc_event_.active)
472                 return;
473
474         dc_event_.active = false;
475
476         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
477                 dc_event_.x, dc_event_.y,
478                 q_button_state(dc_event_.state));
479         this->dispatch(cmd);
480 }
481
482
483 void QWorkArea::resizeEvent(QResizeEvent * resizeEvent)
484 {
485         workWidth_ = viewport()->width();
486         workHeight_ = viewport()->height();
487
488         verticalScrollBar()->setPageStep(viewport()->height());
489
490         pixmap_.reset(new QPixmap(viewport()->width(), viewport()->height()));
491
492         this->workAreaResize();
493
494         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
495                 << "\n QWidget width\t" << this->QWidget::width()
496                 << "\n QWidget height\t" << this->QWidget::height()
497                 << "\n viewport width\t" << viewport()->width()
498                 << "\n viewport height\t" << viewport()->height()
499                 << "\n QResizeEvent rect left\t" << rect().left()
500                 << "\n QResizeEvent rect right\t" << rect().right()
501                 << endl;
502 }
503
504 void QWorkArea::paintEvent(QPaintEvent * e)
505 {
506         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
507                 << "\n QWidget width\t" << this->width()
508                 << "\n QWidget height\t" << this->height()
509                 << "\n viewport width\t" << viewport()->width()
510                 << "\n viewport height\t" << viewport()->height()
511                 << "\n pixmap width\t" << pixmap_->width()
512                 << "\n pixmap height\t" << pixmap_->height()
513                 << "\n QPaintEvent x\t" << e->rect().x()
514                 << "\n QPaintEvent y\t" << e->rect().y()
515                 << "\n QPaintEvent w\t" << e->rect().width()
516                 << "\n QPaintEvent h\t" << e->rect().height()
517                 << endl;
518
519         QPainter q(viewport());
520         q.drawPixmap(e->rect(), *pixmap_.get(), e->rect());
521 }
522
523
524 ///////////////////////////////////////////////////////////////
525 ///////////////////////////////////////////////////////////////
526 // Specific stuff
527
528 ////////////////////////////////////////////////////////////////////////
529 // qt-immodule specific stuff goes here...
530
531 #if USE_INPUT_METHODS
532 // to make qt-immodule work
533
534 void QWorkArea::inputMethodEvent(QInputMethodEvent * e) 
535 {
536         QString const text = e->text();
537         if (!text.isEmpty()) {
538                 int key = 0;
539                 // needed to make math superscript work on some systems
540                 // ideally, such special coding should not be necessary
541                 if (text == "^")
542                         key = Qt::Key_AsciiCircum;
543                 QKeyEvent ev(QEvent::KeyPress, key, *text.ascii(), 0, text);
544                 keyPressEvent(&ev);
545         }
546         e->accept();
547 }
548 #endif
549
550
551 ////////////////////////////////////////////////////////////////////////
552 // X11 specific stuff goes here...
553
554 #ifdef Q_WS_X11
555 bool lyxX11EventFilter(XEvent * xev)
556 {
557         switch (xev->type) {
558         case SelectionRequest:
559                 lyxerr[Debug::GUI] << "X requested selection." << endl;
560                 if (wa_ptr)
561                         wa_ptr->selectionRequested();
562                 break;
563         case SelectionClear:
564                 lyxerr[Debug::GUI] << "Lost selection." << endl;
565                 if (wa_ptr)
566                         wa_ptr->selectionLost();
567                 break;
568         }
569         return false;
570 }
571 #endif
572
573
574 ////////////////////////////////////////////////////////////////////////
575 // Mac OSX specific stuff goes here...
576
577 #ifdef Q_WS_MACX
578 namespace{
579 OSErr checkAppleEventForMissingParams(const AppleEvent& theAppleEvent)
580  {
581         DescType returnedType;
582         Size actualSize;
583         OSErr err = AEGetAttributePtr(&theAppleEvent, keyMissedKeywordAttr,
584                                       typeWildCard, &returnedType, nil, 0,
585                                       &actualSize);
586         switch (err) {
587         case errAEDescNotFound:
588                 return noErr;
589         case noErr:
590                 return errAEEventNotHandled;
591         default:
592                 return err;
593         }
594  }
595 }
596
597 pascal OSErr handleOpenDocuments(const AppleEvent* inEvent,
598                                  AppleEvent* /*reply*/, long /*refCon*/)
599 {
600         QString s_arg;
601         AEDescList documentList;
602         OSErr err = AEGetParamDesc(inEvent, keyDirectObject, typeAEList,
603                                    &documentList);
604         if (err != noErr)
605                 return err;
606
607         err = checkAppleEventForMissingParams(*inEvent);
608         if (err == noErr) {
609                 long documentCount;
610                 err = AECountItems(&documentList, &documentCount);
611                 for (long documentIndex = 1;
612                      err == noErr && documentIndex <= documentCount;
613                      documentIndex++) {
614                         DescType returnedType;
615                         Size actualSize;
616                         AEKeyword keyword;
617                         FSRef ref;
618                         char qstr_buf[1024];
619                         err = AESizeOfNthItem(&documentList, documentIndex,
620                                               &returnedType, &actualSize);
621                         if (err == noErr) {
622                                 err = AEGetNthPtr(&documentList, documentIndex,
623                                                   typeFSRef, &keyword,
624                                                   &returnedType, (Ptr)&ref,
625                                                   sizeof(FSRef), &actualSize);
626                                 if (err == noErr) {
627                                         FSRefMakePath(&ref, (UInt8*)qstr_buf,
628                                                       1024);
629                                         s_arg=QString::fromUtf8(qstr_buf);
630                                         wa_ptr->dispatch(
631                                                 FuncRequest(LFUN_FILE_OPEN,
632                                                             fromqstr(s_arg)));
633                                         break;
634                                 }
635                         }
636                 } // for ...
637         }
638         AEDisposeDesc(&documentList);
639         return err;
640 }
641 #endif  // Q_WS_MACX