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