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