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