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