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