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