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