]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.cpp
try using std::tr1::shared_ptr instead of boost::shared_ptr
[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                 cursorInView = false;
572
573         // show cursor on screen
574         bool completable = cur.inset().showCompletionCursor()
575                 && completer_->completionAvailable()
576                 && !completer_->popupVisible()
577                 && !completer_->inlineVisible();
578         if (cursorInView) {
579                 cursor_visible_ = true;
580                 showCursor(x, y, h, l_shape, isrtl, completable);
581         }
582 }
583
584
585 void GuiWorkArea::hideCursor()
586 {
587         if (!cursor_visible_)
588                 return;
589
590         cursor_visible_ = false;
591         removeCursor();
592 }
593
594
595 void GuiWorkArea::toggleCursor()
596 {
597         if (cursor_visible_)
598                 hideCursor();
599         else
600                 showCursor();
601 }
602
603
604 void GuiWorkArea::updateScrollbar()
605 {
606         ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
607         // WARNING: don't touch at the scrollbar value like this:
608         //   verticalScrollBar()->setValue(scroll_.position);
609         // because this would cause a recursive signal/slot calling with
610         // GuiWorkArea::scrollTo
611         verticalScrollBar()->setRange(scroll_.min, scroll_.max);
612         verticalScrollBar()->setPageStep(scroll_.page_step);
613         verticalScrollBar()->setSingleStep(scroll_.single_step);
614         verticalScrollBar()->setSliderPosition(scroll_.position);
615 }
616
617
618 void GuiWorkArea::scrollTo(int value)
619 {
620         stopBlinkingCursor();
621         buffer_view_->scrollDocView(value);
622
623         if (lyxrc.cursor_follows_scrollbar) {
624                 buffer_view_->setCursorFromScrollbar();
625                 lyx_view_->updateLayoutList();
626         }
627         // Show the cursor immediately after any operation.
628         startBlinkingCursor();
629         QApplication::syncX();
630 }
631
632
633 bool GuiWorkArea::event(QEvent * e)
634 {
635         switch (e->type()) {
636         case QEvent::ToolTip: {
637                 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
638                 if (lyxrc.use_tooltip) {
639                         QPoint pos = helpEvent->pos();
640                         if (pos.x() < viewport()->width()) {
641                                 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
642                                 QToolTip::showText(helpEvent->globalPos(), s);
643                         }
644                         else
645                                 QToolTip::hideText();
646                 }
647                 // Don't forget to accept the event!
648                 e->accept();
649                 return true;
650         }
651
652         case QEvent::ShortcutOverride: {
653                 // We catch this event in order to catch the Tab or Shift+Tab key press
654                 // which are otherwise reserved to focus switching between controls
655                 // within a dialog.
656                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
657                 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
658                         || ke->modifiers() & Qt::ControlModifier)
659                         return QAbstractScrollArea::event(e);
660                 keyPressEvent(ke);
661                 return true;
662         }
663
664         default:
665                 return QAbstractScrollArea::event(e);
666         }
667         return false;
668 }
669
670
671 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
672 {
673         QPoint pos = e->pos();
674         docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
675         if (name.empty()) {
676                 QAbstractScrollArea::contextMenuEvent(e);
677                 return;
678         }
679         QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
680         if (!menu) {
681                 QAbstractScrollArea::contextMenuEvent(e);
682                 return;
683         }
684         // Position the menu to the right.
685         // FIXME: menu position should be different for RTL text.
686         menu->exec(e->globalPos());
687         e->accept();
688 }
689
690
691 void GuiWorkArea::focusInEvent(QFocusEvent * e)
692 {
693         /*
694         LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << std::endl);
695         GuiWorkArea * old_gwa = const_cast<GuiWorkArea *>(guiApp->currentView()->currentWorkArea());
696         if (old_gwa)
697                 old_gwa->stopBlinkingCursor();
698         lyx_view_->setCurrentWorkArea(this);
699         */
700
701         if (lyx_view_->currentWorkArea() != this)
702                 lyx_view_->setCurrentWorkArea(this);
703
704         startBlinkingCursor();
705         QAbstractScrollArea::focusInEvent(e);
706 }
707
708
709 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
710 {
711         LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << std::endl);
712         stopBlinkingCursor();
713         QAbstractScrollArea::focusOutEvent(e);
714 }
715
716
717 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
718 {
719         if (dc_event_.active && dc_event_ == *e) {
720                 dc_event_.active = false;
721                 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
722                         q_button_state(e->button()));
723                 dispatch(cmd);
724                 e->accept();
725                 return;
726         }
727
728         inputContext()->reset();
729
730         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
731                 q_button_state(e->button()));
732         dispatch(cmd, q_key_state(e->modifiers()));
733         e->accept();
734 }
735
736
737 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
738 {
739         if (synthetic_mouse_event_.timeout.running())
740                 synthetic_mouse_event_.timeout.stop();
741
742         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
743                               q_button_state(e->button()));
744         dispatch(cmd);
745         e->accept();
746 }
747
748
749 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
750 {
751         // we kill the triple click if we move
752         doubleClickTimeout();
753         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
754                 q_motion_state(e->buttons()));
755
756         e->accept();
757
758         // If we're above or below the work area...
759         if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
760                 // Make sure only a synthetic event can cause a page scroll,
761                 // so they come at a steady rate:
762                 if (e->y() <= 20)
763                         // _Force_ a scroll up:
764                         cmd.y = -40;
765                 else
766                         cmd.y = viewport()->height();
767                 // Store the event, to be handled when the timeout expires.
768                 synthetic_mouse_event_.cmd = cmd;
769
770                 if (synthetic_mouse_event_.timeout.running())
771                         // Discard the event. Note that it _may_ be handled
772                         // when the timeout expires if
773                         // synthetic_mouse_event_.cmd has not been overwritten.
774                         // Ie, when the timeout expires, we handle the
775                         // most recent event but discard all others that
776                         // occurred after the one used to start the timeout
777                         // in the first place.
778                         return;
779
780                 synthetic_mouse_event_.restart_timeout = true;
781                 synthetic_mouse_event_.timeout.start();
782                 // Fall through to handle this event...
783
784         } else if (synthetic_mouse_event_.timeout.running()) {
785                 // Store the event, to be possibly handled when the timeout
786                 // expires.
787                 // Once the timeout has expired, normal control is returned
788                 // to mouseMoveEvent (restart_timeout = false).
789                 // This results in a much smoother 'feel' when moving the
790                 // mouse back into the work area.
791                 synthetic_mouse_event_.cmd = cmd;
792                 synthetic_mouse_event_.restart_timeout = false;
793                 return;
794         }
795
796         // Has anything changed on-screen since the last QMouseEvent
797         // was received?
798         double const scrollbar_value = verticalScrollBar()->value();
799         if (e->x() == synthetic_mouse_event_.x_old
800                 && e->y() == synthetic_mouse_event_.y_old
801                 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
802                 // Nothing changed on-screen since the last QMouseEvent.
803                 return;
804         }
805
806         // Yes something has changed. Store the params used to check this.
807         synthetic_mouse_event_.x_old = e->x();
808         synthetic_mouse_event_.y_old = e->y();
809         synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
810
811         // ... and dispatch the event to the LyX core.
812         dispatch(cmd);
813 }
814
815
816 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
817 {
818         // Wheel rotation by one notch results in a delta() of 120 (see
819         // documentation of QWheelEvent)
820         int const delta = ev->delta() / 120;
821         if (ev->modifiers() & Qt::ControlModifier) {
822                 lyxrc.zoom += 5 * delta;
823                 if (lyxrc.zoom < 10)
824                         lyxrc.zoom = 10;
825                 // The global QPixmapCache is used in GuiPainter to cache text
826                 // painting so we must reset it.
827                 QPixmapCache::clear();
828                 guiApp->fontLoader().update();
829                 ev->accept();
830                 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
831                 return;
832         }
833
834         // Take into account the desktop wide settings.
835         int const lines = qApp->wheelScrollLines();
836         int const page_step = verticalScrollBar()->pageStep();
837         // Test if the wheel mouse is set to one screen at a time.
838         int scroll_value = lines > page_step
839                 ? page_step : lines * verticalScrollBar()->singleStep();
840
841         // Take into account the rotation.
842         scroll_value *= delta;
843
844         // Take into account user preference.
845         scroll_value *= lyxrc.mouse_wheel_speed;
846         LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
847                         << " delta = " << delta << " scroll_value = " << scroll_value
848                         << " page_step = " << page_step);
849         // Now scroll.
850         verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
851
852         ev->accept();
853 }
854
855
856 void GuiWorkArea::generateSyntheticMouseEvent()
857 {
858         // Set things off to generate the _next_ 'pseudo' event.
859         if (synthetic_mouse_event_.restart_timeout)
860                 synthetic_mouse_event_.timeout.start();
861
862         // Has anything changed on-screen since the last timeout signal
863         // was received?
864         double const scrollbar_value = verticalScrollBar()->value();
865         if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
866                 // Yes it has. Store the params used to check this.
867                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
868
869                 // ... and dispatch the event to the LyX core.
870                 dispatch(synthetic_mouse_event_.cmd);
871         }
872 }
873
874
875 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
876 {
877         // Do not process here some keys if dialog_mode_ is set
878         if (dialog_mode_
879                 && (ev->modifiers() == Qt::NoModifier
880                     || ev->modifiers() == Qt::ShiftModifier)
881                 && (ev->key() == Qt::Key_Escape
882                     || ev->key() == Qt::Key_Enter
883                     || ev->key() == Qt::Key_Return)
884             ) {
885                 ev->ignore();
886                 return;
887         }
888
889         // intercept some keys if completion popup is visible
890         if (completer_->popupVisible()) {
891                 switch (ev->key()) {
892                 case Qt::Key_Enter:
893                 case Qt::Key_Return:
894                         completer_->activate();
895                         ev->accept();
896                         return;
897                 }
898         }
899
900         // do nothing if there are other events
901         // (the auto repeated events come too fast)
902         // \todo FIXME: remove hard coded Qt keys, process the key binding
903 #ifdef Q_WS_X11
904         if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
905                         && (Qt::Key_PageDown || Qt::Key_PageUp)) {
906                 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
907                 ev->ignore();
908                 return;
909         }
910 #endif
911
912         LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
913                 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
914
915         KeySymbol sym;
916         setKeySymbol(&sym, ev);
917         processKeySym(sym, q_key_state(ev->modifiers()));
918         ev->accept();
919 }
920
921
922 void GuiWorkArea::doubleClickTimeout()
923 {
924         dc_event_.active = false;
925 }
926
927
928 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
929 {
930         dc_event_ = DoubleClick(ev);
931         QTimer::singleShot(QApplication::doubleClickInterval(), this,
932                            SLOT(doubleClickTimeout()));
933         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
934                         ev->x(), ev->y(),
935                         q_button_state(ev->button()));
936         dispatch(cmd);
937         ev->accept();
938 }
939
940
941 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
942 {
943         QAbstractScrollArea::resizeEvent(ev);
944         need_resize_ = true;
945         ev->accept();
946 }
947
948
949 void GuiWorkArea::update(int x, int y, int w, int h)
950 {
951         viewport()->repaint(x, y, w, h);
952 }
953
954
955 void GuiWorkArea::paintEvent(QPaintEvent * ev)
956 {
957         QRect const rc = ev->rect();
958         // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
959         //      << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
960
961         if (need_resize_) {
962                 screen_ = QPixmap(viewport()->width(), viewport()->height());
963                 resizeBufferView();
964                 hideCursor();
965                 showCursor();
966         }
967
968         QPainter pain(viewport());
969         pain.drawPixmap(rc, screen_, rc);
970         cursor_->draw(pain);
971         ev->accept();
972 }
973
974
975 void GuiWorkArea::updateScreen()
976 {
977         GuiPainter pain(&screen_);
978         buffer_view_->draw(pain);
979 }
980
981
982 void GuiWorkArea::showCursor(int x, int y, int h,
983         bool l_shape, bool rtl, bool completable)
984 {
985         if (schedule_redraw_) {
986                 // This happens when a graphic conversion is finished. As we don't know
987                 // the size of the new graphics, it's better the update everything.
988                 // We can't use redraw() here because this would trigger a infinite
989                 // recursive loop with showCursor().
990                 buffer_view_->resize(viewport()->width(), viewport()->height());
991                 updateScreen();
992                 updateScrollbar();
993                 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
994                 schedule_redraw_ = false;
995                 // Show the cursor immediately after the update.
996                 hideCursor();
997                 toggleCursor();
998                 return;
999         }
1000
1001         cursor_->update(x, y, h, l_shape, rtl, completable);
1002         cursor_->show();
1003         viewport()->update(cursor_->rect());
1004 }
1005
1006
1007 void GuiWorkArea::removeCursor()
1008 {
1009         cursor_->hide();
1010         //if (!qApp->focusWidget())
1011                 viewport()->update(cursor_->rect());
1012 }
1013
1014
1015 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1016 {
1017         QString const & commit_string = e->commitString();
1018         docstring const & preedit_string
1019                 = qstring_to_ucs4(e->preeditString());
1020
1021         if (!commit_string.isEmpty()) {
1022
1023                 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1024                         << " commitString: " << e->commitString());
1025
1026                 int key = 0;
1027
1028                 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1029                 for (int i = 0; i != commit_string.size(); ++i) {
1030                         QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1031                         keyPressEvent(&ev);
1032                 }
1033         }
1034
1035         // Hide the cursor during the kana-kanji transformation.
1036         if (preedit_string.empty())
1037                 startBlinkingCursor();
1038         else
1039                 stopBlinkingCursor();
1040
1041         // last_width : for checking if last preedit string was/wasn't empty.
1042         static bool last_width = false;
1043         if (!last_width && preedit_string.empty()) {
1044                 // if last_width is last length of preedit string.
1045                 e->accept();
1046                 return;
1047         }
1048
1049         GuiPainter pain(&screen_);
1050         buffer_view_->updateMetrics();
1051         buffer_view_->draw(pain);
1052         FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1053         FontMetrics const & fm = theFontMetrics(font);
1054         int height = fm.maxHeight();
1055         int cur_x = cursor_->rect().left();
1056         int cur_y = cursor_->rect().bottom();
1057
1058         // redraw area of preedit string.
1059         update(0, cur_y - height, viewport()->width(),
1060                 (height + 1) * preedit_lines_);
1061
1062         if (preedit_string.empty()) {
1063                 last_width = false;
1064                 preedit_lines_ = 1;
1065                 e->accept();
1066                 return;
1067         }
1068         last_width = true;
1069
1070         // att : stores an IM attribute.
1071         QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1072
1073         // get attributes of input method cursor.
1074         // cursor_pos : cursor position in preedit string.
1075         size_t cursor_pos = 0;
1076         bool cursor_is_visible = false;
1077         for (int i = 0; i != att.size(); ++i) {
1078                 if (att.at(i).type == QInputMethodEvent::Cursor) {
1079                         cursor_pos = att.at(i).start;
1080                         cursor_is_visible = att.at(i).length != 0;
1081                         break;
1082                 }
1083         }
1084
1085         size_t preedit_length = preedit_string.length();
1086
1087         // get position of selection in input method.
1088         // FIXME: isn't there a way to do this simplier?
1089         // rStart : cursor position in selected string in IM.
1090         size_t rStart = 0;
1091         // rLength : selected string length in IM.
1092         size_t rLength = 0;
1093         if (cursor_pos < preedit_length) {
1094                 for (int i = 0; i != att.size(); ++i) {
1095                         if (att.at(i).type == QInputMethodEvent::TextFormat) {
1096                                 if (att.at(i).start <= int(cursor_pos)
1097                                         && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1098                                                 rStart = att.at(i).start;
1099                                                 rLength = att.at(i).length;
1100                                                 if (!cursor_is_visible)
1101                                                         cursor_pos += rLength;
1102                                                 break;
1103                                 }
1104                         }
1105                 }
1106         }
1107         else {
1108                 rStart = cursor_pos;
1109                 rLength = 0;
1110         }
1111
1112         int const right_margin = buffer_view_->rightMargin();
1113         Painter::preedit_style ps;
1114         // Most often there would be only one line:
1115         preedit_lines_ = 1;
1116         for (size_t pos = 0; pos != preedit_length; ++pos) {
1117                 char_type const typed_char = preedit_string[pos];
1118                 // reset preedit string style
1119                 ps = Painter::preedit_default;
1120
1121                 // if we reached the right extremity of the screen, go to next line.
1122                 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1123                         cur_x = right_margin;
1124                         cur_y += height + 1;
1125                         ++preedit_lines_;
1126                 }
1127                 // preedit strings are displayed with dashed underline
1128                 // and partial strings are displayed white on black indicating
1129                 // that we are in selecting mode in the input method.
1130                 // FIXME: rLength == preedit_length is not a changing condition
1131                 // FIXME: should be put out of the loop.
1132                 if (pos >= rStart
1133                         && pos < rStart + rLength
1134                         && !(cursor_pos < rLength && rLength == preedit_length))
1135                         ps = Painter::preedit_selecting;
1136
1137                 if (pos == cursor_pos
1138                         && (cursor_pos < rLength && rLength == preedit_length))
1139                         ps = Painter::preedit_cursor;
1140
1141                 // draw one character and update cur_x.
1142                 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1143         }
1144
1145         // update the preedit string screen area.
1146         update(0, cur_y - preedit_lines_*height, viewport()->width(),
1147                 (height + 1) * preedit_lines_);
1148
1149         // Don't forget to accept the event!
1150         e->accept();
1151 }
1152
1153
1154 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1155 {
1156         QRect cur_r(0, 0, 0, 0);
1157         switch (query) {
1158                 // this is the CJK-specific composition window position.
1159                 case Qt::ImMicroFocus:
1160                         cur_r = cursor_->rect();
1161                         if (preedit_lines_ != 1)
1162                                 cur_r.moveLeft(10);
1163                         cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1164                         // return lower right of cursor in LyX.
1165                         return cur_r;
1166                 default:
1167                         return QWidget::inputMethodQuery(query);
1168         }
1169 }
1170
1171
1172 void GuiWorkArea::updateWindowTitle()
1173 {
1174         docstring maximize_title;
1175         docstring minimize_title;
1176
1177         Buffer & buf = buffer_view_->buffer();
1178         FileName const fileName = buf.fileName();
1179         if (!fileName.empty()) {
1180                 maximize_title = fileName.displayName(30);
1181                 minimize_title = from_utf8(fileName.onlyFileName());
1182                 if (buf.lyxvc().inUse())
1183                         maximize_title +=  _(" (version control)");
1184                 if (!buf.isClean()) {
1185                         maximize_title += _(" (changed)");
1186                         minimize_title += char_type('*');
1187                 }
1188                 if (buf.isReadonly())
1189                         maximize_title += _(" (read only)");
1190         }
1191
1192         QString title = windowTitle();
1193         QString new_title = toqstr(maximize_title);
1194         if (title == new_title)
1195                 return;
1196
1197         QWidget::setWindowTitle(new_title);
1198         QWidget::setWindowIconText(toqstr(minimize_title));
1199         titleChanged(this);
1200 }
1201
1202
1203 void GuiWorkArea::setReadOnly(bool)
1204 {
1205         updateWindowTitle();
1206         if (this == lyx_view_->currentWorkArea())
1207                 lyx_view_->updateDialogs();
1208 }
1209
1210
1211 bool GuiWorkArea::isFullScreen()
1212 {
1213         return lyx_view_ && lyx_view_->isFullScreen();
1214 }
1215
1216
1217 ////////////////////////////////////////////////////////////////////
1218 //
1219 // TabWorkArea
1220 //
1221 ////////////////////////////////////////////////////////////////////
1222
1223 #ifdef Q_WS_MACX
1224 class NoTabFrameMacStyle : public QMacStyle {
1225 public:
1226         ///
1227         QRect subElementRect(SubElement element, const QStyleOption * option,
1228                              const QWidget * widget = 0) const
1229         {
1230                 QRect rect = QMacStyle::subElementRect(element, option, widget);
1231                 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1232
1233                 // The Qt Mac style puts the contents into a 3 pixel wide box
1234                 // which looks very ugly and not like other Mac applications.
1235                 // Hence we remove this here, and moreover the 16 pixel round
1236                 // frame above if the tab bar is hidden.
1237                 if (element == QStyle::SE_TabWidgetTabContents) {
1238                         rect.adjust(- rect.left(), 0, rect.left(), 0);
1239                         if (noBar)
1240                                 rect.setTop(0);
1241                 }
1242
1243                 return rect;
1244         }
1245 };
1246
1247 NoTabFrameMacStyle noTabFrameMacStyle;
1248 #endif
1249
1250
1251 TabWorkArea::TabWorkArea(QWidget * parent)
1252         : QTabWidget(parent), clicked_tab_(-1)
1253 {
1254 #ifdef Q_WS_MACX
1255         setStyle(&noTabFrameMacStyle);
1256 #endif
1257
1258         QPalette pal = palette();
1259         pal.setColor(QPalette::Active, QPalette::Button,
1260                 pal.color(QPalette::Active, QPalette::Window));
1261         pal.setColor(QPalette::Disabled, QPalette::Button,
1262                 pal.color(QPalette::Disabled, QPalette::Window));
1263         pal.setColor(QPalette::Inactive, QPalette::Button,
1264                 pal.color(QPalette::Inactive, QPalette::Window));
1265
1266         QObject::connect(this, SIGNAL(currentChanged(int)),
1267                 this, SLOT(on_currentTabChanged(int)));
1268
1269         QToolButton * closeBufferButton = new QToolButton(this);
1270         closeBufferButton->setPalette(pal);
1271         // FIXME: rename the icon to closebuffer.png
1272         closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1273         closeBufferButton->setText("Close File");
1274         closeBufferButton->setAutoRaise(true);
1275         closeBufferButton->setCursor(Qt::ArrowCursor);
1276         closeBufferButton->setToolTip(qt_("Close File"));
1277         closeBufferButton->setEnabled(true);
1278         QObject::connect(closeBufferButton, SIGNAL(clicked()),
1279                 this, SLOT(closeCurrentBuffer()));
1280         setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1281
1282         // setup drag'n'drop
1283         QTabBar* tb = new DragTabBar;
1284         connect(tb, SIGNAL(tabMoveRequested(int, int)),
1285                 this, SLOT(moveTab(int, int)));
1286         tb->setElideMode(Qt::ElideNone);
1287         setTabBar(tb);
1288
1289         // make us responsible for the context menu of the tabbar
1290         tb->setContextMenuPolicy(Qt::CustomContextMenu);
1291         connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1292                 this, SLOT(showContextMenu(const QPoint &)));
1293
1294         setUsesScrollButtons(true);
1295 }
1296
1297
1298 void TabWorkArea::setFullScreen(bool full_screen)
1299 {
1300         for (int i = 0; i != count(); ++i) {
1301                 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1302                         wa->setFullScreen(full_screen);
1303         }
1304
1305         if (lyxrc.full_screen_tabbar)
1306                 showBar(!full_screen && count()>1);
1307 }
1308
1309
1310 void TabWorkArea::showBar(bool show)
1311 {
1312         tabBar()->setEnabled(show);
1313         tabBar()->setVisible(show);
1314 }
1315
1316
1317 GuiWorkArea * TabWorkArea::currentWorkArea()
1318 {
1319         if (count() == 0)
1320                 return 0;
1321
1322         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1323         LASSERT(wa, /**/);
1324         return wa;
1325 }
1326
1327
1328 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1329 {
1330         for (int i = 0; i != count(); ++i) {
1331                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1332                 LASSERT(wa, return 0);
1333                 if (&wa->bufferView().buffer() == &buffer)
1334                         return wa;
1335         }
1336         return 0;
1337 }
1338
1339
1340 void TabWorkArea::closeAll()
1341 {
1342         while (count()) {
1343                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1344                 LASSERT(wa, /**/);
1345                 removeTab(0);
1346                 delete wa;
1347         }
1348 }
1349
1350
1351 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1352 {
1353         LASSERT(work_area, /**/);
1354         int index = indexOf(work_area);
1355         if (index == -1)
1356                 return false;
1357
1358         if (index == currentIndex())
1359                 // Make sure the work area is up to date.
1360                 on_currentTabChanged(index);
1361         else
1362                 // Switch to the work area.
1363                 setCurrentIndex(index);
1364         work_area->setFocus();
1365
1366         return true;
1367 }
1368
1369
1370 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1371 {
1372         GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1373         wa->setUpdatesEnabled(false);
1374         // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1375         // when hiding it again below).
1376         if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1377                 showBar(count() > 0);
1378         addTab(wa, wa->windowTitle());
1379         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1380                 this, SLOT(updateTabTexts()));
1381         if (currentWorkArea() && currentWorkArea()->isFullScreen())
1382                 setFullScreen(true);
1383         else
1384                 // Hide tabbar if there's only one tab.
1385                 showBar(count() > 1);
1386
1387         updateTabTexts();
1388
1389         return wa;
1390 }
1391
1392
1393 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1394 {
1395         LASSERT(work_area, return false);
1396         int index = indexOf(work_area);
1397         if (index == -1)
1398                 return false;
1399
1400         work_area->setUpdatesEnabled(false);
1401         removeTab(index);
1402         delete work_area;
1403
1404         if (count()) {
1405                 // make sure the next work area is enabled.
1406                 currentWidget()->setUpdatesEnabled(true);
1407                 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1408                         setFullScreen(true);
1409                 else
1410                         // Hide tabbar if there's only one tab.
1411                         showBar(count() > 1);
1412         } else {
1413                 lastWorkAreaRemoved();
1414         }
1415
1416         updateTabTexts();
1417
1418         return true;
1419 }
1420
1421
1422 void TabWorkArea::on_currentTabChanged(int i)
1423 {
1424         // returns e.g. on application destruction
1425         if (i == -1)
1426                 return;
1427         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1428         LASSERT(wa, return);
1429         BufferView & bv = wa->bufferView();
1430         bv.cursor().fixIfBroken();
1431         bv.updateMetrics();
1432         wa->setUpdatesEnabled(true);
1433         wa->redraw();
1434         wa->setFocus();
1435         ///
1436         currentWorkAreaChanged(wa);
1437
1438         LYXERR(Debug::GUI, "currentTabChanged " << i
1439                 << "File" << bv.buffer().absFileName());
1440 }
1441
1442
1443 void TabWorkArea::closeCurrentBuffer()
1444 {
1445         if (clicked_tab_ != -1)
1446                 setCurrentIndex(clicked_tab_);
1447
1448         lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1449 }
1450
1451
1452 void TabWorkArea::closeCurrentTab()
1453 {
1454         if (clicked_tab_ == -1)
1455                 removeWorkArea(currentWorkArea());
1456         else {
1457                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1458                 LASSERT(wa, /**/);
1459                 removeWorkArea(wa);
1460         }
1461 }
1462
1463 ///
1464 class DisplayPath {
1465 public:
1466         /// make vector happy
1467         DisplayPath() {}
1468         ///
1469         DisplayPath(int tab, FileName const & filename)
1470                 : tab_(tab)
1471         {
1472                 filename_ = toqstr(filename.onlyFileNameWithoutExt());
1473                 postfix_ = toqstr(filename.absoluteFilePath()).
1474                         split("/", QString::SkipEmptyParts);
1475                 postfix_.pop_back();
1476                 abs_ = toqstr(filename.absoluteFilePath());
1477                 dottedPrefix_ = false;
1478         }
1479
1480         /// Absolute path for debugging.
1481         QString abs() const
1482         {
1483                 return abs_;
1484         }
1485         /// Add the first segment from the postfix or three dots to the prefix.
1486         /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1487         /// when really needed.
1488         void shiftPathSegment(bool dotted)
1489         {
1490                 if (postfix_.count() <= 0)
1491                         return;
1492
1493                 if (!dotted) {
1494                         if (dottedPrefix_ && !prefix_.isEmpty())
1495                                 prefix_ += ".../";
1496                         prefix_ += postfix_.front() + "/";
1497                 }
1498                 dottedPrefix_ = dotted && !prefix_.isEmpty();
1499                 postfix_.pop_front();
1500         }
1501         ///
1502         QString displayString() const
1503         {
1504                 if (prefix_.isEmpty())
1505                         return filename_;
1506
1507                 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1508                 return prefix_ + (dots ? ".../" : "") + filename_;
1509         }
1510         ///
1511         QString forecastPathString() const
1512         {
1513                 if (postfix_.count() == 0)
1514                         return displayString();
1515
1516                 return prefix_
1517                         + (dottedPrefix_ ? ".../" : "")
1518                         + postfix_.front() + "/";
1519         }
1520         ///
1521         bool final() const { return postfix_.empty(); }
1522         ///
1523         int tab() const { return tab_; }
1524
1525 private:
1526         ///
1527         QString prefix_;
1528         ///
1529         QStringList postfix_;
1530         ///
1531         QString filename_;
1532         ///
1533         QString abs_;
1534         ///
1535         int tab_;
1536         ///
1537         bool dottedPrefix_;
1538 };
1539
1540
1541 ///
1542 bool operator<(DisplayPath const & a, DisplayPath const & b)
1543 {
1544         return a.displayString() < b.displayString();
1545 }
1546
1547 ///
1548 bool operator==(DisplayPath const & a, DisplayPath const & b)
1549 {
1550         return a.displayString() == b.displayString();
1551 }
1552
1553
1554 void TabWorkArea::updateTabTexts()
1555 {
1556         size_t n = count();
1557         if (n == 0)
1558                 return;
1559         std::list<DisplayPath> paths;
1560         typedef std::list<DisplayPath>::iterator It;
1561
1562         // collect full names first: path into postfix, empty prefix and
1563         // filename without extension
1564         for (size_t i = 0; i < n; ++i) {
1565                 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(i));
1566                 FileName const fn = i_wa->bufferView().buffer().fileName();
1567                 paths.push_back(DisplayPath(i, fn));
1568         }
1569
1570         // go through path segments and see if it helps to make the path more unique
1571         bool somethingChanged = true;
1572         bool allFinal = false;
1573         while (somethingChanged && !allFinal) {
1574                 // adding path segments changes order
1575                 paths.sort();
1576
1577                 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1578                 somethingChanged = false;
1579                 allFinal = true;
1580
1581                 // find segments which are not unique (i.e. non-atomic)
1582                 It it = paths.begin();
1583                 It segStart = it;
1584                 QString segString = it->displayString();
1585                 for (; it != paths.end(); ++it) {
1586                         // look to the next item
1587                         It next = it;
1588                         ++next;
1589
1590                         // final?
1591                         allFinal = allFinal && it->final();
1592
1593                         LYXERR(Debug::GUI, "it = " << it->abs()
1594                                << " => " << it->displayString());
1595
1596                         // still the same segment?
1597                         QString nextString;
1598                         if ((next != paths.end()
1599                              && (nextString = next->displayString()) == segString))
1600                                 continue;
1601                         LYXERR(Debug::GUI, "segment ended");
1602
1603                         // only a trivial one with one element?
1604                         if (it == segStart) {
1605                                 // start new segment
1606                                 segStart = next;
1607                                 segString = nextString;
1608                                 continue;
1609                         }
1610
1611                         // we found a non-atomic segment segStart <= sit <= it < next.
1612                         // Shift path segments and hope for the best
1613                         // that it makes the path more unique.
1614                         somethingChanged = true;
1615                         It sit = segStart;
1616                         QString dspString = sit->forecastPathString();
1617                         LYXERR(Debug::GUI, "first forecast found for "
1618                                << sit->abs() << " => " << dspString);
1619                         ++sit;
1620                         bool moreUnique = false;
1621                         for (; sit != next; ++sit) {
1622                                 if (sit->forecastPathString() != dspString) {
1623                                         LYXERR(Debug::GUI, "different forecast found for "
1624                                                 << sit->abs() << " => " << sit->forecastPathString());
1625                                         moreUnique = true;
1626                                         break;
1627                                 }
1628                                 LYXERR(Debug::GUI, "same forecast found for "
1629                                         << sit->abs() << " => " << dspString);
1630                         }
1631
1632                         // if the path segment helped, add it. Otherwise add dots
1633                         bool dots = !moreUnique;
1634                         LYXERR(Debug::GUI, "using dots = " << dots);
1635                         for (sit = segStart; sit != next; ++sit) {
1636                                 sit->shiftPathSegment(dots);
1637                                 LYXERR(Debug::GUI, "shifting "
1638                                         << sit->abs() << " => " << sit->displayString());
1639                         }
1640
1641                         // start new segment
1642                         segStart = next;
1643                         segString = nextString;
1644                 }
1645         }
1646
1647         // set new tab titles
1648         for (It it = paths.begin(); it != paths.end(); ++it) {
1649                 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(it->tab()));
1650                 Buffer & buf = i_wa->bufferView().buffer();
1651                 if (!buf.fileName().empty() && !buf.isClean())
1652                         setTabText(it->tab(), it->displayString() + "*");
1653                 else
1654                         setTabText(it->tab(), it->displayString());
1655         }
1656 }
1657
1658
1659 void TabWorkArea::showContextMenu(const QPoint & pos)
1660 {
1661         // which tab?
1662         clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1663         if (clicked_tab_ == -1)
1664                 return;
1665
1666         // show tab popup
1667         QMenu popup;
1668         popup.addAction(QIcon(":/images/hidetab.png"),
1669                 qt_("Hide tab"), this, SLOT(closeCurrentTab()));
1670         popup.addAction(QIcon(":/images/closetab.png"),
1671                 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1672         popup.exec(tabBar()->mapToGlobal(pos));
1673
1674         clicked_tab_ = -1;
1675 }
1676
1677
1678 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1679 {
1680         QWidget * w = widget(fromIndex);
1681         QIcon icon = tabIcon(fromIndex);
1682         QString text = tabText(fromIndex);
1683
1684         setCurrentIndex(fromIndex);
1685         removeTab(fromIndex);
1686         insertTab(toIndex, w, icon, text);
1687         setCurrentIndex(toIndex);
1688 }
1689
1690
1691 DragTabBar::DragTabBar(QWidget* parent)
1692         : QTabBar(parent)
1693 {
1694         setAcceptDrops(true);
1695 }
1696
1697
1698 #if QT_VERSION < 0x040300
1699 int DragTabBar::tabAt(QPoint const & position) const
1700 {
1701         const int max = count();
1702         for (int i = 0; i < max; ++i) {
1703                 if (tabRect(i).contains(position))
1704                         return i;
1705         }
1706         return -1;
1707 }
1708 #endif
1709
1710
1711 void DragTabBar::mousePressEvent(QMouseEvent * event)
1712 {
1713         if (event->button() == Qt::LeftButton)
1714                 dragStartPos_ = event->pos();
1715         QTabBar::mousePressEvent(event);
1716 }
1717
1718
1719 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1720 {
1721         // If the left button isn't pressed anymore then return
1722         if (!(event->buttons() & Qt::LeftButton))
1723                 return;
1724
1725         // If the distance is too small then return
1726         if ((event->pos() - dragStartPos_).manhattanLength()
1727             < QApplication::startDragDistance())
1728                 return;
1729
1730         // did we hit something after all?
1731         int tab = tabAt(dragStartPos_);
1732         if (tab == -1)
1733                 return;
1734
1735         // simulate button release to remove highlight from button
1736         int i = currentIndex();
1737         QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1738                 event->button(), event->buttons(), 0);
1739         QTabBar::mouseReleaseEvent(&me);
1740         setCurrentIndex(i);
1741
1742         // initiate Drag
1743         QDrag * drag = new QDrag(this);
1744         QMimeData * mimeData = new QMimeData;
1745         // a crude way to distinguish tab-reodering drops from other ones
1746         mimeData->setData("action", "tab-reordering") ;
1747         drag->setMimeData(mimeData);
1748
1749 #if QT_VERSION >= 0x040300
1750         // get tab pixmap as cursor
1751         QRect r = tabRect(tab);
1752         QPixmap pixmap(r.size());
1753         render(&pixmap, - r.topLeft());
1754         drag->setPixmap(pixmap);
1755         drag->exec();
1756 #else
1757         drag->start(Qt::MoveAction);
1758 #endif
1759
1760 }
1761
1762
1763 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1764 {
1765         // Only accept if it's an tab-reordering request
1766         QMimeData const * m = event->mimeData();
1767         QStringList formats = m->formats();
1768         if (formats.contains("action")
1769             && m->data("action") == "tab-reordering")
1770                 event->acceptProposedAction();
1771 }
1772
1773
1774 void DragTabBar::dropEvent(QDropEvent * event)
1775 {
1776         int fromIndex = tabAt(dragStartPos_);
1777         int toIndex = tabAt(event->pos());
1778
1779         // Tell interested objects that
1780         if (fromIndex != toIndex)
1781                 tabMoveRequested(fromIndex, toIndex);
1782         event->acceptProposedAction();
1783 }
1784
1785
1786 } // namespace frontend
1787 } // namespace lyx
1788
1789 #include "moc_GuiWorkArea.cpp"