]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.cpp
* The BufferView sets up its scrollbar data when it first gets its
[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 << "wheelScrollLines = " << qApp->wheelScrollLines()
672                 << " delta = " << e->delta()
673                 << " lines = " << lines
674                 << std::endl;
675         verticalScrollBar()->setValue(verticalScrollBar()->value() -
676                 int(lines *  verticalScrollBar()->singleStep()));
677 }
678
679
680 void GuiWorkArea::generateSyntheticMouseEvent()
681 {
682 // Set things off to generate the _next_ 'pseudo' event.
683         if (synthetic_mouse_event_.restart_timeout)
684                 synthetic_mouse_event_.timeout.start();
685
686         // Has anything changed on-screen since the last timeout signal
687         // was received?
688         double const scrollbar_value = verticalScrollBar()->value();
689         if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
690                 // Yes it has. Store the params used to check this.
691                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
692
693                 // ... and dispatch the event to the LyX core.
694                 dispatch(synthetic_mouse_event_.cmd);
695         }
696 }
697
698
699 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
700 {
701         // do nothing if there are other events
702         // (the auto repeated events come too fast)
703         // \todo FIXME: remove hard coded Qt keys, process the key binding
704 #ifdef Q_WS_X11
705         if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat() 
706                         && (Qt::Key_PageDown || Qt::Key_PageUp)) {
707                 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
708                 ev->ignore();
709                 return;
710         }
711 #endif
712
713         LYXERR(Debug::KEY, " count: " << ev->count()
714                 << " text: " << fromqstr(ev->text())
715                 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
716
717         KeySymbol sym;
718         setKeySymbol(&sym, ev);
719         processKeySym(sym, q_key_state(ev->modifiers()));
720         ev->accept();
721 }
722
723
724 void GuiWorkArea::doubleClickTimeout()
725 {
726         dc_event_.active = false;
727 }
728
729
730 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
731 {
732         dc_event_ = DoubleClick(ev);
733         QTimer::singleShot(QApplication::doubleClickInterval(), this,
734                            SLOT(doubleClickTimeout()));
735         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
736                         ev->x(), ev->y(),
737                         q_button_state(ev->button()));
738         dispatch(cmd);
739 }
740
741
742 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
743 {
744         QAbstractScrollArea::resizeEvent(ev);
745         need_resize_ = true;
746 }
747
748
749 void GuiWorkArea::update(int x, int y, int w, int h)
750 {
751         viewport()->repaint(x, y, w, h);
752 }
753
754
755 void GuiWorkArea::paintEvent(QPaintEvent * ev)
756 {
757         QRect const rc = ev->rect();
758         // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
759         //      << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
760
761         if (need_resize_) {
762                 screen_ = QPixmap(viewport()->width(), viewport()->height());
763                 resizeBufferView();
764                 
765                 // Update scrollbars which might have changed due different
766                 // BufferView dimension. This is especially important when the 
767                 // BufferView goes from zero-size to the real-size for the first time,
768                 // as the scrollbar paramters are then set for the first time.
769                 updateScrollbar();
770                 BOOST_ASSERT(need_resize_ == false);
771                 
772                 updateScreen();
773                 hideCursor();
774                 showCursor();
775         }
776
777         QPainter pain(viewport());
778         pain.drawPixmap(rc, screen_, rc);
779         cursor_->draw(pain);
780 }
781
782
783 void GuiWorkArea::updateScreen()
784 {
785         GuiPainter pain(&screen_);
786         buffer_view_->draw(pain);
787 }
788
789
790 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
791 {
792         if (schedule_redraw_) {
793                 buffer_view_->updateMetrics();
794                 updateScreen();
795                 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
796                 schedule_redraw_ = false;
797                 // Show the cursor immediately after the update.
798                 hideCursor();
799                 toggleCursor();
800                 return;
801         }
802
803         cursor_->update(x, y, h, shape);
804         cursor_->show();
805         viewport()->update(cursor_->rect());
806 }
807
808
809 void GuiWorkArea::removeCursor()
810 {
811         cursor_->hide();
812         //if (!qApp->focusWidget())
813                 viewport()->update(cursor_->rect());
814 }
815
816
817 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
818 {
819         QString const & commit_string = e->commitString();
820         docstring const & preedit_string
821                 = qstring_to_ucs4(e->preeditString());
822
823         if (!commit_string.isEmpty()) {
824
825                 LYXERR(Debug::KEY, "preeditString: " << fromqstr(e->preeditString())
826                         << " commitString: " << fromqstr(e->commitString()));
827
828                 int key = 0;
829
830                 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
831                 for (int i = 0; i != commit_string.size(); ++i) {
832                         QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
833                         keyPressEvent(&ev);
834                 }
835         }
836
837         // Hide the cursor during the kana-kanji transformation.
838         if (preedit_string.empty())
839                 startBlinkingCursor();
840         else
841                 stopBlinkingCursor();
842
843         // last_width : for checking if last preedit string was/wasn't empty.
844         static bool last_width = false;
845         if (!last_width && preedit_string.empty()) {
846                 // if last_width is last length of preedit string.
847                 e->accept();
848                 return;
849         }
850
851         GuiPainter pain(&screen_);
852         buffer_view_->updateMetrics();
853         buffer_view_->draw(pain);
854         FontInfo font = buffer_view_->cursor().getFont().fontInfo();
855         FontMetrics const & fm = theFontMetrics(font);
856         int height = fm.maxHeight();
857         int cur_x = cursor_->rect().left();
858         int cur_y = cursor_->rect().bottom();
859
860         // redraw area of preedit string.
861         update(0, cur_y - height, viewport()->width(),
862                 (height + 1) * preedit_lines_);
863
864         if (preedit_string.empty()) {
865                 last_width = false;
866                 preedit_lines_ = 1;
867                 e->accept();
868                 return;
869         }
870         last_width = true;
871
872         // att : stores an IM attribute.
873         QList<QInputMethodEvent::Attribute> const & att = e->attributes();
874
875         // get attributes of input method cursor.
876         // cursor_pos : cursor position in preedit string.
877         size_t cursor_pos = 0;
878         bool cursor_is_visible = false;
879         for (int i = 0; i != att.size(); ++i) {
880                 if (att.at(i).type == QInputMethodEvent::Cursor) {
881                         cursor_pos = att.at(i).start;
882                         cursor_is_visible = att.at(i).length != 0;
883                         break;
884                 }
885         }
886
887         size_t preedit_length = preedit_string.length();
888
889         // get position of selection in input method.
890         // FIXME: isn't there a way to do this simplier?
891         // rStart : cursor position in selected string in IM.
892         size_t rStart = 0;
893         // rLength : selected string length in IM.
894         size_t rLength = 0;
895         if (cursor_pos < preedit_length) {
896                 for (int i = 0; i != att.size(); ++i) {
897                         if (att.at(i).type == QInputMethodEvent::TextFormat) {
898                                 if (att.at(i).start <= int(cursor_pos)
899                                         && int(cursor_pos) < att.at(i).start + att.at(i).length) {
900                                                 rStart = att.at(i).start;
901                                                 rLength = att.at(i).length;
902                                                 if (!cursor_is_visible)
903                                                         cursor_pos += rLength;
904                                                 break;
905                                 }
906                         }
907                 }
908         }
909         else {
910                 rStart = cursor_pos;
911                 rLength = 0;
912         }
913
914         int const right_margin = rightMargin();
915         Painter::preedit_style ps;
916         // Most often there would be only one line:
917         preedit_lines_ = 1;
918         for (size_t pos = 0; pos != preedit_length; ++pos) {
919                 char_type const typed_char = preedit_string[pos];
920                 // reset preedit string style
921                 ps = Painter::preedit_default;
922
923                 // if we reached the right extremity of the screen, go to next line.
924                 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
925                         cur_x = right_margin;
926                         cur_y += height + 1;
927                         ++preedit_lines_;
928                 }
929                 // preedit strings are displayed with dashed underline
930                 // and partial strings are displayed white on black indicating
931                 // that we are in selecting mode in the input method.
932                 // FIXME: rLength == preedit_length is not a changing condition
933                 // FIXME: should be put out of the loop.
934                 if (pos >= rStart
935                         && pos < rStart + rLength
936                         && !(cursor_pos < rLength && rLength == preedit_length))
937                         ps = Painter::preedit_selecting;
938
939                 if (pos == cursor_pos
940                         && (cursor_pos < rLength && rLength == preedit_length))
941                         ps = Painter::preedit_cursor;
942
943                 // draw one character and update cur_x.
944                 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
945         }
946
947         // update the preedit string screen area.
948         update(0, cur_y - preedit_lines_*height, viewport()->width(),
949                 (height + 1) * preedit_lines_);
950
951         // Don't forget to accept the event!
952         e->accept();
953 }
954
955
956 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
957 {
958         QRect cur_r(0,0,0,0);
959         switch (query) {
960                 // this is the CJK-specific composition window position.
961                 case Qt::ImMicroFocus:
962                         cur_r = cursor_->rect();
963                         if (preedit_lines_ != 1)
964                                 cur_r.moveLeft(10);
965                         cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
966                         // return lower right of cursor in LyX.
967                         return cur_r;
968                 default:
969                         return QWidget::inputMethodQuery(query);
970         }
971 }
972
973
974 void GuiWorkArea::updateWindowTitle()
975 {
976         docstring maximize_title;
977         docstring minimize_title;
978
979         Buffer & buf = buffer_view_->buffer();
980         FileName const fileName = buf.fileName();
981         if (!fileName.empty()) {
982                 maximize_title = fileName.displayName(30);
983                 minimize_title = from_utf8(fileName.onlyFileName());
984                 if (!buf.isClean()) {
985                         maximize_title += _(" (changed)");
986                         minimize_title += char_type('*');
987                 }
988                 if (buf.isReadonly())
989                         maximize_title += _(" (read only)");
990         }
991
992         QString title = windowTitle();
993         QString new_title = toqstr(maximize_title);
994         if (title == new_title)
995                 return;
996
997         QWidget::setWindowTitle(new_title);
998         QWidget::setWindowIconText(toqstr(minimize_title));
999         titleChanged(this);
1000 }
1001
1002
1003 void GuiWorkArea::setReadOnly(bool)
1004 {
1005         updateWindowTitle();
1006         if (this == lyx_view_->currentWorkArea())
1007                 lyx_view_->updateBufferDependent(false);
1008 }
1009
1010
1011 ////////////////////////////////////////////////////////////////////
1012 //
1013 // TabWorkArea 
1014 //
1015 ////////////////////////////////////////////////////////////////////
1016
1017 TabWorkArea::TabWorkArea(QWidget * parent) : QTabWidget(parent)
1018 {
1019         QPalette pal = palette();
1020         pal.setColor(QPalette::Active, QPalette::Button,
1021                 pal.color(QPalette::Active, QPalette::Window));
1022         pal.setColor(QPalette::Disabled, QPalette::Button,
1023                 pal.color(QPalette::Disabled, QPalette::Window));
1024         pal.setColor(QPalette::Inactive, QPalette::Button,
1025                 pal.color(QPalette::Inactive, QPalette::Window));
1026
1027         QToolButton * closeTabButton = new QToolButton(this);
1028     closeTabButton->setPalette(pal);
1029         closeTabButton->setIcon(QIcon(":/images/closetab.png"));
1030         closeTabButton->setText("Close");
1031         closeTabButton->setAutoRaise(true);
1032         closeTabButton->setCursor(Qt::ArrowCursor);
1033         closeTabButton->setToolTip(tr("Close tab"));
1034         closeTabButton->setEnabled(true);
1035
1036         QObject::connect(this, SIGNAL(currentChanged(int)),
1037                 this, SLOT(on_currentTabChanged(int)));
1038         QObject::connect(closeTabButton, SIGNAL(clicked()),
1039                 this, SLOT(closeCurrentTab()));
1040
1041         setCornerWidget(closeTabButton);
1042         setUsesScrollButtons(true);
1043 }
1044
1045
1046 void TabWorkArea::showBar(bool show)
1047 {
1048         tabBar()->setEnabled(show);
1049         tabBar()->setVisible(show);
1050 }
1051
1052
1053 GuiWorkArea * TabWorkArea::currentWorkArea()
1054 {
1055         if (count() == 0)
1056                 return 0;
1057
1058         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget()); 
1059         BOOST_ASSERT(wa);
1060         return wa;
1061 }
1062
1063
1064 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1065 {
1066         for (int i = 0; i != count(); ++i) {
1067                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1068                 BOOST_ASSERT(wa);
1069                 if (&wa->bufferView().buffer() == &buffer)
1070                         return wa;
1071         }
1072         return 0;
1073 }
1074
1075
1076 void TabWorkArea::closeAll()
1077 {
1078         while (count()) {
1079                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1080                 BOOST_ASSERT(wa);
1081                 removeTab(0);
1082                 delete wa;
1083         }
1084 }
1085
1086
1087 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1088 {
1089         BOOST_ASSERT(work_area);
1090         int index = indexOf(work_area);
1091         if (index == -1)
1092                 return false;
1093
1094         if (index == currentIndex())
1095                 // Make sure the work area is up to date.
1096                 on_currentTabChanged(index);
1097         else
1098                 // Switch to the work area.
1099                 setCurrentIndex(index);
1100         work_area->setFocus();
1101
1102         return true;
1103 }
1104
1105
1106 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1107 {
1108         GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1109         wa->setUpdatesEnabled(false);
1110         // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1111         // when hiding it again below).
1112         showBar(count() > 0);
1113         addTab(wa, wa->windowTitle());
1114         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1115                 this, SLOT(updateTabText(GuiWorkArea *)));
1116         // Hide tabbar if there's only one tab.
1117         showBar(count() > 1);
1118         return wa;
1119 }
1120
1121
1122 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1123 {
1124         BOOST_ASSERT(work_area);
1125         int index = indexOf(work_area);
1126         if (index == -1)
1127                 return false;
1128
1129         work_area->setUpdatesEnabled(false);
1130         removeTab(index);
1131         delete work_area;
1132
1133         if (count()) {
1134                 // make sure the next work area is enabled.
1135                 currentWidget()->setUpdatesEnabled(true);
1136                 // Hide tabbar if there's only one tab.
1137                 showBar(count() > 1);
1138         }
1139         return true;
1140 }
1141
1142
1143 void TabWorkArea::on_currentTabChanged(int i)
1144 {
1145         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1146         BOOST_ASSERT(wa);
1147         BufferView & bv = wa->bufferView();
1148         bv.cursor().fixIfBroken();
1149         bv.updateMetrics();
1150         wa->setUpdatesEnabled(true);
1151         wa->redraw();
1152         wa->setFocus();
1153         ///
1154         currentWorkAreaChanged(wa);
1155
1156         LYXERR(Debug::GUI, "currentTabChanged " << i
1157                 << "File" << bv.buffer().absFileName());
1158 }
1159
1160
1161 void TabWorkArea::closeCurrentTab()
1162 {
1163         lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1164 }
1165
1166
1167 void TabWorkArea::updateTabText(GuiWorkArea * wa)
1168 {
1169         int const i = indexOf(wa);
1170         if (i < 0)
1171                 return;
1172         setTabText(i, wa->windowTitle());
1173 }
1174
1175 } // namespace frontend
1176 } // namespace lyx
1177
1178 #include "GuiWorkArea_moc.cpp"