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