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