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