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