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