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