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