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