]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.cpp
Transfer forked process checking from GuiWorkArea to GuiApplication. I got rid of...
[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                 updateScreen();
765                 hideCursor();
766                 showCursor();
767         }
768
769         QPainter pain(viewport());
770         pain.drawPixmap(rc, screen_, rc);
771         cursor_->draw(pain);
772 }
773
774
775 void GuiWorkArea::updateScreen()
776 {
777         GuiPainter pain(&screen_);
778         buffer_view_->draw(pain);
779 }
780
781
782 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
783 {
784         if (schedule_redraw_) {
785                 buffer_view_->updateMetrics();
786                 updateScreen();
787                 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
788                 schedule_redraw_ = false;
789                 // Show the cursor immediately after the update.
790                 hideCursor();
791                 toggleCursor();
792                 return;
793         }
794
795         cursor_->update(x, y, h, shape);
796         cursor_->show();
797         viewport()->update(cursor_->rect());
798 }
799
800
801 void GuiWorkArea::removeCursor()
802 {
803         cursor_->hide();
804         //if (!qApp->focusWidget())
805                 viewport()->update(cursor_->rect());
806 }
807
808
809 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
810 {
811         QString const & commit_string = e->commitString();
812         docstring const & preedit_string
813                 = qstring_to_ucs4(e->preeditString());
814
815         if (!commit_string.isEmpty()) {
816
817                 LYXERR(Debug::KEY, "preeditString: " << fromqstr(e->preeditString())
818                         << " commitString: " << fromqstr(e->commitString()));
819
820                 int key = 0;
821
822                 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
823                 for (int i = 0; i != commit_string.size(); ++i) {
824                         QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
825                         keyPressEvent(&ev);
826                 }
827         }
828
829         // Hide the cursor during the kana-kanji transformation.
830         if (preedit_string.empty())
831                 startBlinkingCursor();
832         else
833                 stopBlinkingCursor();
834
835         // last_width : for checking if last preedit string was/wasn't empty.
836         static bool last_width = false;
837         if (!last_width && preedit_string.empty()) {
838                 // if last_width is last length of preedit string.
839                 e->accept();
840                 return;
841         }
842
843         GuiPainter pain(&screen_);
844         buffer_view_->updateMetrics();
845         buffer_view_->draw(pain);
846         FontInfo font = buffer_view_->cursor().getFont().fontInfo();
847         FontMetrics const & fm = theFontMetrics(font);
848         int height = fm.maxHeight();
849         int cur_x = cursor_->rect().left();
850         int cur_y = cursor_->rect().bottom();
851
852         // redraw area of preedit string.
853         update(0, cur_y - height, viewport()->width(),
854                 (height + 1) * preedit_lines_);
855
856         if (preedit_string.empty()) {
857                 last_width = false;
858                 preedit_lines_ = 1;
859                 e->accept();
860                 return;
861         }
862         last_width = true;
863
864         // att : stores an IM attribute.
865         QList<QInputMethodEvent::Attribute> const & att = e->attributes();
866
867         // get attributes of input method cursor.
868         // cursor_pos : cursor position in preedit string.
869         size_t cursor_pos = 0;
870         bool cursor_is_visible = false;
871         for (int i = 0; i != att.size(); ++i) {
872                 if (att.at(i).type == QInputMethodEvent::Cursor) {
873                         cursor_pos = att.at(i).start;
874                         cursor_is_visible = att.at(i).length != 0;
875                         break;
876                 }
877         }
878
879         size_t preedit_length = preedit_string.length();
880
881         // get position of selection in input method.
882         // FIXME: isn't there a way to do this simplier?
883         // rStart : cursor position in selected string in IM.
884         size_t rStart = 0;
885         // rLength : selected string length in IM.
886         size_t rLength = 0;
887         if (cursor_pos < preedit_length) {
888                 for (int i = 0; i != att.size(); ++i) {
889                         if (att.at(i).type == QInputMethodEvent::TextFormat) {
890                                 if (att.at(i).start <= int(cursor_pos)
891                                         && int(cursor_pos) < att.at(i).start + att.at(i).length) {
892                                                 rStart = att.at(i).start;
893                                                 rLength = att.at(i).length;
894                                                 if (!cursor_is_visible)
895                                                         cursor_pos += rLength;
896                                                 break;
897                                 }
898                         }
899                 }
900         }
901         else {
902                 rStart = cursor_pos;
903                 rLength = 0;
904         }
905
906         int const right_margin = rightMargin();
907         Painter::preedit_style ps;
908         // Most often there would be only one line:
909         preedit_lines_ = 1;
910         for (size_t pos = 0; pos != preedit_length; ++pos) {
911                 char_type const typed_char = preedit_string[pos];
912                 // reset preedit string style
913                 ps = Painter::preedit_default;
914
915                 // if we reached the right extremity of the screen, go to next line.
916                 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
917                         cur_x = right_margin;
918                         cur_y += height + 1;
919                         ++preedit_lines_;
920                 }
921                 // preedit strings are displayed with dashed underline
922                 // and partial strings are displayed white on black indicating
923                 // that we are in selecting mode in the input method.
924                 // FIXME: rLength == preedit_length is not a changing condition
925                 // FIXME: should be put out of the loop.
926                 if (pos >= rStart
927                         && pos < rStart + rLength
928                         && !(cursor_pos < rLength && rLength == preedit_length))
929                         ps = Painter::preedit_selecting;
930
931                 if (pos == cursor_pos
932                         && (cursor_pos < rLength && rLength == preedit_length))
933                         ps = Painter::preedit_cursor;
934
935                 // draw one character and update cur_x.
936                 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
937         }
938
939         // update the preedit string screen area.
940         update(0, cur_y - preedit_lines_*height, viewport()->width(),
941                 (height + 1) * preedit_lines_);
942
943         // Don't forget to accept the event!
944         e->accept();
945 }
946
947
948 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
949 {
950         QRect cur_r(0,0,0,0);
951         switch (query) {
952                 // this is the CJK-specific composition window position.
953                 case Qt::ImMicroFocus:
954                         cur_r = cursor_->rect();
955                         if (preedit_lines_ != 1)
956                                 cur_r.moveLeft(10);
957                         cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
958                         // return lower right of cursor in LyX.
959                         return cur_r;
960                 default:
961                         return QWidget::inputMethodQuery(query);
962         }
963 }
964
965
966 void GuiWorkArea::updateWindowTitle()
967 {
968         docstring maximize_title;
969         docstring minimize_title;
970
971         Buffer & buf = buffer_view_->buffer();
972         FileName const fileName = buf.fileName();
973         if (!fileName.empty()) {
974                 maximize_title = fileName.displayName(30);
975                 minimize_title = from_utf8(fileName.onlyFileName());
976                 if (!buf.isClean()) {
977                         maximize_title += _(" (changed)");
978                         minimize_title += char_type('*');
979                 }
980                 if (buf.isReadonly())
981                         maximize_title += _(" (read only)");
982         }
983
984         QString title = windowTitle();
985         QString new_title = toqstr(maximize_title);
986         if (title == new_title)
987                 return;
988
989         QWidget::setWindowTitle(new_title);
990         QWidget::setWindowIconText(toqstr(minimize_title));
991         titleChanged(this);
992 }
993
994
995 void GuiWorkArea::setReadOnly(bool)
996 {
997         updateWindowTitle();
998         if (this == lyx_view_->currentWorkArea())
999                 lyx_view_->updateBufferDependent(false);
1000 }
1001
1002
1003 ////////////////////////////////////////////////////////////////////
1004 //
1005 // TabWorkArea 
1006 //
1007 ////////////////////////////////////////////////////////////////////
1008
1009 TabWorkArea::TabWorkArea(QWidget * parent) : QTabWidget(parent)
1010 {
1011         QPalette pal = palette();
1012         pal.setColor(QPalette::Active, QPalette::Button,
1013                 pal.color(QPalette::Active, QPalette::Window));
1014         pal.setColor(QPalette::Disabled, QPalette::Button,
1015                 pal.color(QPalette::Disabled, QPalette::Window));
1016         pal.setColor(QPalette::Inactive, QPalette::Button,
1017                 pal.color(QPalette::Inactive, QPalette::Window));
1018
1019         QToolButton * closeTabButton = new QToolButton(this);
1020     closeTabButton->setPalette(pal);
1021         closeTabButton->setIcon(QIcon(":/images/closetab.png"));
1022         closeTabButton->setText("Close");
1023         closeTabButton->setAutoRaise(true);
1024         closeTabButton->setCursor(Qt::ArrowCursor);
1025         closeTabButton->setToolTip(tr("Close tab"));
1026         closeTabButton->setEnabled(true);
1027
1028         QObject::connect(this, SIGNAL(currentChanged(int)),
1029                 this, SLOT(on_currentTabChanged(int)));
1030         QObject::connect(closeTabButton, SIGNAL(clicked()),
1031                 this, SLOT(closeCurrentTab()));
1032
1033         setCornerWidget(closeTabButton);
1034         setUsesScrollButtons(true);
1035 }
1036
1037
1038 void TabWorkArea::showBar(bool show)
1039 {
1040         tabBar()->setEnabled(show);
1041         tabBar()->setVisible(show);
1042 }
1043
1044
1045 GuiWorkArea * TabWorkArea::currentWorkArea()
1046 {
1047         if (count() == 0)
1048                 return 0;
1049
1050         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget()); 
1051         BOOST_ASSERT(wa);
1052         return wa;
1053 }
1054
1055
1056 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1057 {
1058         for (int i = 0; i != count(); ++i) {
1059                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1060                 BOOST_ASSERT(wa);
1061                 if (&wa->bufferView().buffer() == &buffer)
1062                         return wa;
1063         }
1064         return 0;
1065 }
1066
1067
1068 void TabWorkArea::closeAll()
1069 {
1070         while (count()) {
1071                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1072                 BOOST_ASSERT(wa);
1073                 removeTab(0);
1074                 delete wa;
1075         }
1076 }
1077
1078
1079 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1080 {
1081         BOOST_ASSERT(work_area);
1082         int index = indexOf(work_area);
1083         if (index == -1)
1084                 return false;
1085
1086         if (index == currentIndex())
1087                 // Make sure the work area is up to date.
1088                 on_currentTabChanged(index);
1089         else
1090                 // Switch to the work area.
1091                 setCurrentIndex(index);
1092         work_area->setFocus();
1093
1094         return true;
1095 }
1096
1097
1098 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1099 {
1100         GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1101         wa->setUpdatesEnabled(false);
1102         // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1103         // when hiding it again below).
1104         showBar(count() > 0);
1105         addTab(wa, wa->windowTitle());
1106         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1107                 this, SLOT(updateTabText(GuiWorkArea *)));
1108         // Hide tabbar if there's only one tab.
1109         showBar(count() > 1);
1110         return wa;
1111 }
1112
1113
1114 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1115 {
1116         BOOST_ASSERT(work_area);
1117         int index = indexOf(work_area);
1118         if (index == -1)
1119                 return false;
1120
1121         work_area->setUpdatesEnabled(false);
1122         removeTab(index);
1123         delete work_area;
1124
1125         if (count()) {
1126                 // make sure the next work area is enabled.
1127                 currentWidget()->setUpdatesEnabled(true);
1128                 // Hide tabbar if there's only one tab.
1129                 showBar(count() > 1);
1130         }
1131         return true;
1132 }
1133
1134
1135 void TabWorkArea::on_currentTabChanged(int i)
1136 {
1137         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1138         BOOST_ASSERT(wa);
1139         BufferView & bv = wa->bufferView();
1140         bv.cursor().fixIfBroken();
1141         bv.updateMetrics();
1142         wa->setUpdatesEnabled(true);
1143         wa->redraw();
1144         wa->setFocus();
1145         ///
1146         currentWorkAreaChanged(wa);
1147
1148         LYXERR(Debug::GUI, "currentTabChanged " << i
1149                 << "File" << bv.buffer().absFileName());
1150 }
1151
1152
1153 void TabWorkArea::closeCurrentTab()
1154 {
1155         lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1156 }
1157
1158
1159 void TabWorkArea::updateTabText(GuiWorkArea * wa)
1160 {
1161         int const i = indexOf(wa);
1162         if (i < 0)
1163                 return;
1164         setTabText(i, wa->windowTitle());
1165 }
1166
1167 } // namespace frontend
1168 } // namespace lyx
1169
1170 #include "GuiWorkArea_moc.cpp"