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