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