]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.cpp
The BufferView/WorkArea/LyXView reorg a.k.a Multiple WorkAreas:
[lyx.git] / src / frontends / qt4 / GuiWorkArea.cpp
1 /**
2  * \file GuiWorkArea.cpp
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 "QKeySymbol.h"
19 #include "qt_helpers.h"
20
21 #include "frontends/LyXView.h"
22
23 #include "BufferView.h"
24 #include "Color.h"
25 #include "debug.h"
26 #include "FuncRequest.h"
27 #include "LyXRC.h"
28 #include "rowpainter.h"
29 #include "version.h"
30
31 #include "support/filetools.h" // LibFileSearch
32 #include "support/convert.h"
33
34 #include "graphics/GraphicsImage.h"
35 #include "graphics/GraphicsLoader.h"
36
37 #include <QInputContext>
38 #include <QLayout>
39 #include <QMainWindow>
40 #include <QPainter>
41 #include <QScrollBar>
42 #include <QTimer>
43
44 #include <boost/bind.hpp>
45 #include <boost/current_function.hpp>
46
47 #ifdef Q_WS_X11
48 #include <QX11Info>
49 extern "C" int XEventsQueued(Display *display, int mode);
50 #endif
51
52 #ifdef Q_WS_WIN
53 int const CursorWidth = 2;
54 #else
55 int const CursorWidth = 1;
56 #endif
57
58 #undef KeyPress
59 #undef NoModifier 
60
61 using std::endl;
62 using std::string;
63
64 namespace lyx {
65
66 using support::FileName;
67
68 /// return the LyX mouse button state from Qt's
69 static mouse_button::state q_button_state(Qt::MouseButton button)
70 {
71         mouse_button::state b = mouse_button::none;
72         switch (button) {
73                 case Qt::LeftButton:
74                         b = mouse_button::button1;
75                         break;
76                 case Qt::MidButton:
77                         b = mouse_button::button2;
78                         break;
79                 case Qt::RightButton:
80                         b = mouse_button::button3;
81                         break;
82                 default:
83                         break;
84         }
85         return b;
86 }
87
88
89 /// return the LyX mouse button state from Qt's
90 mouse_button::state q_motion_state(Qt::MouseButtons state)
91 {
92         mouse_button::state b = mouse_button::none;
93         if (state & Qt::LeftButton)
94                 b |= mouse_button::button1;
95         if (state & Qt::MidButton)
96                 b |= mouse_button::button2;
97         if (state & Qt::RightButton)
98                 b |= mouse_button::button3;
99         return b;
100 }
101
102
103 namespace frontend {
104
105 class CursorWidget {
106 public:
107         CursorWidget() {}
108
109         void draw(QPainter & painter)
110         {
111                 if (show_ && rect_.isValid()) {
112                         switch (shape_) {
113                         case L_SHAPE:
114                                 painter.fillRect(rect_.x(), rect_.y(), CursorWidth, rect_.height(), color_);
115                                 painter.setPen(color_);
116                                 painter.drawLine(rect_.bottomLeft().x() + CursorWidth, rect_.bottomLeft().y(),
117                                                                                                  rect_.bottomRight().x(), rect_.bottomLeft().y());
118                                 break;
119                         
120                         case REVERSED_L_SHAPE:
121                                 painter.fillRect(rect_.x() + rect_.height() / 3, rect_.y(), CursorWidth, rect_.height(), color_);
122                                 painter.setPen(color_);
123                                 painter.drawLine(rect_.bottomRight().x() - CursorWidth, rect_.bottomLeft().y(),
124                                                                                                          rect_.bottomLeft().x(), rect_.bottomLeft().y());
125                                 break;
126                                         
127                         default:
128                                 painter.fillRect(rect_, color_);
129                                 break;
130                         }
131                 }
132         }
133
134         void update(int x, int y, int h, CursorShape shape)
135         {
136                 color_ = guiApp->colorCache().get(Color::cursor);
137                 shape_ = shape;
138                 switch (shape) {
139                 case L_SHAPE:
140                         rect_ = QRect(x, y, CursorWidth + h / 3, h);
141                         break;
142                 case REVERSED_L_SHAPE:
143                         rect_ = QRect(x - h / 3, y, CursorWidth + h / 3, h);
144                         break;
145                 default: 
146                         rect_ = QRect(x, y, CursorWidth, h);
147                         break;
148                 }
149         }
150
151         void show(bool set_show = true) { show_ = set_show; }
152         void hide() { show_ = false; }
153
154         QRect const & rect() { return rect_; }
155
156 private:
157         ///
158         CursorShape shape_;
159         ///
160         bool show_;
161         ///
162         QColor color_;
163         ///
164         QRect rect_;
165 };
166
167
168 // This is a 'heartbeat' generating synthetic mouse move events when the
169 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
170 SyntheticMouseEvent::SyntheticMouseEvent()
171         : timeout(200), restart_timeout(true),
172           x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
173 {}
174
175
176 GuiWorkArea::GuiWorkArea(Buffer & buf, LyXView & lv)
177         : WorkArea(buf, lv), need_resize_(false), schedule_redraw_(false),
178           preedit_lines_(1)
179 {
180         screen_ = QPixmap(viewport()->width(), viewport()->height());
181         cursor_ = new frontend::CursorWidget();
182         cursor_->hide();
183
184         setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
185         setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
186         setAcceptDrops(true);
187         setMouseTracking(true);
188         setMinimumSize(100, 70);
189
190         viewport()->setAutoFillBackground(false);
191         // We don't need double-buffering nor SystemBackground on
192         // the viewport because we have our own backing pixmap.
193         viewport()->setAttribute(Qt::WA_NoSystemBackground);
194
195         setFocusPolicy(Qt::WheelFocus);
196
197         viewport()->setCursor(Qt::IBeamCursor);
198
199         synthetic_mouse_event_.timeout.timeout.connect(
200                 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
201                             this));
202
203         // Initialize the vertical Scroll Bar
204         QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
205                 this, SLOT(adjustViewWithScrollBar(int)));
206
207         // disable context menu for the scrollbar
208         verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu);
209
210         // PageStep only depends on the viewport height.
211         verticalScrollBar()->setPageStep(viewport()->height());
212
213         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
214                 << "\n Area width\t" << width()
215                 << "\n Area height\t" << height()
216                 << "\n viewport width\t" << viewport()->width()
217                 << "\n viewport height\t" << viewport()->height()
218                 << endl;
219
220         // Enables input methods for asian languages.
221         // Must be set when creating custom text editing widgets.
222         setAttribute(Qt::WA_InputMethodEnabled, true);
223 }
224
225
226 void GuiWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
227 {
228         if (verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOn)
229                 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
230
231         verticalScrollBar()->setTracking(false);
232
233         // do what cursor movement does (some grey)
234         h += height() / 4;
235         int scroll_max_ = std::max(0, h - height());
236
237         verticalScrollBar()->setRange(0, scroll_max_);
238         verticalScrollBar()->setSliderPosition(scroll_pos);
239         verticalScrollBar()->setSingleStep(scroll_line_step);
240         verticalScrollBar()->setValue(scroll_pos);
241
242         verticalScrollBar()->setTracking(true);
243 }
244
245
246 void GuiWorkArea::adjustViewWithScrollBar(int)
247 {
248         scrollBufferView(verticalScrollBar()->sliderPosition());
249         QApplication::syncX();
250 }
251
252
253 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
254 {
255         // No need to do anything if we didn't change views...
256 //      if (theApp() == 0 || &lyx_view_ == theApp()->currentView())
257 //              return;
258
259         theApp()->setCurrentView(*lyx_view_);
260
261         // Repaint the whole screen.
262         // Note: this is different from redraw() as only the backing pixmap
263         // will be redrawn, which is cheap.
264         viewport()->repaint();
265
266         startBlinkingCursor();
267 }
268
269
270 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
271 {
272         stopBlinkingCursor();
273 }
274
275
276 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
277 {
278         if (dc_event_.active && dc_event_ == *e) {
279                 dc_event_.active = false;
280                 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
281                         e->x(), e->y(),
282                         q_button_state(e->button()));
283                 dispatch(cmd);
284                 return;
285         }
286
287         inputContext()->reset();
288
289         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
290                 q_button_state(e->button()));
291         dispatch(cmd, q_key_state(e->modifiers()));
292 }
293
294
295 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
296 {
297         if (synthetic_mouse_event_.timeout.running())
298                 synthetic_mouse_event_.timeout.stop();
299
300         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
301                               q_button_state(e->button()));
302         dispatch(cmd);
303 }
304
305
306 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
307 {
308         // we kill the triple click if we move
309         doubleClickTimeout();
310         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
311                               q_motion_state(e->buttons()));
312
313         // If we're above or below the work area...
314         if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
315                 // Make sure only a synthetic event can cause a page scroll,
316                 // so they come at a steady rate:
317                 if (e->y() <= 20)
318                         // _Force_ a scroll up:
319                         cmd.y = -40;
320                 else
321                         cmd.y = viewport()->height();
322                 // Store the event, to be handled when the timeout expires.
323                 synthetic_mouse_event_.cmd = cmd;
324
325                 if (synthetic_mouse_event_.timeout.running())
326                         // Discard the event. Note that it _may_ be handled
327                         // when the timeout expires if
328                         // synthetic_mouse_event_.cmd has not been overwritten.
329                         // Ie, when the timeout expires, we handle the
330                         // most recent event but discard all others that
331                         // occurred after the one used to start the timeout
332                         // in the first place.
333                         return;
334                 else {
335                         synthetic_mouse_event_.restart_timeout = true;
336                         synthetic_mouse_event_.timeout.start();
337                         // Fall through to handle this event...
338                 }
339
340         } else if (synthetic_mouse_event_.timeout.running()) {
341                 // Store the event, to be possibly handled when the timeout
342                 // expires.
343                 // Once the timeout has expired, normal control is returned
344                 // to mouseMoveEvent (restart_timeout = false).
345                 // This results in a much smoother 'feel' when moving the
346                 // mouse back into the work area.
347                 synthetic_mouse_event_.cmd = cmd;
348                 synthetic_mouse_event_.restart_timeout = false;
349                 return;
350         }
351
352         // Has anything changed on-screen since the last QMouseEvent
353         // was received?
354         double const scrollbar_value = verticalScrollBar()->value();
355         if (e->x() != synthetic_mouse_event_.x_old ||
356             e->y() != synthetic_mouse_event_.y_old ||
357             scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
358                 // Yes it has. Store the params used to check this.
359                 synthetic_mouse_event_.x_old = e->x();
360                 synthetic_mouse_event_.y_old = e->y();
361                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
362
363                 // ... and dispatch the event to the LyX core.
364                 dispatch(cmd);
365         }
366 }
367
368
369 void GuiWorkArea::wheelEvent(QWheelEvent * e)
370 {
371         // Wheel rotation by one notch results in a delta() of 120 (see
372         // documentation of QWheelEvent)
373         int const lines = qApp->wheelScrollLines() * e->delta() / 120;
374         verticalScrollBar()->setValue(verticalScrollBar()->value() -
375                         lines *  verticalScrollBar()->singleStep());
376         adjustViewWithScrollBar();
377 }
378
379
380 void GuiWorkArea::generateSyntheticMouseEvent()
381 {
382 // Set things off to generate the _next_ 'pseudo' event.
383         if (synthetic_mouse_event_.restart_timeout)
384                 synthetic_mouse_event_.timeout.start();
385
386         // Has anything changed on-screen since the last timeout signal
387         // was received?
388         double const scrollbar_value = verticalScrollBar()->value();
389         if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
390                 // Yes it has. Store the params used to check this.
391                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
392
393                 // ... and dispatch the event to the LyX core.
394                 dispatch(synthetic_mouse_event_.cmd);
395         }
396 }
397
398
399 void GuiWorkArea::keyPressEvent(QKeyEvent * e)
400 {
401         // do nothing if there are other events
402         // (the auto repeated events come too fast)
403         // \todo FIXME: remove hard coded Qt keys, process the key binding
404 #ifdef Q_WS_X11
405         if (XEventsQueued(QX11Info::display(), 0) > 1 && e->isAutoRepeat() 
406                         && (Qt::Key_PageDown || Qt::Key_PageUp)) {
407                 LYXERR(Debug::KEY)      
408                         << BOOST_CURRENT_FUNCTION << endl
409                         << "system is busy: scroll key event ignored" << endl;
410                 e->ignore();
411                 return;
412         }
413 #endif
414
415         LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
416                 << " count=" << e->count()
417                 << " text=" << fromqstr(e->text())
418                 << " isAutoRepeat=" << e->isAutoRepeat()
419                 << " key=" << e->key()
420                 << endl;
421
422         boost::shared_ptr<QKeySymbol> sym(new QKeySymbol);
423         sym->set(e);
424         processKeySym(sym, q_key_state(e->modifiers()));
425 }
426
427 void GuiWorkArea::doubleClickTimeout() {
428         dc_event_.active = false;
429 }
430
431 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
432 {
433         dc_event_ = double_click(e);
434         QTimer::singleShot(QApplication::doubleClickInterval(), this,
435                            SLOT(doubleClickTimeout()));
436         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
437                         e->x(), e->y(),
438                         q_button_state(e->button()));
439         dispatch(cmd);
440 }
441
442
443 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
444 {
445         QAbstractScrollArea::resizeEvent(ev);
446         need_resize_ = true;
447 }
448
449
450 void GuiWorkArea::update(int x, int y, int w, int h)
451 {
452         viewport()->repaint(x, y, w, h);
453 }
454
455
456 void GuiWorkArea::paintEvent(QPaintEvent * ev)
457 {
458         QRect const rc = ev->rect();
459         /*
460         LYXERR(Debug::PAINTING) << "paintEvent begin: x: " << rc.x()
461                 << " y: " << rc.y()
462                 << " w: " << rc.width()
463                 << " h: " << rc.height() << endl;
464         */
465
466         if (need_resize_) {
467                 verticalScrollBar()->setPageStep(viewport()->height());
468                 screen_ = QPixmap(viewport()->width(), viewport()->height());
469                 resizeBufferView();
470                 updateScreen();
471                 WorkArea::hideCursor();
472                 WorkArea::showCursor();
473                 need_resize_ = false;
474         }
475
476         QPainter pain(viewport());
477         pain.drawPixmap(rc, screen_, rc);
478         cursor_->draw(pain);
479 }
480
481
482 void GuiWorkArea::expose(int x, int y, int w, int h)
483 {
484         updateScreen();
485         update(x, y, w, h);
486 }
487
488
489 void GuiWorkArea::updateScreen()
490 {
491         QLPainter pain(&screen_);
492         verticalScrollBar()->show();
493         paintText(*buffer_view_, pain);
494 }
495
496
497 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
498 {
499         if (schedule_redraw_) {
500                 buffer_view_->update(Update::Force);
501                 updateScreen();
502                 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
503                 schedule_redraw_ = false;
504                 // Show the cursor immediately after the update.
505                 hideCursor();
506                 toggleCursor();
507                 return;
508         }
509
510         cursor_->update(x, y, h, shape);
511         cursor_->show();
512         viewport()->update(cursor_->rect());
513 }
514
515
516 void GuiWorkArea::removeCursor()
517 {
518         cursor_->hide();
519         //if (!qApp->focusWidget())
520                 viewport()->update(cursor_->rect());
521 }
522
523
524 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
525 {
526         QString const & commit_string = e->commitString();
527         docstring const & preedit_string
528                 = qstring_to_ucs4(e->preeditString());
529
530         if (!commit_string.isEmpty()) {
531
532                 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
533                         << " preeditString =" << fromqstr(e->preeditString())
534                         << " commitString  =" << fromqstr(e->commitString())
535                         << endl;
536
537                 int key = 0;
538
539                 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
540                 for (int i = 0; i < commit_string.size(); ++i) {
541                         QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
542                         keyPressEvent(&ev);
543                 }
544         }
545
546         // Hide the cursor during the kana-kanji transformation.
547         if (preedit_string.empty())
548                 startBlinkingCursor();
549         else
550                 stopBlinkingCursor();
551
552         // last_width : for checking if last preedit string was/wasn't empty.
553         static bool last_width = false;
554         if (!last_width && preedit_string.empty()) {
555                 // if last_width is last length of preedit string.
556                 e->accept();
557                 return;
558         }
559
560         QLPainter pain(&screen_);
561         buffer_view_->updateMetrics(false);
562         paintText(*buffer_view_, pain);
563         Font font = buffer_view_->cursor().getFont();
564         FontMetrics const & fm = theFontMetrics(font);
565         int height = fm.maxHeight();
566         int cur_x = cursor_->rect().left();
567         int cur_y = cursor_->rect().bottom();
568
569         // redraw area of preedit string.
570         update(0, cur_y - height, GuiWorkArea::width(),
571                 (height + 1) * preedit_lines_);
572
573         if (preedit_string.empty()) {
574                 last_width = false;
575                 preedit_lines_ = 1;
576                 e->accept();
577                 return;
578         }
579         last_width = true;
580
581         // att : stores an IM attribute.
582         QList<QInputMethodEvent::Attribute> const & att = e->attributes();
583
584         // get attributes of input method cursor.
585         // cursor_pos : cursor position in preedit string.
586         size_t cursor_pos = 0;
587         bool cursor_is_visible = false;
588         for (int i = 0; i < att.size(); ++i) {
589                 if (att.at(i).type == QInputMethodEvent::Cursor) {
590                         cursor_pos = att.at(i).start;
591                         cursor_is_visible = att.at(i).length != 0;
592                         break;
593                 }
594         }
595
596         size_t preedit_length = preedit_string.length();
597
598         // get position of selection in input method.
599         // FIXME: isn't there a way to do this simplier?
600         // rStart : cursor position in selected string in IM.
601         size_t rStart = 0;
602         // rLength : selected string length in IM.
603         size_t rLength = 0;
604         if (cursor_pos < preedit_length) {
605                 for (int i = 0; i < att.size(); ++i) {
606                         if (att.at(i).type == QInputMethodEvent::TextFormat) {
607                                 if (att.at(i).start <= int(cursor_pos)
608                                         && int(cursor_pos) < att.at(i).start + att.at(i).length) {
609                                                 rStart = att.at(i).start;
610                                                 rLength = att.at(i).length;
611                                                 if (!cursor_is_visible)
612                                                         cursor_pos += rLength;
613                                                 break;
614                                 }
615                         }
616                 }
617         }
618         else {
619                 rStart = cursor_pos;
620                 rLength = 0;
621         }
622
623         int const right_margin = rightMargin();
624         Painter::preedit_style ps;
625         // Most often there would be only one line:
626         preedit_lines_ = 1;
627         for (size_t pos = 0; pos != preedit_length; ++pos) {
628                 char_type const typed_char = preedit_string[pos];
629                 // reset preedit string style
630                 ps = Painter::preedit_default;
631
632                 // if we reached the right extremity of the screen, go to next line.
633                 if (cur_x + fm.width(typed_char) > GuiWorkArea::width() - right_margin) {
634                         cur_x = right_margin;
635                         cur_y += height + 1;
636                         ++preedit_lines_;
637                 }
638                 // preedit strings are displayed with dashed underline
639                 // and partial strings are displayed white on black indicating
640                 // that we are in selecting mode in the input method.
641                 // FIXME: rLength == preedit_length is not a changing condition
642                 // FIXME: should be put out of the loop.
643                 if (pos >= rStart
644                         && pos < rStart + rLength
645                         && !(cursor_pos < rLength && rLength == preedit_length))
646                         ps = Painter::preedit_selecting;
647
648                 if (pos == cursor_pos
649                         && (cursor_pos < rLength && rLength == preedit_length))
650                         ps = Painter::preedit_cursor;
651
652                 // draw one character and update cur_x.
653                 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
654         }
655
656         // update the preedit string screen area.
657         update(0, cur_y - preedit_lines_*height, GuiWorkArea::width(),
658                 (height + 1) * preedit_lines_);
659
660         // Don't forget to accept the event!
661         e->accept();
662 }
663
664
665 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
666 {
667         QRect cur_r(0,0,0,0);
668         switch (query) {
669                 // this is the CJK-specific composition window position.
670                 case Qt::ImMicroFocus:
671                         cur_r = cursor_->rect();
672                         if (preedit_lines_ != 1)
673                                 cur_r.moveLeft(10);
674                         cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
675                         // return lower right of cursor in LyX.
676                         return cur_r;
677                 default:
678                         return QWidget::inputMethodQuery(query);
679         }
680 }
681
682 } // namespace frontend
683 } // namespace lyx
684
685 #include "GuiWorkArea_moc.cpp"