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