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