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