]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.C
GuiWorkArea::inputMethodEvent(QInputMethodEvent * e):
[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 "QLPainter.h"
17 #include "QLyXKeySym.h"
18
19 #include "ColorCache.h"
20 #include "qt_helpers.h"
21 #include "Application.h"
22 #include "BufferView.h"
23 #include "debug.h"
24 #include "funcrequest.h"
25 #include "LColor.h"
26 #include "support/os.h"
27
28 #include <QLayout>
29 #include <QMainWindow>
30 #include <QMimeData>
31 #include <QUrl>
32 #include <QDragEnterEvent>
33 #include <QPixmap>
34 #include <QPainter>
35 #include <QScrollBar>
36
37 #include <boost/bind.hpp>
38 #include <boost/current_function.hpp>
39
40 // Abdel (26/06/2006):
41 // On windows-XP the UserGuide PageDown scroll test is faster without event pruning (16 s)
42 // than with it (23 s).
43 #ifdef Q_WS_WIN
44  #define USE_EVENT_PRUNING 0
45 #else
46  #define USE_EVENT_PRUNING 0
47 #endif
48
49 using std::endl;
50 using std::string;
51
52 namespace os = lyx::support::os;
53
54 namespace {
55
56 /// return the LyX key state from Qt's
57 key_modifier::state q_key_state(Qt::KeyboardModifiers state)
58 {
59         key_modifier::state k = key_modifier::none;
60         if (state & Qt::ControlModifier)
61                 k |= key_modifier::ctrl;
62         if (state & Qt::ShiftModifier)
63                 k |= key_modifier::shift;
64         if (state & Qt::AltModifier || state & Qt::MetaModifier)
65                 k |= key_modifier::alt;
66         return k;
67 }
68
69
70 /// return the LyX mouse button state from Qt's
71 mouse_button::state q_button_state(Qt::MouseButton button)
72 {
73         mouse_button::state b = mouse_button::none;
74         switch (button) {
75                 case Qt::LeftButton:
76                         b = mouse_button::button1;
77                         break;
78                 case Qt::MidButton:
79                         b = mouse_button::button2;
80                         break;
81                 case Qt::RightButton:
82                         b = mouse_button::button3;
83                         break;
84                 default:
85                         break;
86         }
87         return b;
88 }
89
90
91 /// return the LyX mouse button state from Qt's
92 mouse_button::state q_motion_state(Qt::MouseButton state)
93 {
94         mouse_button::state b = mouse_button::none;
95         if (state & Qt::LeftButton)
96                 b |= mouse_button::button1;
97         if (state & Qt::MidButton)
98                 b |= mouse_button::button2;
99         if (state & Qt::RightButton)
100                 b |= mouse_button::button3;
101         return b;
102 }
103
104 } // namespace anon
105
106 namespace lyx {
107 namespace frontend {
108
109 // This is a 'heartbeat' generating synthetic mouse move events when the
110 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
111 SyntheticMouseEvent::SyntheticMouseEvent()
112         : timeout(200), restart_timeout(true),
113           x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
114 {}
115
116
117 GuiWorkArea::GuiWorkArea(int w, int h, LyXView & lyx_view)
118 : WorkArea(lyx_view), painter_(this)
119 {
120         setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
121         setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
122
123         setAcceptDrops(true);
124
125         setMinimumSize(100, 70);
126
127         viewport()->setAutoFillBackground(false);
128         viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
129
130         viewport()->setFocusPolicy(Qt::WheelFocus);
131         viewport()->setFocus();
132         setFocusPolicy(Qt::WheelFocus);
133
134         viewport()->setCursor(Qt::IBeamCursor);
135
136         resize(w, h);
137         workWidth_ = w;
138         workHeight_ = h;
139
140         synthetic_mouse_event_.timeout.timeout.connect(
141                 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
142                             this));
143
144         // Initialize the vertical Scroll Bar
145         QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
146                 this, SLOT(adjustViewWithScrollBar(int)));
147
148         // PageStep only depends on the viewport height.
149         verticalScrollBar()->setPageStep(workHeight_);
150
151         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
152                 << "\n Area width\t" << width()
153                 << "\n Area height\t" << height()
154                 << "\n viewport width\t" << viewport()->width()
155                 << "\n viewport height\t" << viewport()->height()
156                 << endl;
157
158         if (USE_EVENT_PRUNING) {
159                 // This is the keyboard buffering stuff...
160                 // I don't see any need for this under windows. The keyboard is reactive
161                 // enough...
162
163                 if ( !QObject::connect(&step_timer_, SIGNAL(timeout()),
164                         this, SLOT(keyeventTimeout())) )
165                         lyxerr[Debug::GUI] << "ERROR: keyeventTimeout cannot connect!" << endl;
166
167                 // Start the timer, one-shot.
168                 step_timer_.setSingleShot(true);
169                 step_timer_.start(50);
170         }
171
172         // Enables input methods for asian languages.
173         // Must be set when creating custom text editing widgets.
174         setAttribute(Qt::WA_InputMethodEnabled, true);
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         workWidth_ = viewport()->width();
424         workHeight_ = viewport()->height();
425
426         verticalScrollBar()->setPageStep(viewport()->height());
427
428 //      screen_device_ = QPixmap(viewport()->width(), viewport()->height());
429 //      paint_device_ = QImage(viewport()->width(), viewport()->height(), QImage::Format_RGB32);
430         paint_device_ = QPixmap(viewport()->width(), viewport()->height());
431
432         resizeBufferView();
433
434         /*
435         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
436                 << "\n QWidget width\t" << this->QWidget::width()
437                 << "\n QWidget height\t" << this->QWidget::height()
438                 << "\n viewport width\t" << viewport()->width()
439                 << "\n viewport height\t" << viewport()->height()
440                 << "\n QResizeEvent rect left\t" << rect().left()
441                 << "\n QResizeEvent rect right\t" << rect().right()
442                 << endl;
443                 */
444 }
445
446
447 void GuiWorkArea::update(int x, int y, int w, int h)
448 {
449         //screen_device_.fromImage(paint_device_);
450         //QPainter q(&screen_device_);
451         //q.drawImage(x, y, paint_device_.copy(x, y, w, h));
452
453         viewport()->update(x, y, w, h);
454 }
455
456
457 void GuiWorkArea::paintEvent(QPaintEvent * e)
458 {
459         /*
460         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
461                 << "\n QWidget width\t" << this->width()
462                 << "\n QWidget height\t" << this->height()
463                 << "\n viewport width\t" << viewport()->width()
464                 << "\n viewport height\t" << viewport()->height()
465                 << "\n pixmap width\t" << pixmap_->width()
466                 << "\n pixmap height\t" << pixmap_->height()
467                 << "\n QPaintEvent x\t" << e->rect().x()
468                 << "\n QPaintEvent y\t" << e->rect().y()
469                 << "\n QPaintEvent w\t" << e->rect().width()
470                 << "\n QPaintEvent h\t" << e->rect().height()
471                 << endl;
472         */
473
474         QPainter q(viewport());
475         q.drawPixmap(e->rect(), paint_device_, e->rect());
476
477         if (show_vcursor_)
478                 q.drawPixmap(cursor_x_, cursor_y_, vcursor_);
479
480         if (show_hcursor_)
481                 q.drawPixmap(cursor_x_, cursor_y_ + cursor_h_ - 1, hcursor_);
482 }
483
484
485 QPixmap GuiWorkArea::copyScreen(int x, int y, int w, int h) const
486 {
487         return paint_device_.copy(x, y, w, h);
488 }
489
490
491 void GuiWorkArea::drawScreen(int x, int y, QPixmap pixmap)
492 {
493         QPainter q(&paint_device_);
494         q.drawPixmap(x, y, pixmap);
495         update(x, y, pixmap.width(), pixmap.height());
496 }
497
498
499 void GuiWorkArea::expose(int x, int y, int w, int h)
500 {
501         /*
502         if (x == 0 && y == 0 && w == viewport()->width() && h == viewport()->height()) {
503                 viewport()->repaint(x, y, w, h);
504                 return;
505         }
506         */
507
508         update(x, y, w, h);
509 }
510
511
512 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
513 {
514         if (!qApp->focusWidget())
515                 return;
516
517         show_vcursor_ = true;
518
519         QColor const & required_color = lcolorcache.get(LColor::cursor);
520
521         if (x==cursor_x_ && y==cursor_y_ && h==cursor_h_
522                 && cursor_color_ == required_color
523                 && cursor_shape_ == shape) {
524                 show_hcursor_ = lshape_cursor_;
525                 update(cursor_x_, cursor_y_, cursor_w_, cursor_h_);
526                 return;
527         }
528
529         // Cache the dimensions of the cursor.
530         cursor_x_ = x;
531         cursor_y_ = y;
532         cursor_h_ = h;
533         cursor_color_ = required_color;
534         cursor_shape_ = shape;
535
536         switch (cursor_shape_) {
537         case BAR_SHAPE:
538                 // FIXME the cursor width shouldn't be hard-coded!
539                 cursor_w_ = 2;
540                 lshape_cursor_ = false;
541                 break;
542         case L_SHAPE:
543                 cursor_w_ = cursor_h_ / 3;
544                 lshape_cursor_ = true;
545                 break;
546         case REVERSED_L_SHAPE:
547                 cursor_w_ = cursor_h_ / 3;
548                 cursor_x_ -= cursor_w_ - 1;
549                 lshape_cursor_ = true;
550                 break;
551         }
552
553         // We cache two pixmaps:
554         // 1 the vertical line of the cursor.
555         // 2 the horizontal line of the L-shaped cursor (if necessary).
556
557         // Draw the new (vertical) cursor.
558         vcursor_ = QPixmap(cursor_w_, cursor_h_);
559         vcursor_.fill(cursor_color_);
560
561         // Draw the new (horizontal) cursor if necessary.
562         if (lshape_cursor_) {
563                 hcursor_ = QPixmap(cursor_w_, 1);
564                 hcursor_.fill(cursor_color_);
565                 show_hcursor_ = true;
566         }
567
568         update(cursor_x_, cursor_y_, cursor_w_, cursor_h_);
569 }
570
571
572 void GuiWorkArea::removeCursor()
573 {
574         show_vcursor_ = false;
575         show_hcursor_ = false;
576
577         update(cursor_x_, cursor_y_, cursor_w_, cursor_h_);
578 }
579
580
581 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
582 {
583         QString const & text = e->commitString();
584         if (!text.isEmpty()) {
585
586                 lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
587                         << " preeditString =" << fromqstr(e->preeditString())
588                         << " commitString  =" << fromqstr(e->commitString())
589                         << endl;
590
591                 int key = 0;
592                 // needed to make math superscript work on some systems
593                 // ideally, such special coding should not be necessary
594                 if (text == "^")
595                         key = Qt::Key_AsciiCircum;
596                 QKeyEvent ev(QEvent::KeyPress, key,
597                         Qt::KeyboardModifiers(Qt::NoModifier), text);
598                 keyPressEvent(&ev);
599         }
600         e->accept();
601 }
602
603
604 } // namespace frontend
605 } // namespace lyx
606
607 #include "GuiWorkArea_moc.cpp"