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