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