]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.cpp
* cosmetic
[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         if (lyx_view_->currentWorkArea() != this)
616                 lyx_view_->setCurrentWorkArea(this);
617
618         // Repaint the whole screen.
619         // Note: this is different from redraw() as only the backing pixmap
620         // will be redrawn, which is cheap.
621         viewport()->repaint();
622
623         startBlinkingCursor();
624         QAbstractScrollArea::focusInEvent(e);
625 }
626
627
628 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
629 {
630         stopBlinkingCursor();
631         QAbstractScrollArea::focusOutEvent(e);
632 }
633
634
635 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
636 {
637         if (dc_event_.active && dc_event_ == *e) {
638                 dc_event_.active = false;
639                 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
640                         q_button_state(e->button()));
641                 dispatch(cmd);
642                 e->accept();
643                 return;
644         }
645
646         inputContext()->reset();
647
648         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
649                 q_button_state(e->button()));
650         dispatch(cmd, q_key_state(e->modifiers()));
651         e->accept();
652 }
653
654
655 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
656 {
657         if (synthetic_mouse_event_.timeout.running())
658                 synthetic_mouse_event_.timeout.stop();
659
660         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
661                               q_button_state(e->button()));
662         dispatch(cmd);
663         e->accept();
664 }
665
666
667 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
668 {
669         // we kill the triple click if we move
670         doubleClickTimeout();
671         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
672                 q_motion_state(e->buttons()));
673
674         e->accept();
675
676         // If we're above or below the work area...
677         if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
678                 // Make sure only a synthetic event can cause a page scroll,
679                 // so they come at a steady rate:
680                 if (e->y() <= 20)
681                         // _Force_ a scroll up:
682                         cmd.y = -40;
683                 else
684                         cmd.y = viewport()->height();
685                 // Store the event, to be handled when the timeout expires.
686                 synthetic_mouse_event_.cmd = cmd;
687
688                 if (synthetic_mouse_event_.timeout.running())
689                         // Discard the event. Note that it _may_ be handled
690                         // when the timeout expires if
691                         // synthetic_mouse_event_.cmd has not been overwritten.
692                         // Ie, when the timeout expires, we handle the
693                         // most recent event but discard all others that
694                         // occurred after the one used to start the timeout
695                         // in the first place.
696                         return;
697
698                 synthetic_mouse_event_.restart_timeout = true;
699                 synthetic_mouse_event_.timeout.start();
700                 // Fall through to handle this event...
701
702         } else if (synthetic_mouse_event_.timeout.running()) {
703                 // Store the event, to be possibly handled when the timeout
704                 // expires.
705                 // Once the timeout has expired, normal control is returned
706                 // to mouseMoveEvent (restart_timeout = false).
707                 // This results in a much smoother 'feel' when moving the
708                 // mouse back into the work area.
709                 synthetic_mouse_event_.cmd = cmd;
710                 synthetic_mouse_event_.restart_timeout = false;
711                 return;
712         }
713
714         // Has anything changed on-screen since the last QMouseEvent
715         // was received?
716         double const scrollbar_value = verticalScrollBar()->value();
717         if (e->x() == synthetic_mouse_event_.x_old
718                 && e->y() == synthetic_mouse_event_.y_old
719                 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
720                 // Nothing changed on-screen since the last QMouseEvent.
721                 return;
722         }
723
724         // Yes something has changed. Store the params used to check this.
725         synthetic_mouse_event_.x_old = e->x();
726         synthetic_mouse_event_.y_old = e->y();
727         synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
728
729         // ... and dispatch the event to the LyX core.
730         dispatch(cmd);
731 }
732
733
734 void GuiWorkArea::wheelEvent(QWheelEvent * e)
735 {
736         // Wheel rotation by one notch results in a delta() of 120 (see
737         // documentation of QWheelEvent)
738         double const lines = qApp->wheelScrollLines()
739                 * lyxrc.mouse_wheel_speed
740                 * e->delta() / 120.0;
741         LYXERR(Debug::SCROLLING, "wheelScrollLines = " << qApp->wheelScrollLines()
742                 << " delta = " << e->delta()
743                 << " lines = " << lines);
744         verticalScrollBar()->setValue(verticalScrollBar()->value() -
745                 int(lines *  verticalScrollBar()->singleStep()));
746         e->accept();
747 }
748
749
750 void GuiWorkArea::generateSyntheticMouseEvent()
751 {
752         // Set things off to generate the _next_ 'pseudo' event.
753         if (synthetic_mouse_event_.restart_timeout)
754                 synthetic_mouse_event_.timeout.start();
755
756         // Has anything changed on-screen since the last timeout signal
757         // was received?
758         double const scrollbar_value = verticalScrollBar()->value();
759         if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
760                 // Yes it has. Store the params used to check this.
761                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
762
763                 // ... and dispatch the event to the LyX core.
764                 dispatch(synthetic_mouse_event_.cmd);
765         }
766 }
767
768
769 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
770 {
771         // intercept some keys if completion popup is visible
772         if (completer_.popupVisible()) {
773                 switch (ev->key()) {
774                 case Qt::Key_Enter:
775                 case Qt::Key_Return:
776                         completer_.activate();
777                         ev->accept();
778                         return;
779                 }
780         }
781         
782         // intercept keys for the completion
783         if (ev->key() == Qt::Key_Tab) {
784                 completer_.tab();
785                 ev->accept();
786                 return;
787         } 
788
789         if (completer_.popupVisible() && ev->key() == Qt::Key_Escape) {
790                 completer_.hidePopup();
791                 ev->accept();
792                 return;
793         }
794
795         if (completer_.inlineVisible() && ev->key() == Qt::Key_Escape) {
796                 completer_.hideInline();
797                 ev->accept();
798                 return;
799         }
800
801         // do nothing if there are other events
802         // (the auto repeated events come too fast)
803         // \todo FIXME: remove hard coded Qt keys, process the key binding
804 #ifdef Q_WS_X11
805         if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat() 
806                         && (Qt::Key_PageDown || Qt::Key_PageUp)) {
807                 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
808                 ev->ignore();
809                 return;
810         }
811 #endif
812
813         LYXERR(Debug::KEY, " count: " << ev->count()
814                 << " text: " << fromqstr(ev->text())
815                 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
816
817         KeySymbol sym;
818         setKeySymbol(&sym, ev);
819         processKeySym(sym, q_key_state(ev->modifiers()));
820         ev->accept();
821 }
822
823
824 void GuiWorkArea::doubleClickTimeout()
825 {
826         dc_event_.active = false;
827 }
828
829
830 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
831 {
832         dc_event_ = DoubleClick(ev);
833         QTimer::singleShot(QApplication::doubleClickInterval(), this,
834                            SLOT(doubleClickTimeout()));
835         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
836                         ev->x(), ev->y(),
837                         q_button_state(ev->button()));
838         dispatch(cmd);
839         ev->accept();
840 }
841
842
843 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
844 {
845         QAbstractScrollArea::resizeEvent(ev);
846         need_resize_ = true;
847         ev->accept();
848 }
849
850
851 void GuiWorkArea::update(int x, int y, int w, int h)
852 {
853         viewport()->repaint(x, y, w, h);
854 }
855
856
857 void GuiWorkArea::paintEvent(QPaintEvent * ev)
858 {
859         QRect const rc = ev->rect();
860         // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
861         //      << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
862
863         if (need_resize_) {
864                 screen_ = QPixmap(viewport()->width(), viewport()->height());
865                 resizeBufferView();
866                 hideCursor();
867                 showCursor();
868         }
869
870         QPainter pain(viewport());
871         pain.drawPixmap(rc, screen_, rc);
872         cursor_->draw(pain);
873         ev->accept();
874 }
875
876
877 void GuiWorkArea::updateScreen()
878 {
879         GuiPainter pain(&screen_);
880         buffer_view_->draw(pain);
881 }
882
883
884 void GuiWorkArea::showCursor(int x, int y, int h,
885         bool l_shape, bool rtl, bool completable)
886 {
887         if (schedule_redraw_) {
888                 buffer_view_->updateMetrics();
889                 updateScreen();
890                 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
891                 schedule_redraw_ = false;
892                 // Show the cursor immediately after the update.
893                 hideCursor();
894                 toggleCursor();
895                 return;
896         }
897
898         cursor_->update(x, y, h, l_shape, rtl, completable);
899         cursor_->show();
900         viewport()->update(cursor_->rect());
901 }
902
903
904 void GuiWorkArea::removeCursor()
905 {
906         cursor_->hide();
907         //if (!qApp->focusWidget())
908                 viewport()->update(cursor_->rect());
909 }
910
911
912 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
913 {
914         QString const & commit_string = e->commitString();
915         docstring const & preedit_string
916                 = qstring_to_ucs4(e->preeditString());
917
918         if (!commit_string.isEmpty()) {
919
920                 LYXERR(Debug::KEY, "preeditString: " << fromqstr(e->preeditString())
921                         << " commitString: " << fromqstr(e->commitString()));
922
923                 int key = 0;
924
925                 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
926                 for (int i = 0; i != commit_string.size(); ++i) {
927                         QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
928                         keyPressEvent(&ev);
929                 }
930         }
931
932         // Hide the cursor during the kana-kanji transformation.
933         if (preedit_string.empty())
934                 startBlinkingCursor();
935         else
936                 stopBlinkingCursor();
937
938         // last_width : for checking if last preedit string was/wasn't empty.
939         static bool last_width = false;
940         if (!last_width && preedit_string.empty()) {
941                 // if last_width is last length of preedit string.
942                 e->accept();
943                 return;
944         }
945
946         GuiPainter pain(&screen_);
947         buffer_view_->updateMetrics();
948         buffer_view_->draw(pain);
949         FontInfo font = buffer_view_->cursor().getFont().fontInfo();
950         FontMetrics const & fm = theFontMetrics(font);
951         int height = fm.maxHeight();
952         int cur_x = cursor_->rect().left();
953         int cur_y = cursor_->rect().bottom();
954
955         // redraw area of preedit string.
956         update(0, cur_y - height, viewport()->width(),
957                 (height + 1) * preedit_lines_);
958
959         if (preedit_string.empty()) {
960                 last_width = false;
961                 preedit_lines_ = 1;
962                 e->accept();
963                 return;
964         }
965         last_width = true;
966
967         // att : stores an IM attribute.
968         QList<QInputMethodEvent::Attribute> const & att = e->attributes();
969
970         // get attributes of input method cursor.
971         // cursor_pos : cursor position in preedit string.
972         size_t cursor_pos = 0;
973         bool cursor_is_visible = false;
974         for (int i = 0; i != att.size(); ++i) {
975                 if (att.at(i).type == QInputMethodEvent::Cursor) {
976                         cursor_pos = att.at(i).start;
977                         cursor_is_visible = att.at(i).length != 0;
978                         break;
979                 }
980         }
981
982         size_t preedit_length = preedit_string.length();
983
984         // get position of selection in input method.
985         // FIXME: isn't there a way to do this simplier?
986         // rStart : cursor position in selected string in IM.
987         size_t rStart = 0;
988         // rLength : selected string length in IM.
989         size_t rLength = 0;
990         if (cursor_pos < preedit_length) {
991                 for (int i = 0; i != att.size(); ++i) {
992                         if (att.at(i).type == QInputMethodEvent::TextFormat) {
993                                 if (att.at(i).start <= int(cursor_pos)
994                                         && int(cursor_pos) < att.at(i).start + att.at(i).length) {
995                                                 rStart = att.at(i).start;
996                                                 rLength = att.at(i).length;
997                                                 if (!cursor_is_visible)
998                                                         cursor_pos += rLength;
999                                                 break;
1000                                 }
1001                         }
1002                 }
1003         }
1004         else {
1005                 rStart = cursor_pos;
1006                 rLength = 0;
1007         }
1008
1009         int const right_margin = buffer_view_->rightMargin();
1010         Painter::preedit_style ps;
1011         // Most often there would be only one line:
1012         preedit_lines_ = 1;
1013         for (size_t pos = 0; pos != preedit_length; ++pos) {
1014                 char_type const typed_char = preedit_string[pos];
1015                 // reset preedit string style
1016                 ps = Painter::preedit_default;
1017
1018                 // if we reached the right extremity of the screen, go to next line.
1019                 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1020                         cur_x = right_margin;
1021                         cur_y += height + 1;
1022                         ++preedit_lines_;
1023                 }
1024                 // preedit strings are displayed with dashed underline
1025                 // and partial strings are displayed white on black indicating
1026                 // that we are in selecting mode in the input method.
1027                 // FIXME: rLength == preedit_length is not a changing condition
1028                 // FIXME: should be put out of the loop.
1029                 if (pos >= rStart
1030                         && pos < rStart + rLength
1031                         && !(cursor_pos < rLength && rLength == preedit_length))
1032                         ps = Painter::preedit_selecting;
1033
1034                 if (pos == cursor_pos
1035                         && (cursor_pos < rLength && rLength == preedit_length))
1036                         ps = Painter::preedit_cursor;
1037
1038                 // draw one character and update cur_x.
1039                 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1040         }
1041
1042         // update the preedit string screen area.
1043         update(0, cur_y - preedit_lines_*height, viewport()->width(),
1044                 (height + 1) * preedit_lines_);
1045
1046         // Don't forget to accept the event!
1047         e->accept();
1048 }
1049
1050
1051 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1052 {
1053         QRect cur_r(0,0,0,0);
1054         switch (query) {
1055                 // this is the CJK-specific composition window position.
1056                 case Qt::ImMicroFocus:
1057                         cur_r = cursor_->rect();
1058                         if (preedit_lines_ != 1)
1059                                 cur_r.moveLeft(10);
1060                         cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1061                         // return lower right of cursor in LyX.
1062                         return cur_r;
1063                 default:
1064                         return QWidget::inputMethodQuery(query);
1065         }
1066 }
1067
1068
1069 void GuiWorkArea::updateWindowTitle()
1070 {
1071         docstring maximize_title;
1072         docstring minimize_title;
1073
1074         Buffer & buf = buffer_view_->buffer();
1075         FileName const fileName = buf.fileName();
1076         if (!fileName.empty()) {
1077                 maximize_title = fileName.displayName(30);
1078                 minimize_title = from_utf8(fileName.onlyFileName());
1079                 if (!buf.isClean()) {
1080                         maximize_title += _(" (changed)");
1081                         minimize_title += char_type('*');
1082                 }
1083                 if (buf.isReadonly())
1084                         maximize_title += _(" (read only)");
1085         }
1086
1087         QString title = windowTitle();
1088         QString new_title = toqstr(maximize_title);
1089         if (title == new_title)
1090                 return;
1091
1092         QWidget::setWindowTitle(new_title);
1093         QWidget::setWindowIconText(toqstr(minimize_title));
1094         titleChanged(this);
1095 }
1096
1097
1098 void GuiWorkArea::setReadOnly(bool)
1099 {
1100         updateWindowTitle();
1101         if (this == lyx_view_->currentWorkArea())
1102                 lyx_view_->updateBufferDependent(false);
1103 }
1104
1105
1106 bool GuiWorkArea::isFullScreen()
1107 {
1108         return lyx_view_ && lyx_view_->isFullScreen();
1109 }
1110
1111
1112 ////////////////////////////////////////////////////////////////////
1113 //
1114 // TabWorkArea 
1115 //
1116 ////////////////////////////////////////////////////////////////////
1117
1118 TabWorkArea::TabWorkArea(QWidget * parent) : QTabWidget(parent)
1119 {
1120         QPalette pal = palette();
1121         pal.setColor(QPalette::Active, QPalette::Button,
1122                 pal.color(QPalette::Active, QPalette::Window));
1123         pal.setColor(QPalette::Disabled, QPalette::Button,
1124                 pal.color(QPalette::Disabled, QPalette::Window));
1125         pal.setColor(QPalette::Inactive, QPalette::Button,
1126                 pal.color(QPalette::Inactive, QPalette::Window));
1127
1128         QObject::connect(this, SIGNAL(currentChanged(int)),
1129                 this, SLOT(on_currentTabChanged(int)));
1130
1131         QToolButton * closeBufferButton = new QToolButton(this);
1132     closeBufferButton->setPalette(pal);
1133         // FIXME: rename the icon to closebuffer.png
1134         closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1135         closeBufferButton->setText("Close File");
1136         closeBufferButton->setAutoRaise(true);
1137         closeBufferButton->setCursor(Qt::ArrowCursor);
1138         closeBufferButton->setToolTip(qt_("Close File"));
1139         closeBufferButton->setEnabled(true);
1140         QObject::connect(closeBufferButton, SIGNAL(clicked()),
1141                 this, SLOT(closeCurrentBuffer()));
1142         setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1143
1144         QToolButton * closeTabButton = new QToolButton(this);
1145     closeTabButton->setPalette(pal);
1146         closeTabButton->setIcon(QIcon(":/images/hidetab.png"));
1147         closeTabButton->setText("Hide tab");
1148         closeTabButton->setAutoRaise(true);
1149         closeTabButton->setCursor(Qt::ArrowCursor);
1150         closeTabButton->setToolTip(qt_("Hide tab"));
1151         closeTabButton->setEnabled(true);
1152         QObject::connect(closeTabButton, SIGNAL(clicked()),
1153                 this, SLOT(closeCurrentTab()));
1154         setCornerWidget(closeTabButton, Qt::TopLeftCorner);
1155
1156         setUsesScrollButtons(true);
1157 }
1158
1159
1160 void TabWorkArea::setFullScreen(bool full_screen)
1161 {
1162         for (int i = 0; i != count(); ++i) {
1163                 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1164                         wa->setFullScreen(full_screen);
1165         }
1166
1167         if (lyxrc.full_screen_tabbar)
1168                 showBar(!full_screen && count()>1);
1169 }
1170
1171
1172 void TabWorkArea::showBar(bool show)
1173 {
1174         tabBar()->setEnabled(show);
1175         tabBar()->setVisible(show);
1176 }
1177
1178
1179 GuiWorkArea * TabWorkArea::currentWorkArea()
1180 {
1181         if (count() == 0)
1182                 return 0;
1183
1184         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget()); 
1185         BOOST_ASSERT(wa);
1186         return wa;
1187 }
1188
1189
1190 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1191 {
1192         for (int i = 0; i != count(); ++i) {
1193                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1194                 BOOST_ASSERT(wa);
1195                 if (&wa->bufferView().buffer() == &buffer)
1196                         return wa;
1197         }
1198         return 0;
1199 }
1200
1201
1202 void TabWorkArea::closeAll()
1203 {
1204         while (count()) {
1205                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1206                 BOOST_ASSERT(wa);
1207                 removeTab(0);
1208                 delete wa;
1209         }
1210 }
1211
1212
1213 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1214 {
1215         BOOST_ASSERT(work_area);
1216         int index = indexOf(work_area);
1217         if (index == -1)
1218                 return false;
1219
1220         if (index == currentIndex())
1221                 // Make sure the work area is up to date.
1222                 on_currentTabChanged(index);
1223         else
1224                 // Switch to the work area.
1225                 setCurrentIndex(index);
1226         work_area->setFocus();
1227
1228         return true;
1229 }
1230
1231
1232 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1233 {
1234         GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1235         wa->setUpdatesEnabled(false);
1236         // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1237         // when hiding it again below).
1238         if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1239                 showBar(count() > 0);
1240         addTab(wa, wa->windowTitle());
1241         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1242                 this, SLOT(updateTabText(GuiWorkArea *)));
1243         if (currentWorkArea() && currentWorkArea()->isFullScreen())
1244                 setFullScreen(true);
1245         else
1246                 // Hide tabbar if there's only one tab.
1247                 showBar(count() > 1);
1248
1249         return wa;
1250 }
1251
1252
1253 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1254 {
1255         BOOST_ASSERT(work_area);
1256         int index = indexOf(work_area);
1257         if (index == -1)
1258                 return false;
1259
1260         work_area->setUpdatesEnabled(false);
1261         removeTab(index);
1262         delete work_area;
1263
1264         if (count()) {
1265                 // make sure the next work area is enabled.
1266                 currentWidget()->setUpdatesEnabled(true);
1267                 if ((currentWorkArea() && currentWorkArea()->isFullScreen()))
1268                         setFullScreen(true);
1269                 else
1270                         // Hide tabbar if there's only one tab.
1271                         showBar(count() > 1);
1272         }
1273         return true;
1274 }
1275
1276
1277 void TabWorkArea::on_currentTabChanged(int i)
1278 {
1279         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1280         BOOST_ASSERT(wa);
1281         BufferView & bv = wa->bufferView();
1282         bv.cursor().fixIfBroken();
1283         bv.updateMetrics();
1284         wa->setUpdatesEnabled(true);
1285         wa->redraw();
1286         wa->setFocus();
1287         ///
1288         currentWorkAreaChanged(wa);
1289
1290         LYXERR(Debug::GUI, "currentTabChanged " << i
1291                 << "File" << bv.buffer().absFileName());
1292 }
1293
1294
1295 void TabWorkArea::closeCurrentBuffer()
1296 {
1297         lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1298 }
1299
1300
1301 void TabWorkArea::closeCurrentTab()
1302 {
1303         removeWorkArea(currentWorkArea());
1304 }
1305
1306
1307 void TabWorkArea::updateTabText(GuiWorkArea * wa)
1308 {
1309         int const i = indexOf(wa);
1310         if (i < 0)
1311                 return;
1312         setTabText(i, wa->windowTitle());
1313 }
1314
1315 } // namespace frontend
1316 } // namespace lyx
1317
1318 #include "GuiWorkArea_moc.cpp"