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