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