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