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