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