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