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