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