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