]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.C
re-enable opaque widget optimization following Trolltech developer advice (in order...
[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 "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 {
120 public:
121         CursorWidget() {}
122
123         void draw(QPainter & painter)
124         {
125                 // FIXME: do something depending on the cursor shape.
126                 if (show_ && rect_.isValid())
127                         painter.fillRect(rect_, color_);
128         }
129
130         void update(int x, int y, int h, CursorShape shape)
131         {
132                 color_ = guiApp->colorCache().get(LColor::cursor);
133                 rect_ = QRect(x, y, CursorWidth, h);
134                 shape_ = shape;
135         }
136
137         void show(bool set_show = true) { show_ = set_show; }
138         void hide() { show_ = false; }
139
140         QRect const & rect() { return rect_; }
141
142 private:
143         ///
144         CursorShape shape_;
145         ///
146         bool show_;
147         ///
148         QColor color_;
149         ///
150         QRect rect_;
151 };
152
153
154 // This is a 'heartbeat' generating synthetic mouse move events when the
155 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
156 SyntheticMouseEvent::SyntheticMouseEvent()
157         : timeout(200), restart_timeout(true),
158           x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
159 {}
160
161
162 GuiWorkArea::GuiWorkArea(int w, int h, int id, LyXView & lyx_view)
163         : WorkArea(id, lyx_view)
164 {
165         cursor_ = new frontend::CursorWidget();
166         cursor_->hide();
167
168         setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
169         setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
170         setAcceptDrops(true);
171         setMinimumSize(100, 70);
172
173         viewport()->setAutoFillBackground(false);
174         viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
175         setFocusPolicy(Qt::WheelFocus);
176
177         viewport()->setCursor(Qt::IBeamCursor);
178
179         resize(w, h);
180
181         synthetic_mouse_event_.timeout.timeout.connect(
182                 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
183                             this));
184
185         // Initialize the vertical Scroll Bar
186         QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
187                 this, SLOT(adjustViewWithScrollBar(int)));
188
189         // PageStep only depends on the viewport height.
190         verticalScrollBar()->setPageStep(viewport()->height());
191
192         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
193                 << "\n Area width\t" << width()
194                 << "\n Area height\t" << height()
195                 << "\n viewport width\t" << viewport()->width()
196                 << "\n viewport height\t" << viewport()->height()
197                 << endl;
198
199         if (USE_EVENT_PRUNING) {
200                 // This is the keyboard buffering stuff...
201                 // I don't see any need for this under windows. The keyboard is reactive
202                 // enough...
203
204                 if ( !QObject::connect(&step_timer_, SIGNAL(timeout()),
205                         this, SLOT(keyeventTimeout())) )
206                         lyxerr[Debug::GUI] << "ERROR: keyeventTimeout cannot connect!" << endl;
207
208                 // Start the timer, one-shot.
209                 step_timer_.setSingleShot(true);
210                 step_timer_.start(50);
211         }
212
213         // Enables input methods for asian languages.
214         // Must be set when creating custom text editing widgets.
215         setAttribute(Qt::WA_InputMethodEnabled, true);
216 }
217
218
219 void GuiWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
220 {
221         verticalScrollBar()->setTracking(false);
222
223         // do what cursor movement does (some grey)
224         h += height() / 4;
225         int scroll_max_ = std::max(0, h - height());
226
227         verticalScrollBar()->setRange(0, scroll_max_);
228         verticalScrollBar()->setSliderPosition(scroll_pos);
229         verticalScrollBar()->setSingleStep(scroll_line_step);
230         verticalScrollBar()->setValue(scroll_pos);
231
232         verticalScrollBar()->setTracking(true);
233 }
234
235
236 void GuiWorkArea::adjustViewWithScrollBar(int)
237 {
238         scrollBufferView(verticalScrollBar()->sliderPosition());
239 }
240
241
242 void GuiWorkArea::dragEnterEvent(QDragEnterEvent * event)
243 {
244         if (event->mimeData()->hasUrls())
245                 event->accept();
246         /// \todo Ask lyx-devel is this is enough:
247         /// if (event->mimeData()->hasFormat("text/plain"))
248         ///     event->acceptProposedAction();
249 }
250
251
252 void GuiWorkArea::dropEvent(QDropEvent* event)
253 {
254         QList<QUrl> files = event->mimeData()->urls();
255         if (files.isEmpty())
256                 return;
257
258         lyxerr[Debug::GUI] << "GuiWorkArea::dropEvent: got URIs!" << endl;
259         for (int i = 0; i!=files.size(); ++i) {
260                 string const file = os::internal_path(fromqstr(files.at(i).toLocalFile()));
261                 if (!file.empty())
262                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
263         }
264 }
265
266
267 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
268 {
269         // No need to do anything if we didn't change views...
270         if (&lyx_view_ == &theApp->currentView())
271                 return;
272
273         theApp->setCurrentView(lyx_view_);
274
275         // FIXME: it would be better to send a signal "newBuffer()"
276         // in BufferList that could be connected to the different tabbars.
277         lyx_view_.updateTab();
278
279         startBlinkingCursor();
280
281         //FIXME: Use case: Two windows share the same buffer.
282         // The first window is resize. This modify the inner Buffer
283         // structure because Paragraph has a notion of line break and
284         // thus line width (this is very bad!).
285         // When switching to the other window which does not have the
286         // same size, LyX crashes because the line break is not adapted
287         // the this BufferView width.
288         // The following line fix the crash by resizing the BufferView 
289         // on a focusInEvent(). That is not a good fix but it is a fix
290         // nevertheless. The bad side effect is that when the two
291         // BufferViews show the same portion of the Buffer, the second 
292         // BufferView will show the same line breaks as the first one;
293         // even though those line breaks are not adapted to the second
294         // BufferView width... such is life!
295         resizeBufferView();
296 }
297
298
299 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
300 {
301         // No need to do anything if we didn't change views...
302         if (&lyx_view_ == &theApp->currentView())
303                 return;
304
305         stopBlinkingCursor();
306 }
307
308
309 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
310 {
311         if (dc_event_.active && dc_event_ == *e) {
312                 dc_event_.active = false;
313                 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
314                         dc_event_.x, dc_event_.y,
315                         q_button_state(dc_event_.state));
316                 dispatch(cmd);
317                 return;
318         }
319
320         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
321                               q_button_state(e->button()));
322         dispatch(cmd);
323 }
324
325
326 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
327 {
328         if (synthetic_mouse_event_.timeout.running())
329                 synthetic_mouse_event_.timeout.stop();
330
331         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
332                               q_button_state(e->button()));
333         dispatch(cmd);
334 }
335
336
337 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
338 {
339         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
340                               q_motion_state(e->buttons()));
341
342         // If we're above or below the work area...
343         if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
344                 // Make sure only a synthetic event can cause a page scroll,
345                 // so they come at a steady rate:
346                 if (e->y() <= 20)
347                         // _Force_ a scroll up:
348                         cmd.y = -40;
349                 else
350                         cmd.y = viewport()->height();
351                 // Store the event, to be handled when the timeout expires.
352                 synthetic_mouse_event_.cmd = cmd;
353
354                 if (synthetic_mouse_event_.timeout.running())
355                         // Discard the event. Note that it _may_ be handled
356                         // when the timeout expires if
357                         // synthetic_mouse_event_.cmd has not been overwritten.
358                         // Ie, when the timeout expires, we handle the
359                         // most recent event but discard all others that
360                         // occurred after the one used to start the timeout
361                         // in the first place.
362                         return;
363                 else {
364                         synthetic_mouse_event_.restart_timeout = true;
365                         synthetic_mouse_event_.timeout.start();
366                         // Fall through to handle this event...
367                 }
368
369         } else if (synthetic_mouse_event_.timeout.running()) {
370                 // Store the event, to be possibly handled when the timeout
371                 // expires.
372                 // Once the timeout has expired, normal control is returned
373                 // to mouseMoveEvent (restart_timeout = false).
374                 // This results in a much smoother 'feel' when moving the
375                 // mouse back into the work area.
376                 synthetic_mouse_event_.cmd = cmd;
377                 synthetic_mouse_event_.restart_timeout = false;
378                 return;
379         }
380
381         // Has anything changed on-screen since the last QMouseEvent
382         // was received?
383         double const scrollbar_value = verticalScrollBar()->value();
384         if (e->x() != synthetic_mouse_event_.x_old ||
385             e->y() != synthetic_mouse_event_.y_old ||
386             scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
387                 // Yes it has. Store the params used to check this.
388                 synthetic_mouse_event_.x_old = e->x();
389                 synthetic_mouse_event_.y_old = e->y();
390                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
391
392                 // ... and dispatch the event to the LyX core.
393                 dispatch(cmd);
394         }
395 }
396
397
398 void GuiWorkArea::wheelEvent(QWheelEvent * e)
399 {
400         // Wheel rotation by one notch results in a delta() of 120 (see
401         // documentation of QWheelEvent)
402         int const lines = qApp->wheelScrollLines() * e->delta() / 120;
403         verticalScrollBar()->setValue(verticalScrollBar()->value() -
404                         lines *  verticalScrollBar()->singleStep());
405         adjustViewWithScrollBar();
406 }
407
408
409 void GuiWorkArea::generateSyntheticMouseEvent()
410 {
411 // Set things off to generate the _next_ 'pseudo' event.
412         if (synthetic_mouse_event_.restart_timeout)
413                 synthetic_mouse_event_.timeout.start();
414
415         // Has anything changed on-screen since the last timeout signal
416         // was received?
417         double const scrollbar_value = verticalScrollBar()->value();
418         if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
419                 // Yes it has. Store the params used to check this.
420                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
421
422                 // ... and dispatch the event to the LyX core.
423                 dispatch(synthetic_mouse_event_.cmd);
424         }
425 }
426
427
428 void GuiWorkArea::keyPressEvent(QKeyEvent * e)
429 {
430         lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
431                 << " count=" << e->count()
432                 << " text=" << fromqstr(e->text())
433                 << " isAutoRepeat=" << e->isAutoRepeat()
434                 << " key=" << e->key()
435                 << endl;
436
437         if (USE_EVENT_PRUNING) {
438                 keyeventQueue_.push(boost::shared_ptr<QKeyEvent>(new QKeyEvent(*e)));
439         }
440         else {
441                 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
442                 sym->set(e);
443                 processKeySym(sym, q_key_state(e->modifiers()));
444         }
445 }
446
447
448 // This is used only if USE_EVENT_PRUNING is defined...
449 void GuiWorkArea::keyeventTimeout()
450 {
451         bool handle_autos = true;
452
453         while (!keyeventQueue_.empty()) {
454                 boost::shared_ptr<QKeyEvent> ev = keyeventQueue_.front();
455
456                 // We never handle more than one auto repeated
457                 // char in a list of queued up events.
458                 if (!handle_autos && ev->isAutoRepeat()) {
459                         keyeventQueue_.pop();
460                         continue;
461                 }
462
463                 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
464                 sym->set(ev.get());
465
466                 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
467                                    << " count=" << ev->count()
468                                    << " text=" <<  fromqstr(ev->text())
469                                    << " isAutoRepeat=" << ev->isAutoRepeat()
470                                    << " key=" << ev->key()
471                                    << endl;
472
473                 processKeySym(sym, q_key_state(ev->modifiers()));
474                 keyeventQueue_.pop();
475
476                 handle_autos = false;
477         }
478
479         // Restart the timer.
480         step_timer_.setSingleShot(true);
481         step_timer_.start(25);
482 }
483
484
485 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
486 {
487         dc_event_ = double_click(e);
488
489         if (!dc_event_.active)
490                 return;
491
492         dc_event_.active = false;
493
494         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
495                 dc_event_.x, dc_event_.y,
496                 q_button_state(dc_event_.state));
497         dispatch(cmd);
498 }
499
500
501 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
502 {
503         stopBlinkingCursor();
504         screen_ = QPixmap(ev->size().width(), ev->size().height());
505         verticalScrollBar()->setPageStep(viewport()->height());
506         QAbstractScrollArea::resizeEvent(ev);
507         resizeBufferView();
508         startBlinkingCursor();
509 }
510
511
512 void GuiWorkArea::update(int x, int y, int w, int h)
513 {
514         viewport()->update(x, y, w, h);
515 }
516
517
518 void GuiWorkArea::doGreyOut(QLPainter & pain)
519 {
520         pain.fillRectangle(0, 0, width(), height(),
521                 LColor::bottomarea);
522
523         //if (!lyxrc.show_banner)
524         //      return;
525         lyxerr << "show banner: " << lyxrc.show_banner << endl;
526         /// The text to be written on top of the pixmap
527         string const text = lyx_version ? lyx_version : "unknown";
528         string const file = support::libFileSearch("images", "banner", "ppm");
529         if (file.empty())
530                 return;
531
532         QPixmap pm(toqstr(file));
533         if (!pm) {
534                 lyxerr << "could not load splash screen: '" << file << "'" << endl;
535                 return;
536         }
537
538         QFont font;
539         // The font used to display the version info
540         font.setStyleHint(QFont::SansSerif);
541         font.setWeight(QFont::Bold);
542         font.setPointSize(LyXFont::SIZE_NORMAL);
543
544         int const w = pm.width();
545         int const h = pm.height();
546
547         int x = (width() - w) / 2;
548         int y = (height() - h) / 2;
549
550         pain.drawPixmap(x, y, pm);
551
552         x += 260;
553         y += 265;
554
555         pain.setPen(QColor(255, 255, 0));
556         pain.setFont(font);
557         pain.drawText(x, y, toqstr(text));
558 }
559
560
561 void GuiWorkArea::paintEvent(QPaintEvent * ev)
562 {
563         QRect const rc = ev->rect(); 
564         lyxerr[Debug::PAINTING] << "paintEvent begin: x: " << rc.x()
565                 << " y: " << rc.y()
566                 << " w: " << rc.width()
567                 << " h: " << rc.height() << endl;
568
569         QPainter pain(viewport());
570         pain.drawPixmap(rc, screen_, rc);
571         cursor_->draw(pain);
572 }
573
574
575 void GuiWorkArea::expose(int x, int y, int w, int h)
576 {
577         QLPainter pain(&screen_);
578
579         if (greyed_out_) {
580                 lyxerr << "splash screen requested" << endl;
581                 doGreyOut(pain);
582                 verticalScrollBar()->hide();
583                 update(0, 0, width(), height());
584                 return;
585         }
586
587         verticalScrollBar()->show();
588         paintText(*buffer_view_, pain);
589         update(x, y, w, h);
590 }
591
592
593 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
594 {
595         cursor_->update(x, y, h, shape);
596         cursor_->show();
597         viewport()->update(cursor_->rect());
598 }
599
600
601 void GuiWorkArea::removeCursor()
602 {
603         cursor_->hide();
604         //if (!qApp->focusWidget())
605                 viewport()->update(cursor_->rect());
606 }
607
608
609 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
610 {
611         QString const & text = e->commitString();
612         if (!text.isEmpty()) {
613
614                 lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
615                         << " preeditString =" << fromqstr(e->preeditString())
616                         << " commitString  =" << fromqstr(e->commitString())
617                         << endl;
618
619                 int key = 0;
620                 // needed to make math superscript work on some systems
621                 // ideally, such special coding should not be necessary
622                 if (text == "^")
623                         key = Qt::Key_AsciiCircum;
624                 // FIXME: Needs for investigation, this key is not really used,
625                 // the ctor below just check if key is different from 0.
626                 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, text);
627                 keyPressEvent(&ev);
628         }
629         e->accept();
630 }
631
632 } // namespace frontend
633 } // namespace lyx
634
635 #include "GuiWorkArea_moc.cpp"