]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.cpp
reverting 25454 and fix http://bugzilla.lyx.org/show_bug.cgi?id=4758; again!
[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 const delta = ev->delta() / 120;
779         if (ev->modifiers() & Qt::ControlModifier) {
780                 lyxrc.zoom -= 5 * delta;
781                 if (lyxrc.zoom < 10)
782                         lyxrc.zoom = 10;
783                 // The global QPixmapCache is used in GuiPainter to cache text
784                 // painting so we must reset it.
785                 QPixmapCache::clear();
786                 guiApp->fontLoader().update();
787                 ev->accept();
788                 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
789                 return;
790         }
791
792         // Take into account the desktop wide settings.
793         int const lines = qApp->wheelScrollLines();
794         int const page_step = verticalScrollBar()->pageStep();
795         // Test if the wheel mouse is set to one screen at a time.
796         int scroll_value = lines > page_step
797                 ? page_step : lines * verticalScrollBar()->singleStep();
798
799         // Take into account the rotation.
800         scroll_value *= delta;
801
802         // Take into account user preference.
803         scroll_value *= lyxrc.mouse_wheel_speed;
804         LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
805                         << " delta = " << delta << " scroll_value = " << scroll_value
806                         << " page_step = " << page_step);
807         // Now scroll.
808         verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
809
810         ev->accept();
811 }
812
813
814 void GuiWorkArea::generateSyntheticMouseEvent()
815 {
816         // Set things off to generate the _next_ 'pseudo' event.
817         if (synthetic_mouse_event_.restart_timeout)
818                 synthetic_mouse_event_.timeout.start();
819
820         // Has anything changed on-screen since the last timeout signal
821         // was received?
822         double const scrollbar_value = verticalScrollBar()->value();
823         if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
824                 // Yes it has. Store the params used to check this.
825                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
826
827                 // ... and dispatch the event to the LyX core.
828                 dispatch(synthetic_mouse_event_.cmd);
829         }
830 }
831
832
833 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
834 {
835         // intercept some keys if completion popup is visible
836         if (completer_->popupVisible()) {
837                 switch (ev->key()) {
838                 case Qt::Key_Enter:
839                 case Qt::Key_Return:
840                         completer_->activate();
841                         ev->accept();
842                         return;
843                 }
844         }
845         
846         // intercept keys for the completion
847         if (ev->key() == Qt::Key_Tab) {
848                 completer_->tab();
849                 ev->accept();
850                 return;
851         } 
852
853         if (completer_->popupVisible() && ev->key() == Qt::Key_Escape) {
854                 completer_->hidePopup();
855                 ev->accept();
856                 return;
857         }
858
859         if (completer_->inlineVisible() && ev->key() == Qt::Key_Escape) {
860                 completer_->hideInline();
861                 ev->accept();
862                 return;
863         }
864
865         // do nothing if there are other events
866         // (the auto repeated events come too fast)
867         // \todo FIXME: remove hard coded Qt keys, process the key binding
868 #ifdef Q_WS_X11
869         if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat() 
870                         && (Qt::Key_PageDown || Qt::Key_PageUp)) {
871                 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
872                 ev->ignore();
873                 return;
874         }
875 #endif
876
877         LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
878                 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
879
880         KeySymbol sym;
881         setKeySymbol(&sym, ev);
882         processKeySym(sym, q_key_state(ev->modifiers()));
883         ev->accept();
884 }
885
886
887 void GuiWorkArea::doubleClickTimeout()
888 {
889         dc_event_.active = false;
890 }
891
892
893 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
894 {
895         dc_event_ = DoubleClick(ev);
896         QTimer::singleShot(QApplication::doubleClickInterval(), this,
897                            SLOT(doubleClickTimeout()));
898         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
899                         ev->x(), ev->y(),
900                         q_button_state(ev->button()));
901         dispatch(cmd);
902         ev->accept();
903 }
904
905
906 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
907 {
908         QAbstractScrollArea::resizeEvent(ev);
909         need_resize_ = true;
910         ev->accept();
911 }
912
913
914 void GuiWorkArea::update(int x, int y, int w, int h)
915 {
916         viewport()->repaint(x, y, w, h);
917 }
918
919
920 void GuiWorkArea::paintEvent(QPaintEvent * ev)
921 {
922         QRect const rc = ev->rect();
923         // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
924         //      << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
925
926         if (need_resize_) {
927                 screen_ = QPixmap(viewport()->width(), viewport()->height());
928                 resizeBufferView();
929                 hideCursor();
930                 showCursor();
931         }
932
933         QPainter pain(viewport());
934         pain.drawPixmap(rc, screen_, rc);
935         cursor_->draw(pain);
936         ev->accept();
937 }
938
939
940 void GuiWorkArea::updateScreen()
941 {
942         GuiPainter pain(&screen_);
943         buffer_view_->draw(pain);
944 }
945
946
947 void GuiWorkArea::showCursor(int x, int y, int h,
948         bool l_shape, bool rtl, bool completable)
949 {
950         if (schedule_redraw_) {
951                 // This happens when a graphic conversion is finished. As we don't know
952                 // the size of the new graphics, it's better the update everything.
953                 // We can't use redraw() here because this would trigger a infinite
954                 // recursive loop with showCursor().
955                 buffer_view_->resize(viewport()->width(), viewport()->height());
956                 updateScreen();
957                 updateScrollbar();
958                 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
959                 schedule_redraw_ = false;
960                 // Show the cursor immediately after the update.
961                 hideCursor();
962                 toggleCursor();
963                 return;
964         }
965
966         cursor_->update(x, y, h, l_shape, rtl, completable);
967         cursor_->show();
968         viewport()->update(cursor_->rect());
969 }
970
971
972 void GuiWorkArea::removeCursor()
973 {
974         cursor_->hide();
975         //if (!qApp->focusWidget())
976                 viewport()->update(cursor_->rect());
977 }
978
979
980 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
981 {
982         QString const & commit_string = e->commitString();
983         docstring const & preedit_string
984                 = qstring_to_ucs4(e->preeditString());
985
986         if (!commit_string.isEmpty()) {
987
988                 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
989                         << " commitString: " << e->commitString());
990
991                 int key = 0;
992
993                 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
994                 for (int i = 0; i != commit_string.size(); ++i) {
995                         QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
996                         keyPressEvent(&ev);
997                 }
998         }
999
1000         // Hide the cursor during the kana-kanji transformation.
1001         if (preedit_string.empty())
1002                 startBlinkingCursor();
1003         else
1004                 stopBlinkingCursor();
1005
1006         // last_width : for checking if last preedit string was/wasn't empty.
1007         static bool last_width = false;
1008         if (!last_width && preedit_string.empty()) {
1009                 // if last_width is last length of preedit string.
1010                 e->accept();
1011                 return;
1012         }
1013
1014         GuiPainter pain(&screen_);
1015         buffer_view_->updateMetrics();
1016         buffer_view_->draw(pain);
1017         FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1018         FontMetrics const & fm = theFontMetrics(font);
1019         int height = fm.maxHeight();
1020         int cur_x = cursor_->rect().left();
1021         int cur_y = cursor_->rect().bottom();
1022
1023         // redraw area of preedit string.
1024         update(0, cur_y - height, viewport()->width(),
1025                 (height + 1) * preedit_lines_);
1026
1027         if (preedit_string.empty()) {
1028                 last_width = false;
1029                 preedit_lines_ = 1;
1030                 e->accept();
1031                 return;
1032         }
1033         last_width = true;
1034
1035         // att : stores an IM attribute.
1036         QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1037
1038         // get attributes of input method cursor.
1039         // cursor_pos : cursor position in preedit string.
1040         size_t cursor_pos = 0;
1041         bool cursor_is_visible = false;
1042         for (int i = 0; i != att.size(); ++i) {
1043                 if (att.at(i).type == QInputMethodEvent::Cursor) {
1044                         cursor_pos = att.at(i).start;
1045                         cursor_is_visible = att.at(i).length != 0;
1046                         break;
1047                 }
1048         }
1049
1050         size_t preedit_length = preedit_string.length();
1051
1052         // get position of selection in input method.
1053         // FIXME: isn't there a way to do this simplier?
1054         // rStart : cursor position in selected string in IM.
1055         size_t rStart = 0;
1056         // rLength : selected string length in IM.
1057         size_t rLength = 0;
1058         if (cursor_pos < preedit_length) {
1059                 for (int i = 0; i != att.size(); ++i) {
1060                         if (att.at(i).type == QInputMethodEvent::TextFormat) {
1061                                 if (att.at(i).start <= int(cursor_pos)
1062                                         && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1063                                                 rStart = att.at(i).start;
1064                                                 rLength = att.at(i).length;
1065                                                 if (!cursor_is_visible)
1066                                                         cursor_pos += rLength;
1067                                                 break;
1068                                 }
1069                         }
1070                 }
1071         }
1072         else {
1073                 rStart = cursor_pos;
1074                 rLength = 0;
1075         }
1076
1077         int const right_margin = buffer_view_->rightMargin();
1078         Painter::preedit_style ps;
1079         // Most often there would be only one line:
1080         preedit_lines_ = 1;
1081         for (size_t pos = 0; pos != preedit_length; ++pos) {
1082                 char_type const typed_char = preedit_string[pos];
1083                 // reset preedit string style
1084                 ps = Painter::preedit_default;
1085
1086                 // if we reached the right extremity of the screen, go to next line.
1087                 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1088                         cur_x = right_margin;
1089                         cur_y += height + 1;
1090                         ++preedit_lines_;
1091                 }
1092                 // preedit strings are displayed with dashed underline
1093                 // and partial strings are displayed white on black indicating
1094                 // that we are in selecting mode in the input method.
1095                 // FIXME: rLength == preedit_length is not a changing condition
1096                 // FIXME: should be put out of the loop.
1097                 if (pos >= rStart
1098                         && pos < rStart + rLength
1099                         && !(cursor_pos < rLength && rLength == preedit_length))
1100                         ps = Painter::preedit_selecting;
1101
1102                 if (pos == cursor_pos
1103                         && (cursor_pos < rLength && rLength == preedit_length))
1104                         ps = Painter::preedit_cursor;
1105
1106                 // draw one character and update cur_x.
1107                 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1108         }
1109
1110         // update the preedit string screen area.
1111         update(0, cur_y - preedit_lines_*height, viewport()->width(),
1112                 (height + 1) * preedit_lines_);
1113
1114         // Don't forget to accept the event!
1115         e->accept();
1116 }
1117
1118
1119 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1120 {
1121         QRect cur_r(0,0,0,0);
1122         switch (query) {
1123                 // this is the CJK-specific composition window position.
1124                 case Qt::ImMicroFocus:
1125                         cur_r = cursor_->rect();
1126                         if (preedit_lines_ != 1)
1127                                 cur_r.moveLeft(10);
1128                         cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1129                         // return lower right of cursor in LyX.
1130                         return cur_r;
1131                 default:
1132                         return QWidget::inputMethodQuery(query);
1133         }
1134 }
1135
1136
1137 void GuiWorkArea::updateWindowTitle()
1138 {
1139         docstring maximize_title;
1140         docstring minimize_title;
1141
1142         Buffer & buf = buffer_view_->buffer();
1143         FileName const fileName = buf.fileName();
1144         if (!fileName.empty()) {
1145                 maximize_title = fileName.displayName(30);
1146                 minimize_title = from_utf8(fileName.onlyFileName());
1147                 if (!buf.isClean()) {
1148                         maximize_title += _(" (changed)");
1149                         minimize_title += char_type('*');
1150                 }
1151                 if (buf.isReadonly())
1152                         maximize_title += _(" (read only)");
1153         }
1154
1155         QString title = windowTitle();
1156         QString new_title = toqstr(maximize_title);
1157         if (title == new_title)
1158                 return;
1159
1160         QWidget::setWindowTitle(new_title);
1161         QWidget::setWindowIconText(toqstr(minimize_title));
1162         titleChanged(this);
1163 }
1164
1165
1166 void GuiWorkArea::setReadOnly(bool)
1167 {
1168         updateWindowTitle();
1169         if (this == lyx_view_->currentWorkArea())
1170                 lyx_view_->updateDialogs();
1171 }
1172
1173
1174 bool GuiWorkArea::isFullScreen()
1175 {
1176         return lyx_view_ && lyx_view_->isFullScreen();
1177 }
1178
1179
1180 ////////////////////////////////////////////////////////////////////
1181 //
1182 // TabWorkArea 
1183 //
1184 ////////////////////////////////////////////////////////////////////
1185
1186 #ifdef Q_WS_MACX
1187 class NoTabFrameMacStyle : public QMacStyle {
1188 public:
1189         ///
1190         QRect subElementRect(SubElement element, const QStyleOption * option,
1191                              const QWidget * widget = 0) const
1192         {
1193                 QRect rect = QMacStyle::subElementRect(element, option, widget);
1194                 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1195                 
1196                 // The Qt Mac style puts the contents into a 3 pixel wide box
1197                 // which looks very ugly and not like other Mac applications.
1198                 // Hence we remove this here, and moreover the 16 pixel round
1199                 // frame above if the tab bar is hidden.
1200                 if (element == QStyle::SE_TabWidgetTabContents) {
1201                         rect.adjust(- rect.left(), 0, rect.left(), 0);
1202                         if (noBar)
1203                                 rect.setTop(0);
1204                 }
1205
1206                 return rect;
1207         }
1208 };
1209
1210 NoTabFrameMacStyle noTabFrameMacStyle;
1211 #endif
1212
1213
1214 TabWorkArea::TabWorkArea(QWidget * parent)
1215         : QTabWidget(parent), clicked_tab_(-1)
1216 {
1217 #ifdef Q_WS_MACX
1218         setStyle(&noTabFrameMacStyle);
1219 #endif
1220
1221         QPalette pal = palette();
1222         pal.setColor(QPalette::Active, QPalette::Button,
1223                 pal.color(QPalette::Active, QPalette::Window));
1224         pal.setColor(QPalette::Disabled, QPalette::Button,
1225                 pal.color(QPalette::Disabled, QPalette::Window));
1226         pal.setColor(QPalette::Inactive, QPalette::Button,
1227                 pal.color(QPalette::Inactive, QPalette::Window));
1228
1229         QObject::connect(this, SIGNAL(currentChanged(int)),
1230                 this, SLOT(on_currentTabChanged(int)));
1231
1232         QToolButton * closeBufferButton = new QToolButton(this);
1233         closeBufferButton->setPalette(pal);
1234         // FIXME: rename the icon to closebuffer.png
1235         closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1236         closeBufferButton->setText("Close File");
1237         closeBufferButton->setAutoRaise(true);
1238         closeBufferButton->setCursor(Qt::ArrowCursor);
1239         closeBufferButton->setToolTip(qt_("Close File"));
1240         closeBufferButton->setEnabled(true);
1241         QObject::connect(closeBufferButton, SIGNAL(clicked()),
1242                 this, SLOT(closeCurrentBuffer()));
1243         setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1244         
1245         // setup drag'n'drop
1246         QTabBar* tb = new DragTabBar;
1247         connect(tb, SIGNAL(tabMoveRequested(int, int)),
1248                 this, SLOT(moveTab(int, int)));
1249         tb->setElideMode(Qt::ElideNone);
1250         setTabBar(tb);
1251
1252         // make us responsible for the context menu of the tabbar
1253         tb->setContextMenuPolicy(Qt::CustomContextMenu);
1254         connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1255                 this, SLOT(showContextMenu(const QPoint &)));
1256         
1257         setUsesScrollButtons(true);
1258 }
1259
1260
1261 void TabWorkArea::setFullScreen(bool full_screen)
1262 {
1263         for (int i = 0; i != count(); ++i) {
1264                 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1265                         wa->setFullScreen(full_screen);
1266         }
1267
1268         if (lyxrc.full_screen_tabbar)
1269                 showBar(!full_screen && count()>1);
1270 }
1271
1272
1273 void TabWorkArea::showBar(bool show)
1274 {
1275         tabBar()->setEnabled(show);
1276         tabBar()->setVisible(show);
1277 }
1278
1279
1280 GuiWorkArea * TabWorkArea::currentWorkArea()
1281 {
1282         if (count() == 0)
1283                 return 0;
1284
1285         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget()); 
1286         LASSERT(wa, /**/);
1287         return wa;
1288 }
1289
1290
1291 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1292 {
1293         for (int i = 0; i != count(); ++i) {
1294                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1295                 LASSERT(wa, return 0);
1296                 if (&wa->bufferView().buffer() == &buffer)
1297                         return wa;
1298         }
1299         return 0;
1300 }
1301
1302
1303 void TabWorkArea::closeAll()
1304 {
1305         while (count()) {
1306                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1307                 LASSERT(wa, /**/);
1308                 removeTab(0);
1309                 delete wa;
1310         }
1311 }
1312
1313
1314 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1315 {
1316         LASSERT(work_area, /**/);
1317         int index = indexOf(work_area);
1318         if (index == -1)
1319                 return false;
1320
1321         if (index == currentIndex())
1322                 // Make sure the work area is up to date.
1323                 on_currentTabChanged(index);
1324         else
1325                 // Switch to the work area.
1326                 setCurrentIndex(index);
1327         work_area->setFocus();
1328
1329         return true;
1330 }
1331
1332
1333 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1334 {
1335         GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1336         wa->setUpdatesEnabled(false);
1337         // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1338         // when hiding it again below).
1339         if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1340                 showBar(count() > 0);
1341         addTab(wa, wa->windowTitle());
1342         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1343                 this, SLOT(updateTabTexts()));
1344         if (currentWorkArea() && currentWorkArea()->isFullScreen())
1345                 setFullScreen(true);
1346         else
1347                 // Hide tabbar if there's only one tab.
1348                 showBar(count() > 1);
1349
1350         updateTabTexts();
1351         
1352         return wa;
1353 }
1354
1355
1356 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1357 {
1358         LASSERT(work_area, return false);
1359         int index = indexOf(work_area);
1360         if (index == -1)
1361                 return false;
1362
1363         work_area->setUpdatesEnabled(false);
1364         removeTab(index);
1365         delete work_area;
1366
1367         if (count()) {
1368                 // make sure the next work area is enabled.
1369                 currentWidget()->setUpdatesEnabled(true);
1370                 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1371                         setFullScreen(true);
1372                 else
1373                         // Hide tabbar if there's only one tab.
1374                         showBar(count() > 1);
1375         } else {
1376                 lastWorkAreaRemoved();
1377         }
1378
1379         updateTabTexts();
1380
1381         return true;
1382 }
1383
1384
1385 void TabWorkArea::on_currentTabChanged(int i)
1386 {
1387         // returns e.g. on application destruction
1388         if (i == -1)
1389                 return;
1390         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1391         LASSERT(wa, return);
1392         BufferView & bv = wa->bufferView();
1393         bv.cursor().fixIfBroken();
1394         bv.updateMetrics();
1395         wa->setUpdatesEnabled(true);
1396         wa->redraw();
1397         wa->setFocus();
1398         ///
1399         currentWorkAreaChanged(wa);
1400
1401         LYXERR(Debug::GUI, "currentTabChanged " << i
1402                 << "File" << bv.buffer().absFileName());
1403 }
1404
1405
1406 void TabWorkArea::closeCurrentBuffer()
1407 {
1408         if (clicked_tab_ != -1)
1409                 setCurrentIndex(clicked_tab_);
1410
1411         lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1412 }
1413
1414
1415 void TabWorkArea::closeCurrentTab()
1416 {
1417         if (clicked_tab_ == -1)
1418                 removeWorkArea(currentWorkArea());
1419         else {
1420                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_)); 
1421                 LASSERT(wa, /**/);
1422                 removeWorkArea(wa);
1423         }
1424 }
1425
1426 ///
1427 class DisplayPath {
1428 public:
1429         /// make vector happy
1430         DisplayPath() {}
1431         ///
1432         DisplayPath(int tab, FileName const & filename)
1433                 : tab_(tab)
1434         {
1435                 filename_ = toqstr(filename.onlyFileNameWithoutExt());
1436                 postfix_ = toqstr(filename.absoluteFilePath()).
1437                         split("/", QString::SkipEmptyParts);
1438                 postfix_.pop_back();
1439                 abs_ = toqstr(filename.absoluteFilePath());
1440                 dottedPrefix_ = false;
1441         }
1442         
1443         /// Absolute path for debugging.
1444         QString abs() const
1445         {
1446                 return abs_;
1447         }
1448         /// Add the first segment from the postfix or three dots to the prefix.
1449         /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1450         /// when really needed.
1451         void shiftPathSegment(bool dotted)
1452         {
1453                 if (postfix_.count() <= 0)
1454                         return;
1455
1456                 if (!dotted) {
1457                         if (dottedPrefix_ && !prefix_.isEmpty())
1458                                 prefix_ += ".../";
1459                         prefix_ += postfix_.front() + "/";
1460                 }
1461                 dottedPrefix_ = dotted && !prefix_.isEmpty();
1462                 postfix_.pop_front();
1463         }
1464         ///
1465         QString displayString() const
1466         {
1467                 if (prefix_.isEmpty())
1468                         return filename_;
1469
1470                 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1471                 return prefix_ + (dots ? ".../" : "") + filename_;
1472         }
1473         ///
1474         QString forecastPathString() const
1475         {
1476                 if (postfix_.count() == 0)
1477                         return displayString();
1478                 
1479                 return prefix_
1480                         + (dottedPrefix_ ? ".../" : "")
1481                         + postfix_.front() + "/";
1482         }
1483         ///
1484         bool final() const { return postfix_.empty(); }
1485         ///
1486         int tab() const { return tab_; }
1487         
1488 private:
1489         ///
1490         QString prefix_;
1491         ///
1492         QStringList postfix_;
1493         ///
1494         QString filename_;
1495         ///
1496         QString abs_;
1497         ///
1498         int tab_;
1499         ///
1500         bool dottedPrefix_;
1501 };
1502
1503
1504 ///
1505 bool operator<(DisplayPath const & a, DisplayPath const & b)
1506 {
1507         return a.displayString() < b.displayString();
1508 }
1509
1510 ///
1511 bool operator==(DisplayPath const & a, DisplayPath const & b)
1512 {
1513         return a.displayString() == b.displayString();
1514 }
1515
1516
1517 void TabWorkArea::updateTabTexts()
1518 {
1519         size_t n = count();
1520         if (n == 0)
1521                 return;
1522         std::list<DisplayPath> paths;
1523         typedef std::list<DisplayPath>::iterator It;
1524         
1525         // collect full names first: path into postfix, empty prefix and 
1526         // filename without extension
1527         for (size_t i = 0; i < n; ++i) {
1528                 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(i)); 
1529                 FileName const fn = i_wa->bufferView().buffer().fileName();
1530                 paths.push_back(DisplayPath(i, fn));
1531         }
1532         
1533         // go through path segments and see if it helps to make the path more unique
1534         bool somethingChanged = true;
1535         bool allFinal = false;
1536         while (somethingChanged && !allFinal) {
1537                 // adding path segments changes order
1538                 paths.sort();
1539                 
1540                 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1541                 somethingChanged = false;
1542                 allFinal = true;
1543                 
1544                 // find segments which are not unique (i.e. non-atomic)
1545                 It it = paths.begin();
1546                 It segStart = it;
1547                 QString segString = it->displayString();
1548                 for (; it != paths.end(); ++it) {
1549                         // look to the next item
1550                         It next = it;
1551                         ++next;
1552                         
1553                         // final?
1554                         allFinal = allFinal && it->final();
1555                         
1556                         LYXERR(Debug::GUI, "it = " << it->abs()
1557                                << " => " << it->displayString());
1558                         
1559                         // still the same segment?
1560                         QString nextString;
1561                         if ((next != paths.end()
1562                              && (nextString = next->displayString()) == segString))
1563                                 continue;
1564                         LYXERR(Debug::GUI, "segment ended");
1565                         
1566                         // only a trivial one with one element?
1567                         if (it == segStart) {
1568                                 // start new segment
1569                                 segStart = next;
1570                                 segString = nextString;
1571                                 continue;
1572                         }
1573                         
1574                         // we found a non-atomic segment segStart <= sit <= it < next.
1575                         // Shift path segments and hope for the best
1576                         // that it makes the path more unique.
1577                         somethingChanged = true;
1578                         It sit = segStart;
1579                         QString dspString = sit->forecastPathString();
1580                         LYXERR(Debug::GUI, "first forecast found for "
1581                                << sit->abs() << " => " << dspString);
1582                         ++sit;
1583                         bool moreUnique = false;
1584                         for (; sit != next; ++sit) {
1585                                 if (sit->forecastPathString() != dspString) {
1586                                         LYXERR(Debug::GUI, "different forecast found for "
1587                                                 << sit->abs() << " => " << sit->forecastPathString());
1588                                         moreUnique = true;
1589                                         break;
1590                                 }
1591                                 LYXERR(Debug::GUI, "same forecast found for "
1592                                         << sit->abs() << " => " << dspString);
1593                         }
1594                         
1595                         // if the path segment helped, add it. Otherwise add dots
1596                         bool dots = !moreUnique;
1597                         LYXERR(Debug::GUI, "using dots = " << dots);
1598                         for (sit = segStart; sit != next; ++sit) {
1599                                 sit->shiftPathSegment(dots);
1600                                 LYXERR(Debug::GUI, "shifting "
1601                                         << sit->abs() << " => " << sit->displayString());
1602                         }
1603
1604                         // start new segment
1605                         segStart = next;
1606                         segString = nextString;
1607                 }
1608         }
1609         
1610         // set new tab titles
1611         for (It it = paths.begin(); it != paths.end(); ++it) {
1612                 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(it->tab())); 
1613                 Buffer & buf = i_wa->bufferView().buffer();
1614                 if (!buf.fileName().empty() && !buf.isClean())
1615                         setTabText(it->tab(), it->displayString() + "*");
1616                 else
1617                         setTabText(it->tab(), it->displayString());
1618         }
1619 }
1620
1621
1622 void TabWorkArea::showContextMenu(const QPoint & pos)
1623 {
1624         // which tab?
1625         clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1626         if (clicked_tab_ == -1)
1627                 return;
1628         
1629         // show tab popup
1630         QMenu popup;
1631         popup.addAction(QIcon(":/images/hidetab.png"),
1632                 qt_("Hide tab"), this, SLOT(closeCurrentTab()));
1633         popup.addAction(QIcon(":/images/closetab.png"),
1634                 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1635         popup.exec(tabBar()->mapToGlobal(pos));
1636
1637         clicked_tab_ = -1;
1638 }
1639
1640
1641 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1642 {
1643         QWidget * w = widget(fromIndex);
1644         QIcon icon = tabIcon(fromIndex);
1645         QString text = tabText(fromIndex);
1646
1647         setCurrentIndex(fromIndex);
1648         removeTab(fromIndex);
1649         insertTab(toIndex, w, icon, text);
1650         setCurrentIndex(toIndex);
1651 }
1652         
1653
1654 DragTabBar::DragTabBar(QWidget* parent)
1655         : QTabBar(parent)
1656 {
1657         setAcceptDrops(true);
1658 }
1659
1660
1661 #if QT_VERSION < 0x040300
1662 int DragTabBar::tabAt(QPoint const & position) const
1663 {
1664         const int max = count();
1665         for (int i = 0; i < max; ++i) {
1666                 if (tabRect(i).contains(position))
1667                         return i;
1668         }
1669         return -1;
1670 }
1671 #endif
1672
1673
1674 void DragTabBar::mousePressEvent(QMouseEvent * event)
1675 {
1676         if (event->button() == Qt::LeftButton)
1677                 dragStartPos_ = event->pos();
1678         QTabBar::mousePressEvent(event);
1679 }
1680
1681
1682 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1683 {
1684         // If the left button isn't pressed anymore then return
1685         if (!(event->buttons() & Qt::LeftButton))
1686                 return;
1687         
1688         // If the distance is too small then return
1689         if ((event->pos() - dragStartPos_).manhattanLength()
1690             < QApplication::startDragDistance())
1691                 return;
1692
1693         // did we hit something after all?
1694         int tab = tabAt(dragStartPos_);
1695         if (tab == -1)
1696                 return;
1697         
1698         // simulate button release to remove highlight from button
1699         int i = currentIndex();
1700         QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1701                 event->button(), event->buttons(), 0);
1702         QTabBar::mouseReleaseEvent(&me);
1703         setCurrentIndex(i);
1704         
1705         // initiate Drag
1706         QDrag * drag = new QDrag(this);
1707         QMimeData * mimeData = new QMimeData;
1708         // a crude way to distinguish tab-reodering drops from other ones
1709         mimeData->setData("action", "tab-reordering") ;
1710         drag->setMimeData(mimeData);
1711         
1712 #if QT_VERSION >= 0x040300
1713         // get tab pixmap as cursor
1714         QRect r = tabRect(tab);
1715         QPixmap pixmap(r.size());
1716         render(&pixmap, - r.topLeft());
1717         drag->setPixmap(pixmap);
1718         drag->exec();
1719 #else
1720         drag->start(Qt::MoveAction);
1721 #endif
1722         
1723 }
1724
1725
1726 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1727 {
1728         // Only accept if it's an tab-reordering request
1729         QMimeData const * m = event->mimeData();
1730         QStringList formats = m->formats();
1731         if (formats.contains("action") 
1732             && m->data("action") == "tab-reordering")
1733                 event->acceptProposedAction();
1734 }
1735
1736
1737 void DragTabBar::dropEvent(QDropEvent * event)
1738 {
1739         int fromIndex = tabAt(dragStartPos_);
1740         int toIndex = tabAt(event->pos());
1741         
1742         // Tell interested objects that 
1743         if (fromIndex != toIndex)
1744                 tabMoveRequested(fromIndex, toIndex);
1745         event->acceptProposedAction();
1746 }
1747
1748
1749 } // namespace frontend
1750 } // namespace lyx
1751
1752 #include "GuiWorkArea_moc.cpp"