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