]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.cpp
Use QFontMetrics information for underlines (and friends) width and position
[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 #include "GuiWorkArea_Private.h"
16
17 #include "ColorCache.h"
18 #include "FontLoader.h"
19 #include "Menus.h"
20
21 #include "Buffer.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "CoordCache.h"
26 #include "Cursor.h"
27 #include "Font.h"
28 #include "FuncRequest.h"
29 #include "GuiApplication.h"
30 #include "GuiCompleter.h"
31 #include "GuiKeySymbol.h"
32 #include "GuiPainter.h"
33 #include "GuiView.h"
34 #include "KeySymbol.h"
35 #include "Language.h"
36 #include "LyX.h"
37 #include "LyXRC.h"
38 #include "LyXVC.h"
39 #include "qt_helpers.h"
40 #include "Text.h"
41 #include "TextMetrics.h"
42 #include "version.h"
43
44 #include "graphics/GraphicsImage.h"
45 #include "graphics/GraphicsLoader.h"
46
47 #include "support/convert.h"
48 #include "support/debug.h"
49 #include "support/gettext.h"
50 #include "support/FileName.h"
51 #include "support/lassert.h"
52 #include "support/TempFile.h"
53
54 #include "frontends/Application.h"
55 #include "frontends/FontMetrics.h"
56 #include "frontends/WorkAreaManager.h"
57
58 #include <QContextMenuEvent>
59 #if (QT_VERSION < 0x050000)
60 #include <QInputContext>
61 #endif
62 #include <QDrag>
63 #include <QHelpEvent>
64 #ifdef Q_OS_MAC
65 #include <QProxyStyle>
66 #endif
67 #include <QMainWindow>
68 #include <QMimeData>
69 #include <QMenu>
70 #include <QPainter>
71 #include <QPalette>
72 #include <QPixmapCache>
73 #include <QScrollBar>
74 #include <QStyleOption>
75 #include <QStylePainter>
76 #include <QTimer>
77 #include <QToolButton>
78 #include <QToolTip>
79 #include <QMenuBar>
80
81 #include "support/bind.h"
82
83 #include <cmath>
84
85 int const TabIndicatorWidth = 3;
86
87 #undef KeyPress
88 #undef NoModifier
89
90 using namespace std;
91 using namespace lyx::support;
92
93 namespace lyx {
94
95
96 /// return the LyX mouse button state from Qt's
97 static mouse_button::state q_button_state(Qt::MouseButton button)
98 {
99         mouse_button::state b = mouse_button::none;
100         switch (button) {
101                 case Qt::LeftButton:
102                         b = mouse_button::button1;
103                         break;
104                 case Qt::MidButton:
105                         b = mouse_button::button2;
106                         break;
107                 case Qt::RightButton:
108                         b = mouse_button::button3;
109                         break;
110                 default:
111                         break;
112         }
113         return b;
114 }
115
116
117 /// return the LyX mouse button state from Qt's
118 mouse_button::state q_motion_state(Qt::MouseButtons state)
119 {
120         mouse_button::state b = mouse_button::none;
121         if (state & Qt::LeftButton)
122                 b |= mouse_button::button1;
123         if (state & Qt::MidButton)
124                 b |= mouse_button::button2;
125         if (state & Qt::RightButton)
126                 b |= mouse_button::button3;
127         return b;
128 }
129
130
131 namespace frontend {
132
133 class CursorWidget {
134 public:
135         CursorWidget() {
136                 recomputeWidth();
137         }
138
139         void draw(QPainter & painter)
140         {
141                 if (!show_ || !rect_.isValid())
142                         return;
143
144                 int y = rect_.top();
145                 int l = x_ - rect_.left();
146                 int r = rect_.right() - x_;
147                 int bot = rect_.bottom();
148
149                 // draw vertical line
150                 painter.fillRect(x_, y, cursor_width_, rect_.height(), color_);
151
152                 // draw RTL/LTR indication
153                 painter.setPen(color_);
154                 if (l_shape_) {
155                         if (rtl_)
156                                 painter.drawLine(x_, bot, x_ - l, bot);
157                         else
158                                 painter.drawLine(x_, bot, x_ + cursor_width_ + r, bot);
159                 }
160
161                 // draw completion triangle
162                 if (completable_) {
163                         int m = y + rect_.height() / 2;
164                         int d = TabIndicatorWidth - 1;
165                         if (rtl_) {
166                                 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
167                                 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
168                         } else {
169                                 painter.drawLine(x_ + cursor_width_, m - d, x_ + cursor_width_ + d, m);
170                                 painter.drawLine(x_ + cursor_width_, m + d, x_ + cursor_width_ + d, m);
171                         }
172                 }
173         }
174
175         void update(int x, int y, int h, bool l_shape,
176                 bool rtl, bool completable)
177         {
178                 color_ = guiApp->colorCache().get(Color_cursor);
179                 l_shape_ = l_shape;
180                 rtl_ = rtl;
181                 completable_ = completable;
182                 x_ = x;
183
184                 // extension to left and right
185                 int l = 0;
186                 int r = 0;
187
188                 // RTL/LTR indication
189                 if (l_shape_) {
190                         if (rtl)
191                                 l += h / 3;
192                         else
193                                 r += h / 3;
194                 }
195
196                 // completion triangle
197                 if (completable_) {
198                         if (rtl)
199                                 l = max(l, TabIndicatorWidth);
200                         else
201                                 r = max(r, TabIndicatorWidth);
202                 }
203
204                 // compute overall rectangle
205                 rect_ = QRect(x - l, y, cursor_width_ + r + l, h);
206         }
207
208         void show(bool set_show = true) { show_ = set_show; }
209         void hide() { show_ = false; }
210         int cursorWidth() const { return cursor_width_; }
211         void recomputeWidth() {
212                 cursor_width_ = lyxrc.cursor_width
213                         ? lyxrc.cursor_width 
214                         : 1 + int((lyxrc.zoom + 50) / 200.0);
215         }
216
217         QRect const & rect() { return rect_; }
218
219 private:
220         /// cursor is in RTL or LTR text
221         bool rtl_;
222         /// indication for RTL or LTR
223         bool l_shape_;
224         /// triangle to show that a completion is available
225         bool completable_;
226         ///
227         bool show_;
228         ///
229         QColor color_;
230         /// rectangle, possibly with l_shape and completion triangle
231         QRect rect_;
232         /// x position (were the vertical line is drawn)
233         int x_;
234         
235         int cursor_width_;
236 };
237
238
239 // This is a 'heartbeat' generating synthetic mouse move events when the
240 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
241 SyntheticMouseEvent::SyntheticMouseEvent()
242         : timeout(200), restart_timeout(true)
243 {}
244
245
246 GuiWorkArea::Private::Private(GuiWorkArea * parent)
247 : p(parent), screen_(0), buffer_view_(0), lyx_view_(0), cursor_visible_(false),
248 need_resize_(false), schedule_redraw_(false), preedit_lines_(1),
249 pixel_ratio_(1.0),
250 completer_(new GuiCompleter(p, p))
251 {
252 }
253
254
255 GuiWorkArea::GuiWorkArea(QWidget * /* w */)
256 : d(new Private(this)) 
257 {
258 }
259
260
261 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
262 : d(new Private(this))
263 {
264         setGuiView(gv);
265         buffer.params().display_pixel_ratio = theGuiApp()->pixelRatio();
266         setBuffer(buffer);
267         init();
268 }
269
270
271 double GuiWorkArea::pixelRatio() const
272 {
273 #if QT_VERSION >= 0x050000
274         return devicePixelRatio();
275 #else
276         return 1.0;
277 #endif
278 }
279
280
281 void GuiWorkArea::init()
282 {
283         // Setup the signals
284         connect(&d->cursor_timeout_, SIGNAL(timeout()),
285                 this, SLOT(toggleCursor()));
286
287         int const time = QApplication::cursorFlashTime() / 2;
288         if (time > 0) {
289                 d->cursor_timeout_.setInterval(time);
290                 d->cursor_timeout_.start();
291         } else {
292                 // let's initialize this just to be safe
293                 d->cursor_timeout_.setInterval(500);
294         }
295
296         d->resetScreen();
297         // With Qt4.5 a mouse event will happen before the first paint event
298         // so make sure that the buffer view has an up to date metrics.
299         d->buffer_view_->resize(viewport()->width(), viewport()->height());
300         d->cursor_ = new frontend::CursorWidget();
301         d->cursor_->hide();
302
303         setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
304         setAcceptDrops(true);
305         setMouseTracking(true);
306         setMinimumSize(100, 70);
307         setFrameStyle(QFrame::NoFrame);
308         updateWindowTitle();
309
310         viewport()->setAutoFillBackground(false);
311         // We don't need double-buffering nor SystemBackground on
312         // the viewport because we have our own backing pixmap.
313         viewport()->setAttribute(Qt::WA_NoSystemBackground);
314
315         setFocusPolicy(Qt::StrongFocus);
316
317         d->setCursorShape(Qt::IBeamCursor);
318
319         d->synthetic_mouse_event_.timeout.timeout.connect(
320                 bind(&GuiWorkArea::generateSyntheticMouseEvent,
321                                         this));
322
323         // Initialize the vertical Scroll Bar
324         QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
325                 this, SLOT(scrollTo(int)));
326
327         LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
328                 << "  viewport height: " << viewport()->height());
329
330         // Enables input methods for asian languages.
331         // Must be set when creating custom text editing widgets.
332         setAttribute(Qt::WA_InputMethodEnabled, true);
333
334         d->dialog_mode_ = false;
335 }
336
337
338 GuiWorkArea::~GuiWorkArea()
339 {
340         d->buffer_view_->buffer().workAreaManager().remove(this);
341         delete d->screen_;
342         delete d->buffer_view_;
343         delete d->cursor_;
344         // Completer has a QObject parent and is thus automatically destroyed.
345         // See #4758.
346         // delete completer_;
347         delete d;
348 }
349
350
351 Qt::CursorShape GuiWorkArea::cursorShape() const
352 {
353         return viewport()->cursor().shape();
354 }
355
356
357 void GuiWorkArea::Private::setCursorShape(Qt::CursorShape shape)
358 {
359         p->viewport()->setCursor(shape);
360 }
361
362
363 void GuiWorkArea::Private::updateCursorShape()
364 {
365         setCursorShape(buffer_view_->clickableInset() 
366                 ? Qt::PointingHandCursor : Qt::IBeamCursor);
367 }
368
369
370 void GuiWorkArea::setGuiView(GuiView & gv)
371 {
372         d->lyx_view_ = &gv;
373 }
374
375
376 void GuiWorkArea::setBuffer(Buffer & buffer)
377 {
378         delete d->buffer_view_;
379         d->buffer_view_ = new BufferView(buffer);
380         buffer.workAreaManager().add(this);
381
382         // HACK: Prevents an additional redraw when the scrollbar pops up
383         // which regularily happens on documents with more than one page.
384         // The policy  should be set to "Qt::ScrollBarAsNeeded" soon.
385         // Since we have no geometry information yet, we assume that
386         // a document needs a scrollbar if there is more then four
387         // paragraph in the outermost text.
388         if (buffer.text().paragraphs().size() > 4)
389                 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
390         QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
391 }
392
393
394 void GuiWorkArea::fixVerticalScrollBar()
395 {
396         if (!isFullScreen())
397                 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
398 }
399
400
401 void GuiWorkArea::close()
402 {
403         d->lyx_view_->removeWorkArea(this);
404 }
405
406
407 void GuiWorkArea::setFullScreen(bool full_screen)
408 {
409         d->buffer_view_->setFullScreen(full_screen);
410         setFrameStyle(QFrame::NoFrame);
411         if (full_screen) {
412                 setFrameStyle(QFrame::NoFrame);
413                 if (lyxrc.full_screen_scrollbar)
414                         setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
415         } else
416                 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
417 }
418
419
420 BufferView & GuiWorkArea::bufferView()
421 {
422         return *d->buffer_view_;
423 }
424
425
426 BufferView const & GuiWorkArea::bufferView() const
427 {
428         return *d->buffer_view_;
429 }
430
431
432 void GuiWorkArea::stopBlinkingCursor()
433 {
434         d->cursor_timeout_.stop();
435         d->hideCursor();
436 }
437
438
439 void GuiWorkArea::startBlinkingCursor()
440 {
441         // do not show the cursor if the view is busy
442         if (view().busy())
443                 return;
444
445         Point p;
446         int h = 0;
447         d->buffer_view_->cursorPosAndHeight(p, h);
448         // Don't start blinking if the cursor isn't on screen.
449         if (!d->buffer_view_->cursorInView(p, h))
450                 return;
451
452         d->showCursor();
453
454         //we're not supposed to cache this value.
455         int const time = QApplication::cursorFlashTime() / 2;
456         if (time <= 0)
457                 return;
458         d->cursor_timeout_.setInterval(time);
459         d->cursor_timeout_.start();
460 }
461
462
463 void GuiWorkArea::redraw(bool update_metrics)
464 {
465         if (!isVisible())
466                 // No need to redraw in this case.
467                 return;
468
469         // No need to do anything if this is the current view. The BufferView
470         // metrics are already up to date.
471         if (update_metrics || d->lyx_view_ != guiApp->currentView()
472                 || d->lyx_view_->currentWorkArea() != this) {
473                 // FIXME: it would be nice to optimize for the off-screen case.
474                 d->buffer_view_->cursor().fixIfBroken();
475                 d->buffer_view_->updateMetrics();
476                 d->buffer_view_->cursor().fixIfBroken();
477         }
478
479         // update cursor position, because otherwise it has to wait until
480         // the blinking interval is over
481         if (d->cursor_visible_) {
482                 d->hideCursor();
483                 d->showCursor();
484         }
485
486         LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
487         d->updateScreen();
488         update(0, 0, viewport()->width(), viewport()->height());
489
490         /// \warning: scrollbar updating *must* be done after the BufferView is drawn
491         /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
492         d->updateScrollbar();
493         d->lyx_view_->updateStatusBar();
494
495         if (lyxerr.debugging(Debug::WORKAREA))
496                 d->buffer_view_->coordCache().dump();
497
498         updateWindowTitle();
499
500         d->updateCursorShape();
501 }
502
503
504 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
505 {
506         if (d->lyx_view_->isFullScreen() && d->lyx_view_->menuBar()->isVisible()
507                 && lyxrc.full_screen_menubar) {
508                 // FIXME HACK: we should not have to do this here. See related comment
509                 // in GuiView::event() (QEvent::ShortcutOverride)
510                 d->lyx_view_->menuBar()->hide();
511         }
512
513         // In order to avoid bad surprise in the middle of an operation,
514         // we better stop the blinking cursor...
515         // the cursor gets restarted in GuiView::restartCursor()
516         stopBlinkingCursor();
517         guiApp->processKeySym(key, mod);
518 }
519
520
521 void GuiWorkArea::Private::dispatch(FuncRequest const & cmd0, KeyModifier mod)
522 {
523         // Handle drag&drop
524         if (cmd0.action() == LFUN_FILE_OPEN) {
525                 DispatchResult dr;
526                 lyx_view_->dispatch(cmd0, dr);
527                 return;
528         }
529
530         FuncRequest cmd;
531
532         if (cmd0.action() == LFUN_MOUSE_PRESS) {
533                 if (mod == ShiftModifier)
534                         cmd = FuncRequest(cmd0, "region-select");
535                 else if (mod == ControlModifier)
536                         cmd = FuncRequest(cmd0, "paragraph-select");
537                 else
538                         cmd = cmd0;
539         }
540         else
541                 cmd = cmd0;
542
543         bool const notJustMovingTheMouse =
544                 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
545
546         // In order to avoid bad surprise in the middle of an operation, we better stop
547         // the blinking cursor.
548         if (notJustMovingTheMouse)
549                 p->stopBlinkingCursor();
550
551         buffer_view_->mouseEventDispatch(cmd);
552
553         // Skip these when selecting
554         // FIXME: let GuiView take care of those.
555         if (cmd.action() != LFUN_MOUSE_MOTION) {
556                 completer_->updateVisibility(false, false);
557                 lyx_view_->updateDialogs();
558                 lyx_view_->updateStatusBar();
559         }
560
561         // GUI tweaks except with mouse motion with no button pressed.
562         if (notJustMovingTheMouse) {
563                 // Slight hack: this is only called currently when we
564                 // clicked somewhere, so we force through the display
565                 // of the new status here.
566                 // FIXME: let GuiView take care of those.
567                 lyx_view_->clearMessage();
568
569                 // Show the cursor immediately after any operation
570                 p->startBlinkingCursor();
571         }
572
573         updateCursorShape();
574 }
575
576
577 void GuiWorkArea::Private::resizeBufferView()
578 {
579         // WARNING: Please don't put any code that will trigger a repaint here!
580         // We are already inside a paint event.
581         p->stopBlinkingCursor();
582         // Warn our container (GuiView).
583         p->busy(true);
584
585         Point point;
586         int h = 0;
587         buffer_view_->cursorPosAndHeight(point, h);
588         bool const cursor_in_view = buffer_view_->cursorInView(point, h);
589         buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
590         if (cursor_in_view)
591                 buffer_view_->scrollToCursor();
592         updateScreen();
593
594         // Update scrollbars which might have changed due different
595         // BufferView dimension. This is especially important when the
596         // BufferView goes from zero-size to the real-size for the first time,
597         // as the scrollbar paramters are then set for the first time.
598         updateScrollbar();
599
600         need_resize_ = false;
601         p->busy(false);
602         // Eventually, restart the cursor after the resize event.
603         // We might be resizing even if the focus is on another widget so we only
604         // restart the cursor if we have the focus.
605         if (p->hasFocus())
606                 QTimer::singleShot(50, p, SLOT(startBlinkingCursor()));
607 }
608
609
610 void GuiWorkArea::Private::showCursor()
611 {
612         if (cursor_visible_)
613                 return;
614
615         Point p;
616         int h = 0;
617         buffer_view_->cursorPosAndHeight(p, h);
618         if (!buffer_view_->cursorInView(p, h))
619                 return;
620
621         // RTL or not RTL
622         bool l_shape = false;
623         Font const & realfont = buffer_view_->cursor().real_current_font;
624         BufferParams const & bp = buffer_view_->buffer().params();
625         bool const samelang = realfont.language() == bp.language;
626         bool const isrtl = realfont.isVisibleRightToLeft();
627
628         if (!samelang || isrtl != bp.language->rightToLeft())
629                 l_shape = true;
630
631         // The ERT language hack needs fixing up
632         if (realfont.language() == latex_language)
633                 l_shape = false;
634
635         // show cursor on screen
636         Cursor & cur = buffer_view_->cursor();
637         bool completable = cur.inset().showCompletionCursor()
638                 && completer_->completionAvailable()
639                 && !completer_->popupVisible()
640                 && !completer_->inlineVisible();
641         cursor_visible_ = true;
642         cursor_->recomputeWidth();
643
644         //int cur_x = buffer_view_->getPos(cur).x_;
645         // We may have decided to slide the cursor row so that cursor
646         // is visible.
647         p.x_ -= buffer_view_->horizScrollOffset();
648
649         showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
650 }
651
652
653 void GuiWorkArea::Private::hideCursor()
654 {
655         if (!cursor_visible_)
656                 return;
657
658         cursor_visible_ = false;
659         removeCursor();
660 }
661
662
663 void GuiWorkArea::toggleCursor()
664 {
665         if (d->cursor_visible_)
666                 d->hideCursor();
667         else
668                 d->showCursor();
669 }
670
671
672 void GuiWorkArea::Private::updateScrollbar()
673 {
674         ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
675         // WARNING: don't touch at the scrollbar value like this:
676         //   verticalScrollBar()->setValue(scroll_.position);
677         // because this would cause a recursive signal/slot calling with
678         // GuiWorkArea::scrollTo
679         p->verticalScrollBar()->setRange(scroll_.min, scroll_.max);
680         p->verticalScrollBar()->setPageStep(scroll_.page_step);
681         p->verticalScrollBar()->setSingleStep(scroll_.single_step);
682         p->verticalScrollBar()->setSliderPosition(scroll_.position);
683 }
684
685
686 void GuiWorkArea::scrollTo(int value)
687 {
688         stopBlinkingCursor();
689         d->buffer_view_->scrollDocView(value, true);
690
691         if (lyxrc.cursor_follows_scrollbar) {
692                 d->buffer_view_->setCursorFromScrollbar();
693                 // FIXME: let GuiView take care of those.
694                 d->lyx_view_->updateLayoutList();
695         }
696         // Show the cursor immediately after any operation.
697         startBlinkingCursor();
698         // FIXME QT5
699 #ifdef Q_WS_X11
700         QApplication::syncX();
701 #endif
702 }
703
704
705 bool GuiWorkArea::event(QEvent * e)
706 {
707         switch (e->type()) {
708         case QEvent::ToolTip: {
709                 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
710                 if (lyxrc.use_tooltip) {
711                         QPoint pos = helpEvent->pos();
712                         if (pos.x() < viewport()->width()) {
713                                 QString s = toqstr(d->buffer_view_->toolTip(pos.x(), pos.y()));
714                                 QToolTip::showText(helpEvent->globalPos(), s);
715                         }
716                         else
717                                 QToolTip::hideText();
718                 }
719                 // Don't forget to accept the event!
720                 e->accept();
721                 return true;
722         }
723
724         case QEvent::ShortcutOverride: {
725                 // We catch this event in order to catch the Tab or Shift+Tab key press
726                 // which are otherwise reserved to focus switching between controls
727                 // within a dialog.
728                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
729                 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
730                         || (ke->key() == Qt::Key_Backtab && (
731                                 ke->modifiers() == Qt::ShiftModifier
732                                 || ke->modifiers() == Qt::NoModifier))) {
733                         keyPressEvent(ke);
734                         return true;
735                 }
736                 return QAbstractScrollArea::event(e);
737         }
738
739         default:
740                 return QAbstractScrollArea::event(e);
741         }
742         return false;
743 }
744
745
746 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
747 {
748         string name;
749         if (e->reason() == QContextMenuEvent::Mouse)
750                 // the menu name is set on mouse press
751                 name = d->context_menu_name_;
752         else {
753                 QPoint pos = e->pos();
754                 Cursor const & cur = d->buffer_view_->cursor();
755                 if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
756                         // Do not access the context menu of math right in front of before
757                         // the cursor. This does not work when the cursor is in text.
758                         Inset * inset = cur.paragraph().getInset(cur.pos());
759                         if (inset && inset->asInsetMath())
760                                 --pos.rx();
761                         else if (cur.pos() > 0) {
762                                 Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
763                                 if (inset)
764                                         ++pos.rx();
765                         }
766                 }
767                 name = d->buffer_view_->contextMenu(pos.x(), pos.y());
768         }
769         
770         if (name.empty()) {
771                 QAbstractScrollArea::contextMenuEvent(e);
772                 return;
773         }
774         // always show mnemonics when the keyboard is used to show the context menu
775         // FIXME: This should be fixed in Qt itself
776         bool const keyboard = (e->reason() == QContextMenuEvent::Keyboard);
777         QMenu * menu = guiApp->menus().menu(toqstr(name), *d->lyx_view_, keyboard);
778         if (!menu) {
779                 QAbstractScrollArea::contextMenuEvent(e);
780                 return;
781         }
782         // Position the menu to the right.
783         // FIXME: menu position should be different for RTL text.
784         menu->exec(e->globalPos());
785         e->accept();
786 }
787
788
789 void GuiWorkArea::focusInEvent(QFocusEvent * e)
790 {
791         LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
792         if (d->lyx_view_->currentWorkArea() != this) {
793                 d->lyx_view_->setCurrentWorkArea(this);
794                 d->lyx_view_->currentWorkArea()->bufferView().buffer().updateBuffer();
795         }
796
797         startBlinkingCursor();
798         QAbstractScrollArea::focusInEvent(e);
799 }
800
801
802 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
803 {
804         LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
805         stopBlinkingCursor();
806         QAbstractScrollArea::focusOutEvent(e);
807 }
808
809
810 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
811 {
812         if (d->dc_event_.active && d->dc_event_ == *e) {
813                 d->dc_event_.active = false;
814                 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
815                         q_button_state(e->button()));
816                 d->dispatch(cmd);
817                 e->accept();
818                 return;
819         }
820
821 #if (QT_VERSION < 0x050000) && !defined(__HAIKU__)
822         inputContext()->reset();
823 #endif
824
825         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
826                 q_button_state(e->button()));
827         d->dispatch(cmd, q_key_state(e->modifiers()));
828
829         // Save the context menu on mouse press, because also the mouse
830         // cursor is set on mouse press. Afterwards, we can either release
831         // the mousebutton somewhere else, or the cursor might have moved
832         // due to the DEPM. We need to do this after the mouse has been
833         // set in dispatch(), because the selection state might change.
834         if (e->button() == Qt::RightButton)
835                 d->context_menu_name_ = d->buffer_view_->contextMenu(e->x(), e->y());
836
837         e->accept();
838 }
839
840
841 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
842 {
843         if (d->synthetic_mouse_event_.timeout.running())
844                 d->synthetic_mouse_event_.timeout.stop();
845
846         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
847                               q_button_state(e->button()));
848         d->dispatch(cmd);
849         e->accept();
850 }
851
852
853 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
854 {
855         // we kill the triple click if we move
856         doubleClickTimeout();
857         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
858                 q_motion_state(e->buttons()));
859
860         e->accept();
861
862         // If we're above or below the work area...
863         if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
864                         && e->buttons() == mouse_button::button1) {
865                 // Make sure only a synthetic event can cause a page scroll,
866                 // so they come at a steady rate:
867                 if (e->y() <= 20)
868                         // _Force_ a scroll up:
869                         cmd.set_y(e->y() - 21);
870                 else
871                         cmd.set_y(e->y() + 21);
872                 // Store the event, to be handled when the timeout expires.
873                 d->synthetic_mouse_event_.cmd = cmd;
874
875                 if (d->synthetic_mouse_event_.timeout.running()) {
876                         // Discard the event. Note that it _may_ be handled
877                         // when the timeout expires if
878                         // synthetic_mouse_event_.cmd has not been overwritten.
879                         // Ie, when the timeout expires, we handle the
880                         // most recent event but discard all others that
881                         // occurred after the one used to start the timeout
882                         // in the first place.
883                         return;
884                 }
885                 
886                 d->synthetic_mouse_event_.restart_timeout = true;
887                 d->synthetic_mouse_event_.timeout.start();
888                 // Fall through to handle this event...
889
890         } else if (d->synthetic_mouse_event_.timeout.running()) {
891                 // Store the event, to be possibly handled when the timeout
892                 // expires.
893                 // Once the timeout has expired, normal control is returned
894                 // to mouseMoveEvent (restart_timeout = false).
895                 // This results in a much smoother 'feel' when moving the
896                 // mouse back into the work area.
897                 d->synthetic_mouse_event_.cmd = cmd;
898                 d->synthetic_mouse_event_.restart_timeout = false;
899                 return;
900         }
901         d->dispatch(cmd);
902 }
903
904
905 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
906 {
907         // Wheel rotation by one notch results in a delta() of 120 (see
908         // documentation of QWheelEvent)
909         double const delta = ev->delta() / 120.0;
910         bool zoom = false;
911         switch (lyxrc.scroll_wheel_zoom) {
912         case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
913                 zoom = ev->modifiers() & Qt::ControlModifier;
914                 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
915                 break;
916         case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
917                 zoom = ev->modifiers() & Qt::ShiftModifier;
918                 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
919                 break;
920         case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
921                 zoom = ev->modifiers() & Qt::AltModifier;
922                 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
923                 break;
924         case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
925                 break;
926         }
927         if (zoom) {
928                 docstring arg = convert<docstring>(int(5 * delta));
929                 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
930                 return;
931         }
932
933         // Take into account the desktop wide settings.
934         int const lines = qApp->wheelScrollLines();
935         int const page_step = verticalScrollBar()->pageStep();
936         // Test if the wheel mouse is set to one screen at a time.
937         int scroll_value = lines > page_step
938                 ? page_step : lines * verticalScrollBar()->singleStep();
939
940         // Take into account the rotation and the user preferences.
941         scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
942         LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
943                         << " delta = " << delta << " scroll_value = " << scroll_value
944                         << " page_step = " << page_step);
945         // Now scroll.
946         verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
947
948         ev->accept();
949 }
950
951
952 void GuiWorkArea::generateSyntheticMouseEvent()
953 {
954         int const e_y = d->synthetic_mouse_event_.cmd.y();
955         int const wh = d->buffer_view_->workHeight();
956         bool const up = e_y < 0;
957         bool const down = e_y > wh;
958
959         // Set things off to generate the _next_ 'pseudo' event.
960         int step = 50;
961         if (d->synthetic_mouse_event_.restart_timeout) {
962                 // This is some magic formulae to determine the speed
963                 // of scrolling related to the position of the mouse.
964                 int time = 200;
965                 if (up || down) {
966                         int dist = up ? -e_y : e_y - wh;
967                         time = max(min(200, 250000 / (dist * dist)), 1) ;
968                         
969                         if (time < 40) {
970                                 step = 80000 / (time * time);
971                                 time = 40;
972                         }
973                 }
974                 d->synthetic_mouse_event_.timeout.setTimeout(time);
975                 d->synthetic_mouse_event_.timeout.start();
976         }
977
978         // Can we scroll further ?
979         int const value = verticalScrollBar()->value();
980         if (value == verticalScrollBar()->maximum()
981                   || value == verticalScrollBar()->minimum()) {
982                 d->synthetic_mouse_event_.timeout.stop();
983                 return;
984         }
985
986         // Scroll
987         if (step <= 2 * wh) {
988                 d->buffer_view_->scroll(up ? -step : step);
989                 d->buffer_view_->updateMetrics();
990         } else {
991                 d->buffer_view_->scrollDocView(value + (up ? -step : step), false);
992         }
993
994         // In which paragraph do we have to set the cursor ?
995         Cursor & cur = d->buffer_view_->cursor();
996         // FIXME: we don't know howto handle math.
997         Text * text = cur.text();
998         if (!text)
999                 return;
1000         TextMetrics const & tm = d->buffer_view_->textMetrics(text);
1001
1002         pair<pit_type, const ParagraphMetrics *> pp = up ? tm.first() : tm.last();
1003         ParagraphMetrics const & pm = *pp.second;
1004         pit_type const pit = pp.first;
1005
1006         if (pm.rows().empty())
1007                 return;
1008
1009         // Find the row at which we set the cursor.
1010         RowList::const_iterator rit = pm.rows().begin();
1011         RowList::const_iterator rlast = pm.rows().end();
1012         int yy = pm.position() - pm.ascent();
1013         for (--rlast; rit != rlast; ++rit) {
1014                 int h = rit->height();
1015                 if ((up && yy + h > 0)
1016                           || (!up && yy + h > wh - defaultRowHeight()))
1017                         break;
1018                 yy += h;
1019         }
1020
1021         // Find the position of the cursor
1022         bool bound;
1023         int x = d->synthetic_mouse_event_.cmd.x();
1024         pos_type const pos = tm.getPosNearX(*rit, x, bound);
1025
1026         // Set the cursor
1027         cur.pit() = pit;
1028         cur.pos() = pos;
1029         cur.boundary(bound);
1030
1031         d->buffer_view_->buffer().changed(false);
1032         return;
1033 }
1034
1035
1036 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
1037 {
1038         // Do not process here some keys if dialog_mode_ is set
1039         if (d->dialog_mode_
1040                 && (ev->modifiers() == Qt::NoModifier
1041                     || ev->modifiers() == Qt::ShiftModifier)
1042                 && (ev->key() == Qt::Key_Escape
1043                     || ev->key() == Qt::Key_Enter
1044                     || ev->key() == Qt::Key_Return)
1045             ) {
1046                 ev->ignore();
1047                 return;
1048         }
1049
1050         // intercept some keys if completion popup is visible
1051         if (d->completer_->popupVisible()) {
1052                 switch (ev->key()) {
1053                 case Qt::Key_Enter:
1054                 case Qt::Key_Return:
1055                         d->completer_->activate();
1056                         ev->accept();
1057                         return;
1058                 }
1059         }
1060
1061         // do nothing if there are other events
1062         // (the auto repeated events come too fast)
1063         // it looks like this is only needed on X11
1064 #if defined(Q_WS_X11) || defined(QPA_XCB)
1065         if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
1066                 switch (ev->key()) {
1067                 case Qt::Key_PageDown:
1068                 case Qt::Key_PageUp:
1069                 case Qt::Key_Left:
1070                 case Qt::Key_Right:
1071                 case Qt::Key_Up:
1072                 case Qt::Key_Down:
1073                         LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
1074                         ev->ignore();
1075                         return;
1076                 }
1077         }
1078 #endif
1079
1080         KeyModifier m = q_key_state(ev->modifiers());
1081
1082         std::string str;
1083         if (m & ShiftModifier)
1084                 str += "Shift-";
1085         if (m & ControlModifier)
1086                 str += "Control-";
1087         if (m & AltModifier)
1088                 str += "Alt-";
1089         if (m & MetaModifier)
1090                 str += "Meta-";
1091         
1092         LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
1093                 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key()
1094                 << " keyState: " << str);
1095
1096         KeySymbol sym;
1097         setKeySymbol(&sym, ev);
1098         if (sym.isOK()) {
1099                 processKeySym(sym, q_key_state(ev->modifiers()));
1100                 ev->accept();
1101         } else {
1102                 ev->ignore();
1103         }
1104 }
1105
1106
1107 void GuiWorkArea::doubleClickTimeout()
1108 {
1109         d->dc_event_.active = false;
1110 }
1111
1112
1113 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1114 {
1115         d->dc_event_ = DoubleClick(ev);
1116         QTimer::singleShot(QApplication::doubleClickInterval(), this,
1117                            SLOT(doubleClickTimeout()));
1118         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1119                         ev->x(), ev->y(),
1120                         q_button_state(ev->button()));
1121         d->dispatch(cmd);
1122         ev->accept();
1123 }
1124
1125
1126 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1127 {
1128         QAbstractScrollArea::resizeEvent(ev);
1129         d->need_resize_ = true;
1130         ev->accept();
1131 }
1132
1133
1134 void GuiWorkArea::Private::update(int x, int y, int w, int h)
1135 {
1136         p->viewport()->update(x, y, w, h);
1137 }
1138
1139
1140 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1141 {
1142         QRectF const rc = ev->rect();
1143         // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1144         //      << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1145
1146         if (d->needResize()) {
1147                 d->resetScreen();
1148                 d->resizeBufferView();
1149                 if (d->cursor_visible_) {
1150                         d->hideCursor();
1151                         d->showCursor();
1152                 }
1153         }
1154
1155         QPainter pain(viewport());
1156         double const pr = pixelRatio();
1157         QRectF const rcs = QRectF(rc.x() * pr, rc.y() * pr, rc.width() * pr, rc.height() * pr);
1158
1159         if (lyxrc.use_qimage) {
1160                 QImage const & image = static_cast<QImage const &>(*d->screen_);
1161                 pain.drawImage(rc, image, rcs);
1162         } else {
1163                 QPixmap const & pixmap = static_cast<QPixmap const &>(*d->screen_);
1164                 pain.drawPixmap(rc, pixmap, rcs);
1165         }
1166         d->cursor_->draw(pain);
1167         ev->accept();
1168 }
1169
1170
1171 void GuiWorkArea::Private::updateScreen()
1172 {
1173         GuiPainter pain(screen_, p->pixelRatio());
1174         buffer_view_->draw(pain);
1175 }
1176
1177
1178 void GuiWorkArea::Private::showCursor(int x, int y, int h,
1179         bool l_shape, bool rtl, bool completable)
1180 {
1181         if (schedule_redraw_) {
1182                 // This happens when a graphic conversion is finished. As we don't know
1183                 // the size of the new graphics, it's better the update everything.
1184                 // We can't use redraw() here because this would trigger a infinite
1185                 // recursive loop with showCursor().
1186                 buffer_view_->resize(p->viewport()->width(), p->viewport()->height());
1187                 updateScreen();
1188                 updateScrollbar();
1189                 p->viewport()->update(QRect(0, 0, p->viewport()->width(), p->viewport()->height()));
1190                 schedule_redraw_ = false;
1191                 // Show the cursor immediately after the update.
1192                 hideCursor();
1193                 p->toggleCursor();
1194                 return;
1195         }
1196
1197         cursor_->update(x, y, h, l_shape, rtl, completable);
1198         cursor_->show();
1199         p->viewport()->update(cursor_->rect());
1200 }
1201
1202
1203 void GuiWorkArea::Private::removeCursor()
1204 {
1205         cursor_->hide();
1206         //if (!qApp->focusWidget())
1207                 p->viewport()->update(cursor_->rect());
1208 }
1209
1210
1211 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1212 {
1213         QString const & commit_string = e->commitString();
1214         docstring const & preedit_string
1215                 = qstring_to_ucs4(e->preeditString());
1216
1217         if (!commit_string.isEmpty()) {
1218
1219                 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1220                         << " commitString: " << e->commitString());
1221
1222                 int key = 0;
1223
1224                 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1225                 for (int i = 0; i != commit_string.size(); ++i) {
1226                         QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1227                         keyPressEvent(&ev);
1228                 }
1229         }
1230
1231         // Hide the cursor during the kana-kanji transformation.
1232         if (preedit_string.empty())
1233                 startBlinkingCursor();
1234         else
1235                 stopBlinkingCursor();
1236
1237         // last_width : for checking if last preedit string was/wasn't empty.
1238         // FIXME THREAD
1239         // We could have more than one work area, right?
1240         static bool last_width = false;
1241         if (!last_width && preedit_string.empty()) {
1242                 // if last_width is last length of preedit string.
1243                 e->accept();
1244                 return;
1245         }
1246
1247         GuiPainter pain(d->screen_, pixelRatio());
1248         d->buffer_view_->updateMetrics();
1249         d->buffer_view_->draw(pain);
1250         FontInfo font = d->buffer_view_->cursor().getFont().fontInfo();
1251         FontMetrics const & fm = theFontMetrics(font);
1252         int height = fm.maxHeight();
1253         int cur_x = d->cursor_->rect().left();
1254         int cur_y = d->cursor_->rect().bottom();
1255
1256         // redraw area of preedit string.
1257         update(0, cur_y - height, viewport()->width(),
1258                 (height + 1) * d->preedit_lines_);
1259
1260         if (preedit_string.empty()) {
1261                 last_width = false;
1262                 d->preedit_lines_ = 1;
1263                 e->accept();
1264                 return;
1265         }
1266         last_width = true;
1267
1268         // att : stores an IM attribute.
1269         QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1270
1271         // get attributes of input method cursor.
1272         // cursor_pos : cursor position in preedit string.
1273         size_t cursor_pos = 0;
1274         bool cursor_is_visible = false;
1275         for (int i = 0; i != att.size(); ++i) {
1276                 if (att.at(i).type == QInputMethodEvent::Cursor) {
1277                         cursor_pos = att.at(i).start;
1278                         cursor_is_visible = att.at(i).length != 0;
1279                         break;
1280                 }
1281         }
1282
1283         size_t preedit_length = preedit_string.length();
1284
1285         // get position of selection in input method.
1286         // FIXME: isn't there a way to do this simplier?
1287         // rStart : cursor position in selected string in IM.
1288         size_t rStart = 0;
1289         // rLength : selected string length in IM.
1290         size_t rLength = 0;
1291         if (cursor_pos < preedit_length) {
1292                 for (int i = 0; i != att.size(); ++i) {
1293                         if (att.at(i).type == QInputMethodEvent::TextFormat) {
1294                                 if (att.at(i).start <= int(cursor_pos)
1295                                         && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1296                                                 rStart = att.at(i).start;
1297                                                 rLength = att.at(i).length;
1298                                                 if (!cursor_is_visible)
1299                                                         cursor_pos += rLength;
1300                                                 break;
1301                                 }
1302                         }
1303                 }
1304         }
1305         else {
1306                 rStart = cursor_pos;
1307                 rLength = 0;
1308         }
1309
1310         int const right_margin = d->buffer_view_->rightMargin();
1311         Painter::preedit_style ps;
1312         // Most often there would be only one line:
1313         d->preedit_lines_ = 1;
1314         for (size_t pos = 0; pos != preedit_length; ++pos) {
1315                 char_type const typed_char = preedit_string[pos];
1316                 // reset preedit string style
1317                 ps = Painter::preedit_default;
1318
1319                 // if we reached the right extremity of the screen, go to next line.
1320                 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1321                         cur_x = right_margin;
1322                         cur_y += height + 1;
1323                         ++d->preedit_lines_;
1324                 }
1325                 // preedit strings are displayed with dashed underline
1326                 // and partial strings are displayed white on black indicating
1327                 // that we are in selecting mode in the input method.
1328                 // FIXME: rLength == preedit_length is not a changing condition
1329                 // FIXME: should be put out of the loop.
1330                 if (pos >= rStart
1331                         && pos < rStart + rLength
1332                         && !(cursor_pos < rLength && rLength == preedit_length))
1333                         ps = Painter::preedit_selecting;
1334
1335                 if (pos == cursor_pos
1336                         && (cursor_pos < rLength && rLength == preedit_length))
1337                         ps = Painter::preedit_cursor;
1338
1339                 // draw one character and update cur_x.
1340                 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1341         }
1342
1343         // update the preedit string screen area.
1344         update(0, cur_y - d->preedit_lines_*height, viewport()->width(),
1345                 (height + 1) * d->preedit_lines_);
1346
1347         // Don't forget to accept the event!
1348         e->accept();
1349 }
1350
1351
1352 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1353 {
1354         QRect cur_r(0, 0, 0, 0);
1355         switch (query) {
1356                 // this is the CJK-specific composition window position and
1357                 // the context menu position when the menu key is pressed.
1358                 case Qt::ImMicroFocus:
1359                         cur_r = d->cursor_->rect();
1360                         if (d->preedit_lines_ != 1)
1361                                 cur_r.moveLeft(10);
1362                         cur_r.moveBottom(cur_r.bottom()
1363                                 + cur_r.height() * (d->preedit_lines_ - 1));
1364                         // return lower right of cursor in LyX.
1365                         return cur_r;
1366                 default:
1367                         return QWidget::inputMethodQuery(query);
1368         }
1369 }
1370
1371
1372 void GuiWorkArea::updateWindowTitle()
1373 {
1374         docstring maximize_title;
1375         docstring minimize_title;
1376
1377         Buffer const & buf = d->buffer_view_->buffer();
1378         FileName const file_name = buf.fileName();
1379         if (!file_name.empty()) {
1380                 maximize_title = file_name.displayName(130);
1381                 minimize_title = from_utf8(file_name.onlyFileName());
1382                 if (buf.lyxvc().inUse()) {
1383                         if (buf.lyxvc().locking())
1384                                 maximize_title +=  _(" (version control, locking)");
1385                         else
1386                                 maximize_title +=  _(" (version control)");
1387                 }
1388                 if (!buf.isClean()) {
1389                         maximize_title += _(" (changed)");
1390                         minimize_title += char_type('*');
1391                 }
1392                 if (buf.isReadonly())
1393                         maximize_title += _(" (read only)");
1394         }
1395
1396         QString const new_title = toqstr(maximize_title);
1397         if (new_title != windowTitle()) {
1398                 QWidget::setWindowTitle(new_title);
1399                 QWidget::setWindowIconText(toqstr(minimize_title));
1400                 titleChanged(this);
1401         }
1402 }
1403
1404
1405 bool GuiWorkArea::isFullScreen() const
1406 {
1407         return d->lyx_view_ && d->lyx_view_->isFullScreen();
1408 }
1409
1410
1411 void GuiWorkArea::scheduleRedraw()
1412 {
1413         d->schedule_redraw_ = true;
1414 }
1415
1416
1417 bool GuiWorkArea::inDialogMode() const
1418 {
1419         return d->dialog_mode_;
1420 }
1421
1422
1423 void GuiWorkArea::setDialogMode(bool mode)
1424 {
1425         d->dialog_mode_ = mode;
1426 }
1427
1428
1429 GuiCompleter & GuiWorkArea::completer()
1430 {
1431         return *d->completer_;
1432 }
1433
1434 GuiView const & GuiWorkArea::view() const
1435 {
1436         return *d->lyx_view_;
1437 }
1438
1439
1440 GuiView & GuiWorkArea::view()
1441 {
1442         return *d->lyx_view_;
1443 }
1444
1445 ////////////////////////////////////////////////////////////////////
1446 //
1447 // EmbeddedWorkArea
1448 //
1449 ////////////////////////////////////////////////////////////////////
1450
1451
1452 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1453 {
1454         support::TempFile tempfile("embedded.internal");
1455         tempfile.setAutoRemove(false);
1456         buffer_ = theBufferList().newInternalBuffer(tempfile.name().absFileName());
1457         buffer_->setUnnamed(true);
1458         buffer_->setFullyLoaded(true);
1459         setBuffer(*buffer_);
1460         setDialogMode(true);
1461 }
1462
1463
1464 EmbeddedWorkArea::~EmbeddedWorkArea()
1465 {
1466         // No need to destroy buffer and bufferview here, because it is done
1467         // in theBufferList() destruction loop at application exit
1468 }
1469
1470
1471 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1472 {
1473         disable();
1474         GuiWorkArea::closeEvent(ev);
1475 }
1476
1477
1478 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1479 {
1480         disable();
1481         GuiWorkArea::hideEvent(ev);
1482 }
1483
1484
1485 QSize EmbeddedWorkArea::sizeHint () const
1486 {
1487         // FIXME(?):
1488         // GuiWorkArea sets the size to the screen's viewport
1489         // by returning a value this gets overridden
1490         // EmbeddedWorkArea is now sized to fit in the layout
1491         // of the parent, and has a minimum size set in GuiWorkArea
1492         // which is what we return here
1493         return QSize(100, 70);
1494 }
1495
1496
1497 void EmbeddedWorkArea::disable()
1498 {
1499         stopBlinkingCursor();
1500         if (view().currentWorkArea() != this)
1501                 return;
1502         // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1503         // tolerates it and shows the background logo), what happens if
1504         // an EmbeddedWorkArea is closed after closing all document WAs
1505         view().setCurrentWorkArea(view().currentMainWorkArea());
1506 }
1507
1508 ////////////////////////////////////////////////////////////////////
1509 //
1510 // TabWorkArea
1511 //
1512 ////////////////////////////////////////////////////////////////////
1513
1514 #ifdef Q_OS_MAC
1515 class NoTabFrameMacStyle : public QProxyStyle {
1516 public:
1517         ///
1518         QRect subElementRect(SubElement element, const QStyleOption * option,
1519                              const QWidget * widget = 0) const
1520         {
1521                 QRect rect = QProxyStyle::subElementRect(element, option, widget);
1522                 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1523
1524                 // The Qt Mac style puts the contents into a 3 pixel wide box
1525                 // which looks very ugly and not like other Mac applications.
1526                 // Hence we remove this here, and moreover the 16 pixel round
1527                 // frame above if the tab bar is hidden.
1528                 if (element == QStyle::SE_TabWidgetTabContents) {
1529                         rect.adjust(- rect.left(), 0, rect.left(), 0);
1530                         if (noBar)
1531                                 rect.setTop(0);
1532                 }
1533
1534                 return rect;
1535         }
1536 };
1537
1538 NoTabFrameMacStyle noTabFrameMacStyle;
1539 #endif
1540
1541
1542 TabWorkArea::TabWorkArea(QWidget * parent)
1543         : QTabWidget(parent), clicked_tab_(-1)
1544 {
1545 #ifdef Q_OS_MAC
1546         setStyle(&noTabFrameMacStyle);
1547 #endif
1548
1549         QPalette pal = palette();
1550         pal.setColor(QPalette::Active, QPalette::Button,
1551                 pal.color(QPalette::Active, QPalette::Window));
1552         pal.setColor(QPalette::Disabled, QPalette::Button,
1553                 pal.color(QPalette::Disabled, QPalette::Window));
1554         pal.setColor(QPalette::Inactive, QPalette::Button,
1555                 pal.color(QPalette::Inactive, QPalette::Window));
1556
1557         QObject::connect(this, SIGNAL(currentChanged(int)),
1558                 this, SLOT(on_currentTabChanged(int)));
1559
1560         closeBufferButton = new QToolButton(this);
1561         closeBufferButton->setPalette(pal);
1562         // FIXME: rename the icon to closebuffer.png
1563         closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "svgz,png")));
1564         closeBufferButton->setText("Close File");
1565         closeBufferButton->setAutoRaise(true);
1566         closeBufferButton->setCursor(Qt::ArrowCursor);
1567         closeBufferButton->setToolTip(qt_("Close File"));
1568         closeBufferButton->setEnabled(true);
1569         QObject::connect(closeBufferButton, SIGNAL(clicked()),
1570                 this, SLOT(closeCurrentBuffer()));
1571         setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1572
1573         // setup drag'n'drop
1574         QTabBar* tb = new DragTabBar;
1575         connect(tb, SIGNAL(tabMoveRequested(int, int)),
1576                 this, SLOT(moveTab(int, int)));
1577         tb->setElideMode(Qt::ElideNone);
1578         setTabBar(tb);
1579
1580         // make us responsible for the context menu of the tabbar
1581         tb->setContextMenuPolicy(Qt::CustomContextMenu);
1582         connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1583                 this, SLOT(showContextMenu(const QPoint &)));
1584         connect(tb, SIGNAL(tabCloseRequested(int)),
1585                 this, SLOT(closeTab(int)));
1586
1587         setUsesScrollButtons(true);
1588 }
1589
1590
1591 void TabWorkArea::paintEvent(QPaintEvent * event)
1592 {
1593         if (tabBar()->isVisible()) {
1594                 QTabWidget::paintEvent(event);
1595         } else {
1596                 // Prevent the selected tab to influence the 
1597                 // painting of the frame of the tab widget.
1598                 // This is needed for gtk style in Qt.
1599                 QStylePainter p(this);
1600 #if QT_VERSION < 0x050000
1601                 QStyleOptionTabWidgetFrameV2 opt;
1602 #else
1603                 QStyleOptionTabWidgetFrame opt;
1604 #endif
1605                 initStyleOption(&opt);
1606                 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1607                         &opt, this);
1608                 opt.selectedTabRect = QRect();
1609                 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1610         }
1611 }
1612
1613
1614 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1615 {
1616         if (event->button() != Qt::LeftButton)
1617                 return;
1618
1619         // return early if double click on existing tabs
1620         for (int i = 0; i < count(); ++i)
1621                 if (tabBar()->tabRect(i).contains(event->pos()))
1622                         return;
1623
1624         dispatch(FuncRequest(LFUN_BUFFER_NEW));
1625 }
1626
1627
1628 void TabWorkArea::setFullScreen(bool full_screen)
1629 {
1630         for (int i = 0; i != count(); ++i) {
1631                 if (GuiWorkArea * wa = workArea(i))
1632                         wa->setFullScreen(full_screen);
1633         }
1634
1635         if (lyxrc.full_screen_tabbar)
1636                 showBar(!full_screen && count() > 1);
1637         else
1638                 showBar(count() > 1);
1639 }
1640
1641
1642 void TabWorkArea::showBar(bool show)
1643 {
1644         tabBar()->setEnabled(show);
1645         tabBar()->setVisible(show);
1646         closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1647         setTabsClosable(!lyxrc.single_close_tab_button);
1648 }
1649
1650
1651 GuiWorkArea * TabWorkArea::currentWorkArea()
1652 {
1653         if (count() == 0)
1654                 return 0;
1655
1656         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1657         LATTEST(wa);
1658         return wa;
1659 }
1660
1661
1662 GuiWorkArea * TabWorkArea::workArea(int index)
1663 {
1664         return dynamic_cast<GuiWorkArea *>(widget(index));
1665 }
1666
1667
1668 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1669 {
1670         // FIXME: this method doesn't work if we have more than work area
1671         // showing the same buffer.
1672         for (int i = 0; i != count(); ++i) {
1673                 GuiWorkArea * wa = workArea(i);
1674                 LASSERT(wa, return 0);
1675                 if (&wa->bufferView().buffer() == &buffer)
1676                         return wa;
1677         }
1678         return 0;
1679 }
1680
1681
1682 void TabWorkArea::closeAll()
1683 {
1684         while (count()) {
1685                 GuiWorkArea * wa = workArea(0);
1686                 LASSERT(wa, return);
1687                 removeTab(0);
1688                 delete wa;
1689         }
1690 }
1691
1692
1693 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1694 {
1695         LASSERT(work_area, return false);
1696         int index = indexOf(work_area);
1697         if (index == -1)
1698                 return false;
1699
1700         if (index == currentIndex())
1701                 // Make sure the work area is up to date.
1702                 on_currentTabChanged(index);
1703         else
1704                 // Switch to the work area.
1705                 setCurrentIndex(index);
1706         work_area->setFocus();
1707
1708         return true;
1709 }
1710
1711
1712 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1713 {
1714         GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1715         wa->setUpdatesEnabled(false);
1716         // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1717         // when hiding it again below).
1718         if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1719                 showBar(count() > 0);
1720         addTab(wa, wa->windowTitle());
1721         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1722                 this, SLOT(updateTabTexts()));
1723         if (currentWorkArea() && currentWorkArea()->isFullScreen())
1724                 setFullScreen(true);
1725         else
1726                 // Hide tabbar if there's only one tab.
1727                 showBar(count() > 1);
1728
1729         updateTabTexts();
1730
1731         return wa;
1732 }
1733
1734
1735 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1736 {
1737         LASSERT(work_area, return false);
1738         int index = indexOf(work_area);
1739         if (index == -1)
1740                 return false;
1741
1742         work_area->setUpdatesEnabled(false);
1743         removeTab(index);
1744         delete work_area;
1745
1746         if (count()) {
1747                 // make sure the next work area is enabled.
1748                 currentWidget()->setUpdatesEnabled(true);
1749                 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1750                         setFullScreen(true);
1751                 else
1752                         // Show tabbar only if there's more than one tab.
1753                         showBar(count() > 1);
1754         } else
1755                 lastWorkAreaRemoved();
1756
1757         updateTabTexts();
1758
1759         return true;
1760 }
1761
1762
1763 void TabWorkArea::on_currentTabChanged(int i)
1764 {
1765         // returns e.g. on application destruction
1766         if (i == -1)
1767                 return;
1768         GuiWorkArea * wa = workArea(i);
1769         LASSERT(wa, return);
1770         wa->setUpdatesEnabled(true);
1771         wa->redraw(true);
1772         wa->setFocus();
1773         ///
1774         currentWorkAreaChanged(wa);
1775
1776         LYXERR(Debug::GUI, "currentTabChanged " << i
1777                 << " File: " << wa->bufferView().buffer().absFileName());
1778 }
1779
1780
1781 void TabWorkArea::closeCurrentBuffer()
1782 {
1783         GuiWorkArea * wa;
1784         if (clicked_tab_ == -1)
1785                 wa = currentWorkArea();
1786         else {
1787                 wa = workArea(clicked_tab_);
1788                 LASSERT(wa, return);
1789         }
1790         wa->view().closeWorkArea(wa);
1791 }
1792
1793
1794 void TabWorkArea::hideCurrentTab()
1795 {
1796         GuiWorkArea * wa;
1797         if (clicked_tab_ == -1)
1798                 wa = currentWorkArea();
1799         else {
1800                 wa = workArea(clicked_tab_);
1801                 LASSERT(wa, return);
1802         }
1803         wa->view().hideWorkArea(wa);
1804 }
1805
1806
1807 void TabWorkArea::closeTab(int index)
1808 {
1809         on_currentTabChanged(index);
1810         GuiWorkArea * wa;
1811         if (index == -1)
1812                 wa = currentWorkArea();
1813         else {
1814                 wa = workArea(index);
1815                 LASSERT(wa, return);
1816         }
1817         wa->view().closeWorkArea(wa);
1818 }
1819
1820
1821 ///
1822 class DisplayPath {
1823 public:
1824         /// make vector happy
1825         DisplayPath() {}
1826         ///
1827         DisplayPath(int tab, FileName const & filename)
1828                 : tab_(tab)
1829         {
1830                 filename_ = (filename.extension() == "lyx") ?
1831                         toqstr(filename.onlyFileNameWithoutExt())
1832                         : toqstr(filename.onlyFileName());
1833                 postfix_ = toqstr(filename.absoluteFilePath()).
1834                         split("/", QString::SkipEmptyParts);
1835                 postfix_.pop_back();
1836                 abs_ = toqstr(filename.absoluteFilePath());
1837                 dottedPrefix_ = false;
1838         }
1839
1840         /// Absolute path for debugging.
1841         QString abs() const
1842         {
1843                 return abs_;
1844         }
1845         /// Add the first segment from the postfix or three dots to the prefix.
1846         /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1847         /// when really needed.
1848         void shiftPathSegment(bool dotted)
1849         {
1850                 if (postfix_.count() <= 0)
1851                         return;
1852
1853                 if (!dotted) {
1854                         if (dottedPrefix_ && !prefix_.isEmpty())
1855                                 prefix_ += ".../";
1856                         prefix_ += postfix_.front() + "/";
1857                 }
1858                 dottedPrefix_ = dotted && !prefix_.isEmpty();
1859                 postfix_.pop_front();
1860         }
1861         ///
1862         QString displayString() const
1863         {
1864                 if (prefix_.isEmpty())
1865                         return filename_;
1866
1867                 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1868                 return prefix_ + (dots ? ".../" : "") + filename_;
1869         }
1870         ///
1871         QString forecastPathString() const
1872         {
1873                 if (postfix_.count() == 0)
1874                         return displayString();
1875
1876                 return prefix_
1877                         + (dottedPrefix_ ? ".../" : "")
1878                         + postfix_.front() + "/";
1879         }
1880         ///
1881         bool final() const { return postfix_.empty(); }
1882         ///
1883         int tab() const { return tab_; }
1884
1885 private:
1886         ///
1887         QString prefix_;
1888         ///
1889         QStringList postfix_;
1890         ///
1891         QString filename_;
1892         ///
1893         QString abs_;
1894         ///
1895         int tab_;
1896         ///
1897         bool dottedPrefix_;
1898 };
1899
1900
1901 ///
1902 bool operator<(DisplayPath const & a, DisplayPath const & b)
1903 {
1904         return a.displayString() < b.displayString();
1905 }
1906
1907 ///
1908 bool operator==(DisplayPath const & a, DisplayPath const & b)
1909 {
1910         return a.displayString() == b.displayString();
1911 }
1912
1913
1914 void TabWorkArea::updateTabTexts()
1915 {
1916         size_t n = count();
1917         if (n == 0)
1918                 return;
1919         std::list<DisplayPath> paths;
1920         typedef std::list<DisplayPath>::iterator It;
1921
1922         // collect full names first: path into postfix, empty prefix and
1923         // filename without extension
1924         for (size_t i = 0; i < n; ++i) {
1925                 GuiWorkArea * i_wa = workArea(i);
1926                 FileName const fn = i_wa->bufferView().buffer().fileName();
1927                 paths.push_back(DisplayPath(i, fn));
1928         }
1929
1930         // go through path segments and see if it helps to make the path more unique
1931         bool somethingChanged = true;
1932         bool allFinal = false;
1933         while (somethingChanged && !allFinal) {
1934                 // adding path segments changes order
1935                 paths.sort();
1936
1937                 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1938                 somethingChanged = false;
1939                 allFinal = true;
1940
1941                 // find segments which are not unique (i.e. non-atomic)
1942                 It it = paths.begin();
1943                 It segStart = it;
1944                 QString segString = it->displayString();
1945                 for (; it != paths.end(); ++it) {
1946                         // look to the next item
1947                         It next = it;
1948                         ++next;
1949
1950                         // final?
1951                         allFinal = allFinal && it->final();
1952
1953                         LYXERR(Debug::GUI, "it = " << it->abs()
1954                                << " => " << it->displayString());
1955
1956                         // still the same segment?
1957                         QString nextString;
1958                         if ((next != paths.end()
1959                              && (nextString = next->displayString()) == segString))
1960                                 continue;
1961                         LYXERR(Debug::GUI, "segment ended");
1962
1963                         // only a trivial one with one element?
1964                         if (it == segStart) {
1965                                 // start new segment
1966                                 segStart = next;
1967                                 segString = nextString;
1968                                 continue;
1969                         }
1970
1971                         // we found a non-atomic segment segStart <= sit <= it < next.
1972                         // Shift path segments and hope for the best
1973                         // that it makes the path more unique.
1974                         somethingChanged = true;
1975                         It sit = segStart;
1976                         QString dspString = sit->forecastPathString();
1977                         LYXERR(Debug::GUI, "first forecast found for "
1978                                << sit->abs() << " => " << dspString);
1979                         ++sit;
1980                         bool moreUnique = false;
1981                         for (; sit != next; ++sit) {
1982                                 if (sit->forecastPathString() != dspString) {
1983                                         LYXERR(Debug::GUI, "different forecast found for "
1984                                                 << sit->abs() << " => " << sit->forecastPathString());
1985                                         moreUnique = true;
1986                                         break;
1987                                 }
1988                                 LYXERR(Debug::GUI, "same forecast found for "
1989                                         << sit->abs() << " => " << dspString);
1990                         }
1991
1992                         // if the path segment helped, add it. Otherwise add dots
1993                         bool dots = !moreUnique;
1994                         LYXERR(Debug::GUI, "using dots = " << dots);
1995                         for (sit = segStart; sit != next; ++sit) {
1996                                 sit->shiftPathSegment(dots);
1997                                 LYXERR(Debug::GUI, "shifting "
1998                                         << sit->abs() << " => " << sit->displayString());
1999                         }
2000
2001                         // start new segment
2002                         segStart = next;
2003                         segString = nextString;
2004                 }
2005         }
2006
2007         // set new tab titles
2008         for (It it = paths.begin(); it != paths.end(); ++it) {
2009                 int const tab_index = it->tab();
2010                 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
2011                 QString tab_text = it->displayString().replace("&", "&&");
2012                 if (!buf.fileName().empty() && !buf.isClean())
2013                         tab_text += "*";
2014                 QString tab_tooltip = it->abs();
2015                 if (buf.isReadonly()) {
2016                         setTabIcon(tab_index, QIcon(getPixmap("images/", "emblem-readonly", "svgz,png")));
2017                         tab_tooltip = qt_("%1 (read only)").arg(it->abs());
2018                 } else
2019                         setTabIcon(tab_index, QIcon());
2020                 setTabText(tab_index, tab_text);
2021                 setTabToolTip(tab_index, tab_tooltip);
2022         }
2023 }
2024
2025
2026 void TabWorkArea::showContextMenu(const QPoint & pos)
2027 {
2028         // which tab?
2029         clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
2030         if (clicked_tab_ == -1)
2031                 return;
2032
2033         // show tab popup
2034         QMenu popup;
2035         popup.addAction(QIcon(getPixmap("images/", "hidetab", "svgz,png")),
2036                 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2037         popup.addAction(QIcon(getPixmap("images/", "closetab", "svgz,png")),
2038                 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2039         popup.exec(tabBar()->mapToGlobal(pos));
2040
2041         clicked_tab_ = -1;
2042 }
2043
2044
2045 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2046 {
2047         QWidget * w = widget(fromIndex);
2048         QIcon icon = tabIcon(fromIndex);
2049         QString text = tabText(fromIndex);
2050
2051         setCurrentIndex(fromIndex);
2052         removeTab(fromIndex);
2053         insertTab(toIndex, w, icon, text);
2054         setCurrentIndex(toIndex);
2055 }
2056
2057
2058 DragTabBar::DragTabBar(QWidget* parent)
2059         : QTabBar(parent)
2060 {
2061         setAcceptDrops(true);
2062         setTabsClosable(!lyxrc.single_close_tab_button);
2063 }
2064
2065
2066 void DragTabBar::mousePressEvent(QMouseEvent * event)
2067 {
2068         if (event->button() == Qt::LeftButton)
2069                 dragStartPos_ = event->pos();
2070         QTabBar::mousePressEvent(event);
2071 }
2072
2073
2074 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2075 {
2076         // If the left button isn't pressed anymore then return
2077         if (!(event->buttons() & Qt::LeftButton))
2078                 return;
2079
2080         // If the distance is too small then return
2081         if ((event->pos() - dragStartPos_).manhattanLength()
2082             < QApplication::startDragDistance())
2083                 return;
2084
2085         // did we hit something after all?
2086         int tab = tabAt(dragStartPos_);
2087         if (tab == -1)
2088                 return;
2089
2090         // simulate button release to remove highlight from button
2091         int i = currentIndex();
2092         QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2093                 event->button(), event->buttons(), 0);
2094         QTabBar::mouseReleaseEvent(&me);
2095         setCurrentIndex(i);
2096
2097         // initiate Drag
2098         QDrag * drag = new QDrag(this);
2099         QMimeData * mimeData = new QMimeData;
2100         // a crude way to distinguish tab-reodering drops from other ones
2101         mimeData->setData("action", "tab-reordering") ;
2102         drag->setMimeData(mimeData);
2103
2104         // get tab pixmap as cursor
2105         QRect r = tabRect(tab);
2106         QPixmap pixmap(r.size());
2107         render(&pixmap, - r.topLeft());
2108         drag->setPixmap(pixmap);
2109         drag->exec();
2110 }
2111
2112
2113 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2114 {
2115         // Only accept if it's an tab-reordering request
2116         QMimeData const * m = event->mimeData();
2117         QStringList formats = m->formats();
2118         if (formats.contains("action")
2119             && m->data("action") == "tab-reordering")
2120                 event->acceptProposedAction();
2121 }
2122
2123
2124 void DragTabBar::dropEvent(QDropEvent * event)
2125 {
2126         int fromIndex = tabAt(dragStartPos_);
2127         int toIndex = tabAt(event->pos());
2128
2129         // Tell interested objects that
2130         if (fromIndex != toIndex)
2131                 tabMoveRequested(fromIndex, toIndex);
2132         event->acceptProposedAction();
2133 }
2134
2135
2136 } // namespace frontend
2137 } // namespace lyx
2138
2139 #include "moc_GuiWorkArea.cpp"