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