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