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