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