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