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