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