]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.C
* src/frontends/qt4/GuiWorkArea.[Ch]:
[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 "gettext.h"
22 #include "LyXView.h"
23
24 #include "BufferView.h"
25 #include "rowpainter.h"
26 #include "debug.h"
27 #include "funcrequest.h"
28 #include "LColor.h"
29 #include "version.h"
30 #include "lyxrc.h"
31
32 #include "support/filetools.h" // LibFileSearch
33 #include "support/os.h"
34 #include "support/convert.h"
35
36 #include "graphics/GraphicsImage.h"
37 #include "graphics/GraphicsLoader.h"
38
39 #include <QLayout>
40 #include <QMainWindow>
41 #include <QMimeData>
42 #include <QUrl>
43 #include <QDragEnterEvent>
44 #include <QPainter>
45 #include <QScrollBar>
46 #include <QTimer>
47
48 #include <boost/bind.hpp>
49 #include <boost/current_function.hpp>
50
51 #ifdef Q_WS_WIN
52 int const CursorWidth = 2;
53 #else
54 int const CursorWidth = 1;
55 #endif
56
57
58 using std::endl;
59 using std::string;
60
61 namespace os = lyx::support::os;
62
63
64 namespace lyx {
65
66 using support::FileName;
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 = true) { show_ = set_show; }
138         void hide() { show_ = false; }
139
140         QRect const & rect() { return rect_; }
141
142 private:
143         ///
144         CursorShape shape_;
145         ///
146         bool show_;
147         ///
148         QColor color_;
149         ///
150         QRect rect_;
151 };
152
153
154 // This is a 'heartbeat' generating synthetic mouse move events when the
155 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
156 SyntheticMouseEvent::SyntheticMouseEvent()
157         : timeout(200), restart_timeout(true),
158           x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
159 {}
160
161
162 GuiWorkArea::GuiWorkArea(int w, int h, int id, LyXView & lyx_view)
163         : WorkArea(id, lyx_view), need_resize_(false), schedule_redraw_(false)
164 {
165         screen_ = QPixmap(viewport()->width(), viewport()->height());
166         cursor_ = new frontend::CursorWidget();
167         cursor_->hide();
168
169         setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
170         setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
171         setAcceptDrops(true);
172         setMouseTracking(true);
173         setMinimumSize(100, 70);
174
175         viewport()->setAutoFillBackground(false);
176         // We don't need double-buffering nor SystemBackground on
177         // the viewport because we have our own backing pixmap.
178         viewport()->setAttribute(Qt::WA_NoSystemBackground);
179
180         setFocusPolicy(Qt::WheelFocus);
181
182         viewport()->setCursor(Qt::IBeamCursor);
183
184         resize(w, h);
185
186         synthetic_mouse_event_.timeout.timeout.connect(
187                 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
188                             this));
189
190         // Initialize the vertical Scroll Bar
191         QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
192                 this, SLOT(adjustViewWithScrollBar(int)));
193
194         // disable context menu for the scrollbar
195         verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu);
196
197         // PageStep only depends on the viewport height.
198         verticalScrollBar()->setPageStep(viewport()->height());
199
200         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
201                 << "\n Area width\t" << width()
202                 << "\n Area height\t" << height()
203                 << "\n viewport width\t" << viewport()->width()
204                 << "\n viewport height\t" << viewport()->height()
205                 << endl;
206
207         // Enables input methods for asian languages.
208         // Must be set when creating custom text editing widgets.
209         setAttribute(Qt::WA_InputMethodEnabled, true);
210 }
211
212
213 void GuiWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
214 {
215         if (verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOn)
216                 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
217
218         verticalScrollBar()->setTracking(false);
219
220         // do what cursor movement does (some grey)
221         h += height() / 4;
222         int scroll_max_ = std::max(0, h - height());
223
224         verticalScrollBar()->setRange(0, scroll_max_);
225         verticalScrollBar()->setSliderPosition(scroll_pos);
226         verticalScrollBar()->setSingleStep(scroll_line_step);
227         verticalScrollBar()->setValue(scroll_pos);
228
229         verticalScrollBar()->setTracking(true);
230 }
231
232
233 void GuiWorkArea::adjustViewWithScrollBar(int)
234 {
235         scrollBufferView(verticalScrollBar()->sliderPosition());
236 }
237
238
239 void GuiWorkArea::dragEnterEvent(QDragEnterEvent * event)
240 {
241         if (event->mimeData()->hasUrls())
242                 event->accept();
243         /// \todo Ask lyx-devel is this is enough:
244         /// if (event->mimeData()->hasFormat("text/plain"))
245         ///     event->acceptProposedAction();
246 }
247
248
249 void GuiWorkArea::dropEvent(QDropEvent* event)
250 {
251         QList<QUrl> files = event->mimeData()->urls();
252         if (files.isEmpty())
253                 return;
254
255         lyxerr[Debug::GUI] << "GuiWorkArea::dropEvent: got URIs!" << endl;
256         for (int i = 0; i!=files.size(); ++i) {
257                 string const file = os::internal_path(fromqstr(files.at(i).toLocalFile()));
258                 if (!file.empty())
259                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
260         }
261 }
262
263
264 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
265 {
266         // No need to do anything if we didn't change views...
267 //      if (theApp() == 0 || &lyx_view_ == theApp()->currentView())
268 //              return;
269
270         theApp()->setCurrentView(lyx_view_);
271
272         // Repaint the whole screen.
273         // Note: this is different from redraw() as only the backing pixmap
274         // will be redrawn, which is cheap.
275         viewport()->repaint();
276
277         // FIXME: it would be better to send a signal "newBuffer()"
278         // in BufferList that could be connected to the different tabbars.
279         lyx_view_.updateTab();
280
281         startBlinkingCursor();
282 }
283
284
285 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
286 {
287         stopBlinkingCursor();
288 }
289
290
291 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
292 {
293         if (dc_event_.active && dc_event_ == *e) {
294                 dc_event_.active = false;
295                 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
296                         e->x(), e->y(),
297                         q_button_state(e->button()));
298                 dispatch(cmd);
299                 return;
300         }
301
302         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
303                 q_button_state(e->button()));
304         dispatch(cmd, q_key_state(e->modifiers()));
305 }
306
307
308 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
309 {
310         if (synthetic_mouse_event_.timeout.running())
311                 synthetic_mouse_event_.timeout.stop();
312
313         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
314                               q_button_state(e->button()));
315         dispatch(cmd);
316 }
317
318
319 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
320 {
321         //we kill the triple click if we move
322         doubleClickTimeout();
323         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
324                               q_motion_state(e->buttons()));
325
326         // If we're above or below the work area...
327         if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
328                 // Make sure only a synthetic event can cause a page scroll,
329                 // so they come at a steady rate:
330                 if (e->y() <= 20)
331                         // _Force_ a scroll up:
332                         cmd.y = -40;
333                 else
334                         cmd.y = viewport()->height();
335                 // Store the event, to be handled when the timeout expires.
336                 synthetic_mouse_event_.cmd = cmd;
337
338                 if (synthetic_mouse_event_.timeout.running())
339                         // Discard the event. Note that it _may_ be handled
340                         // when the timeout expires if
341                         // synthetic_mouse_event_.cmd has not been overwritten.
342                         // Ie, when the timeout expires, we handle the
343                         // most recent event but discard all others that
344                         // occurred after the one used to start the timeout
345                         // in the first place.
346                         return;
347                 else {
348                         synthetic_mouse_event_.restart_timeout = true;
349                         synthetic_mouse_event_.timeout.start();
350                         // Fall through to handle this event...
351                 }
352
353         } else if (synthetic_mouse_event_.timeout.running()) {
354                 // Store the event, to be possibly handled when the timeout
355                 // expires.
356                 // Once the timeout has expired, normal control is returned
357                 // to mouseMoveEvent (restart_timeout = false).
358                 // This results in a much smoother 'feel' when moving the
359                 // mouse back into the work area.
360                 synthetic_mouse_event_.cmd = cmd;
361                 synthetic_mouse_event_.restart_timeout = false;
362                 return;
363         }
364
365         // Has anything changed on-screen since the last QMouseEvent
366         // was received?
367         double const scrollbar_value = verticalScrollBar()->value();
368         if (e->x() != synthetic_mouse_event_.x_old ||
369             e->y() != synthetic_mouse_event_.y_old ||
370             scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
371                 // Yes it has. Store the params used to check this.
372                 synthetic_mouse_event_.x_old = e->x();
373                 synthetic_mouse_event_.y_old = e->y();
374                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
375
376                 // ... and dispatch the event to the LyX core.
377                 dispatch(cmd);
378         }
379 }
380
381
382 void GuiWorkArea::wheelEvent(QWheelEvent * e)
383 {
384         // Wheel rotation by one notch results in a delta() of 120 (see
385         // documentation of QWheelEvent)
386         int const lines = qApp->wheelScrollLines() * e->delta() / 120;
387         verticalScrollBar()->setValue(verticalScrollBar()->value() -
388                         lines *  verticalScrollBar()->singleStep());
389         adjustViewWithScrollBar();
390 }
391
392
393 void GuiWorkArea::generateSyntheticMouseEvent()
394 {
395 // Set things off to generate the _next_ 'pseudo' event.
396         if (synthetic_mouse_event_.restart_timeout)
397                 synthetic_mouse_event_.timeout.start();
398
399         // Has anything changed on-screen since the last timeout signal
400         // was received?
401         double const scrollbar_value = verticalScrollBar()->value();
402         if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
403                 // Yes it has. Store the params used to check this.
404                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
405
406                 // ... and dispatch the event to the LyX core.
407                 dispatch(synthetic_mouse_event_.cmd);
408         }
409 }
410
411
412 void GuiWorkArea::keyPressEvent(QKeyEvent * e)
413 {
414         lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
415                 << " count=" << e->count()
416                 << " text=" << fromqstr(e->text())
417                 << " isAutoRepeat=" << e->isAutoRepeat()
418                 << " key=" << e->key()
419                 << endl;
420
421         boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
422         sym->set(e);
423         processKeySym(sym, q_key_state(e->modifiers()));
424 }
425
426 void GuiWorkArea::doubleClickTimeout() {
427         dc_event_.active = false;
428 }
429
430 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
431 {
432         dc_event_ = double_click(e);
433         QTimer::singleShot(QApplication::doubleClickInterval(), this, SLOT(doubleClickTimeout()));
434         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
435                                                                         e->x(), e->y(), 
436                                                                                          q_button_state(e->button()));
437         dispatch(cmd);
438 }
439
440
441 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
442 {
443         QAbstractScrollArea::resizeEvent(ev);
444         need_resize_ = true;
445 }
446
447
448 void GuiWorkArea::update(int x, int y, int w, int h)
449 {
450         viewport()->repaint(x, y, w, h);
451 }
452
453
454 void GuiWorkArea::doGreyOut(QLPainter & pain)
455 {
456         pain.fillRectangle(0, 0, width(), height(),
457                 LColor::bottomarea);
458
459         //if (!lyxrc.show_banner)
460         //      return;
461         lyxerr[Debug::GUI] << "show banner: " << lyxrc.show_banner << endl;
462         /// The text to be written on top of the pixmap
463         QString const text = lyx_version ? QString(lyx_version) : qt_("unknown version");
464         FileName const file = support::libFileSearch("images", "banner", "ppm");
465         if (file.empty())
466                 return;
467
468         QPixmap pm(toqstr(file.absFilename()));
469         if (!pm) {
470                 lyxerr << "could not load splash screen: '" << file << "'" << endl;
471                 return;
472         }
473
474         QFont font;
475         // The font used to display the version info
476         font.setStyleHint(QFont::SansSerif);
477         font.setWeight(QFont::Bold);
478         font.setPointSize(convert<int>(lyxrc.font_sizes[LyXFont::SIZE_LARGE]));
479
480         int const w = pm.width();
481         int const h = pm.height();
482
483         int x = (width() - w) / 2;
484         int y = (height() - h) / 2;
485
486         pain.drawPixmap(x, y, pm);
487
488         x += 300;
489         y += 265;
490
491         pain.setPen(QColor(255, 255, 0));
492         pain.setFont(font);
493         pain.drawText(x, y, text);
494 }
495
496
497 void GuiWorkArea::paintEvent(QPaintEvent * ev)
498 {
499         QRect const rc = ev->rect(); 
500         /*
501         lyxerr[Debug::PAINTING] << "paintEvent begin: x: " << rc.x()
502                 << " y: " << rc.y()
503                 << " w: " << rc.width()
504                 << " h: " << rc.height() << endl;
505         */
506
507         if (need_resize_) {
508                 verticalScrollBar()->setPageStep(viewport()->height());
509                 screen_ = QPixmap(viewport()->width(), viewport()->height());
510                 resizeBufferView();
511                 updateScreen();
512                 need_resize_ = false;
513         }
514
515         QPainter pain(viewport());
516         pain.drawPixmap(rc, screen_, rc);
517         cursor_->draw(pain);
518 }
519
520
521 void GuiWorkArea::expose(int x, int y, int w, int h)
522 {
523         updateScreen();
524         update(x, y, w, h);
525 }
526
527
528 void GuiWorkArea::updateScreen()
529 {
530         QLPainter pain(&screen_);
531
532         if (greyed_out_) {
533                 lyxerr[Debug::GUI] << "splash screen requested" << endl;
534                 verticalScrollBar()->hide();
535                 doGreyOut(pain);
536                 return;
537         }
538
539         verticalScrollBar()->show();
540         paintText(*buffer_view_, pain);
541 }
542
543
544 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
545 {
546         if (schedule_redraw_) {
547                 if (buffer_view_ && buffer_view_->buffer()) {
548                         buffer_view_->update(Update::Force);
549                         updateScreen();
550                         viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
551                 }
552                 schedule_redraw_ = false;
553                 // Show the cursor immediately after the update.
554                 hideCursor();
555                 toggleCursor();
556                 return;
557         }
558
559         cursor_->update(x, y, h, shape);
560         cursor_->show();
561         viewport()->update(cursor_->rect());
562 }
563
564
565 void GuiWorkArea::removeCursor()
566 {
567         cursor_->hide();
568         //if (!qApp->focusWidget())
569                 viewport()->update(cursor_->rect());
570 }
571
572
573 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
574 {
575         QString const & text = e->commitString();
576         if (!text.isEmpty()) {
577
578                 lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
579                         << " preeditString =" << fromqstr(e->preeditString())
580                         << " commitString  =" << fromqstr(e->commitString())
581                         << endl;
582
583                 int key = 0;
584
585                 // FIXME Abdel 10/02/07: Remove?
586                 // needed to make math superscript work on some systems
587                 // ideally, such special coding should not be necessary
588                 if (text == "^")
589                         key = Qt::Key_AsciiCircum;
590
591                 // FIXME Abdel 10/02/07: Minimal support for CJK, aka systems
592                 // with input methods. What should we do with e->preeditString()?
593                 // Do we need an inputMethodQuery() method?
594                 // FIXME 2: we should take care also of UTF16 surrogates here.
595                 for (int i = 0; i < text.size(); ++i) {
596                         // FIXME: Needs for investigation, this key is not really used,
597                         // the ctor below just check if key is different from 0.
598                         QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, text[i]);
599                         keyPressEvent(&ev);
600                 }
601         }
602         e->accept();
603 }
604
605 } // namespace frontend
606 } // namespace lyx
607
608 #include "GuiWorkArea_moc.cpp"