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