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