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