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