]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/QWorkArea.C
rename LFUN enum values according to their command (as used in th minibuffer/bind...
[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 #include "BufferView.h"
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 * 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 & owner, int w, int h)
124     : QAbstractScrollArea(qApp->mainWidget()), WorkArea(), view_(owner), 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         view_.view()->scrollDocView(verticalScrollBar()->sliderPosition());
228 }
229
230
231 void QWorkArea::haveSelection(bool own) const
232 {
233         /// \todo ask X11 and MAC devels why this wa_ptr is useful.
234         wa_ptr = const_cast<QWorkArea*>(this);
235
236         if (!QApplication::clipboard()->supportsSelection())
237                 return;
238
239         if (own) {
240                 QApplication::clipboard()->setText(QString(), QClipboard::Selection);
241         }
242         // We don't need to do anything if own = false, as this case is
243         // handled by QT.
244 }
245
246
247 string const QWorkArea::getClipboard() const
248 {
249         QString str = QApplication::clipboard()->text(QClipboard::Selection);
250         lyxerr[Debug::ACTION] << "getClipboard: " << (const char*) str << endl;
251         if (str.isNull())
252                 return string();
253 #ifdef Q_WS_MACX
254         // The MAC clipboard uses \r for lineendings, and we use \n
255         return subst(fromqstr(str), '\r', '\n');
256 #else
257         return fromqstr(str);
258 #endif
259 }
260
261
262 void QWorkArea::putClipboard(string const & str) const
263 {
264 #ifdef Q_WS_MACX
265         // The MAC clipboard uses \r for lineendings, and we use \n
266         QApplication::clipboard()->setText(toqstr(subst(str, '\n', '\r')),
267                                            QClipboard::Selection);
268 #else
269         QApplication::clipboard()->setText(toqstr(str), QClipboard::Selection);
270 #endif
271         lyxerr[Debug::ACTION] << "putClipboard: " << str << endl;
272 }
273
274
275 void QWorkArea::dragEnterEvent(QDragEnterEvent * event)
276 {
277         event->accept(Q3UriDrag::canDecode(event));
278
279         /// \todo Ask lyx-devel is this is enough:
280         /// if (event->mimeData()->hasFormat("text/plain"))
281         ///     event->acceptProposedAction();
282
283 }
284
285
286 void QWorkArea::dropEvent(QDropEvent* event)
287 {
288         QStringList files;
289
290         if (Q3UriDrag::decodeLocalFiles(event, files)) {
291                 lyxerr[Debug::GUI] << "QWorkArea::dropEvent: got URIs!"
292                                    << endl;
293                 for (QStringList::Iterator i = files.begin();
294                      i!=files.end(); ++i) {
295                         string const file = os::internal_path(fromqstr(*i));
296                         view_.view()->workAreaDispatch(FuncRequest(LFUN_FILE_OPEN, file));
297                 }
298         }
299 }
300
301
302 void QWorkArea::mousePressEvent(QMouseEvent * e)
303 {
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);
310                 return;
311         }
312
313         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
314                               q_button_state(e->button()));
315         view_.view()->workAreaDispatch(cmd);
316 }
317
318
319 void QWorkArea::mouseReleaseEvent(QMouseEvent * e)
320 {
321         if (synthetic_mouse_event_.timeout.running())
322                 synthetic_mouse_event_.timeout.stop();
323
324         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
325                               q_button_state(e->button()));
326         view_.view()->workAreaDispatch(cmd);
327 }
328
329
330 void QWorkArea::mouseMoveEvent(QMouseEvent * e)
331 {
332         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
333                               q_motion_state(e->state()));
334
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:
339                 if (e->y() <= 20)
340                         // _Force_ a scroll up:
341                         cmd.y = -40;
342                 else
343                         cmd.y = viewport()->height();
344                 // Store the event, to be handled when the timeout expires.
345                 synthetic_mouse_event_.cmd = cmd;
346
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.
355                         return;
356                 else {
357                         synthetic_mouse_event_.restart_timeout = true;
358                         synthetic_mouse_event_.timeout.start();
359                         // Fall through to handle this event...
360                 }
361
362         } else if (synthetic_mouse_event_.timeout.running()) {
363                 // Store the event, to be possibly handled when the timeout
364                 // expires.
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;
371                 return;
372         }
373
374         // Has anything changed on-screen since the last QMouseEvent
375         // was received?
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;
384
385                 // ... and dispatch the event to the LyX core.
386                 view_.view()->workAreaDispatch(cmd);
387         }
388 }
389
390
391 void QWorkArea::wheelEvent(QWheelEvent * e)
392 {
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();
399 }
400
401
402 void QWorkArea::generateSyntheticMouseEvent()
403 {
404         // Set things off to generate the _next_ 'pseudo' event.
405         if (synthetic_mouse_event_.restart_timeout)
406                 synthetic_mouse_event_.timeout.start();
407
408         // Has anything changed on-screen since the last timeout signal
409         // was received?
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;
414
415                 // ... and dispatch the event to the LyX core.
416                 view_.view()->workAreaDispatch(synthetic_mouse_event_.cmd);
417         }
418 }
419
420 void QWorkArea::keyPressEvent(QKeyEvent * e)
421 {
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()
427                 << endl;
428
429 //      keyeventQueue_.push(boost::shared_ptr<QKeyEvent>(new QKeyEvent(*e)));
430
431     boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
432     sym->set(e);
433     view_.view()->workAreaKeyPress(sym, q_key_state(e->state()));
434
435 }
436
437 // This is not used for now...
438 void QWorkArea::keyeventTimeout()
439 {
440         bool handle_autos = true;
441
442         while (!keyeventQueue_.empty()) {
443                 boost::shared_ptr<QKeyEvent> ev = keyeventQueue_.front();
444
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();
449                         continue;
450                 }
451
452                 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
453                 sym->set(ev.get());
454
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()
460                                    << endl;
461
462                 view_.view()->workAreaKeyPress(sym, q_key_state(ev->state()));
463                 keyeventQueue_.pop();
464
465                 handle_autos = false;
466         }
467
468         // Restart the timer.
469         step_timer_.start(25, true);
470 }
471
472
473 void QWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
474 {
475         dc_event_ = double_click(e);
476
477         if (!dc_event_.active)
478                 return;
479
480         dc_event_.active = false;
481
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);
486 }
487
488
489 void QWorkArea::resizeEvent(QResizeEvent * resizeEvent)
490 {
491         workWidth_ = viewport()->width();
492         workHeight_ = viewport()->height();
493
494         verticalScrollBar()->setPageStep(viewport()->height());
495
496         screen_device_ = QPixmap(viewport()->width(), viewport()->height());
497         paint_device_ = QImage(viewport()->width(), viewport()->height(), QImage::Format_RGB32);
498
499         view_.view()->workAreaResize();
500
501         /*
502         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
503                 << "\n QWidget width\t" << this->QWidget::width()
504                 << "\n QWidget height\t" << this->QWidget::height()
505                 << "\n viewport width\t" << viewport()->width()
506                 << "\n viewport height\t" << viewport()->height()
507                 << "\n QResizeEvent rect left\t" << rect().left()
508                 << "\n QResizeEvent rect right\t" << rect().right()
509                 << endl;
510                 */
511 }
512
513 void QWorkArea::update(int x, int y, int w, int h)
514 {
515         //screen_device_.fromImage(paint_device_);
516         QPainter q(&screen_device_);
517         q.drawImage(x, y, paint_device_.copy(x, y, w, h));
518
519         viewport()->update(x, y, w, h);
520 }
521
522 void QWorkArea::paintEvent(QPaintEvent * e)
523 {
524         /*
525         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
526                 << "\n QWidget width\t" << this->width()
527                 << "\n QWidget height\t" << this->height()
528                 << "\n viewport width\t" << viewport()->width()
529                 << "\n viewport height\t" << viewport()->height()
530                 << "\n pixmap width\t" << pixmap_->width()
531                 << "\n pixmap height\t" << pixmap_->height()
532                 << "\n QPaintEvent x\t" << e->rect().x()
533                 << "\n QPaintEvent y\t" << e->rect().y()
534                 << "\n QPaintEvent w\t" << e->rect().width()
535                 << "\n QPaintEvent h\t" << e->rect().height()
536                 << endl;
537         */
538         QPainter q(viewport());
539         q.drawPixmap(e->rect(), screen_device_, e->rect());
540 }
541
542
543 QPixmap QWorkArea::copyScreen(int x, int y, int w, int h) const
544 {
545         return screen_device_.copy(x, y, w, h);
546 }
547
548 void QWorkArea::drawScreen(int x, int y, QPixmap pixmap)
549 {
550         QPainter q(&screen_device_);
551         q.drawPixmap(x, y, pixmap);
552         viewport()->update(x, y, pixmap.width(), pixmap.height());
553 }
554
555
556 ///////////////////////////////////////////////////////////////
557 ///////////////////////////////////////////////////////////////
558 // Specific stuff
559
560 ////////////////////////////////////////////////////////////////////////
561 // qt-immodule specific stuff goes here...
562
563 #if USE_INPUT_METHODS
564 // to make qt-immodule work
565
566 void QWorkArea::inputMethodEvent(QInputMethodEvent * e)
567 {
568         QString const text = e->text();
569         if (!text.isEmpty()) {
570                 int key = 0;
571                 // needed to make math superscript work on some systems
572                 // ideally, such special coding should not be necessary
573                 if (text == "^")
574                         key = Qt::Key_AsciiCircum;
575                 QKeyEvent ev(QEvent::KeyPress, key, *text.ascii(), 0, text);
576                 keyPressEvent(&ev);
577         }
578         e->accept();
579 }
580 #endif
581
582
583 ////////////////////////////////////////////////////////////////////////
584 // X11 specific stuff goes here...
585
586 #ifdef Q_WS_X11
587 bool lyxX11EventFilter(XEvent * xev)
588 {
589         switch (xev->type) {
590         case SelectionRequest:
591                 lyxerr[Debug::GUI] << "X requested selection." << endl;
592                 if (wa_ptr)
593                         wa_ptr->view().view()->selectionRequested();
594                 break;
595         case SelectionClear:
596                 lyxerr[Debug::GUI] << "Lost selection." << endl;
597                 if (wa_ptr)
598                         wa_ptr->view().view()->selectionLost();
599                 break;
600         }
601         return false;
602 }
603 #endif
604
605
606 ////////////////////////////////////////////////////////////////////////
607 // Mac OSX specific stuff goes here...
608
609 #ifdef Q_WS_MACX
610 namespace{
611 OSErr checkAppleEventForMissingParams(const AppleEvent& theAppleEvent)
612  {
613         DescType returnedType;
614         Size actualSize;
615         OSErr err = AEGetAttributePtr(&theAppleEvent, keyMissedKeywordAttr,
616                                       typeWildCard, &returnedType, nil, 0,
617                                       &actualSize);
618         switch (err) {
619         case errAEDescNotFound:
620                 return noErr;
621         case noErr:
622                 return errAEEventNotHandled;
623         default:
624                 return err;
625         }
626  }
627 }
628
629 pascal OSErr handleOpenDocuments(const AppleEvent* inEvent,
630                                  AppleEvent* /*reply*/, long /*refCon*/)
631 {
632         QString s_arg;
633         AEDescList documentList;
634         OSErr err = AEGetParamDesc(inEvent, keyDirectObject, typeAEList,
635                                    &documentList);
636         if (err != noErr)
637                 return err;
638
639         err = checkAppleEventForMissingParams(*inEvent);
640         if (err == noErr) {
641                 long documentCount;
642                 err = AECountItems(&documentList, &documentCount);
643                 for (long documentIndex = 1;
644                      err == noErr && documentIndex <= documentCount;
645                      documentIndex++) {
646                         DescType returnedType;
647                         Size actualSize;
648                         AEKeyword keyword;
649                         FSRef ref;
650                         char qstr_buf[1024];
651                         err = AESizeOfNthItem(&documentList, documentIndex,
652                                               &returnedType, &actualSize);
653                         if (err == noErr) {
654                                 err = AEGetNthPtr(&documentList, documentIndex,
655                                                   typeFSRef, &keyword,
656                                                   &returnedType, (Ptr)&ref,
657                                                   sizeof(FSRef), &actualSize);
658                                 if (err == noErr) {
659                                         FSRefMakePath(&ref, (UInt8*)qstr_buf,
660                                                       1024);
661                                         s_arg=QString::fromUtf8(qstr_buf);
662                                         wa_ptr->view().view()->workAreaDispatch(
663                                                 FuncRequest(LFUN_FILE_OPEN,
664                                                             fromqstr(s_arg)));
665                                         break;
666                                 }
667                         }
668                 } // for ...
669         }
670         AEDisposeDesc(&documentList);
671         return err;
672 }
673 #endif  // Q_WS_MACX