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