]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.cpp
* completion cursor
[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 "Buffer.h"
17 #include "BufferParams.h"
18 #include "BufferView.h"
19 #include "CoordCache.h"
20 #include "Cursor.h"
21 #include "Font.h"
22 #include "FuncRequest.h"
23 #include "GuiApplication.h"
24 #include "GuiKeySymbol.h"
25 #include "GuiPainter.h"
26 #include "GuiPopupMenu.h"
27 #include "GuiView.h"
28 #include "KeySymbol.h"
29 #include "Language.h"
30 #include "LyXFunc.h"
31 #include "LyXRC.h"
32 #include "MetricsInfo.h"
33 #include "qt_helpers.h"
34 #include "version.h"
35
36 #include "graphics/GraphicsImage.h"
37 #include "graphics/GraphicsLoader.h"
38
39 #include "support/debug.h"
40 #include "support/gettext.h"
41 #include "support/FileName.h"
42
43 #include "frontends/Application.h"
44 #include "frontends/FontMetrics.h"
45 #include "frontends/WorkAreaManager.h"
46
47 #include <QContextMenuEvent>
48 #include <QInputContext>
49 #include <QHelpEvent>
50 #include <QMainWindow>
51 #include <QPainter>
52 #include <QPalette>
53 #include <QScrollBar>
54 #include <QTabBar>
55 #include <QTimer>
56 #include <QToolButton>
57 #include <QToolTip>
58
59 #include <boost/bind.hpp>
60
61 #ifdef Q_WS_X11
62 #include <QX11Info>
63 extern "C" int XEventsQueued(Display *display, int mode);
64 #endif
65
66 #ifdef Q_WS_WIN
67 int const CursorWidth = 2;
68 #else
69 int const CursorWidth = 1;
70 #endif
71 int const TabIndicatorWidth = 4;
72
73 #undef KeyPress
74 #undef NoModifier 
75
76 using namespace std;
77 using namespace lyx::support;
78
79 namespace lyx {
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                 if (!show_ || !rect_.isValid())
126                         return;
127                 
128                 int l = x_ - rect_.left();
129                 int r = rect_.right() - x_;
130                 int h = rect_.height();
131
132                 painter.fillRect(x_, y_, CursorWidth, h, color_);
133                 painter.setPen(color_);
134                 if (l_shape_) {
135                         if (rtl_)
136                                 painter.drawLine(x_, y_ + h, x_ - l, y_ + h);
137                         else
138                                 painter.drawLine(x_ + CursorWidth, y_ + h, 
139                                         x_ + CursorWidth + r, y_ + h);
140                 }
141                 
142                 if (completable_) {
143                         int m = y_ + h / 2;
144                         int d = TabIndicatorWidth - 1;
145                         if (rtl_) {
146                                 painter.drawLine(x_ - 1 , m - d, x_ - d - 1, m);
147                                 painter.drawLine(x_ - 1 , m + d, x_ - d - 1, m);
148                         } else {
149                                 painter.drawLine(x_ + CursorWidth , m - d, x_ + d + CursorWidth, m);
150                                 painter.drawLine(x_ + CursorWidth , m + d, x_ + d + CursorWidth, m);
151                         }
152                 }
153         }
154
155         void update(int x, int y, int h, bool l_shape,
156                 bool rtl, bool completable)
157         {
158                 color_ = guiApp->colorCache().get(Color_cursor);
159                 l_shape_ = l_shape;
160                 rtl_ = rtl;
161                 completable_ = completable;
162                 x_ = x;
163                 y_ = y;
164                 int l = 0;
165                 int r = 0;
166
167                 if (l_shape_) {
168                         if (rtl)
169                                 l += h / 3;
170                         else
171                                 r += h / 3;
172                 }
173                 
174                 if (completable_) {
175                         if (rtl)
176                                 l = max(r, TabIndicatorWidth);
177                         else
178                                 r = max(l, TabIndicatorWidth);
179                 }
180
181                 rect_ = QRect(x - l, y, CursorWidth + r + l, h);
182         }
183
184         void show(bool set_show = true) { show_ = set_show; }
185         void hide() { show_ = false; }
186
187         QRect const & rect() { return rect_; }
188
189 private:
190         ///
191         bool rtl_;
192         ///
193         bool l_shape_;
194         ///
195         bool completable_;
196         ///
197         bool show_;
198         ///
199         QColor color_;
200         ///
201         QRect rect_;
202         ///
203         int x_;
204         ///
205         int y_;
206 };
207
208
209 // This is a 'heartbeat' generating synthetic mouse move events when the
210 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
211 SyntheticMouseEvent::SyntheticMouseEvent()
212         : timeout(200), restart_timeout(true),
213           x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
214 {}
215
216
217
218 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & lv)
219         : buffer_view_(new BufferView(buffer)), lyx_view_(&lv),
220         cursor_visible_(false),
221         need_resize_(false), schedule_redraw_(false),
222         preedit_lines_(1), completer_(this)
223 {
224         buffer.workAreaManager().add(this);
225         // Setup the signals
226         connect(&cursor_timeout_, SIGNAL(timeout()),
227                 this, SLOT(toggleCursor()));
228         
229         int const time = QApplication::cursorFlashTime() / 2;
230         if (time > 0) {
231                 cursor_timeout_.setInterval(time);
232                 cursor_timeout_.start();
233         } else
234                 // let's initialize this just to be safe
235                 cursor_timeout_.setInterval(500);
236
237         screen_ = QPixmap(viewport()->width(), viewport()->height());
238         cursor_ = new frontend::CursorWidget();
239         cursor_->hide();
240
241         setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
242         setAcceptDrops(true);
243         setMouseTracking(true);
244         setMinimumSize(100, 70);
245         updateWindowTitle();
246
247         viewport()->setAutoFillBackground(false);
248         // We don't need double-buffering nor SystemBackground on
249         // the viewport because we have our own backing pixmap.
250         viewport()->setAttribute(Qt::WA_NoSystemBackground);
251
252         setFocusPolicy(Qt::WheelFocus);
253
254         viewport()->setCursor(Qt::IBeamCursor);
255
256         synthetic_mouse_event_.timeout.timeout.connect(
257                 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
258                                         this));
259
260         // Initialize the vertical Scroll Bar
261         QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
262                 this, SLOT(scrollTo(int)));
263
264         LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
265                 << "  viewport height: " << viewport()->height());
266
267         // Enables input methods for asian languages.
268         // Must be set when creating custom text editing widgets.
269         setAttribute(Qt::WA_InputMethodEnabled, true);
270 }
271
272
273 GuiWorkArea::~GuiWorkArea()
274 {
275         buffer_view_->buffer().workAreaManager().remove(this);
276         delete buffer_view_;
277         delete cursor_;
278 }
279
280
281 void GuiWorkArea::close()
282 {
283         lyx_view_->removeWorkArea(this);
284 }
285
286
287 void GuiWorkArea::setFullScreen(bool full_screen)
288 {
289         buffer_view_->setFullScreen(full_screen);
290         if (full_screen) {
291                 setFrameStyle(QFrame::NoFrame);
292                 if (lyxrc.full_screen_scrollbar)
293                         setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
294         } else {
295                 setFrameStyle(QFrame::Box);
296                 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
297         }
298 }
299
300
301 BufferView & GuiWorkArea::bufferView()
302 {
303         return *buffer_view_;
304 }
305
306
307 BufferView const & GuiWorkArea::bufferView() const
308 {
309         return *buffer_view_;
310 }
311
312
313 void GuiWorkArea::stopBlinkingCursor()
314 {
315         cursor_timeout_.stop();
316         hideCursor();
317 }
318
319
320 void GuiWorkArea::startBlinkingCursor()
321 {
322         showCursor();
323         //we're not supposed to cache this value.
324         int const time = QApplication::cursorFlashTime() / 2;
325         if (time <= 0)
326                 return;
327         cursor_timeout_.setInterval(time);
328         cursor_timeout_.start();
329 }
330
331
332 void GuiWorkArea::redraw()
333 {
334         if (!isVisible())
335                 // No need to redraw in this case.
336                 return;
337
338         // No need to do anything if this is the current view. The BufferView
339         // metrics are already up to date.
340         if (lyx_view_ != guiApp->currentView()
341                 || lyx_view_->currentWorkArea() != this) {
342                 // FIXME: it would be nice to optimize for the off-screen case.
343                 buffer_view_->updateMetrics();
344                 buffer_view_->cursor().fixIfBroken();
345         }
346
347         // update cursor position, because otherwise it has to wait until
348         // the blinking interval is over
349         if (cursor_visible_) {
350                 hideCursor();
351                 showCursor();
352         }
353         
354         LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
355         updateScreen();
356         update(0, 0, viewport()->width(), viewport()->height());
357
358         /// \warning: scrollbar updating *must* be done after the BufferView is drawn
359         /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
360         updateScrollbar();
361         lyx_view_->updateStatusBar();
362
363         if (lyxerr.debugging(Debug::WORKAREA))
364                 buffer_view_->coordCache().dump();
365 }
366
367
368 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
369 {
370         // In order to avoid bad surprise in the middle of an operation,
371         // we better stop the blinking cursor...
372         // the cursor gets restarted in GuiView::restartCursor()
373         stopBlinkingCursor();
374
375         theLyXFunc().setLyXView(lyx_view_);
376         theLyXFunc().processKeySym(key, mod);
377         
378 }
379
380
381 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
382 {
383         // Handle drag&drop
384         if (cmd0.action == LFUN_FILE_OPEN) {
385                 lyx_view_->dispatch(cmd0);
386                 return;
387         }
388
389         theLyXFunc().setLyXView(lyx_view_);
390
391         FuncRequest cmd;
392
393         if (cmd0.action == LFUN_MOUSE_PRESS) {
394                 if (mod == ShiftModifier)
395                         cmd = FuncRequest(cmd0, "region-select");
396                 else if (mod == ControlModifier)
397                         cmd = FuncRequest(cmd0, "paragraph-select");
398                 else
399                         cmd = cmd0;
400         }
401         else
402                 cmd = cmd0;
403
404         bool const notJustMovingTheMouse = 
405                 cmd.action != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
406         
407         // In order to avoid bad surprise in the middle of an operation, we better stop
408         // the blinking cursor.
409         if (notJustMovingTheMouse)
410                 stopBlinkingCursor();
411
412         buffer_view_->mouseEventDispatch(cmd);
413
414         // Skip these when selecting
415         if (cmd.action != LFUN_MOUSE_MOTION) {
416                 completer_.updateVisibility(false, false);
417                 lyx_view_->updateLayoutList();
418                 lyx_view_->updateToolbars();
419         }
420
421         // GUI tweaks except with mouse motion with no button pressed.
422         if (notJustMovingTheMouse) {
423                 // Slight hack: this is only called currently when we
424                 // clicked somewhere, so we force through the display
425                 // of the new status here.
426                 lyx_view_->clearMessage();
427
428                 // Show the cursor immediately after any operation
429                 startBlinkingCursor();
430         }
431 }
432
433
434 void GuiWorkArea::resizeBufferView()
435 {
436         // WARNING: Please don't put any code that will trigger a repaint here!
437         // We are already inside a paint event.
438         lyx_view_->setBusy(true);
439         buffer_view_->resize(viewport()->width(), viewport()->height());
440         updateScreen();
441
442         // Update scrollbars which might have changed due different
443         // BufferView dimension. This is especially important when the 
444         // BufferView goes from zero-size to the real-size for the first time,
445         // as the scrollbar paramters are then set for the first time.
446         updateScrollbar();
447         
448         lyx_view_->updateLayoutList();
449         lyx_view_->setBusy(false);
450         need_resize_ = false;
451 }
452
453
454 void GuiWorkArea::showCursor()
455 {
456         if (cursor_visible_)
457                 return;
458
459         // RTL or not RTL
460         bool l_shape = false;
461         Font const & realfont = buffer_view_->cursor().real_current_font;
462         BufferParams const & bp = buffer_view_->buffer().params();
463         bool const samelang = realfont.language() == bp.language;
464         bool const isrtl = realfont.isVisibleRightToLeft();
465
466         if (!samelang || isrtl != bp.language->rightToLeft())
467                 l_shape = true;
468
469         // The ERT language hack needs fixing up
470         if (realfont.language() == latex_language)
471                 l_shape = false;
472
473         Font const font = buffer_view_->cursor().getFont();
474         FontMetrics const & fm = theFontMetrics(font);
475         int const asc = fm.maxAscent();
476         int const des = fm.maxDescent();
477         int h = asc + des;
478         int x = 0;
479         int y = 0;
480         Cursor & cur = buffer_view_->cursor();
481         cur.getPos(x, y);
482         y -= asc;
483
484         // if it doesn't touch the screen, don't try to show it
485         bool cursorInView = true;
486         if (y + h < 0 || y >= viewport()->height())
487                 cursorInView = false;
488
489         // show cursor on screen
490         bool completable = completer_.completionAvailable();
491         if (cursorInView) {
492                 cursor_visible_ = true;
493                 showCursor(x, y, h, l_shape, isrtl, completable);
494         }
495 }
496
497
498 void GuiWorkArea::hideCursor()
499 {
500         if (!cursor_visible_)
501                 return;
502
503         cursor_visible_ = false;
504         removeCursor();
505 }
506
507
508 void GuiWorkArea::toggleCursor()
509 {
510         if (cursor_visible_)
511                 hideCursor();
512         else
513                 showCursor();
514 }
515
516
517 void GuiWorkArea::updateScrollbar()
518 {
519         ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
520
521         verticalScrollBar()->setRange(scroll_.min, scroll_.max);
522         verticalScrollBar()->setPageStep(scroll_.page_step);
523         verticalScrollBar()->setSingleStep(scroll_.single_step);
524         // Block the scrollbar signal to prevent recursive signal/slot calling.
525         verticalScrollBar()->blockSignals(true);
526         verticalScrollBar()->setValue(scroll_.position);
527         verticalScrollBar()->setSliderPosition(scroll_.position);
528         verticalScrollBar()->blockSignals(false);
529 }
530
531
532 void GuiWorkArea::scrollTo(int value)
533 {
534         stopBlinkingCursor();
535         buffer_view_->scrollDocView(value);
536
537         if (lyxrc.cursor_follows_scrollbar) {
538                 buffer_view_->setCursorFromScrollbar();
539                 lyx_view_->updateLayoutList();
540         }
541         // Show the cursor immediately after any operation.
542         startBlinkingCursor();
543         QApplication::syncX();
544 }
545
546
547 bool GuiWorkArea::event(QEvent * e)
548 {
549         switch (e->type()) {
550         case QEvent::ToolTip: {
551                 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
552                 if (lyxrc.use_tooltip) {
553                         QPoint pos = helpEvent->pos();
554                         if (pos.x() < viewport()->width()) {
555                                 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
556                                 QToolTip::showText(helpEvent->globalPos(), s);
557                         }
558                         else
559                                 QToolTip::hideText();
560                 }
561                 // Don't forget to accept the event!
562                 e->accept();
563                 return true;
564         }
565
566         case QEvent::ShortcutOverride: {
567                 // We catch this event in order to catch the Tab or Shift+Tab key press
568                 // which are otherwise reserved to focus switching between controls
569                 // within a dialog.
570                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
571                 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
572                         || ke->modifiers() & Qt::ControlModifier)
573                         return QAbstractScrollArea::event(e);
574                 keyPressEvent(ke);
575                 return true;
576         }
577
578         default:
579                 return QAbstractScrollArea::event(e);
580         }
581         return false;
582 }
583
584
585 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
586 {
587         QPoint pos = e->pos();
588         docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
589         if (name.empty()) {
590                 QAbstractScrollArea::contextMenuEvent(e);
591                 return;
592         }
593         QMenu * menu = guiApp->menus().menu(toqstr(name));
594         if (!menu) {
595                 QAbstractScrollArea::contextMenuEvent(e);
596                 return;
597         }
598         // Position the menu to the right.
599         // FIXME: menu position should be different for RTL text.
600         menu->exec(e->globalPos());
601         e->accept();
602 }
603
604
605 void GuiWorkArea::focusInEvent(QFocusEvent * e)
606 {
607         lyx_view_->setCurrentWorkArea(this);
608         // Repaint the whole screen.
609         // Note: this is different from redraw() as only the backing pixmap
610         // will be redrawn, which is cheap.
611         viewport()->repaint();
612
613         startBlinkingCursor();
614         QAbstractScrollArea::focusInEvent(e);
615 }
616
617
618 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
619 {
620         stopBlinkingCursor();
621         QAbstractScrollArea::focusOutEvent(e);
622 }
623
624
625 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
626 {
627         if (dc_event_.active && dc_event_ == *e) {
628                 dc_event_.active = false;
629                 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
630                         q_button_state(e->button()));
631                 dispatch(cmd);
632                 e->accept();
633                 return;
634         }
635
636         inputContext()->reset();
637
638         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
639                 q_button_state(e->button()));
640         dispatch(cmd, q_key_state(e->modifiers()));
641         e->accept();
642 }
643
644
645 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
646 {
647         if (synthetic_mouse_event_.timeout.running())
648                 synthetic_mouse_event_.timeout.stop();
649
650         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
651                               q_button_state(e->button()));
652         dispatch(cmd);
653         e->accept();
654 }
655
656
657 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
658 {
659         // we kill the triple click if we move
660         doubleClickTimeout();
661         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
662                 q_motion_state(e->buttons()));
663
664         e->accept();
665
666         // If we're above or below the work area...
667         if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
668                 // Make sure only a synthetic event can cause a page scroll,
669                 // so they come at a steady rate:
670                 if (e->y() <= 20)
671                         // _Force_ a scroll up:
672                         cmd.y = -40;
673                 else
674                         cmd.y = viewport()->height();
675                 // Store the event, to be handled when the timeout expires.
676                 synthetic_mouse_event_.cmd = cmd;
677
678                 if (synthetic_mouse_event_.timeout.running())
679                         // Discard the event. Note that it _may_ be handled
680                         // when the timeout expires if
681                         // synthetic_mouse_event_.cmd has not been overwritten.
682                         // Ie, when the timeout expires, we handle the
683                         // most recent event but discard all others that
684                         // occurred after the one used to start the timeout
685                         // in the first place.
686                         return;
687
688                 synthetic_mouse_event_.restart_timeout = true;
689                 synthetic_mouse_event_.timeout.start();
690                 // Fall through to handle this event...
691
692         } else if (synthetic_mouse_event_.timeout.running()) {
693                 // Store the event, to be possibly handled when the timeout
694                 // expires.
695                 // Once the timeout has expired, normal control is returned
696                 // to mouseMoveEvent (restart_timeout = false).
697                 // This results in a much smoother 'feel' when moving the
698                 // mouse back into the work area.
699                 synthetic_mouse_event_.cmd = cmd;
700                 synthetic_mouse_event_.restart_timeout = false;
701                 return;
702         }
703
704         // Has anything changed on-screen since the last QMouseEvent
705         // was received?
706         double const scrollbar_value = verticalScrollBar()->value();
707         if (e->x() == synthetic_mouse_event_.x_old
708                 && e->y() == synthetic_mouse_event_.y_old
709                 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
710                 // Nothing changed on-screen since the last QMouseEvent.
711                 return;
712         }
713
714         // Yes something has changed. Store the params used to check this.
715         synthetic_mouse_event_.x_old = e->x();
716         synthetic_mouse_event_.y_old = e->y();
717         synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
718
719         // ... and dispatch the event to the LyX core.
720         dispatch(cmd);
721 }
722
723
724 void GuiWorkArea::wheelEvent(QWheelEvent * e)
725 {
726         // Wheel rotation by one notch results in a delta() of 120 (see
727         // documentation of QWheelEvent)
728         double const lines = qApp->wheelScrollLines()
729                 * lyxrc.mouse_wheel_speed
730                 * e->delta() / 120.0;
731         LYXERR(Debug::SCROLLING, "wheelScrollLines = " << qApp->wheelScrollLines()
732                 << " delta = " << e->delta()
733                 << " lines = " << lines);
734         verticalScrollBar()->setValue(verticalScrollBar()->value() -
735                 int(lines *  verticalScrollBar()->singleStep()));
736         e->accept();
737 }
738
739
740 void GuiWorkArea::generateSyntheticMouseEvent()
741 {
742         // Set things off to generate the _next_ 'pseudo' event.
743         if (synthetic_mouse_event_.restart_timeout)
744                 synthetic_mouse_event_.timeout.start();
745
746         // Has anything changed on-screen since the last timeout signal
747         // was received?
748         double const scrollbar_value = verticalScrollBar()->value();
749         if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
750                 // Yes it has. Store the params used to check this.
751                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
752
753                 // ... and dispatch the event to the LyX core.
754                 dispatch(synthetic_mouse_event_.cmd);
755         }
756 }
757
758
759 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
760 {
761         // intercept some keys if completion popup is visible
762         if (completer_.popupVisible()) {
763                 switch (ev->key()) {
764                 case Qt::Key_Enter:
765                 case Qt::Key_Return:
766                         completer_.activate();
767                         ev->accept();
768                         return;
769                 }
770         }
771         
772         // intercept keys for the completion
773         if (ev->key() == Qt::Key_Tab) {
774                 completer_.tab();
775                 ev->accept();
776                 return;
777         } 
778
779         if (completer_.popupVisible() && ev->key() == Qt::Key_Escape) {
780                 completer_.hidePopup();
781                 ev->accept();
782                 return;
783         }
784
785         if (completer_.inlineVisible() && ev->key() == Qt::Key_Escape) {
786                 completer_.hideInline();
787                 ev->accept();
788                 return;
789         }
790
791         // do nothing if there are other events
792         // (the auto repeated events come too fast)
793         // \todo FIXME: remove hard coded Qt keys, process the key binding
794 #ifdef Q_WS_X11
795         if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat() 
796                         && (Qt::Key_PageDown || Qt::Key_PageUp)) {
797                 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
798                 ev->ignore();
799                 return;
800         }
801 #endif
802
803         LYXERR(Debug::KEY, " count: " << ev->count()
804                 << " text: " << fromqstr(ev->text())
805                 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
806
807         KeySymbol sym;
808         setKeySymbol(&sym, ev);
809         processKeySym(sym, q_key_state(ev->modifiers()));
810         ev->accept();
811 }
812
813
814 void GuiWorkArea::doubleClickTimeout()
815 {
816         dc_event_.active = false;
817 }
818
819
820 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
821 {
822         dc_event_ = DoubleClick(ev);
823         QTimer::singleShot(QApplication::doubleClickInterval(), this,
824                            SLOT(doubleClickTimeout()));
825         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
826                         ev->x(), ev->y(),
827                         q_button_state(ev->button()));
828         dispatch(cmd);
829         ev->accept();
830 }
831
832
833 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
834 {
835         QAbstractScrollArea::resizeEvent(ev);
836         need_resize_ = true;
837         ev->accept();
838 }
839
840
841 void GuiWorkArea::update(int x, int y, int w, int h)
842 {
843         viewport()->repaint(x, y, w, h);
844 }
845
846
847 void GuiWorkArea::paintEvent(QPaintEvent * ev)
848 {
849         QRect const rc = ev->rect();
850         // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
851         //      << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
852
853         if (need_resize_) {
854                 screen_ = QPixmap(viewport()->width(), viewport()->height());
855                 resizeBufferView();
856                 hideCursor();
857                 showCursor();
858         }
859
860         QPainter pain(viewport());
861         pain.drawPixmap(rc, screen_, rc);
862         cursor_->draw(pain);
863         ev->accept();
864 }
865
866
867 void GuiWorkArea::updateScreen()
868 {
869         GuiPainter pain(&screen_);
870         buffer_view_->draw(pain);
871 }
872
873
874 void GuiWorkArea::showCursor(int x, int y, int h,
875         bool l_shape, bool rtl, bool completable)
876 {
877         if (schedule_redraw_) {
878                 buffer_view_->updateMetrics();
879                 updateScreen();
880                 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
881                 schedule_redraw_ = false;
882                 // Show the cursor immediately after the update.
883                 hideCursor();
884                 toggleCursor();
885                 return;
886         }
887
888         cursor_->update(x, y, h, l_shape, rtl, completable);
889         cursor_->show();
890         viewport()->update(cursor_->rect());
891 }
892
893
894 void GuiWorkArea::removeCursor()
895 {
896         cursor_->hide();
897         //if (!qApp->focusWidget())
898                 viewport()->update(cursor_->rect());
899 }
900
901
902 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
903 {
904         QString const & commit_string = e->commitString();
905         docstring const & preedit_string
906                 = qstring_to_ucs4(e->preeditString());
907
908         if (!commit_string.isEmpty()) {
909
910                 LYXERR(Debug::KEY, "preeditString: " << fromqstr(e->preeditString())
911                         << " commitString: " << fromqstr(e->commitString()));
912
913                 int key = 0;
914
915                 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
916                 for (int i = 0; i != commit_string.size(); ++i) {
917                         QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
918                         keyPressEvent(&ev);
919                 }
920         }
921
922         // Hide the cursor during the kana-kanji transformation.
923         if (preedit_string.empty())
924                 startBlinkingCursor();
925         else
926                 stopBlinkingCursor();
927
928         // last_width : for checking if last preedit string was/wasn't empty.
929         static bool last_width = false;
930         if (!last_width && preedit_string.empty()) {
931                 // if last_width is last length of preedit string.
932                 e->accept();
933                 return;
934         }
935
936         GuiPainter pain(&screen_);
937         buffer_view_->updateMetrics();
938         buffer_view_->draw(pain);
939         FontInfo font = buffer_view_->cursor().getFont().fontInfo();
940         FontMetrics const & fm = theFontMetrics(font);
941         int height = fm.maxHeight();
942         int cur_x = cursor_->rect().left();
943         int cur_y = cursor_->rect().bottom();
944
945         // redraw area of preedit string.
946         update(0, cur_y - height, viewport()->width(),
947                 (height + 1) * preedit_lines_);
948
949         if (preedit_string.empty()) {
950                 last_width = false;
951                 preedit_lines_ = 1;
952                 e->accept();
953                 return;
954         }
955         last_width = true;
956
957         // att : stores an IM attribute.
958         QList<QInputMethodEvent::Attribute> const & att = e->attributes();
959
960         // get attributes of input method cursor.
961         // cursor_pos : cursor position in preedit string.
962         size_t cursor_pos = 0;
963         bool cursor_is_visible = false;
964         for (int i = 0; i != att.size(); ++i) {
965                 if (att.at(i).type == QInputMethodEvent::Cursor) {
966                         cursor_pos = att.at(i).start;
967                         cursor_is_visible = att.at(i).length != 0;
968                         break;
969                 }
970         }
971
972         size_t preedit_length = preedit_string.length();
973
974         // get position of selection in input method.
975         // FIXME: isn't there a way to do this simplier?
976         // rStart : cursor position in selected string in IM.
977         size_t rStart = 0;
978         // rLength : selected string length in IM.
979         size_t rLength = 0;
980         if (cursor_pos < preedit_length) {
981                 for (int i = 0; i != att.size(); ++i) {
982                         if (att.at(i).type == QInputMethodEvent::TextFormat) {
983                                 if (att.at(i).start <= int(cursor_pos)
984                                         && int(cursor_pos) < att.at(i).start + att.at(i).length) {
985                                                 rStart = att.at(i).start;
986                                                 rLength = att.at(i).length;
987                                                 if (!cursor_is_visible)
988                                                         cursor_pos += rLength;
989                                                 break;
990                                 }
991                         }
992                 }
993         }
994         else {
995                 rStart = cursor_pos;
996                 rLength = 0;
997         }
998
999         int const right_margin = buffer_view_->rightMargin();
1000         Painter::preedit_style ps;
1001         // Most often there would be only one line:
1002         preedit_lines_ = 1;
1003         for (size_t pos = 0; pos != preedit_length; ++pos) {
1004                 char_type const typed_char = preedit_string[pos];
1005                 // reset preedit string style
1006                 ps = Painter::preedit_default;
1007
1008                 // if we reached the right extremity of the screen, go to next line.
1009                 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1010                         cur_x = right_margin;
1011                         cur_y += height + 1;
1012                         ++preedit_lines_;
1013                 }
1014                 // preedit strings are displayed with dashed underline
1015                 // and partial strings are displayed white on black indicating
1016                 // that we are in selecting mode in the input method.
1017                 // FIXME: rLength == preedit_length is not a changing condition
1018                 // FIXME: should be put out of the loop.
1019                 if (pos >= rStart
1020                         && pos < rStart + rLength
1021                         && !(cursor_pos < rLength && rLength == preedit_length))
1022                         ps = Painter::preedit_selecting;
1023
1024                 if (pos == cursor_pos
1025                         && (cursor_pos < rLength && rLength == preedit_length))
1026                         ps = Painter::preedit_cursor;
1027
1028                 // draw one character and update cur_x.
1029                 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1030         }
1031
1032         // update the preedit string screen area.
1033         update(0, cur_y - preedit_lines_*height, viewport()->width(),
1034                 (height + 1) * preedit_lines_);
1035
1036         // Don't forget to accept the event!
1037         e->accept();
1038 }
1039
1040
1041 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1042 {
1043         QRect cur_r(0,0,0,0);
1044         switch (query) {
1045                 // this is the CJK-specific composition window position.
1046                 case Qt::ImMicroFocus:
1047                         cur_r = cursor_->rect();
1048                         if (preedit_lines_ != 1)
1049                                 cur_r.moveLeft(10);
1050                         cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1051                         // return lower right of cursor in LyX.
1052                         return cur_r;
1053                 default:
1054                         return QWidget::inputMethodQuery(query);
1055         }
1056 }
1057
1058
1059 void GuiWorkArea::updateWindowTitle()
1060 {
1061         docstring maximize_title;
1062         docstring minimize_title;
1063
1064         Buffer & buf = buffer_view_->buffer();
1065         FileName const fileName = buf.fileName();
1066         if (!fileName.empty()) {
1067                 maximize_title = fileName.displayName(30);
1068                 minimize_title = from_utf8(fileName.onlyFileName());
1069                 if (!buf.isClean()) {
1070                         maximize_title += _(" (changed)");
1071                         minimize_title += char_type('*');
1072                 }
1073                 if (buf.isReadonly())
1074                         maximize_title += _(" (read only)");
1075         }
1076
1077         QString title = windowTitle();
1078         QString new_title = toqstr(maximize_title);
1079         if (title == new_title)
1080                 return;
1081
1082         QWidget::setWindowTitle(new_title);
1083         QWidget::setWindowIconText(toqstr(minimize_title));
1084         titleChanged(this);
1085 }
1086
1087
1088 void GuiWorkArea::setReadOnly(bool)
1089 {
1090         updateWindowTitle();
1091         if (this == lyx_view_->currentWorkArea())
1092                 lyx_view_->updateBufferDependent(false);
1093 }
1094
1095
1096 bool GuiWorkArea::isFullScreen()
1097 {
1098         return lyx_view_ && lyx_view_->isFullScreen();
1099 }
1100
1101
1102 ////////////////////////////////////////////////////////////////////
1103 //
1104 // TabWorkArea 
1105 //
1106 ////////////////////////////////////////////////////////////////////
1107
1108 TabWorkArea::TabWorkArea(QWidget * parent) : QTabWidget(parent)
1109 {
1110         QPalette pal = palette();
1111         pal.setColor(QPalette::Active, QPalette::Button,
1112                 pal.color(QPalette::Active, QPalette::Window));
1113         pal.setColor(QPalette::Disabled, QPalette::Button,
1114                 pal.color(QPalette::Disabled, QPalette::Window));
1115         pal.setColor(QPalette::Inactive, QPalette::Button,
1116                 pal.color(QPalette::Inactive, QPalette::Window));
1117
1118         QObject::connect(this, SIGNAL(currentChanged(int)),
1119                 this, SLOT(on_currentTabChanged(int)));
1120
1121         QToolButton * closeBufferButton = new QToolButton(this);
1122     closeBufferButton->setPalette(pal);
1123         // FIXME: rename the icon to closebuffer.png
1124         closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1125         closeBufferButton->setText("Close File");
1126         closeBufferButton->setAutoRaise(true);
1127         closeBufferButton->setCursor(Qt::ArrowCursor);
1128         closeBufferButton->setToolTip(qt_("Close File"));
1129         closeBufferButton->setEnabled(true);
1130         QObject::connect(closeBufferButton, SIGNAL(clicked()),
1131                 this, SLOT(closeCurrentBuffer()));
1132         setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1133
1134         QToolButton * closeTabButton = new QToolButton(this);
1135     closeTabButton->setPalette(pal);
1136         closeTabButton->setIcon(QIcon(":/images/hidetab.png"));
1137         closeTabButton->setText("Hide tab");
1138         closeTabButton->setAutoRaise(true);
1139         closeTabButton->setCursor(Qt::ArrowCursor);
1140         closeTabButton->setToolTip(qt_("Hide tab"));
1141         closeTabButton->setEnabled(true);
1142         QObject::connect(closeTabButton, SIGNAL(clicked()),
1143                 this, SLOT(closeCurrentTab()));
1144         setCornerWidget(closeTabButton, Qt::TopLeftCorner);
1145
1146         setUsesScrollButtons(true);
1147 }
1148
1149
1150 void TabWorkArea::setFullScreen(bool full_screen)
1151 {
1152         for (int i = 0; i != count(); ++i) {
1153                 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1154                         wa->setFullScreen(full_screen);
1155         }
1156
1157         if (lyxrc.full_screen_tabbar)
1158                 showBar(!full_screen && count()>1);
1159 }
1160
1161
1162 void TabWorkArea::showBar(bool show)
1163 {
1164         tabBar()->setEnabled(show);
1165         tabBar()->setVisible(show);
1166 }
1167
1168
1169 GuiWorkArea * TabWorkArea::currentWorkArea()
1170 {
1171         if (count() == 0)
1172                 return 0;
1173
1174         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget()); 
1175         BOOST_ASSERT(wa);
1176         return wa;
1177 }
1178
1179
1180 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1181 {
1182         for (int i = 0; i != count(); ++i) {
1183                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1184                 BOOST_ASSERT(wa);
1185                 if (&wa->bufferView().buffer() == &buffer)
1186                         return wa;
1187         }
1188         return 0;
1189 }
1190
1191
1192 void TabWorkArea::closeAll()
1193 {
1194         while (count()) {
1195                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1196                 BOOST_ASSERT(wa);
1197                 removeTab(0);
1198                 delete wa;
1199         }
1200 }
1201
1202
1203 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1204 {
1205         BOOST_ASSERT(work_area);
1206         int index = indexOf(work_area);
1207         if (index == -1)
1208                 return false;
1209
1210         if (index == currentIndex())
1211                 // Make sure the work area is up to date.
1212                 on_currentTabChanged(index);
1213         else
1214                 // Switch to the work area.
1215                 setCurrentIndex(index);
1216         work_area->setFocus();
1217
1218         return true;
1219 }
1220
1221
1222 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1223 {
1224         GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1225         wa->setUpdatesEnabled(false);
1226         // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1227         // when hiding it again below).
1228         if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1229                 showBar(count() > 0);
1230         addTab(wa, wa->windowTitle());
1231         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1232                 this, SLOT(updateTabText(GuiWorkArea *)));
1233         if (currentWorkArea() && currentWorkArea()->isFullScreen())
1234                 setFullScreen(true);
1235         else
1236                 // Hide tabbar if there's only one tab.
1237                 showBar(count() > 1);
1238
1239         return wa;
1240 }
1241
1242
1243 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1244 {
1245         BOOST_ASSERT(work_area);
1246         int index = indexOf(work_area);
1247         if (index == -1)
1248                 return false;
1249
1250         work_area->setUpdatesEnabled(false);
1251         removeTab(index);
1252         delete work_area;
1253
1254         if (count()) {
1255                 // make sure the next work area is enabled.
1256                 currentWidget()->setUpdatesEnabled(true);
1257                 if ((currentWorkArea() && currentWorkArea()->isFullScreen()))
1258                         setFullScreen(true);
1259                 else
1260                         // Hide tabbar if there's only one tab.
1261                         showBar(count() > 1);
1262         }
1263         return true;
1264 }
1265
1266
1267 void TabWorkArea::on_currentTabChanged(int i)
1268 {
1269         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1270         BOOST_ASSERT(wa);
1271         BufferView & bv = wa->bufferView();
1272         bv.cursor().fixIfBroken();
1273         bv.updateMetrics();
1274         wa->setUpdatesEnabled(true);
1275         wa->redraw();
1276         wa->setFocus();
1277         ///
1278         currentWorkAreaChanged(wa);
1279
1280         LYXERR(Debug::GUI, "currentTabChanged " << i
1281                 << "File" << bv.buffer().absFileName());
1282 }
1283
1284
1285 void TabWorkArea::closeCurrentBuffer()
1286 {
1287         lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1288 }
1289
1290
1291 void TabWorkArea::closeCurrentTab()
1292 {
1293         removeWorkArea(currentWorkArea());
1294 }
1295
1296
1297 void TabWorkArea::updateTabText(GuiWorkArea * wa)
1298 {
1299         int const i = indexOf(wa);
1300         if (i < 0)
1301                 return;
1302         setTabText(i, wa->windowTitle());
1303 }
1304
1305 } // namespace frontend
1306 } // namespace lyx
1307
1308 #include "GuiWorkArea_moc.cpp"