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