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