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