]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.C
This commit should hopefully fix all scrolling issues. As an added bonus, mouse scrol...
[lyx.git] / src / frontends / qt4 / GuiWorkArea.C
1 /**
2  * \file GuiWorkArea.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 #undef QT3_SUPPORT
13
14 #include <config.h>
15
16
17 #include "GuiWorkArea.h"
18
19 #include "QLPainter.h"
20 #include "QLyXKeySym.h"
21
22 #include "ColorCache.h"
23 #include "qt_helpers.h"
24 #include "Application.h"
25 #include "BufferView.h"
26 #include "debug.h"
27 #include "funcrequest.h"
28 #include "LColor.h"
29 #include "support/os.h"
30
31 #include <QLayout>
32 #include <QMainWindow>
33 #include <QMimeData>
34 #include <QUrl>
35 #include <QDragEnterEvent>
36 #include <QPixmap>
37 #include <QPainter>
38 #include <QScrollBar>
39
40 #include <boost/bind.hpp>
41 #include <boost/current_function.hpp>
42
43 // Abdel (26/06/2006):
44 // On windows-XP the UserGuide PageDown scroll test is faster without event pruning (16 s)
45 // than with it (23 s).
46 #ifdef Q_WS_WIN
47  #define USE_EVENT_PRUNING 0
48 #else
49  #define USE_EVENT_PRUNING 0
50 #endif
51
52 using std::endl;
53 using std::string;
54
55 namespace os = lyx::support::os;
56
57 namespace {
58
59 /// return the LyX key state from Qt's
60 key_modifier::state q_key_state(Qt::KeyboardModifiers state)
61 {
62         key_modifier::state k = key_modifier::none;
63         if (state & Qt::ControlModifier)
64                 k |= key_modifier::ctrl;
65         if (state & Qt::ShiftModifier)
66                 k |= key_modifier::shift;
67         if (state & Qt::AltModifier || state & Qt::MetaModifier)
68                 k |= key_modifier::alt;
69         return k;
70 }
71
72
73 /// return the LyX mouse button state from Qt's
74 mouse_button::state q_button_state(Qt::MouseButton button)
75 {
76         mouse_button::state b = mouse_button::none;
77         switch (button) {
78                 case Qt::LeftButton:
79                         b = mouse_button::button1;
80                         break;
81                 case Qt::MidButton:
82                         b = mouse_button::button2;
83                         break;
84                 case Qt::RightButton:
85                         b = mouse_button::button3;
86                         break;
87                 default:
88                         break;
89         }
90         return b;
91 }
92
93
94 /// return the LyX mouse button state from Qt's
95 mouse_button::state q_motion_state(Qt::MouseButton state)
96 {
97         mouse_button::state b = mouse_button::none;
98         if (state & Qt::LeftButton)
99                 b |= mouse_button::button1;
100         if (state & Qt::MidButton)
101                 b |= mouse_button::button2;
102         if (state & Qt::RightButton)
103                 b |= mouse_button::button3;
104         return b;
105 }
106
107 } // namespace anon
108
109 namespace lyx {
110 namespace frontend {
111
112 // This is a 'heartbeat' generating synthetic mouse move events when the
113 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
114 SyntheticMouseEvent::SyntheticMouseEvent()
115         : timeout(200), restart_timeout(true),
116           x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
117 {}
118
119
120 GuiWorkArea::GuiWorkArea(int w, int h, LyXView & lyx_view)
121 : WorkArea(lyx_view), painter_(this)
122 {
123         setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
124         setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
125
126         setAcceptDrops(true);
127
128         setMinimumSize(100, 70);
129
130         viewport()->setAutoFillBackground(false);
131         viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
132
133         viewport()->setFocusPolicy(Qt::WheelFocus);
134         viewport()->setFocus();
135         setFocusPolicy(Qt::WheelFocus);
136
137         viewport()->setCursor(Qt::IBeamCursor);
138
139         resize(w, h);
140         workWidth_ = w;
141         workHeight_ = h;
142
143         synthetic_mouse_event_.timeout.timeout.connect(
144                 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
145                             this));
146
147         // Initialize the vertical Scroll Bar
148         QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
149                 this, SLOT(adjustViewWithScrollBar(int)));
150
151         // PageStep only depends on the viewport height.
152         verticalScrollBar()->setPageStep(workHeight_);
153
154         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
155                 << "\n Area width\t" << width()
156                 << "\n Area height\t" << height()
157                 << "\n viewport width\t" << viewport()->width()
158                 << "\n viewport height\t" << viewport()->height()
159                 << endl;
160
161         if (USE_EVENT_PRUNING) {
162                 // This is the keyboard buffering stuff...
163                 // I don't see any need for this under windows. The keyboard is reactive
164                 // enough...
165
166                 if ( !QObject::connect(&step_timer_, SIGNAL(timeout()),
167                         this, SLOT(keyeventTimeout())) )
168                         lyxerr[Debug::GUI] << "ERROR: keyeventTimeout cannot connect!" << endl;
169
170                 // Start the timer, one-shot.
171                 step_timer_.setSingleShot(true);
172                 step_timer_.start(50);
173         }
174
175         // Enables input methods for asian languages.
176         // Must be set when creating custom text editing widgets.
177         setAttribute(Qt::WA_InputMethodEnabled, true);
178 }
179
180 GuiWorkArea::~GuiWorkArea()
181 {
182 }
183
184
185 void GuiWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
186 {
187         verticalScrollBar()->setTracking(false);
188
189         // do what cursor movement does (some grey)
190         h += height() / 4;
191         int scroll_max_ = std::max(0, h - height());
192
193         verticalScrollBar()->setRange(0, scroll_max_);
194         verticalScrollBar()->setSliderPosition(scroll_pos);
195         verticalScrollBar()->setSingleStep(scroll_line_step);
196
197         verticalScrollBar()->setTracking(true);
198 }
199
200
201 void GuiWorkArea::adjustViewWithScrollBar(int)
202 {
203         scrollBufferView(verticalScrollBar()->sliderPosition());
204 }
205
206
207 void GuiWorkArea::dragEnterEvent(QDragEnterEvent * event)
208 {
209         if (event->mimeData()->hasUrls())
210                 event->accept();
211         /// \todo Ask lyx-devel is this is enough:
212         /// if (event->mimeData()->hasFormat("text/plain"))
213         ///     event->acceptProposedAction();
214 }
215
216
217 void GuiWorkArea::dropEvent(QDropEvent* event)
218 {
219         QList<QUrl> files = event->mimeData()->urls();
220         if (files.isEmpty())
221                 return;
222
223         lyxerr[Debug::GUI] << "GuiWorkArea::dropEvent: got URIs!" << endl;
224         for (int i = 0; i!=files.size(); ++i) {
225                 string const file = os::internal_path(fromqstr(files.at(i).toString()));
226                 if (!file.empty())
227                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
228         }
229 }
230
231
232 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
233 {
234         if (dc_event_.active && dc_event_ == *e) {
235                 dc_event_.active = false;
236                 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
237                         dc_event_.x, dc_event_.y,
238                         q_button_state(dc_event_.state));
239                 dispatch(cmd);
240                 return;
241         }
242
243         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
244                               q_button_state(e->button()));
245         dispatch(cmd);
246 }
247
248
249 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
250 {
251         if (synthetic_mouse_event_.timeout.running())
252                 synthetic_mouse_event_.timeout.stop();
253
254         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
255                               q_button_state(e->button()));
256         dispatch(cmd);
257 }
258
259
260 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
261 {
262         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
263                               q_motion_state(e->button()));
264
265         // If we're above or below the work area...
266         if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
267                 // Make sure only a synthetic event can cause a page scroll,
268                 // so they come at a steady rate:
269                 if (e->y() <= 20)
270                         // _Force_ a scroll up:
271                         cmd.y = -40;
272                 else
273                         cmd.y = viewport()->height();
274                 // Store the event, to be handled when the timeout expires.
275                 synthetic_mouse_event_.cmd = cmd;
276
277                 if (synthetic_mouse_event_.timeout.running())
278                         // Discard the event. Note that it _may_ be handled
279                         // when the timeout expires if
280                         // synthetic_mouse_event_.cmd has not been overwritten.
281                         // Ie, when the timeout expires, we handle the
282                         // most recent event but discard all others that
283                         // occurred after the one used to start the timeout
284                         // in the first place.
285                         return;
286                 else {
287                         synthetic_mouse_event_.restart_timeout = true;
288                         synthetic_mouse_event_.timeout.start();
289                         // Fall through to handle this event...
290                 }
291
292         } else if (synthetic_mouse_event_.timeout.running()) {
293                 // Store the event, to be possibly handled when the timeout
294                 // expires.
295                 // Once the timeout has expired, normal control is returned
296                 // to mouseMoveEvent (restart_timeout = false).
297                 // This results in a much smoother 'feel' when moving the
298                 // mouse back into the work area.
299                 synthetic_mouse_event_.cmd = cmd;
300                 synthetic_mouse_event_.restart_timeout = false;
301                 return;
302         }
303
304         // Has anything changed on-screen since the last QMouseEvent
305         // was received?
306         double const scrollbar_value = verticalScrollBar()->value();
307         if (e->x() != synthetic_mouse_event_.x_old ||
308             e->y() != synthetic_mouse_event_.y_old ||
309             scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
310                 // Yes it has. Store the params used to check this.
311                 synthetic_mouse_event_.x_old = e->x();
312                 synthetic_mouse_event_.y_old = e->y();
313                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
314
315                 // ... and dispatch the event to the LyX core.
316                 dispatch(cmd);
317         }
318 }
319
320
321 void GuiWorkArea::wheelEvent(QWheelEvent * e)
322 {
323         // Wheel rotation by one notch results in a delta() of 120 (see
324         // documentation of QWheelEvent)
325         int const lines = qApp->wheelScrollLines() * e->delta() / 120;
326         verticalScrollBar()->setValue(verticalScrollBar()->value() -
327                         lines *  verticalScrollBar()->singleStep());
328         adjustViewWithScrollBar();
329 }
330
331
332 void GuiWorkArea::generateSyntheticMouseEvent()
333 {
334 // Set things off to generate the _next_ 'pseudo' event.
335         if (synthetic_mouse_event_.restart_timeout)
336                 synthetic_mouse_event_.timeout.start();
337
338         // Has anything changed on-screen since the last timeout signal
339         // was received?
340         double const scrollbar_value = verticalScrollBar()->value();
341         if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
342                 // Yes it has. Store the params used to check this.
343                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
344
345                 // ... and dispatch the event to the LyX core.
346                 dispatch(synthetic_mouse_event_.cmd);
347         }
348 }
349
350
351 void GuiWorkArea::keyPressEvent(QKeyEvent * e)
352 {
353         lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
354                 << " count=" << e->count()
355                 << " text=" << fromqstr(e->text())
356                 << " isAutoRepeat=" << e->isAutoRepeat()
357                 << " key=" << e->key()
358                 << endl;
359
360         if (USE_EVENT_PRUNING) {
361                 keyeventQueue_.push(boost::shared_ptr<QKeyEvent>(new QKeyEvent(*e)));
362         }
363         else {
364                 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
365                 sym->set(e);
366                 processKeySym(sym, q_key_state(e->modifiers()));
367         }
368 }
369
370
371 // This is used only if USE_EVENT_PRUNING is defined...
372 void GuiWorkArea::keyeventTimeout()
373 {
374         bool handle_autos = true;
375
376         while (!keyeventQueue_.empty()) {
377                 boost::shared_ptr<QKeyEvent> ev = keyeventQueue_.front();
378
379                 // We never handle more than one auto repeated
380                 // char in a list of queued up events.
381                 if (!handle_autos && ev->isAutoRepeat()) {
382                         keyeventQueue_.pop();
383                         continue;
384                 }
385
386                 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
387                 sym->set(ev.get());
388
389                 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
390                                    << " count=" << ev->count()
391                                    << " text=" <<  fromqstr(ev->text())
392                                    << " isAutoRepeat=" << ev->isAutoRepeat()
393                                    << " key=" << ev->key()
394                                    << endl;
395
396                 processKeySym(sym, q_key_state(ev->modifiers()));
397                 keyeventQueue_.pop();
398
399                 handle_autos = false;
400         }
401
402         // Restart the timer.
403         step_timer_.setSingleShot(true);
404         step_timer_.start(25);
405 }
406
407
408 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
409 {
410         dc_event_ = double_click(e);
411
412         if (!dc_event_.active)
413                 return;
414
415         dc_event_.active = false;
416
417         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
418                 dc_event_.x, dc_event_.y,
419                 q_button_state(dc_event_.state));
420         dispatch(cmd);
421 }
422
423
424 void GuiWorkArea::resizeEvent(QResizeEvent *)
425 {
426         workWidth_ = viewport()->width();
427         workHeight_ = viewport()->height();
428
429         verticalScrollBar()->setPageStep(viewport()->height());
430
431 //      screen_device_ = QPixmap(viewport()->width(), viewport()->height());
432 //      paint_device_ = QImage(viewport()->width(), viewport()->height(), QImage::Format_RGB32);
433         paint_device_ = QPixmap(viewport()->width(), viewport()->height());
434
435         resizeBufferView();
436
437         /*
438         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
439                 << "\n QWidget width\t" << this->QWidget::width()
440                 << "\n QWidget height\t" << this->QWidget::height()
441                 << "\n viewport width\t" << viewport()->width()
442                 << "\n viewport height\t" << viewport()->height()
443                 << "\n QResizeEvent rect left\t" << rect().left()
444                 << "\n QResizeEvent rect right\t" << rect().right()
445                 << endl;
446                 */
447 }
448
449
450 void GuiWorkArea::update(int x, int y, int w, int h)
451 {
452         //screen_device_.fromImage(paint_device_);
453         //QPainter q(&screen_device_);
454         //q.drawImage(x, y, paint_device_.copy(x, y, w, h));
455
456         viewport()->update(x, y, w, h);
457 }
458
459
460 void GuiWorkArea::paintEvent(QPaintEvent * e)
461 {
462         /*
463         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
464                 << "\n QWidget width\t" << this->width()
465                 << "\n QWidget height\t" << this->height()
466                 << "\n viewport width\t" << viewport()->width()
467                 << "\n viewport height\t" << viewport()->height()
468                 << "\n pixmap width\t" << pixmap_->width()
469                 << "\n pixmap height\t" << pixmap_->height()
470                 << "\n QPaintEvent x\t" << e->rect().x()
471                 << "\n QPaintEvent y\t" << e->rect().y()
472                 << "\n QPaintEvent w\t" << e->rect().width()
473                 << "\n QPaintEvent h\t" << e->rect().height()
474                 << endl;
475         */
476
477         QPainter q(viewport());
478         q.drawPixmap(e->rect(), paint_device_, e->rect());
479
480         if (show_vcursor_)
481                 q.drawPixmap(cursor_x_, cursor_y_, vcursor_);
482
483         if (show_hcursor_)
484                 q.drawPixmap(cursor_x_, cursor_y_ + cursor_h_ - 1, hcursor_);
485 }
486
487
488 QPixmap GuiWorkArea::copyScreen(int x, int y, int w, int h) const
489 {
490         return paint_device_.copy(x, y, w, h);
491 }
492
493
494 void GuiWorkArea::drawScreen(int x, int y, QPixmap pixmap)
495 {
496         QPainter q(&paint_device_);
497         q.drawPixmap(x, y, pixmap);
498         update(x, y, pixmap.width(), pixmap.height());
499 }
500
501
502 void GuiWorkArea::expose(int x, int y, int w, int h)
503 {
504         /*
505         if (x == 0 && y == 0 && w == viewport()->width() && h == viewport()->height()) {
506                 viewport()->repaint(x, y, w, h);
507                 return;
508         }
509         */
510
511         update(x, y, w, h);
512 }
513
514
515 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
516 {
517         if (!qApp->focusWidget())
518                 return;
519
520         show_vcursor_ = true;
521
522         QColor const & required_color = lcolorcache.get(LColor::cursor);
523
524         if (x==cursor_x_ && y==cursor_y_ && h==cursor_h_
525                 && cursor_color_ == required_color
526                 && cursor_shape_ == shape) {
527                 show_hcursor_ = lshape_cursor_;
528                 update(cursor_x_, cursor_y_, cursor_w_, cursor_h_);
529                 return;
530         }
531
532         // Cache the dimensions of the cursor.
533         cursor_x_ = x;
534         cursor_y_ = y;
535         cursor_h_ = h;
536         cursor_color_ = required_color;
537         cursor_shape_ = shape;
538
539         switch (cursor_shape_) {
540         case BAR_SHAPE:
541                 // FIXME the cursor width shouldn't be hard-coded!
542                 cursor_w_ = 2;
543                 lshape_cursor_ = false;
544                 break;
545         case L_SHAPE:
546                 cursor_w_ = cursor_h_ / 3;
547                 lshape_cursor_ = true;
548                 break;
549         case REVERSED_L_SHAPE:
550                 cursor_w_ = cursor_h_ / 3;
551                 cursor_x_ -= cursor_w_ - 1;
552                 lshape_cursor_ = true;
553                 break;
554         }
555
556         // We cache two pixmaps:
557         // 1 the vertical line of the cursor.
558         // 2 the horizontal line of the L-shaped cursor (if necessary).
559
560         // Draw the new (vertical) cursor.
561         vcursor_ = QPixmap(cursor_w_, cursor_h_);
562         vcursor_.fill(cursor_color_);
563
564         // Draw the new (horizontal) cursor if necessary.
565         if (lshape_cursor_) {
566                 hcursor_ = QPixmap(cursor_w_, 1);
567                 hcursor_.fill(cursor_color_);
568                 show_hcursor_ = true;
569         }
570
571         update(cursor_x_, cursor_y_, cursor_w_, cursor_h_);
572 }
573
574
575 void GuiWorkArea::removeCursor()
576 {
577         show_vcursor_ = false;
578         show_hcursor_ = false;
579
580         update(cursor_x_, cursor_y_, cursor_w_, cursor_h_);
581 }
582
583
584 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
585 {
586         QString const & text = e->commitString();
587         if (!text.isEmpty()) {
588
589                 lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
590                         << " preeditString =" << fromqstr(e->preeditString())
591                         << " commitString  =" << fromqstr(e->commitString())
592                         << endl;
593
594                 int key = 0;
595                 // needed to make math superscript work on some systems
596                 // ideally, such special coding should not be necessary
597                 if (text == "^")
598                         key = Qt::Key_AsciiCircum;
599                 QKeyEvent ev(QEvent::KeyPress, key, 0, text);
600                 keyPressEvent(&ev);
601         }
602         e->accept();
603 }
604
605
606 } // namespace frontend
607 } // namespace lyx
608
609 #include "GuiWorkArea_moc.cpp"