]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.cpp
Fix a bunch of minor issues discovered by the cppcheck script.
[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         // FIXME THREAD
1214         // We could have more than one work area, right?
1215         static bool last_width = false;
1216         if (!last_width && preedit_string.empty()) {
1217                 // if last_width is last length of preedit string.
1218                 e->accept();
1219                 return;
1220         }
1221
1222         GuiPainter pain(d->screen_);
1223         d->buffer_view_->updateMetrics();
1224         d->buffer_view_->draw(pain);
1225         FontInfo font = d->buffer_view_->cursor().getFont().fontInfo();
1226         FontMetrics const & fm = theFontMetrics(font);
1227         int height = fm.maxHeight();
1228         int cur_x = d->cursor_->rect().left();
1229         int cur_y = d->cursor_->rect().bottom();
1230
1231         // redraw area of preedit string.
1232         update(0, cur_y - height, viewport()->width(),
1233                 (height + 1) * d->preedit_lines_);
1234
1235         if (preedit_string.empty()) {
1236                 last_width = false;
1237                 d->preedit_lines_ = 1;
1238                 e->accept();
1239                 return;
1240         }
1241         last_width = true;
1242
1243         // att : stores an IM attribute.
1244         QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1245
1246         // get attributes of input method cursor.
1247         // cursor_pos : cursor position in preedit string.
1248         size_t cursor_pos = 0;
1249         bool cursor_is_visible = false;
1250         for (int i = 0; i != att.size(); ++i) {
1251                 if (att.at(i).type == QInputMethodEvent::Cursor) {
1252                         cursor_pos = att.at(i).start;
1253                         cursor_is_visible = att.at(i).length != 0;
1254                         break;
1255                 }
1256         }
1257
1258         size_t preedit_length = preedit_string.length();
1259
1260         // get position of selection in input method.
1261         // FIXME: isn't there a way to do this simplier?
1262         // rStart : cursor position in selected string in IM.
1263         size_t rStart = 0;
1264         // rLength : selected string length in IM.
1265         size_t rLength = 0;
1266         if (cursor_pos < preedit_length) {
1267                 for (int i = 0; i != att.size(); ++i) {
1268                         if (att.at(i).type == QInputMethodEvent::TextFormat) {
1269                                 if (att.at(i).start <= int(cursor_pos)
1270                                         && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1271                                                 rStart = att.at(i).start;
1272                                                 rLength = att.at(i).length;
1273                                                 if (!cursor_is_visible)
1274                                                         cursor_pos += rLength;
1275                                                 break;
1276                                 }
1277                         }
1278                 }
1279         }
1280         else {
1281                 rStart = cursor_pos;
1282                 rLength = 0;
1283         }
1284
1285         int const right_margin = d->buffer_view_->rightMargin();
1286         Painter::preedit_style ps;
1287         // Most often there would be only one line:
1288         d->preedit_lines_ = 1;
1289         for (size_t pos = 0; pos != preedit_length; ++pos) {
1290                 char_type const typed_char = preedit_string[pos];
1291                 // reset preedit string style
1292                 ps = Painter::preedit_default;
1293
1294                 // if we reached the right extremity of the screen, go to next line.
1295                 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1296                         cur_x = right_margin;
1297                         cur_y += height + 1;
1298                         ++d->preedit_lines_;
1299                 }
1300                 // preedit strings are displayed with dashed underline
1301                 // and partial strings are displayed white on black indicating
1302                 // that we are in selecting mode in the input method.
1303                 // FIXME: rLength == preedit_length is not a changing condition
1304                 // FIXME: should be put out of the loop.
1305                 if (pos >= rStart
1306                         && pos < rStart + rLength
1307                         && !(cursor_pos < rLength && rLength == preedit_length))
1308                         ps = Painter::preedit_selecting;
1309
1310                 if (pos == cursor_pos
1311                         && (cursor_pos < rLength && rLength == preedit_length))
1312                         ps = Painter::preedit_cursor;
1313
1314                 // draw one character and update cur_x.
1315                 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1316         }
1317
1318         // update the preedit string screen area.
1319         update(0, cur_y - d->preedit_lines_*height, viewport()->width(),
1320                 (height + 1) * d->preedit_lines_);
1321
1322         // Don't forget to accept the event!
1323         e->accept();
1324 }
1325
1326
1327 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1328 {
1329         QRect cur_r(0, 0, 0, 0);
1330         switch (query) {
1331                 // this is the CJK-specific composition window position and
1332                 // the context menu position when the menu key is pressed.
1333                 case Qt::ImMicroFocus:
1334                         cur_r = d->cursor_->rect();
1335                         if (d->preedit_lines_ != 1)
1336                                 cur_r.moveLeft(10);
1337                         cur_r.moveBottom(cur_r.bottom()
1338                                 + cur_r.height() * (d->preedit_lines_ - 1));
1339                         // return lower right of cursor in LyX.
1340                         return cur_r;
1341                 default:
1342                         return QWidget::inputMethodQuery(query);
1343         }
1344 }
1345
1346
1347 void GuiWorkArea::updateWindowTitle()
1348 {
1349         docstring maximize_title;
1350         docstring minimize_title;
1351
1352         Buffer const & buf = d->buffer_view_->buffer();
1353         FileName const file_name = buf.fileName();
1354         if (!file_name.empty()) {
1355                 maximize_title = file_name.displayName(130);
1356                 minimize_title = from_utf8(file_name.onlyFileName());
1357                 if (buf.lyxvc().inUse()) {
1358                         if (buf.lyxvc().locking())
1359                                 maximize_title +=  _(" (version control, locking)");
1360                         else
1361                                 maximize_title +=  _(" (version control)");
1362                 }
1363                 if (!buf.isClean()) {
1364                         maximize_title += _(" (changed)");
1365                         minimize_title += char_type('*');
1366                 }
1367                 if (buf.isReadonly())
1368                         maximize_title += _(" (read only)");
1369         }
1370
1371         QString const new_title = toqstr(maximize_title);
1372         if (new_title != windowTitle()) {
1373                 QWidget::setWindowTitle(new_title);
1374                 QWidget::setWindowIconText(toqstr(minimize_title));
1375                 titleChanged(this);
1376         }
1377 }
1378
1379
1380 bool GuiWorkArea::isFullScreen() const
1381 {
1382         return d->lyx_view_ && d->lyx_view_->isFullScreen();
1383 }
1384
1385
1386 void GuiWorkArea::scheduleRedraw()
1387 {
1388         d->schedule_redraw_ = true;
1389 }
1390
1391
1392 bool GuiWorkArea::inDialogMode() const
1393 {
1394         return d->dialog_mode_;
1395 }
1396
1397
1398 void GuiWorkArea::setDialogMode(bool mode)
1399 {
1400         d->dialog_mode_ = mode;
1401 }
1402
1403
1404 GuiCompleter & GuiWorkArea::completer()
1405 {
1406         return *d->completer_;
1407 }
1408
1409 GuiView const & GuiWorkArea::view() const
1410 {
1411         return *d->lyx_view_;
1412 }
1413
1414
1415 GuiView & GuiWorkArea::view()
1416 {
1417         return *d->lyx_view_;
1418 }
1419
1420 ////////////////////////////////////////////////////////////////////
1421 //
1422 // EmbeddedWorkArea
1423 //
1424 ////////////////////////////////////////////////////////////////////
1425
1426
1427 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1428 {
1429         buffer_ = theBufferList().newInternalBuffer(
1430                 support::FileName::tempName("embedded.internal").absFileName());
1431         buffer_->setUnnamed(true);
1432         buffer_->setFullyLoaded(true);
1433         setBuffer(*buffer_);
1434         setDialogMode(true);
1435 }
1436
1437
1438 EmbeddedWorkArea::~EmbeddedWorkArea()
1439 {
1440         // No need to destroy buffer and bufferview here, because it is done
1441         // in theBufferList() destruction loop at application exit
1442 }
1443
1444
1445 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1446 {
1447         disable();
1448         GuiWorkArea::closeEvent(ev);
1449 }
1450
1451
1452 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1453 {
1454         disable();
1455         GuiWorkArea::hideEvent(ev);
1456 }
1457
1458
1459 QSize EmbeddedWorkArea::sizeHint () const
1460 {
1461         // FIXME(?):
1462         // GuiWorkArea sets the size to the screen's viewport
1463         // by returning a value this gets overridden
1464         // EmbeddedWorkArea is now sized to fit in the layout
1465         // of the parent, and has a minimum size set in GuiWorkArea
1466         // which is what we return here
1467         return QSize(100, 70);
1468 }
1469
1470
1471 void EmbeddedWorkArea::disable()
1472 {
1473         stopBlinkingCursor();
1474         if (view().currentWorkArea() != this)
1475                 return;
1476         // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1477         // tolerates it and shows the background logo), what happens if
1478         // an EmbeddedWorkArea is closed after closing all document WAs
1479         view().setCurrentWorkArea(view().currentMainWorkArea());
1480 }
1481
1482 ////////////////////////////////////////////////////////////////////
1483 //
1484 // TabWorkArea
1485 //
1486 ////////////////////////////////////////////////////////////////////
1487
1488 #ifdef Q_WS_MACX
1489 class NoTabFrameMacStyle : public QMacStyle {
1490 public:
1491         ///
1492         QRect subElementRect(SubElement element, const QStyleOption * option,
1493                              const QWidget * widget = 0) const
1494         {
1495                 QRect rect = QMacStyle::subElementRect(element, option, widget);
1496                 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1497
1498                 // The Qt Mac style puts the contents into a 3 pixel wide box
1499                 // which looks very ugly and not like other Mac applications.
1500                 // Hence we remove this here, and moreover the 16 pixel round
1501                 // frame above if the tab bar is hidden.
1502                 if (element == QStyle::SE_TabWidgetTabContents) {
1503                         rect.adjust(- rect.left(), 0, rect.left(), 0);
1504                         if (noBar)
1505                                 rect.setTop(0);
1506                 }
1507
1508                 return rect;
1509         }
1510 };
1511
1512 NoTabFrameMacStyle noTabFrameMacStyle;
1513 #endif
1514
1515
1516 TabWorkArea::TabWorkArea(QWidget * parent)
1517         : QTabWidget(parent), clicked_tab_(-1)
1518 {
1519 #ifdef Q_WS_MACX
1520         setStyle(&noTabFrameMacStyle);
1521 #endif
1522
1523         QPalette pal = palette();
1524         pal.setColor(QPalette::Active, QPalette::Button,
1525                 pal.color(QPalette::Active, QPalette::Window));
1526         pal.setColor(QPalette::Disabled, QPalette::Button,
1527                 pal.color(QPalette::Disabled, QPalette::Window));
1528         pal.setColor(QPalette::Inactive, QPalette::Button,
1529                 pal.color(QPalette::Inactive, QPalette::Window));
1530
1531         QObject::connect(this, SIGNAL(currentChanged(int)),
1532                 this, SLOT(on_currentTabChanged(int)));
1533
1534         closeBufferButton = new QToolButton(this);
1535         closeBufferButton->setPalette(pal);
1536         // FIXME: rename the icon to closebuffer.png
1537         closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1538         closeBufferButton->setText("Close File");
1539         closeBufferButton->setAutoRaise(true);
1540         closeBufferButton->setCursor(Qt::ArrowCursor);
1541         closeBufferButton->setToolTip(qt_("Close File"));
1542         closeBufferButton->setEnabled(true);
1543         QObject::connect(closeBufferButton, SIGNAL(clicked()),
1544                 this, SLOT(closeCurrentBuffer()));
1545         setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1546
1547         // setup drag'n'drop
1548         QTabBar* tb = new DragTabBar;
1549         connect(tb, SIGNAL(tabMoveRequested(int, int)),
1550                 this, SLOT(moveTab(int, int)));
1551         tb->setElideMode(Qt::ElideNone);
1552         setTabBar(tb);
1553
1554         // make us responsible for the context menu of the tabbar
1555         tb->setContextMenuPolicy(Qt::CustomContextMenu);
1556         connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1557                 this, SLOT(showContextMenu(const QPoint &)));
1558         connect(tb, SIGNAL(tabCloseRequested(int)),
1559                 this, SLOT(closeTab(int)));
1560
1561         setUsesScrollButtons(true);
1562 }
1563
1564
1565 void TabWorkArea::paintEvent(QPaintEvent * event)
1566 {
1567         if (tabBar()->isVisible()) {
1568                 QTabWidget::paintEvent(event);
1569         } else {
1570                 // Prevent the selected tab to influence the 
1571                 // painting of the frame of the tab widget.
1572                 // This is needed for gtk style in Qt.
1573                 QStylePainter p(this);
1574 #if QT_VERSION < 0x050000
1575                 QStyleOptionTabWidgetFrameV2 opt;
1576 #else
1577                 QStyleOptionTabWidgetFrame opt;
1578 #endif
1579                 initStyleOption(&opt);
1580                 opt.rect = style()->subElementRect(QStyle::SE_TabWidgetTabPane,
1581                         &opt, this);
1582                 opt.selectedTabRect = QRect();
1583                 p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
1584         }
1585 }
1586
1587
1588 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1589 {
1590         if (event->button() != Qt::LeftButton)
1591                 return;
1592
1593         // return early if double click on existing tabs
1594         for (int i = 0; i < count(); ++i)
1595                 if (tabBar()->tabRect(i).contains(event->pos()))
1596                         return;
1597
1598         dispatch(FuncRequest(LFUN_BUFFER_NEW));
1599 }
1600
1601
1602 void TabWorkArea::setFullScreen(bool full_screen)
1603 {
1604         for (int i = 0; i != count(); ++i) {
1605                 if (GuiWorkArea * wa = workArea(i))
1606                         wa->setFullScreen(full_screen);
1607         }
1608
1609         if (lyxrc.full_screen_tabbar)
1610                 showBar(!full_screen && count() > 1);
1611         else
1612                 showBar(count() > 1);
1613 }
1614
1615
1616 void TabWorkArea::showBar(bool show)
1617 {
1618         tabBar()->setEnabled(show);
1619         tabBar()->setVisible(show);
1620         closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1621         setTabsClosable(!lyxrc.single_close_tab_button);
1622 }
1623
1624
1625 GuiWorkArea * TabWorkArea::currentWorkArea()
1626 {
1627         if (count() == 0)
1628                 return 0;
1629
1630         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1631         LATTEST(wa);
1632         return wa;
1633 }
1634
1635
1636 GuiWorkArea * TabWorkArea::workArea(int index)
1637 {
1638         return dynamic_cast<GuiWorkArea *>(widget(index));
1639 }
1640
1641
1642 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1643 {
1644         // FIXME: this method doesn't work if we have more than work area
1645         // showing the same buffer.
1646         for (int i = 0; i != count(); ++i) {
1647                 GuiWorkArea * wa = workArea(i);
1648                 LASSERT(wa, return 0);
1649                 if (&wa->bufferView().buffer() == &buffer)
1650                         return wa;
1651         }
1652         return 0;
1653 }
1654
1655
1656 void TabWorkArea::closeAll()
1657 {
1658         while (count()) {
1659                 GuiWorkArea * wa = workArea(0);
1660                 LASSERT(wa, return);
1661                 removeTab(0);
1662                 delete wa;
1663         }
1664 }
1665
1666
1667 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1668 {
1669         LASSERT(work_area, return false);
1670         int index = indexOf(work_area);
1671         if (index == -1)
1672                 return false;
1673
1674         if (index == currentIndex())
1675                 // Make sure the work area is up to date.
1676                 on_currentTabChanged(index);
1677         else
1678                 // Switch to the work area.
1679                 setCurrentIndex(index);
1680         work_area->setFocus();
1681
1682         return true;
1683 }
1684
1685
1686 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1687 {
1688         GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1689         wa->setUpdatesEnabled(false);
1690         // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1691         // when hiding it again below).
1692         if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1693                 showBar(count() > 0);
1694         addTab(wa, wa->windowTitle());
1695         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1696                 this, SLOT(updateTabTexts()));
1697         if (currentWorkArea() && currentWorkArea()->isFullScreen())
1698                 setFullScreen(true);
1699         else
1700                 // Hide tabbar if there's only one tab.
1701                 showBar(count() > 1);
1702
1703         updateTabTexts();
1704
1705         return wa;
1706 }
1707
1708
1709 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1710 {
1711         LASSERT(work_area, return false);
1712         int index = indexOf(work_area);
1713         if (index == -1)
1714                 return false;
1715
1716         work_area->setUpdatesEnabled(false);
1717         removeTab(index);
1718         delete work_area;
1719
1720         if (count()) {
1721                 // make sure the next work area is enabled.
1722                 currentWidget()->setUpdatesEnabled(true);
1723                 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1724                         setFullScreen(true);
1725                 else
1726                         // Show tabbar only if there's more than one tab.
1727                         showBar(count() > 1);
1728         } else
1729                 lastWorkAreaRemoved();
1730
1731         updateTabTexts();
1732
1733         return true;
1734 }
1735
1736
1737 void TabWorkArea::on_currentTabChanged(int i)
1738 {
1739         // returns e.g. on application destruction
1740         if (i == -1)
1741                 return;
1742         GuiWorkArea * wa = workArea(i);
1743         LASSERT(wa, return);
1744         wa->setUpdatesEnabled(true);
1745         wa->redraw(true);
1746         wa->setFocus();
1747         ///
1748         currentWorkAreaChanged(wa);
1749
1750         LYXERR(Debug::GUI, "currentTabChanged " << i
1751                 << " File: " << wa->bufferView().buffer().absFileName());
1752 }
1753
1754
1755 void TabWorkArea::closeCurrentBuffer()
1756 {
1757         GuiWorkArea * wa;
1758         if (clicked_tab_ == -1)
1759                 wa = currentWorkArea();
1760         else {
1761                 wa = workArea(clicked_tab_);
1762                 LASSERT(wa, return);
1763         }
1764         wa->view().closeWorkArea(wa);
1765 }
1766
1767
1768 void TabWorkArea::hideCurrentTab()
1769 {
1770         GuiWorkArea * wa;
1771         if (clicked_tab_ == -1)
1772                 wa = currentWorkArea();
1773         else {
1774                 wa = workArea(clicked_tab_);
1775                 LASSERT(wa, return);
1776         }
1777         wa->view().hideWorkArea(wa);
1778 }
1779
1780
1781 void TabWorkArea::closeTab(int index)
1782 {
1783         on_currentTabChanged(index);
1784         GuiWorkArea * wa;
1785         if (index == -1)
1786                 wa = currentWorkArea();
1787         else {
1788                 wa = workArea(index);
1789                 LASSERT(wa, return);
1790         }
1791         wa->view().closeWorkArea(wa);
1792 }
1793
1794
1795 ///
1796 class DisplayPath {
1797 public:
1798         /// make vector happy
1799         DisplayPath() {}
1800         ///
1801         DisplayPath(int tab, FileName const & filename)
1802                 : tab_(tab)
1803         {
1804                 filename_ = (filename.extension() == "lyx") ?
1805                         toqstr(filename.onlyFileNameWithoutExt())
1806                         : toqstr(filename.onlyFileName());
1807                 postfix_ = toqstr(filename.absoluteFilePath()).
1808                         split("/", QString::SkipEmptyParts);
1809                 postfix_.pop_back();
1810                 abs_ = toqstr(filename.absoluteFilePath());
1811                 dottedPrefix_ = false;
1812         }
1813
1814         /// Absolute path for debugging.
1815         QString abs() const
1816         {
1817                 return abs_;
1818         }
1819         /// Add the first segment from the postfix or three dots to the prefix.
1820         /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1821         /// when really needed.
1822         void shiftPathSegment(bool dotted)
1823         {
1824                 if (postfix_.count() <= 0)
1825                         return;
1826
1827                 if (!dotted) {
1828                         if (dottedPrefix_ && !prefix_.isEmpty())
1829                                 prefix_ += ".../";
1830                         prefix_ += postfix_.front() + "/";
1831                 }
1832                 dottedPrefix_ = dotted && !prefix_.isEmpty();
1833                 postfix_.pop_front();
1834         }
1835         ///
1836         QString displayString() const
1837         {
1838                 if (prefix_.isEmpty())
1839                         return filename_;
1840
1841                 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1842                 return prefix_ + (dots ? ".../" : "") + filename_;
1843         }
1844         ///
1845         QString forecastPathString() const
1846         {
1847                 if (postfix_.count() == 0)
1848                         return displayString();
1849
1850                 return prefix_
1851                         + (dottedPrefix_ ? ".../" : "")
1852                         + postfix_.front() + "/";
1853         }
1854         ///
1855         bool final() const { return postfix_.empty(); }
1856         ///
1857         int tab() const { return tab_; }
1858
1859 private:
1860         ///
1861         QString prefix_;
1862         ///
1863         QStringList postfix_;
1864         ///
1865         QString filename_;
1866         ///
1867         QString abs_;
1868         ///
1869         int tab_;
1870         ///
1871         bool dottedPrefix_;
1872 };
1873
1874
1875 ///
1876 bool operator<(DisplayPath const & a, DisplayPath const & b)
1877 {
1878         return a.displayString() < b.displayString();
1879 }
1880
1881 ///
1882 bool operator==(DisplayPath const & a, DisplayPath const & b)
1883 {
1884         return a.displayString() == b.displayString();
1885 }
1886
1887
1888 void TabWorkArea::updateTabTexts()
1889 {
1890         size_t n = count();
1891         if (n == 0)
1892                 return;
1893         std::list<DisplayPath> paths;
1894         typedef std::list<DisplayPath>::iterator It;
1895
1896         // collect full names first: path into postfix, empty prefix and
1897         // filename without extension
1898         for (size_t i = 0; i < n; ++i) {
1899                 GuiWorkArea * i_wa = workArea(i);
1900                 FileName const fn = i_wa->bufferView().buffer().fileName();
1901                 paths.push_back(DisplayPath(i, fn));
1902         }
1903
1904         // go through path segments and see if it helps to make the path more unique
1905         bool somethingChanged = true;
1906         bool allFinal = false;
1907         while (somethingChanged && !allFinal) {
1908                 // adding path segments changes order
1909                 paths.sort();
1910
1911                 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1912                 somethingChanged = false;
1913                 allFinal = true;
1914
1915                 // find segments which are not unique (i.e. non-atomic)
1916                 It it = paths.begin();
1917                 It segStart = it;
1918                 QString segString = it->displayString();
1919                 for (; it != paths.end(); ++it) {
1920                         // look to the next item
1921                         It next = it;
1922                         ++next;
1923
1924                         // final?
1925                         allFinal = allFinal && it->final();
1926
1927                         LYXERR(Debug::GUI, "it = " << it->abs()
1928                                << " => " << it->displayString());
1929
1930                         // still the same segment?
1931                         QString nextString;
1932                         if ((next != paths.end()
1933                              && (nextString = next->displayString()) == segString))
1934                                 continue;
1935                         LYXERR(Debug::GUI, "segment ended");
1936
1937                         // only a trivial one with one element?
1938                         if (it == segStart) {
1939                                 // start new segment
1940                                 segStart = next;
1941                                 segString = nextString;
1942                                 continue;
1943                         }
1944
1945                         // we found a non-atomic segment segStart <= sit <= it < next.
1946                         // Shift path segments and hope for the best
1947                         // that it makes the path more unique.
1948                         somethingChanged = true;
1949                         It sit = segStart;
1950                         QString dspString = sit->forecastPathString();
1951                         LYXERR(Debug::GUI, "first forecast found for "
1952                                << sit->abs() << " => " << dspString);
1953                         ++sit;
1954                         bool moreUnique = false;
1955                         for (; sit != next; ++sit) {
1956                                 if (sit->forecastPathString() != dspString) {
1957                                         LYXERR(Debug::GUI, "different forecast found for "
1958                                                 << sit->abs() << " => " << sit->forecastPathString());
1959                                         moreUnique = true;
1960                                         break;
1961                                 }
1962                                 LYXERR(Debug::GUI, "same forecast found for "
1963                                         << sit->abs() << " => " << dspString);
1964                         }
1965
1966                         // if the path segment helped, add it. Otherwise add dots
1967                         bool dots = !moreUnique;
1968                         LYXERR(Debug::GUI, "using dots = " << dots);
1969                         for (sit = segStart; sit != next; ++sit) {
1970                                 sit->shiftPathSegment(dots);
1971                                 LYXERR(Debug::GUI, "shifting "
1972                                         << sit->abs() << " => " << sit->displayString());
1973                         }
1974
1975                         // start new segment
1976                         segStart = next;
1977                         segString = nextString;
1978                 }
1979         }
1980
1981         // set new tab titles
1982         for (It it = paths.begin(); it != paths.end(); ++it) {
1983                 int const tab_index = it->tab();
1984                 Buffer const & buf = workArea(tab_index)->bufferView().buffer();
1985                 QString tab_text = it->displayString().replace("&", "&&");
1986                 if (!buf.fileName().empty() && !buf.isClean())
1987                         tab_text += "*";
1988                 setTabText(tab_index, tab_text);
1989                 setTabToolTip(tab_index, it->abs());
1990         }
1991 }
1992
1993
1994 void TabWorkArea::showContextMenu(const QPoint & pos)
1995 {
1996         // which tab?
1997         clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1998         if (clicked_tab_ == -1)
1999                 return;
2000
2001         // show tab popup
2002         QMenu popup;
2003         popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
2004                 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
2005         popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
2006                 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
2007         popup.exec(tabBar()->mapToGlobal(pos));
2008
2009         clicked_tab_ = -1;
2010 }
2011
2012
2013 void TabWorkArea::moveTab(int fromIndex, int toIndex)
2014 {
2015         QWidget * w = widget(fromIndex);
2016         QIcon icon = tabIcon(fromIndex);
2017         QString text = tabText(fromIndex);
2018
2019         setCurrentIndex(fromIndex);
2020         removeTab(fromIndex);
2021         insertTab(toIndex, w, icon, text);
2022         setCurrentIndex(toIndex);
2023 }
2024
2025
2026 DragTabBar::DragTabBar(QWidget* parent)
2027         : QTabBar(parent)
2028 {
2029         setAcceptDrops(true);
2030         setTabsClosable(!lyxrc.single_close_tab_button);
2031 }
2032
2033
2034 void DragTabBar::mousePressEvent(QMouseEvent * event)
2035 {
2036         if (event->button() == Qt::LeftButton)
2037                 dragStartPos_ = event->pos();
2038         QTabBar::mousePressEvent(event);
2039 }
2040
2041
2042 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
2043 {
2044         // If the left button isn't pressed anymore then return
2045         if (!(event->buttons() & Qt::LeftButton))
2046                 return;
2047
2048         // If the distance is too small then return
2049         if ((event->pos() - dragStartPos_).manhattanLength()
2050             < QApplication::startDragDistance())
2051                 return;
2052
2053         // did we hit something after all?
2054         int tab = tabAt(dragStartPos_);
2055         if (tab == -1)
2056                 return;
2057
2058         // simulate button release to remove highlight from button
2059         int i = currentIndex();
2060         QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
2061                 event->button(), event->buttons(), 0);
2062         QTabBar::mouseReleaseEvent(&me);
2063         setCurrentIndex(i);
2064
2065         // initiate Drag
2066         QDrag * drag = new QDrag(this);
2067         QMimeData * mimeData = new QMimeData;
2068         // a crude way to distinguish tab-reodering drops from other ones
2069         mimeData->setData("action", "tab-reordering") ;
2070         drag->setMimeData(mimeData);
2071
2072         // get tab pixmap as cursor
2073         QRect r = tabRect(tab);
2074         QPixmap pixmap(r.size());
2075         render(&pixmap, - r.topLeft());
2076         drag->setPixmap(pixmap);
2077         drag->exec();
2078 }
2079
2080
2081 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
2082 {
2083         // Only accept if it's an tab-reordering request
2084         QMimeData const * m = event->mimeData();
2085         QStringList formats = m->formats();
2086         if (formats.contains("action")
2087             && m->data("action") == "tab-reordering")
2088                 event->acceptProposedAction();
2089 }
2090
2091
2092 void DragTabBar::dropEvent(QDropEvent * event)
2093 {
2094         int fromIndex = tabAt(dragStartPos_);
2095         int toIndex = tabAt(event->pos());
2096
2097         // Tell interested objects that
2098         if (fromIndex != toIndex)
2099                 tabMoveRequested(fromIndex, toIndex);
2100         event->acceptProposedAction();
2101 }
2102
2103
2104 } // namespace frontend
2105 } // namespace lyx
2106
2107 #include "moc_GuiWorkArea.cpp"