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