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