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