]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.C
small cleanup: delete two unneeded lines of code.
[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 "Application.h"
17 #include "ColorCache.h"
18 #include "QLPainter.h"
19 #include "QLyXKeySym.h"
20 #include "qt_helpers.h"
21
22 #include "LyXView.h"
23
24 #include "BufferView.h"
25 #include "debug.h"
26 #include "funcrequest.h"
27 #include "LColor.h"
28
29 #include "support/os.h"
30
31 #include <QLayout>
32 #include <QMainWindow>
33 #include <QMimeData>
34 #include <QUrl>
35 #include <QDragEnterEvent>
36 #include <QPixmap>
37 #include <QPainter>
38 #include <QScrollBar>
39
40 #include <boost/bind.hpp>
41 #include <boost/current_function.hpp>
42
43 // Abdel (26/06/2006):
44 // On windows-XP the UserGuide PageDown scroll test is faster without event pruning (16 s)
45 // than with it (23 s).
46 #ifdef Q_WS_WIN
47  #define USE_EVENT_PRUNING 0
48 #else
49  #define USE_EVENT_PRUNING 0
50 #endif
51
52 using std::endl;
53 using std::string;
54
55 namespace os = lyx::support::os;
56
57 namespace {
58
59 /// return the LyX key state from Qt's
60 key_modifier::state q_key_state(Qt::KeyboardModifiers state)
61 {
62         key_modifier::state k = key_modifier::none;
63         if (state & Qt::ControlModifier)
64                 k |= key_modifier::ctrl;
65         if (state & Qt::ShiftModifier)
66                 k |= key_modifier::shift;
67         if (state & Qt::AltModifier || state & Qt::MetaModifier)
68                 k |= key_modifier::alt;
69         return k;
70 }
71
72
73 /// return the LyX mouse button state from Qt's
74 mouse_button::state q_button_state(Qt::MouseButton button)
75 {
76         mouse_button::state b = mouse_button::none;
77         switch (button) {
78                 case Qt::LeftButton:
79                         b = mouse_button::button1;
80                         break;
81                 case Qt::MidButton:
82                         b = mouse_button::button2;
83                         break;
84                 case Qt::RightButton:
85                         b = mouse_button::button3;
86                         break;
87                 default:
88                         break;
89         }
90         return b;
91 }
92
93
94 /// return the LyX mouse button state from Qt's
95 mouse_button::state q_motion_state(Qt::MouseButton state)
96 {
97         mouse_button::state b = mouse_button::none;
98         if (state & Qt::LeftButton)
99                 b |= mouse_button::button1;
100         if (state & Qt::MidButton)
101                 b |= mouse_button::button2;
102         if (state & Qt::RightButton)
103                 b |= mouse_button::button3;
104         return b;
105 }
106
107 } // namespace anon
108
109 namespace lyx {
110 namespace frontend {
111
112 // This is a 'heartbeat' generating synthetic mouse move events when the
113 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
114 SyntheticMouseEvent::SyntheticMouseEvent()
115         : timeout(200), restart_timeout(true),
116           x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
117 {}
118
119
120 GuiWorkArea::GuiWorkArea(int w, int h, LyXView & lyx_view)
121 : WorkArea(lyx_view), painter_(this)
122 {
123         setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
124         setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
125
126         setAcceptDrops(true);
127
128         setMinimumSize(100, 70);
129
130         viewport()->setAutoFillBackground(false);
131         viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
132         setFocusPolicy(Qt::WheelFocus);
133
134         viewport()->setCursor(Qt::IBeamCursor);
135
136         resize(w, h);
137
138         synthetic_mouse_event_.timeout.timeout.connect(
139                 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
140                             this));
141
142         // Initialize the vertical Scroll Bar
143         QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
144                 this, SLOT(adjustViewWithScrollBar(int)));
145
146         // PageStep only depends on the viewport height.
147         verticalScrollBar()->setPageStep(viewport()->height());
148
149         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
150                 << "\n Area width\t" << width()
151                 << "\n Area height\t" << height()
152                 << "\n viewport width\t" << viewport()->width()
153                 << "\n viewport height\t" << viewport()->height()
154                 << endl;
155
156         if (USE_EVENT_PRUNING) {
157                 // This is the keyboard buffering stuff...
158                 // I don't see any need for this under windows. The keyboard is reactive
159                 // enough...
160
161                 if ( !QObject::connect(&step_timer_, SIGNAL(timeout()),
162                         this, SLOT(keyeventTimeout())) )
163                         lyxerr[Debug::GUI] << "ERROR: keyeventTimeout cannot connect!" << endl;
164
165                 // Start the timer, one-shot.
166                 step_timer_.setSingleShot(true);
167                 step_timer_.start(50);
168         }
169
170         // Enables input methods for asian languages.
171         // Must be set when creating custom text editing widgets.
172         setAttribute(Qt::WA_InputMethodEnabled, true);
173 }
174
175
176 GuiWorkArea::~GuiWorkArea()
177 {
178 }
179
180
181 void GuiWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
182 {
183         verticalScrollBar()->setTracking(false);
184
185         // do what cursor movement does (some grey)
186         h += height() / 4;
187         int scroll_max_ = std::max(0, h - height());
188
189         verticalScrollBar()->setRange(0, scroll_max_);
190         verticalScrollBar()->setSliderPosition(scroll_pos);
191         verticalScrollBar()->setSingleStep(scroll_line_step);
192
193         verticalScrollBar()->setTracking(true);
194 }
195
196
197 void GuiWorkArea::adjustViewWithScrollBar(int)
198 {
199         scrollBufferView(verticalScrollBar()->sliderPosition());
200 }
201
202
203 void GuiWorkArea::dragEnterEvent(QDragEnterEvent * event)
204 {
205         if (event->mimeData()->hasUrls())
206                 event->accept();
207         /// \todo Ask lyx-devel is this is enough:
208         /// if (event->mimeData()->hasFormat("text/plain"))
209         ///     event->acceptProposedAction();
210 }
211
212
213 void GuiWorkArea::dropEvent(QDropEvent* event)
214 {
215         QList<QUrl> files = event->mimeData()->urls();
216         if (files.isEmpty())
217                 return;
218
219         lyxerr[Debug::GUI] << "GuiWorkArea::dropEvent: got URIs!" << endl;
220         for (int i = 0; i!=files.size(); ++i) {
221                 string const file = os::internal_path(fromqstr(files.at(i).toLocalFile()));
222                 if (!file.empty())
223                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
224         }
225 }
226
227
228 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
229 {
230         if (dc_event_.active && dc_event_ == *e) {
231                 dc_event_.active = false;
232                 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
233                         dc_event_.x, dc_event_.y,
234                         q_button_state(dc_event_.state));
235                 dispatch(cmd);
236                 return;
237         }
238
239         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
240                               q_button_state(e->button()));
241         dispatch(cmd);
242 }
243
244
245 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
246 {
247         if (synthetic_mouse_event_.timeout.running())
248                 synthetic_mouse_event_.timeout.stop();
249
250         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
251                               q_button_state(e->button()));
252         dispatch(cmd);
253 }
254
255
256 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
257 {
258         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
259                               q_motion_state(e->button()));
260
261         // If we're above or below the work area...
262         if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
263                 // Make sure only a synthetic event can cause a page scroll,
264                 // so they come at a steady rate:
265                 if (e->y() <= 20)
266                         // _Force_ a scroll up:
267                         cmd.y = -40;
268                 else
269                         cmd.y = viewport()->height();
270                 // Store the event, to be handled when the timeout expires.
271                 synthetic_mouse_event_.cmd = cmd;
272
273                 if (synthetic_mouse_event_.timeout.running())
274                         // Discard the event. Note that it _may_ be handled
275                         // when the timeout expires if
276                         // synthetic_mouse_event_.cmd has not been overwritten.
277                         // Ie, when the timeout expires, we handle the
278                         // most recent event but discard all others that
279                         // occurred after the one used to start the timeout
280                         // in the first place.
281                         return;
282                 else {
283                         synthetic_mouse_event_.restart_timeout = true;
284                         synthetic_mouse_event_.timeout.start();
285                         // Fall through to handle this event...
286                 }
287
288         } else if (synthetic_mouse_event_.timeout.running()) {
289                 // Store the event, to be possibly handled when the timeout
290                 // expires.
291                 // Once the timeout has expired, normal control is returned
292                 // to mouseMoveEvent (restart_timeout = false).
293                 // This results in a much smoother 'feel' when moving the
294                 // mouse back into the work area.
295                 synthetic_mouse_event_.cmd = cmd;
296                 synthetic_mouse_event_.restart_timeout = false;
297                 return;
298         }
299
300         // Has anything changed on-screen since the last QMouseEvent
301         // was received?
302         double const scrollbar_value = verticalScrollBar()->value();
303         if (e->x() != synthetic_mouse_event_.x_old ||
304             e->y() != synthetic_mouse_event_.y_old ||
305             scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
306                 // Yes it has. Store the params used to check this.
307                 synthetic_mouse_event_.x_old = e->x();
308                 synthetic_mouse_event_.y_old = e->y();
309                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
310
311                 // ... and dispatch the event to the LyX core.
312                 dispatch(cmd);
313         }
314 }
315
316
317 void GuiWorkArea::wheelEvent(QWheelEvent * e)
318 {
319         // Wheel rotation by one notch results in a delta() of 120 (see
320         // documentation of QWheelEvent)
321         int const lines = qApp->wheelScrollLines() * e->delta() / 120;
322         verticalScrollBar()->setValue(verticalScrollBar()->value() -
323                         lines *  verticalScrollBar()->singleStep());
324         adjustViewWithScrollBar();
325 }
326
327
328 void GuiWorkArea::generateSyntheticMouseEvent()
329 {
330 // Set things off to generate the _next_ 'pseudo' event.
331         if (synthetic_mouse_event_.restart_timeout)
332                 synthetic_mouse_event_.timeout.start();
333
334         // Has anything changed on-screen since the last timeout signal
335         // was received?
336         double const scrollbar_value = verticalScrollBar()->value();
337         if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
338                 // Yes it has. Store the params used to check this.
339                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
340
341                 // ... and dispatch the event to the LyX core.
342                 dispatch(synthetic_mouse_event_.cmd);
343         }
344 }
345
346
347 void GuiWorkArea::keyPressEvent(QKeyEvent * e)
348 {
349         lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
350                 << " count=" << e->count()
351                 << " text=" << fromqstr(e->text())
352                 << " isAutoRepeat=" << e->isAutoRepeat()
353                 << " key=" << e->key()
354                 << endl;
355
356         if (USE_EVENT_PRUNING) {
357                 keyeventQueue_.push(boost::shared_ptr<QKeyEvent>(new QKeyEvent(*e)));
358         }
359         else {
360                 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
361                 sym->set(e);
362                 processKeySym(sym, q_key_state(e->modifiers()));
363         }
364 }
365
366
367 // This is used only if USE_EVENT_PRUNING is defined...
368 void GuiWorkArea::keyeventTimeout()
369 {
370         bool handle_autos = true;
371
372         while (!keyeventQueue_.empty()) {
373                 boost::shared_ptr<QKeyEvent> ev = keyeventQueue_.front();
374
375                 // We never handle more than one auto repeated
376                 // char in a list of queued up events.
377                 if (!handle_autos && ev->isAutoRepeat()) {
378                         keyeventQueue_.pop();
379                         continue;
380                 }
381
382                 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
383                 sym->set(ev.get());
384
385                 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
386                                    << " count=" << ev->count()
387                                    << " text=" <<  fromqstr(ev->text())
388                                    << " isAutoRepeat=" << ev->isAutoRepeat()
389                                    << " key=" << ev->key()
390                                    << endl;
391
392                 processKeySym(sym, q_key_state(ev->modifiers()));
393                 keyeventQueue_.pop();
394
395                 handle_autos = false;
396         }
397
398         // Restart the timer.
399         step_timer_.setSingleShot(true);
400         step_timer_.start(25);
401 }
402
403
404 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
405 {
406         dc_event_ = double_click(e);
407
408         if (!dc_event_.active)
409                 return;
410
411         dc_event_.active = false;
412
413         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
414                 dc_event_.x, dc_event_.y,
415                 q_button_state(dc_event_.state));
416         dispatch(cmd);
417 }
418
419
420 void GuiWorkArea::resizeEvent(QResizeEvent *)
421 {
422         verticalScrollBar()->setPageStep(viewport()->height());
423         paint_device_ = QPixmap(viewport()->width(), viewport()->height());
424         resizeBufferView();
425 }
426
427
428 void GuiWorkArea::update(int x, int y, int w, int h)
429 {
430         viewport()->update(x, y, w, h);
431 }
432
433
434 void GuiWorkArea::paintEvent(QPaintEvent * e)
435 {
436         /*
437         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
438                 << "\n QWidget width\t" << this->width()
439                 << "\n QWidget height\t" << this->height()
440                 << "\n viewport width\t" << viewport()->width()
441                 << "\n viewport height\t" << viewport()->height()
442                 << "\n pixmap width\t" << pixmap_->width()
443                 << "\n pixmap height\t" << pixmap_->height()
444                 << "\n QPaintEvent x\t" << e->rect().x()
445                 << "\n QPaintEvent y\t" << e->rect().y()
446                 << "\n QPaintEvent w\t" << e->rect().width()
447                 << "\n QPaintEvent h\t" << e->rect().height()
448                 << endl;
449         */
450
451         QPainter q(viewport());
452         q.drawPixmap(e->rect(), paint_device_, e->rect());
453
454         if (show_vcursor_)
455                 q.drawPixmap(cursor_x_, cursor_y_, vcursor_);
456
457         if (show_hcursor_)
458                 q.drawPixmap(cursor_x_, cursor_y_ + cursor_h_ - 1, hcursor_);
459 }
460
461
462 QPixmap GuiWorkArea::copyScreen(int x, int y, int w, int h) const
463 {
464         return paint_device_.copy(x, y, w, h);
465 }
466
467
468 void GuiWorkArea::drawScreen(int x, int y, QPixmap pixmap)
469 {
470         QPainter q(&paint_device_);
471         q.drawPixmap(x, y, pixmap);
472         update(x, y, pixmap.width(), pixmap.height());
473 }
474
475
476 void GuiWorkArea::expose(int x, int y, int w, int h)
477 {
478         /*
479         if (x == 0 && y == 0 && w == viewport()->width() && h == viewport()->height()) {
480                 viewport()->repaint(x, y, w, h);
481                 return;
482         }
483         */
484
485         update(x, y, w, h);
486 }
487
488
489 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
490 {
491         if (!qApp->focusWidget())
492                 return;
493
494         show_vcursor_ = true;
495
496         QColor const & required_color = lcolorcache.get(LColor::cursor);
497
498         if (x==cursor_x_ && y==cursor_y_ && h==cursor_h_
499                 && cursor_color_ == required_color
500                 && cursor_shape_ == shape) {
501                 show_hcursor_ = lshape_cursor_;
502                 update(cursor_x_, cursor_y_, cursor_w_, cursor_h_);
503                 return;
504         }
505
506         // Cache the dimensions of the cursor.
507         cursor_x_ = x;
508         cursor_y_ = y;
509         cursor_h_ = h;
510         cursor_color_ = required_color;
511         cursor_shape_ = shape;
512
513         switch (cursor_shape_) {
514         case BAR_SHAPE:
515                 // FIXME the cursor width shouldn't be hard-coded!
516                 cursor_w_ = 2;
517                 lshape_cursor_ = false;
518                 break;
519         case L_SHAPE:
520                 cursor_w_ = cursor_h_ / 3;
521                 lshape_cursor_ = true;
522                 break;
523         case REVERSED_L_SHAPE:
524                 cursor_w_ = cursor_h_ / 3;
525                 cursor_x_ -= cursor_w_ - 1;
526                 lshape_cursor_ = true;
527                 break;
528         }
529
530         // We cache two pixmaps:
531         // 1 the vertical line of the cursor.
532         // 2 the horizontal line of the L-shaped cursor (if necessary).
533
534         // Draw the new (vertical) cursor.
535         vcursor_ = QPixmap(cursor_w_, cursor_h_);
536         vcursor_.fill(cursor_color_);
537
538         // Draw the new (horizontal) cursor if necessary.
539         if (lshape_cursor_) {
540                 hcursor_ = QPixmap(cursor_w_, 1);
541                 hcursor_.fill(cursor_color_);
542                 show_hcursor_ = true;
543         }
544
545         update(cursor_x_, cursor_y_, cursor_w_, cursor_h_);
546 }
547
548
549 void GuiWorkArea::removeCursor()
550 {
551         show_vcursor_ = false;
552         show_hcursor_ = false;
553
554         update(cursor_x_, cursor_y_, cursor_w_, cursor_h_);
555 }
556
557
558 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
559 {
560         QString const & text = e->commitString();
561         if (!text.isEmpty()) {
562
563                 lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
564                         << " preeditString =" << fromqstr(e->preeditString())
565                         << " commitString  =" << fromqstr(e->commitString())
566                         << endl;
567
568                 int key = 0;
569                 // needed to make math superscript work on some systems
570                 // ideally, such special coding should not be necessary
571                 if (text == "^")
572                         key = Qt::Key_AsciiCircum;
573                 // FIXME: Needs for investigation, this key is not really used,
574                 // the ctor below just check if key is different from 0.
575                 QKeyEvent ev(QEvent::KeyPress, key,
576                         Qt::NoModifier, text);
577                 keyPressEvent(&ev);
578         }
579         e->accept();
580 }
581
582
583 void GuiWorkArea::focusInEvent(QFocusEvent * ev)
584 {
585         QAbstractScrollArea::focusInEvent(ev);
586         lyx_view_.updateToolbars();
587 }
588
589
590 void GuiWorkArea::focusOutEvent(QFocusEvent * ev)
591 {
592         QAbstractScrollArea::focusOutEvent(ev);
593         lyx_view_.updateToolbars();
594 }
595
596 } // namespace frontend
597 } // namespace lyx
598
599 #include "GuiWorkArea_moc.cpp"