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