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