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