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