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