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