]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.C
0d28ddac1a432bf178194a2a91c5a3995f110368
[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,
434                            SLOT(doubleClickTimeout()));
435         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
436                         e->x(), e->y(),
437                         q_button_state(e->button()));
438         dispatch(cmd);
439 }
440
441
442 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
443 {
444         QAbstractScrollArea::resizeEvent(ev);
445         need_resize_ = true;
446 }
447
448
449 void GuiWorkArea::update(int x, int y, int w, int h)
450 {
451         viewport()->repaint(x, y, w, h);
452 }
453
454
455 void GuiWorkArea::doGreyOut(QLPainter & pain)
456 {
457         pain.fillRectangle(0, 0, width(), height(),
458                 LColor::bottomarea);
459
460         //if (!lyxrc.show_banner)
461         //      return;
462         lyxerr[Debug::GUI] << "show banner: " << lyxrc.show_banner << endl;
463         /// The text to be written on top of the pixmap
464         QString const text = lyx_version ? QString(lyx_version) : qt_("unknown version");
465         FileName const file = support::libFileSearch("images", "banner", "ppm");
466         if (file.empty())
467                 return;
468
469         QPixmap pm(toqstr(file.absFilename()));
470         if (!pm) {
471                 lyxerr << "could not load splash screen: '" << file << "'" << endl;
472                 return;
473         }
474
475         QFont font;
476         // The font used to display the version info
477         font.setStyleHint(QFont::SansSerif);
478         font.setWeight(QFont::Bold);
479         font.setPointSize(convert<int>(lyxrc.font_sizes[LyXFont::SIZE_LARGE]));
480
481         int const w = pm.width();
482         int const h = pm.height();
483
484         int x = (width() - w) / 2;
485         int y = (height() - h) / 2;
486
487         pain.drawPixmap(x, y, pm);
488
489         x += 300;
490         y += 265;
491
492         pain.setPen(QColor(255, 255, 0));
493         pain.setFont(font);
494         pain.drawText(x, y, text);
495 }
496
497
498 void GuiWorkArea::paintEvent(QPaintEvent * ev)
499 {
500         QRect const rc = ev->rect(); 
501         /*
502         lyxerr[Debug::PAINTING] << "paintEvent begin: x: " << rc.x()
503                 << " y: " << rc.y()
504                 << " w: " << rc.width()
505                 << " h: " << rc.height() << endl;
506         */
507
508         if (need_resize_) {
509                 verticalScrollBar()->setPageStep(viewport()->height());
510                 screen_ = QPixmap(viewport()->width(), viewport()->height());
511                 resizeBufferView();
512                 updateScreen();
513                 need_resize_ = false;
514         }
515
516         QPainter pain(viewport());
517         pain.drawPixmap(rc, screen_, rc);
518         cursor_->draw(pain);
519 }
520
521
522 void GuiWorkArea::expose(int x, int y, int w, int h)
523 {
524         updateScreen();
525         update(x, y, w, h);
526 }
527
528
529 void GuiWorkArea::updateScreen()
530 {
531         QLPainter pain(&screen_);
532
533         if (greyed_out_) {
534                 lyxerr[Debug::GUI] << "splash screen requested" << endl;
535                 verticalScrollBar()->hide();
536                 doGreyOut(pain);
537                 return;
538         }
539
540         verticalScrollBar()->show();
541         paintText(*buffer_view_, pain);
542 }
543
544
545 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
546 {
547         if (schedule_redraw_) {
548                 if (buffer_view_ && buffer_view_->buffer()) {
549                         buffer_view_->update(Update::Force);
550                         updateScreen();
551                         viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
552                 }
553                 schedule_redraw_ = false;
554                 // Show the cursor immediately after the update.
555                 hideCursor();
556                 toggleCursor();
557                 return;
558         }
559
560         cursor_->update(x, y, h, shape);
561         cursor_->show();
562         viewport()->update(cursor_->rect());
563 }
564
565
566 void GuiWorkArea::removeCursor()
567 {
568         cursor_->hide();
569         //if (!qApp->focusWidget())
570                 viewport()->update(cursor_->rect());
571 }
572
573
574 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
575 {
576         QString const & text = e->commitString();
577         if (!text.isEmpty()) {
578
579                 lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
580                         << " preeditString =" << fromqstr(e->preeditString())
581                         << " commitString  =" << fromqstr(e->commitString())
582                         << endl;
583
584                 int key = 0;
585
586                 // FIXME Abdel 10/02/07: Remove?
587                 // needed to make math superscript work on some systems
588                 // ideally, such special coding should not be necessary
589                 if (text == "^")
590                         key = Qt::Key_AsciiCircum;
591
592                 // FIXME Abdel 10/02/07: Minimal support for CJK, aka systems
593                 // with input methods. What should we do with e->preeditString()?
594                 // Do we need an inputMethodQuery() method?
595                 // FIXME 2: we should take care also of UTF16 surrogates here.
596                 for (int i = 0; i < text.size(); ++i) {
597                         // FIXME: Needs for investigation, this key is not really used,
598                         // the ctor below just check if key is different from 0.
599                         QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, text[i]);
600                         keyPressEvent(&ev);
601                 }
602         }
603         e->accept();
604 }
605
606 } // namespace frontend
607 } // namespace lyx
608
609 #include "GuiWorkArea_moc.cpp"