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