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