]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.cpp
Remove black box around GuiWorkarea? which is visible with Qt4.5.
[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         setFrameStyle(QFrame::NoFrame);
367         if (full_screen) {
368                 setFrameStyle(QFrame::NoFrame);
369                 if (lyxrc.full_screen_scrollbar)
370                         setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
371         } else
372                 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
373 }
374
375
376 BufferView & GuiWorkArea::bufferView()
377 {
378         return *buffer_view_;
379 }
380
381
382 BufferView const & GuiWorkArea::bufferView() const
383 {
384         return *buffer_view_;
385 }
386
387
388 void GuiWorkArea::stopBlinkingCursor()
389 {
390         cursor_timeout_.stop();
391         hideCursor();
392 }
393
394
395 void GuiWorkArea::startBlinkingCursor()
396 {
397         showCursor();
398         //we're not supposed to cache this value.
399         int const time = QApplication::cursorFlashTime() / 2;
400         if (time <= 0)
401                 return;
402         cursor_timeout_.setInterval(time);
403         cursor_timeout_.start();
404 }
405
406
407 void GuiWorkArea::redraw()
408 {
409         if (!isVisible())
410                 // No need to redraw in this case.
411                 return;
412
413         // No need to do anything if this is the current view. The BufferView
414         // metrics are already up to date.
415         if (lyx_view_ != guiApp->currentView()
416                 || lyx_view_->currentWorkArea() != this) {
417                 // FIXME: it would be nice to optimize for the off-screen case.
418                 buffer_view_->updateMetrics();
419                 buffer_view_->cursor().fixIfBroken();
420         }
421
422         // update cursor position, because otherwise it has to wait until
423         // the blinking interval is over
424         if (cursor_visible_) {
425                 hideCursor();
426                 showCursor();
427         }
428
429         LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
430         updateScreen();
431         update(0, 0, viewport()->width(), viewport()->height());
432
433         /// \warning: scrollbar updating *must* be done after the BufferView is drawn
434         /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
435         updateScrollbar();
436         lyx_view_->updateStatusBar();
437
438         if (lyxerr.debugging(Debug::WORKAREA))
439                 buffer_view_->coordCache().dump();
440 }
441
442
443 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
444 {
445         if (lyx_view_->isFullScreen() && lyx_view_->menuBar()->isVisible()
446                 && lyxrc.full_screen_menubar) {
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         if (e->x() == synthetic_mouse_event_.x_old
790                 && e->y() == synthetic_mouse_event_.y_old
791                 && synthetic_mouse_event_.min_scrollbar_old == verticalScrollBar()->minimum()
792                 && synthetic_mouse_event_.max_scrollbar_old == verticalScrollBar()->maximum()) {
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_.min_scrollbar_old = verticalScrollBar()->minimum();
801         synthetic_mouse_event_.max_scrollbar_old = verticalScrollBar()->maximum();
802
803         // ... and dispatch the event to the LyX core.
804         dispatch(cmd);
805 }
806
807
808 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
809 {
810         // Wheel rotation by one notch results in a delta() of 120 (see
811         // documentation of QWheelEvent)
812         int const delta = ev->delta() / 120;
813         if (ev->modifiers() & Qt::ControlModifier) {
814                 docstring arg = convert<docstring>(5 * delta);
815                 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
816                 return;
817         }
818
819         // Take into account the desktop wide settings.
820         int const lines = qApp->wheelScrollLines();
821         int const page_step = verticalScrollBar()->pageStep();
822         // Test if the wheel mouse is set to one screen at a time.
823         int scroll_value = lines > page_step
824                 ? page_step : lines * verticalScrollBar()->singleStep();
825
826         // Take into account the rotation.
827         scroll_value *= delta;
828
829         // Take into account user preference.
830         scroll_value *= lyxrc.mouse_wheel_speed;
831         LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
832                         << " delta = " << delta << " scroll_value = " << scroll_value
833                         << " page_step = " << page_step);
834         // Now scroll.
835         verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
836
837         ev->accept();
838 }
839
840
841 void GuiWorkArea::generateSyntheticMouseEvent()
842 {
843         // Set things off to generate the _next_ 'pseudo' event.
844         if (synthetic_mouse_event_.restart_timeout)
845                 synthetic_mouse_event_.timeout.start();
846
847         // Has anything changed on-screen since the last timeout signal
848         // was received?
849         int const min_scrollbar = verticalScrollBar()->minimum();
850         int const max_scrollbar = verticalScrollBar()->maximum();
851         if (min_scrollbar == synthetic_mouse_event_.min_scrollbar_old
852                 && max_scrollbar == synthetic_mouse_event_.max_scrollbar_old) {
853                 return;
854         }
855         // Yes it has. Store the params used to check this.
856         synthetic_mouse_event_.min_scrollbar_old = min_scrollbar;
857         synthetic_mouse_event_.max_scrollbar_old = max_scrollbar;
858         // ... and dispatch the event to the LyX core.
859         dispatch(synthetic_mouse_event_.cmd);
860 }
861
862
863 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
864 {
865         // Do not process here some keys if dialog_mode_ is set
866         if (dialog_mode_
867                 && (ev->modifiers() == Qt::NoModifier
868                     || ev->modifiers() == Qt::ShiftModifier)
869                 && (ev->key() == Qt::Key_Escape
870                     || ev->key() == Qt::Key_Enter
871                     || ev->key() == Qt::Key_Return)
872             ) {
873                 ev->ignore();
874                 return;
875         }
876
877         // intercept some keys if completion popup is visible
878         if (completer_->popupVisible()) {
879                 switch (ev->key()) {
880                 case Qt::Key_Enter:
881                 case Qt::Key_Return:
882                         completer_->activate();
883                         ev->accept();
884                         return;
885                 }
886         }
887
888         // do nothing if there are other events
889         // (the auto repeated events come too fast)
890         // \todo FIXME: remove hard coded Qt keys, process the key binding
891 #ifdef Q_WS_X11
892         if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
893                         && (Qt::Key_PageDown || Qt::Key_PageUp)) {
894                 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
895                 ev->ignore();
896                 return;
897         }
898 #endif
899
900         LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
901                 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
902
903         KeySymbol sym;
904         setKeySymbol(&sym, ev);
905         processKeySym(sym, q_key_state(ev->modifiers()));
906         ev->accept();
907 }
908
909
910 void GuiWorkArea::doubleClickTimeout()
911 {
912         dc_event_.active = false;
913 }
914
915
916 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
917 {
918         dc_event_ = DoubleClick(ev);
919         QTimer::singleShot(QApplication::doubleClickInterval(), this,
920                            SLOT(doubleClickTimeout()));
921         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
922                         ev->x(), ev->y(),
923                         q_button_state(ev->button()));
924         dispatch(cmd);
925         ev->accept();
926 }
927
928
929 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
930 {
931         QAbstractScrollArea::resizeEvent(ev);
932         need_resize_ = true;
933         ev->accept();
934 }
935
936
937 void GuiWorkArea::update(int x, int y, int w, int h)
938 {
939         viewport()->repaint(x, y, w, h);
940 }
941
942
943 void GuiWorkArea::paintEvent(QPaintEvent * ev)
944 {
945         QRect const rc = ev->rect();
946         // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
947         //      << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
948
949         if (need_resize_) {
950                 screen_ = QPixmap(viewport()->width(), viewport()->height());
951                 resizeBufferView();
952                 hideCursor();
953                 showCursor();
954         }
955
956         QPainter pain(viewport());
957         pain.drawPixmap(rc, screen_, rc);
958         cursor_->draw(pain);
959         ev->accept();
960 }
961
962
963 void GuiWorkArea::updateScreen()
964 {
965         GuiPainter pain(&screen_);
966         buffer_view_->draw(pain);
967 }
968
969
970 void GuiWorkArea::showCursor(int x, int y, int h,
971         bool l_shape, bool rtl, bool completable)
972 {
973         if (schedule_redraw_) {
974                 // This happens when a graphic conversion is finished. As we don't know
975                 // the size of the new graphics, it's better the update everything.
976                 // We can't use redraw() here because this would trigger a infinite
977                 // recursive loop with showCursor().
978                 buffer_view_->resize(viewport()->width(), viewport()->height());
979                 updateScreen();
980                 updateScrollbar();
981                 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
982                 schedule_redraw_ = false;
983                 // Show the cursor immediately after the update.
984                 hideCursor();
985                 toggleCursor();
986                 return;
987         }
988
989         cursor_->update(x, y, h, l_shape, rtl, completable);
990         cursor_->show();
991         viewport()->update(cursor_->rect());
992 }
993
994
995 void GuiWorkArea::removeCursor()
996 {
997         cursor_->hide();
998         //if (!qApp->focusWidget())
999                 viewport()->update(cursor_->rect());
1000 }
1001
1002
1003 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1004 {
1005         QString const & commit_string = e->commitString();
1006         docstring const & preedit_string
1007                 = qstring_to_ucs4(e->preeditString());
1008
1009         if (!commit_string.isEmpty()) {
1010
1011                 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1012                         << " commitString: " << e->commitString());
1013
1014                 int key = 0;
1015
1016                 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1017                 for (int i = 0; i != commit_string.size(); ++i) {
1018                         QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1019                         keyPressEvent(&ev);
1020                 }
1021         }
1022
1023         // Hide the cursor during the kana-kanji transformation.
1024         if (preedit_string.empty())
1025                 startBlinkingCursor();
1026         else
1027                 stopBlinkingCursor();
1028
1029         // last_width : for checking if last preedit string was/wasn't empty.
1030         static bool last_width = false;
1031         if (!last_width && preedit_string.empty()) {
1032                 // if last_width is last length of preedit string.
1033                 e->accept();
1034                 return;
1035         }
1036
1037         GuiPainter pain(&screen_);
1038         buffer_view_->updateMetrics();
1039         buffer_view_->draw(pain);
1040         FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1041         FontMetrics const & fm = theFontMetrics(font);
1042         int height = fm.maxHeight();
1043         int cur_x = cursor_->rect().left();
1044         int cur_y = cursor_->rect().bottom();
1045
1046         // redraw area of preedit string.
1047         update(0, cur_y - height, viewport()->width(),
1048                 (height + 1) * preedit_lines_);
1049
1050         if (preedit_string.empty()) {
1051                 last_width = false;
1052                 preedit_lines_ = 1;
1053                 e->accept();
1054                 return;
1055         }
1056         last_width = true;
1057
1058         // att : stores an IM attribute.
1059         QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1060
1061         // get attributes of input method cursor.
1062         // cursor_pos : cursor position in preedit string.
1063         size_t cursor_pos = 0;
1064         bool cursor_is_visible = false;
1065         for (int i = 0; i != att.size(); ++i) {
1066                 if (att.at(i).type == QInputMethodEvent::Cursor) {
1067                         cursor_pos = att.at(i).start;
1068                         cursor_is_visible = att.at(i).length != 0;
1069                         break;
1070                 }
1071         }
1072
1073         size_t preedit_length = preedit_string.length();
1074
1075         // get position of selection in input method.
1076         // FIXME: isn't there a way to do this simplier?
1077         // rStart : cursor position in selected string in IM.
1078         size_t rStart = 0;
1079         // rLength : selected string length in IM.
1080         size_t rLength = 0;
1081         if (cursor_pos < preedit_length) {
1082                 for (int i = 0; i != att.size(); ++i) {
1083                         if (att.at(i).type == QInputMethodEvent::TextFormat) {
1084                                 if (att.at(i).start <= int(cursor_pos)
1085                                         && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1086                                                 rStart = att.at(i).start;
1087                                                 rLength = att.at(i).length;
1088                                                 if (!cursor_is_visible)
1089                                                         cursor_pos += rLength;
1090                                                 break;
1091                                 }
1092                         }
1093                 }
1094         }
1095         else {
1096                 rStart = cursor_pos;
1097                 rLength = 0;
1098         }
1099
1100         int const right_margin = buffer_view_->rightMargin();
1101         Painter::preedit_style ps;
1102         // Most often there would be only one line:
1103         preedit_lines_ = 1;
1104         for (size_t pos = 0; pos != preedit_length; ++pos) {
1105                 char_type const typed_char = preedit_string[pos];
1106                 // reset preedit string style
1107                 ps = Painter::preedit_default;
1108
1109                 // if we reached the right extremity of the screen, go to next line.
1110                 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1111                         cur_x = right_margin;
1112                         cur_y += height + 1;
1113                         ++preedit_lines_;
1114                 }
1115                 // preedit strings are displayed with dashed underline
1116                 // and partial strings are displayed white on black indicating
1117                 // that we are in selecting mode in the input method.
1118                 // FIXME: rLength == preedit_length is not a changing condition
1119                 // FIXME: should be put out of the loop.
1120                 if (pos >= rStart
1121                         && pos < rStart + rLength
1122                         && !(cursor_pos < rLength && rLength == preedit_length))
1123                         ps = Painter::preedit_selecting;
1124
1125                 if (pos == cursor_pos
1126                         && (cursor_pos < rLength && rLength == preedit_length))
1127                         ps = Painter::preedit_cursor;
1128
1129                 // draw one character and update cur_x.
1130                 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1131         }
1132
1133         // update the preedit string screen area.
1134         update(0, cur_y - preedit_lines_*height, viewport()->width(),
1135                 (height + 1) * preedit_lines_);
1136
1137         // Don't forget to accept the event!
1138         e->accept();
1139 }
1140
1141
1142 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1143 {
1144         QRect cur_r(0, 0, 0, 0);
1145         switch (query) {
1146                 // this is the CJK-specific composition window position.
1147                 case Qt::ImMicroFocus:
1148                         cur_r = cursor_->rect();
1149                         if (preedit_lines_ != 1)
1150                                 cur_r.moveLeft(10);
1151                         cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1152                         // return lower right of cursor in LyX.
1153                         return cur_r;
1154                 default:
1155                         return QWidget::inputMethodQuery(query);
1156         }
1157 }
1158
1159
1160 void GuiWorkArea::updateWindowTitle()
1161 {
1162         docstring maximize_title;
1163         docstring minimize_title;
1164
1165         Buffer & buf = buffer_view_->buffer();
1166         FileName const fileName = buf.fileName();
1167         if (!fileName.empty()) {
1168                 maximize_title = fileName.displayName(30);
1169                 minimize_title = from_utf8(fileName.onlyFileName());
1170                 if (buf.lyxvc().inUse()) {
1171                         if (buf.lyxvc().locker().empty())
1172                                 maximize_title +=  _(" (version control)");
1173                         else
1174                                 maximize_title +=  _(" (version control, locking)");
1175                 }
1176                 if (!buf.isClean()) {
1177                         maximize_title += _(" (changed)");
1178                         minimize_title += char_type('*');
1179                 }
1180                 if (buf.isReadonly())
1181                         maximize_title += _(" (read only)");
1182         }
1183
1184         QString title = windowTitle();
1185         QString new_title = toqstr(maximize_title);
1186         if (title == new_title)
1187                 return;
1188
1189         QWidget::setWindowTitle(new_title);
1190         QWidget::setWindowIconText(toqstr(minimize_title));
1191         titleChanged(this);
1192 }
1193
1194
1195 void GuiWorkArea::setReadOnly(bool)
1196 {
1197         updateWindowTitle();
1198         if (this == lyx_view_->currentWorkArea())
1199                 lyx_view_->updateDialogs();
1200 }
1201
1202
1203 bool GuiWorkArea::isFullScreen()
1204 {
1205         return lyx_view_ && lyx_view_->isFullScreen();
1206 }
1207
1208
1209 ////////////////////////////////////////////////////////////////////
1210 //
1211 // EmbeddedWorkArea
1212 //
1213 ////////////////////////////////////////////////////////////////////
1214
1215
1216 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1217 {
1218         buffer_ = theBufferList().newBuffer(
1219                 support::FileName::tempName().absFilename() + "_embedded.internal");
1220         buffer_->setUnnamed(true);
1221         buffer_->setFullyLoaded(true);
1222         setBuffer(*buffer_);
1223         setDialogMode(true);
1224 }
1225
1226
1227 EmbeddedWorkArea::~EmbeddedWorkArea()
1228 {
1229         // No need to destroy buffer and bufferview here, because it is done
1230         // in theBuffeerList() destruction loop at application exit
1231 }
1232
1233
1234 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1235 {
1236         disable();
1237         GuiWorkArea::closeEvent(ev);
1238 }
1239
1240
1241 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1242 {
1243         disable();
1244         GuiWorkArea::hideEvent(ev);
1245 }
1246
1247
1248 void EmbeddedWorkArea::disable()
1249 {
1250         stopBlinkingCursor();
1251         if (view().currentWorkArea() != this)
1252                 return;
1253         LASSERT(view().currentMainWorkArea(), /* */);
1254         view().setCurrentWorkArea(view().currentMainWorkArea());
1255 }
1256
1257 ////////////////////////////////////////////////////////////////////
1258 //
1259 // TabWorkArea
1260 //
1261 ////////////////////////////////////////////////////////////////////
1262
1263 #ifdef Q_WS_MACX
1264 class NoTabFrameMacStyle : public QMacStyle {
1265 public:
1266         ///
1267         QRect subElementRect(SubElement element, const QStyleOption * option,
1268                              const QWidget * widget = 0) const
1269         {
1270                 QRect rect = QMacStyle::subElementRect(element, option, widget);
1271                 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1272
1273                 // The Qt Mac style puts the contents into a 3 pixel wide box
1274                 // which looks very ugly and not like other Mac applications.
1275                 // Hence we remove this here, and moreover the 16 pixel round
1276                 // frame above if the tab bar is hidden.
1277                 if (element == QStyle::SE_TabWidgetTabContents) {
1278                         rect.adjust(- rect.left(), 0, rect.left(), 0);
1279                         if (noBar)
1280                                 rect.setTop(0);
1281                 }
1282
1283                 return rect;
1284         }
1285 };
1286
1287 NoTabFrameMacStyle noTabFrameMacStyle;
1288 #endif
1289
1290
1291 TabWorkArea::TabWorkArea(QWidget * parent)
1292         : QTabWidget(parent), clicked_tab_(-1)
1293 {
1294 #ifdef Q_WS_MACX
1295         setStyle(&noTabFrameMacStyle);
1296 #endif
1297
1298         QPalette pal = palette();
1299         pal.setColor(QPalette::Active, QPalette::Button,
1300                 pal.color(QPalette::Active, QPalette::Window));
1301         pal.setColor(QPalette::Disabled, QPalette::Button,
1302                 pal.color(QPalette::Disabled, QPalette::Window));
1303         pal.setColor(QPalette::Inactive, QPalette::Button,
1304                 pal.color(QPalette::Inactive, QPalette::Window));
1305
1306         QObject::connect(this, SIGNAL(currentChanged(int)),
1307                 this, SLOT(on_currentTabChanged(int)));
1308
1309 #if QT_VERSION < 0x040500
1310         closeBufferButton = new QToolButton(this);
1311         closeBufferButton->setPalette(pal);
1312         // FIXME: rename the icon to closebuffer.png
1313         closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1314         closeBufferButton->setText("Close File");
1315         closeBufferButton->setAutoRaise(true);
1316         closeBufferButton->setCursor(Qt::ArrowCursor);
1317         closeBufferButton->setToolTip(qt_("Close File"));
1318         closeBufferButton->setEnabled(true);
1319         QObject::connect(closeBufferButton, SIGNAL(clicked()),
1320                 this, SLOT(closeCurrentBuffer()));
1321         setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1322 #endif
1323
1324         // setup drag'n'drop
1325         QTabBar* tb = new DragTabBar;
1326         connect(tb, SIGNAL(tabMoveRequested(int, int)),
1327                 this, SLOT(moveTab(int, int)));
1328         tb->setElideMode(Qt::ElideNone);
1329         setTabBar(tb);
1330
1331         // make us responsible for the context menu of the tabbar
1332         tb->setContextMenuPolicy(Qt::CustomContextMenu);
1333         connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1334                 this, SLOT(showContextMenu(const QPoint &)));
1335 #if QT_VERSION >= 0x040500
1336         connect(tb, SIGNAL(tabCloseRequested(int)),
1337                 tb, SLOT(on_tabCloseRequested(int)));
1338 #endif
1339
1340         setUsesScrollButtons(true);
1341 }
1342
1343
1344 void TabWorkArea::setFullScreen(bool full_screen)
1345 {
1346         for (int i = 0; i != count(); ++i) {
1347                 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1348                         wa->setFullScreen(full_screen);
1349         }
1350
1351         if (lyxrc.full_screen_tabbar)
1352                 showBar(!full_screen && count() > 1);
1353 }
1354
1355
1356 void TabWorkArea::showBar(bool show)
1357 {
1358         tabBar()->setEnabled(show);
1359         tabBar()->setVisible(show);
1360 #if QT_VERSION < 0x040500
1361         closeBufferButton->setVisible(show);    
1362 #endif
1363 }
1364
1365
1366 GuiWorkArea * TabWorkArea::currentWorkArea()
1367 {
1368         if (count() == 0)
1369                 return 0;
1370
1371         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1372         LASSERT(wa, /**/);
1373         return wa;
1374 }
1375
1376
1377 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1378 {
1379         for (int i = 0; i != count(); ++i) {
1380                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1381                 LASSERT(wa, return 0);
1382                 if (&wa->bufferView().buffer() == &buffer)
1383                         return wa;
1384         }
1385         return 0;
1386 }
1387
1388
1389 void TabWorkArea::closeAll()
1390 {
1391         while (count()) {
1392                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1393                 LASSERT(wa, /**/);
1394                 removeTab(0);
1395                 delete wa;
1396         }
1397 }
1398
1399
1400 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1401 {
1402         LASSERT(work_area, /**/);
1403         int index = indexOf(work_area);
1404         if (index == -1)
1405                 return false;
1406
1407         if (index == currentIndex())
1408                 // Make sure the work area is up to date.
1409                 on_currentTabChanged(index);
1410         else
1411                 // Switch to the work area.
1412                 setCurrentIndex(index);
1413         work_area->setFocus();
1414
1415         return true;
1416 }
1417
1418
1419 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1420 {
1421         GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1422         wa->setUpdatesEnabled(false);
1423         // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1424         // when hiding it again below).
1425         if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1426                 showBar(count() > 0);
1427         addTab(wa, wa->windowTitle());
1428         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1429                 this, SLOT(updateTabTexts()));
1430         if (currentWorkArea() && currentWorkArea()->isFullScreen())
1431                 setFullScreen(true);
1432         else
1433                 // Hide tabbar if there's only one tab.
1434                 showBar(count() > 1);
1435
1436         updateTabTexts();
1437
1438         return wa;
1439 }
1440
1441
1442 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1443 {
1444         LASSERT(work_area, return false);
1445         int index = indexOf(work_area);
1446         if (index == -1)
1447                 return false;
1448
1449         work_area->setUpdatesEnabled(false);
1450         removeTab(index);
1451         delete work_area;
1452
1453         if (count()) {
1454                 // make sure the next work area is enabled.
1455                 currentWidget()->setUpdatesEnabled(true);
1456                 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1457                         setFullScreen(true);
1458                 else
1459                         // Show tabbar only if there's more than one tab.
1460                         showBar(count() > 1);
1461         } else
1462                 lastWorkAreaRemoved();
1463
1464         updateTabTexts();
1465
1466         return true;
1467 }
1468
1469
1470 void TabWorkArea::on_currentTabChanged(int i)
1471 {
1472         // returns e.g. on application destruction
1473         if (i == -1)
1474                 return;
1475         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1476         LASSERT(wa, return);
1477         BufferView & bv = wa->bufferView();
1478         bv.cursor().fixIfBroken();
1479         bv.updateMetrics();
1480         wa->setUpdatesEnabled(true);
1481         wa->redraw();
1482         wa->setFocus();
1483         ///
1484         currentWorkAreaChanged(wa);
1485
1486         LYXERR(Debug::GUI, "currentTabChanged " << i
1487                 << "File" << bv.buffer().absFileName());
1488 }
1489
1490
1491 void TabWorkArea::closeCurrentBuffer()
1492 {
1493         if (clicked_tab_ != -1)
1494                 setCurrentIndex(clicked_tab_);
1495         else
1496                 // Before dispatching the LFUN we should be sure this
1497                 // is the current workarea.
1498                 currentWorkAreaChanged(currentWorkArea());
1499
1500         lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1501 }
1502
1503
1504 void TabWorkArea::closeCurrentTab()
1505 {
1506         if (clicked_tab_ == -1)
1507                 removeWorkArea(currentWorkArea());
1508         else {
1509                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1510                 LASSERT(wa, /**/);
1511                 removeWorkArea(wa);
1512         }
1513 }
1514
1515 ///
1516 class DisplayPath {
1517 public:
1518         /// make vector happy
1519         DisplayPath() {}
1520         ///
1521         DisplayPath(int tab, FileName const & filename)
1522                 : tab_(tab)
1523         {
1524                 filename_ = toqstr(filename.onlyFileNameWithoutExt());
1525                 postfix_ = toqstr(filename.absoluteFilePath()).
1526                         split("/", QString::SkipEmptyParts);
1527                 postfix_.pop_back();
1528                 abs_ = toqstr(filename.absoluteFilePath());
1529                 dottedPrefix_ = false;
1530         }
1531
1532         /// Absolute path for debugging.
1533         QString abs() const
1534         {
1535                 return abs_;
1536         }
1537         /// Add the first segment from the postfix or three dots to the prefix.
1538         /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1539         /// when really needed.
1540         void shiftPathSegment(bool dotted)
1541         {
1542                 if (postfix_.count() <= 0)
1543                         return;
1544
1545                 if (!dotted) {
1546                         if (dottedPrefix_ && !prefix_.isEmpty())
1547                                 prefix_ += ".../";
1548                         prefix_ += postfix_.front() + "/";
1549                 }
1550                 dottedPrefix_ = dotted && !prefix_.isEmpty();
1551                 postfix_.pop_front();
1552         }
1553         ///
1554         QString displayString() const
1555         {
1556                 if (prefix_.isEmpty())
1557                         return filename_;
1558
1559                 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1560                 return prefix_ + (dots ? ".../" : "") + filename_;
1561         }
1562         ///
1563         QString forecastPathString() const
1564         {
1565                 if (postfix_.count() == 0)
1566                         return displayString();
1567
1568                 return prefix_
1569                         + (dottedPrefix_ ? ".../" : "")
1570                         + postfix_.front() + "/";
1571         }
1572         ///
1573         bool final() const { return postfix_.empty(); }
1574         ///
1575         int tab() const { return tab_; }
1576
1577 private:
1578         ///
1579         QString prefix_;
1580         ///
1581         QStringList postfix_;
1582         ///
1583         QString filename_;
1584         ///
1585         QString abs_;
1586         ///
1587         int tab_;
1588         ///
1589         bool dottedPrefix_;
1590 };
1591
1592
1593 ///
1594 bool operator<(DisplayPath const & a, DisplayPath const & b)
1595 {
1596         return a.displayString() < b.displayString();
1597 }
1598
1599 ///
1600 bool operator==(DisplayPath const & a, DisplayPath const & b)
1601 {
1602         return a.displayString() == b.displayString();
1603 }
1604
1605
1606 void TabWorkArea::updateTabTexts()
1607 {
1608         size_t n = count();
1609         if (n == 0)
1610                 return;
1611         std::list<DisplayPath> paths;
1612         typedef std::list<DisplayPath>::iterator It;
1613
1614         // collect full names first: path into postfix, empty prefix and
1615         // filename without extension
1616         for (size_t i = 0; i < n; ++i) {
1617                 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(i));
1618                 FileName const fn = i_wa->bufferView().buffer().fileName();
1619                 paths.push_back(DisplayPath(i, fn));
1620         }
1621
1622         // go through path segments and see if it helps to make the path more unique
1623         bool somethingChanged = true;
1624         bool allFinal = false;
1625         while (somethingChanged && !allFinal) {
1626                 // adding path segments changes order
1627                 paths.sort();
1628
1629                 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1630                 somethingChanged = false;
1631                 allFinal = true;
1632
1633                 // find segments which are not unique (i.e. non-atomic)
1634                 It it = paths.begin();
1635                 It segStart = it;
1636                 QString segString = it->displayString();
1637                 for (; it != paths.end(); ++it) {
1638                         // look to the next item
1639                         It next = it;
1640                         ++next;
1641
1642                         // final?
1643                         allFinal = allFinal && it->final();
1644
1645                         LYXERR(Debug::GUI, "it = " << it->abs()
1646                                << " => " << it->displayString());
1647
1648                         // still the same segment?
1649                         QString nextString;
1650                         if ((next != paths.end()
1651                              && (nextString = next->displayString()) == segString))
1652                                 continue;
1653                         LYXERR(Debug::GUI, "segment ended");
1654
1655                         // only a trivial one with one element?
1656                         if (it == segStart) {
1657                                 // start new segment
1658                                 segStart = next;
1659                                 segString = nextString;
1660                                 continue;
1661                         }
1662
1663                         // we found a non-atomic segment segStart <= sit <= it < next.
1664                         // Shift path segments and hope for the best
1665                         // that it makes the path more unique.
1666                         somethingChanged = true;
1667                         It sit = segStart;
1668                         QString dspString = sit->forecastPathString();
1669                         LYXERR(Debug::GUI, "first forecast found for "
1670                                << sit->abs() << " => " << dspString);
1671                         ++sit;
1672                         bool moreUnique = false;
1673                         for (; sit != next; ++sit) {
1674                                 if (sit->forecastPathString() != dspString) {
1675                                         LYXERR(Debug::GUI, "different forecast found for "
1676                                                 << sit->abs() << " => " << sit->forecastPathString());
1677                                         moreUnique = true;
1678                                         break;
1679                                 }
1680                                 LYXERR(Debug::GUI, "same forecast found for "
1681                                         << sit->abs() << " => " << dspString);
1682                         }
1683
1684                         // if the path segment helped, add it. Otherwise add dots
1685                         bool dots = !moreUnique;
1686                         LYXERR(Debug::GUI, "using dots = " << dots);
1687                         for (sit = segStart; sit != next; ++sit) {
1688                                 sit->shiftPathSegment(dots);
1689                                 LYXERR(Debug::GUI, "shifting "
1690                                         << sit->abs() << " => " << sit->displayString());
1691                         }
1692
1693                         // start new segment
1694                         segStart = next;
1695                         segString = nextString;
1696                 }
1697         }
1698
1699         // set new tab titles
1700         for (It it = paths.begin(); it != paths.end(); ++it) {
1701                 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(it->tab()));
1702                 Buffer & buf = i_wa->bufferView().buffer();
1703                 if (!buf.fileName().empty() && !buf.isClean())
1704                         setTabText(it->tab(), it->displayString() + "*");
1705                 else
1706                         setTabText(it->tab(), it->displayString());
1707         }
1708 }
1709
1710
1711 void TabWorkArea::showContextMenu(const QPoint & pos)
1712 {
1713         // which tab?
1714         clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1715         if (clicked_tab_ == -1)
1716                 return;
1717
1718         // show tab popup
1719         QMenu popup;
1720         popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
1721                 qt_("Hide tab"), this, SLOT(closeCurrentTab()));
1722         popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
1723                 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1724         popup.exec(tabBar()->mapToGlobal(pos));
1725
1726         clicked_tab_ = -1;
1727 }
1728
1729
1730 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1731 {
1732         QWidget * w = widget(fromIndex);
1733         QIcon icon = tabIcon(fromIndex);
1734         QString text = tabText(fromIndex);
1735
1736         setCurrentIndex(fromIndex);
1737         removeTab(fromIndex);
1738         insertTab(toIndex, w, icon, text);
1739         setCurrentIndex(toIndex);
1740 }
1741
1742
1743 DragTabBar::DragTabBar(QWidget* parent)
1744         : QTabBar(parent)
1745 {
1746         setAcceptDrops(true);
1747 #if QT_VERSION >= 0x040500
1748         setTabsClosable(true);
1749 #endif
1750 }
1751
1752
1753 void DragTabBar::on_tabCloseRequested(int index)
1754 {
1755         setCurrentIndex(index);
1756         lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1757 }
1758
1759
1760 #if QT_VERSION < 0x040300
1761 int DragTabBar::tabAt(QPoint const & position) const
1762 {
1763         const int max = count();
1764         for (int i = 0; i < max; ++i) {
1765                 if (tabRect(i).contains(position))
1766                         return i;
1767         }
1768         return -1;
1769 }
1770 #endif
1771
1772
1773 void DragTabBar::mousePressEvent(QMouseEvent * event)
1774 {
1775         if (event->button() == Qt::LeftButton)
1776                 dragStartPos_ = event->pos();
1777         QTabBar::mousePressEvent(event);
1778 }
1779
1780
1781 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1782 {
1783         // If the left button isn't pressed anymore then return
1784         if (!(event->buttons() & Qt::LeftButton))
1785                 return;
1786
1787         // If the distance is too small then return
1788         if ((event->pos() - dragStartPos_).manhattanLength()
1789             < QApplication::startDragDistance())
1790                 return;
1791
1792         // did we hit something after all?
1793         int tab = tabAt(dragStartPos_);
1794         if (tab == -1)
1795                 return;
1796
1797         // simulate button release to remove highlight from button
1798         int i = currentIndex();
1799         QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1800                 event->button(), event->buttons(), 0);
1801         QTabBar::mouseReleaseEvent(&me);
1802         setCurrentIndex(i);
1803
1804         // initiate Drag
1805         QDrag * drag = new QDrag(this);
1806         QMimeData * mimeData = new QMimeData;
1807         // a crude way to distinguish tab-reodering drops from other ones
1808         mimeData->setData("action", "tab-reordering") ;
1809         drag->setMimeData(mimeData);
1810
1811 #if QT_VERSION >= 0x040300
1812         // get tab pixmap as cursor
1813         QRect r = tabRect(tab);
1814         QPixmap pixmap(r.size());
1815         render(&pixmap, - r.topLeft());
1816         drag->setPixmap(pixmap);
1817         drag->exec();
1818 #else
1819         drag->start(Qt::MoveAction);
1820 #endif
1821
1822 }
1823
1824
1825 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1826 {
1827         // Only accept if it's an tab-reordering request
1828         QMimeData const * m = event->mimeData();
1829         QStringList formats = m->formats();
1830         if (formats.contains("action")
1831             && m->data("action") == "tab-reordering")
1832                 event->acceptProposedAction();
1833 }
1834
1835
1836 void DragTabBar::dropEvent(QDropEvent * event)
1837 {
1838         int fromIndex = tabAt(dragStartPos_);
1839         int toIndex = tabAt(event->pos());
1840
1841         // Tell interested objects that
1842         if (fromIndex != toIndex)
1843                 tabMoveRequested(fromIndex, toIndex);
1844         event->acceptProposedAction();
1845 }
1846
1847
1848 } // namespace frontend
1849 } // namespace lyx
1850
1851 #include "moc_GuiWorkArea.cpp"