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