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