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