]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.cpp
cosmetics
[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_MACX
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 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
399 {
400         // Handle drag&drop
401         if (cmd0.action == LFUN_FILE_OPEN) {
402                 lyx_view_->dispatch(cmd0);
403                 return;
404         }
405
406         theLyXFunc().setLyXView(lyx_view_);
407
408         FuncRequest cmd;
409
410         if (cmd0.action == LFUN_MOUSE_PRESS) {
411                 if (mod == ShiftModifier)
412                         cmd = FuncRequest(cmd0, "region-select");
413                 else if (mod == ControlModifier)
414                         cmd = FuncRequest(cmd0, "paragraph-select");
415                 else
416                         cmd = cmd0;
417         }
418         else
419                 cmd = cmd0;
420
421         bool const notJustMovingTheMouse = 
422                 cmd.action != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
423         
424         // In order to avoid bad surprise in the middle of an operation, we better stop
425         // the blinking cursor.
426         if (notJustMovingTheMouse)
427                 stopBlinkingCursor();
428
429         buffer_view_->mouseEventDispatch(cmd);
430
431         // Skip these when selecting
432         if (cmd.action != LFUN_MOUSE_MOTION) {
433                 completer_.updateVisibility(false, false);
434                 lyx_view_->updateLayoutList();
435                 lyx_view_->updateToolbars();
436         }
437
438         // GUI tweaks except with mouse motion with no button pressed.
439         if (notJustMovingTheMouse) {
440                 // Slight hack: this is only called currently when we
441                 // clicked somewhere, so we force through the display
442                 // of the new status here.
443                 lyx_view_->clearMessage();
444
445                 // Show the cursor immediately after any operation
446                 startBlinkingCursor();
447         }
448 }
449
450
451 void GuiWorkArea::resizeBufferView()
452 {
453         // WARNING: Please don't put any code that will trigger a repaint here!
454         // We are already inside a paint event.
455         lyx_view_->setBusy(true);
456         buffer_view_->resize(viewport()->width(), viewport()->height());
457         updateScreen();
458
459         // Update scrollbars which might have changed due different
460         // BufferView dimension. This is especially important when the 
461         // BufferView goes from zero-size to the real-size for the first time,
462         // as the scrollbar paramters are then set for the first time.
463         updateScrollbar();
464         
465         lyx_view_->updateLayoutList();
466         lyx_view_->setBusy(false);
467         need_resize_ = false;
468 }
469
470
471 void GuiWorkArea::showCursor()
472 {
473         if (cursor_visible_)
474                 return;
475
476         // RTL or not RTL
477         bool l_shape = false;
478         Font const & realfont = buffer_view_->cursor().real_current_font;
479         BufferParams const & bp = buffer_view_->buffer().params();
480         bool const samelang = realfont.language() == bp.language;
481         bool const isrtl = realfont.isVisibleRightToLeft();
482
483         if (!samelang || isrtl != bp.language->rightToLeft())
484                 l_shape = true;
485
486         // The ERT language hack needs fixing up
487         if (realfont.language() == latex_language)
488                 l_shape = false;
489
490         Font const font = buffer_view_->cursor().getFont();
491         FontMetrics const & fm = theFontMetrics(font);
492         int const asc = fm.maxAscent();
493         int const des = fm.maxDescent();
494         int h = asc + des;
495         int x = 0;
496         int y = 0;
497         Cursor & cur = buffer_view_->cursor();
498         cur.getPos(x, y);
499         y -= asc;
500
501         // if it doesn't touch the screen, don't try to show it
502         bool cursorInView = true;
503         if (y + h < 0 || y >= viewport()->height())
504                 cursorInView = false;
505
506         // show cursor on screen
507         bool completable = cur.inset().showCompletionCursor()
508                 && completer_.completionAvailable()
509                 && !completer_.popupVisible()
510                 && !completer_.inlineVisible();
511         if (cursorInView) {
512                 cursor_visible_ = true;
513                 showCursor(x, y, h, l_shape, isrtl, completable);
514         }
515 }
516
517
518 void GuiWorkArea::hideCursor()
519 {
520         if (!cursor_visible_)
521                 return;
522
523         cursor_visible_ = false;
524         removeCursor();
525 }
526
527
528 void GuiWorkArea::toggleCursor()
529 {
530         if (cursor_visible_)
531                 hideCursor();
532         else
533                 showCursor();
534 }
535
536
537 void GuiWorkArea::updateScrollbar()
538 {
539         ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
540
541         verticalScrollBar()->setRange(scroll_.min, scroll_.max);
542         verticalScrollBar()->setPageStep(scroll_.page_step);
543         verticalScrollBar()->setSingleStep(scroll_.single_step);
544         // Block the scrollbar signal to prevent recursive signal/slot calling.
545         verticalScrollBar()->blockSignals(true);
546         verticalScrollBar()->setValue(scroll_.position);
547         verticalScrollBar()->setSliderPosition(scroll_.position);
548         verticalScrollBar()->blockSignals(false);
549 }
550
551
552 void GuiWorkArea::scrollTo(int value)
553 {
554         stopBlinkingCursor();
555         buffer_view_->scrollDocView(value);
556
557         if (lyxrc.cursor_follows_scrollbar) {
558                 buffer_view_->setCursorFromScrollbar();
559                 lyx_view_->updateLayoutList();
560         }
561         // Show the cursor immediately after any operation.
562         startBlinkingCursor();
563         QApplication::syncX();
564 }
565
566
567 bool GuiWorkArea::event(QEvent * e)
568 {
569         switch (e->type()) {
570         case QEvent::ToolTip: {
571                 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
572                 if (lyxrc.use_tooltip) {
573                         QPoint pos = helpEvent->pos();
574                         if (pos.x() < viewport()->width()) {
575                                 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
576                                 QToolTip::showText(helpEvent->globalPos(), s);
577                         }
578                         else
579                                 QToolTip::hideText();
580                 }
581                 // Don't forget to accept the event!
582                 e->accept();
583                 return true;
584         }
585
586         case QEvent::ShortcutOverride: {
587                 // We catch this event in order to catch the Tab or Shift+Tab key press
588                 // which are otherwise reserved to focus switching between controls
589                 // within a dialog.
590                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
591                 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
592                         || ke->modifiers() & Qt::ControlModifier)
593                         return QAbstractScrollArea::event(e);
594                 keyPressEvent(ke);
595                 return true;
596         }
597
598         default:
599                 return QAbstractScrollArea::event(e);
600         }
601         return false;
602 }
603
604
605 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
606 {
607         QPoint pos = e->pos();
608         docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
609         if (name.empty()) {
610                 QAbstractScrollArea::contextMenuEvent(e);
611                 return;
612         }
613         QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
614         if (!menu) {
615                 QAbstractScrollArea::contextMenuEvent(e);
616                 return;
617         }
618         // Position the menu to the right.
619         // FIXME: menu position should be different for RTL text.
620         menu->exec(e->globalPos());
621         e->accept();
622 }
623
624
625 void GuiWorkArea::focusInEvent(QFocusEvent * e)
626 {
627         if (lyx_view_->currentWorkArea() != this)
628                 lyx_view_->setCurrentWorkArea(this);
629
630         // Repaint the whole screen.
631         // Note: this is different from redraw() as only the backing pixmap
632         // will be redrawn, which is cheap.
633         viewport()->repaint();
634
635         startBlinkingCursor();
636         QAbstractScrollArea::focusInEvent(e);
637 }
638
639
640 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
641 {
642         stopBlinkingCursor();
643         QAbstractScrollArea::focusOutEvent(e);
644 }
645
646
647 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
648 {
649         if (dc_event_.active && dc_event_ == *e) {
650                 dc_event_.active = false;
651                 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
652                         q_button_state(e->button()));
653                 dispatch(cmd);
654                 e->accept();
655                 return;
656         }
657
658         inputContext()->reset();
659
660         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
661                 q_button_state(e->button()));
662         dispatch(cmd, q_key_state(e->modifiers()));
663         e->accept();
664 }
665
666
667 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
668 {
669         if (synthetic_mouse_event_.timeout.running())
670                 synthetic_mouse_event_.timeout.stop();
671
672         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
673                               q_button_state(e->button()));
674         dispatch(cmd);
675         e->accept();
676 }
677
678
679 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
680 {
681         // we kill the triple click if we move
682         doubleClickTimeout();
683         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
684                 q_motion_state(e->buttons()));
685
686         e->accept();
687
688         // If we're above or below the work area...
689         if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
690                 // Make sure only a synthetic event can cause a page scroll,
691                 // so they come at a steady rate:
692                 if (e->y() <= 20)
693                         // _Force_ a scroll up:
694                         cmd.y = -40;
695                 else
696                         cmd.y = viewport()->height();
697                 // Store the event, to be handled when the timeout expires.
698                 synthetic_mouse_event_.cmd = cmd;
699
700                 if (synthetic_mouse_event_.timeout.running())
701                         // Discard the event. Note that it _may_ be handled
702                         // when the timeout expires if
703                         // synthetic_mouse_event_.cmd has not been overwritten.
704                         // Ie, when the timeout expires, we handle the
705                         // most recent event but discard all others that
706                         // occurred after the one used to start the timeout
707                         // in the first place.
708                         return;
709
710                 synthetic_mouse_event_.restart_timeout = true;
711                 synthetic_mouse_event_.timeout.start();
712                 // Fall through to handle this event...
713
714         } else if (synthetic_mouse_event_.timeout.running()) {
715                 // Store the event, to be possibly handled when the timeout
716                 // expires.
717                 // Once the timeout has expired, normal control is returned
718                 // to mouseMoveEvent (restart_timeout = false).
719                 // This results in a much smoother 'feel' when moving the
720                 // mouse back into the work area.
721                 synthetic_mouse_event_.cmd = cmd;
722                 synthetic_mouse_event_.restart_timeout = false;
723                 return;
724         }
725
726         // Has anything changed on-screen since the last QMouseEvent
727         // was received?
728         double const scrollbar_value = verticalScrollBar()->value();
729         if (e->x() == synthetic_mouse_event_.x_old
730                 && e->y() == synthetic_mouse_event_.y_old
731                 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
732                 // Nothing changed on-screen since the last QMouseEvent.
733                 return;
734         }
735
736         // Yes something has changed. Store the params used to check this.
737         synthetic_mouse_event_.x_old = e->x();
738         synthetic_mouse_event_.y_old = e->y();
739         synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
740
741         // ... and dispatch the event to the LyX core.
742         dispatch(cmd);
743 }
744
745
746 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
747 {
748         // Wheel rotation by one notch results in a delta() of 120 (see
749         // documentation of QWheelEvent)
750         int delta = ev->delta() / 120;
751         if (ev->modifiers() & Qt::ControlModifier) {
752                 lyxrc.zoom -= 5 * delta;
753                 if (lyxrc.zoom < 10)
754                         lyxrc.zoom = 10;
755                 // The global QPixmapCache is used in GuiPainter to cache text
756                 // painting so we must reset it.
757                 QPixmapCache::clear();
758                 guiApp->fontLoader().update();
759                 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
760         } else {
761                 double const lines = qApp->wheelScrollLines()
762                         * lyxrc.mouse_wheel_speed * delta;
763                 LYXERR(Debug::SCROLLING, "wheelScrollLines = " << qApp->wheelScrollLines()
764                         << " delta = " << ev->delta() << " lines = " << lines);
765                 verticalScrollBar()->setValue(verticalScrollBar()->value() -
766                         int(lines *  verticalScrollBar()->singleStep()));
767         }
768         ev->accept();
769 }
770
771
772 void GuiWorkArea::generateSyntheticMouseEvent()
773 {
774         // Set things off to generate the _next_ 'pseudo' event.
775         if (synthetic_mouse_event_.restart_timeout)
776                 synthetic_mouse_event_.timeout.start();
777
778         // Has anything changed on-screen since the last timeout signal
779         // was received?
780         double const scrollbar_value = verticalScrollBar()->value();
781         if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
782                 // Yes it has. Store the params used to check this.
783                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
784
785                 // ... and dispatch the event to the LyX core.
786                 dispatch(synthetic_mouse_event_.cmd);
787         }
788 }
789
790
791 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
792 {
793         // intercept some keys if completion popup is visible
794         if (completer_.popupVisible()) {
795                 switch (ev->key()) {
796                 case Qt::Key_Enter:
797                 case Qt::Key_Return:
798                         completer_.activate();
799                         ev->accept();
800                         return;
801                 }
802         }
803         
804         // intercept keys for the completion
805         if (ev->key() == Qt::Key_Tab) {
806                 completer_.tab();
807                 ev->accept();
808                 return;
809         } 
810
811         if (completer_.popupVisible() && ev->key() == Qt::Key_Escape) {
812                 completer_.hidePopup();
813                 ev->accept();
814                 return;
815         }
816
817         if (completer_.inlineVisible() && ev->key() == Qt::Key_Escape) {
818                 completer_.hideInline();
819                 ev->accept();
820                 return;
821         }
822
823         // do nothing if there are other events
824         // (the auto repeated events come too fast)
825         // \todo FIXME: remove hard coded Qt keys, process the key binding
826 #ifdef Q_WS_X11
827         if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat() 
828                         && (Qt::Key_PageDown || Qt::Key_PageUp)) {
829                 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
830                 ev->ignore();
831                 return;
832         }
833 #endif
834
835         LYXERR(Debug::KEY, " count: " << ev->count()
836                 << " text: " << fromqstr(ev->text())
837                 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
838
839         KeySymbol sym;
840         setKeySymbol(&sym, ev);
841         processKeySym(sym, q_key_state(ev->modifiers()));
842         ev->accept();
843 }
844
845
846 void GuiWorkArea::doubleClickTimeout()
847 {
848         dc_event_.active = false;
849 }
850
851
852 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
853 {
854         dc_event_ = DoubleClick(ev);
855         QTimer::singleShot(QApplication::doubleClickInterval(), this,
856                            SLOT(doubleClickTimeout()));
857         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
858                         ev->x(), ev->y(),
859                         q_button_state(ev->button()));
860         dispatch(cmd);
861         ev->accept();
862 }
863
864
865 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
866 {
867         QAbstractScrollArea::resizeEvent(ev);
868         need_resize_ = true;
869         ev->accept();
870 }
871
872
873 void GuiWorkArea::update(int x, int y, int w, int h)
874 {
875         viewport()->repaint(x, y, w, h);
876 }
877
878
879 void GuiWorkArea::paintEvent(QPaintEvent * ev)
880 {
881         QRect const rc = ev->rect();
882         // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
883         //      << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
884
885         if (need_resize_) {
886                 screen_ = QPixmap(viewport()->width(), viewport()->height());
887                 resizeBufferView();
888                 hideCursor();
889                 showCursor();
890         }
891
892         QPainter pain(viewport());
893         pain.drawPixmap(rc, screen_, rc);
894         cursor_->draw(pain);
895         ev->accept();
896 }
897
898
899 void GuiWorkArea::updateScreen()
900 {
901         GuiPainter pain(&screen_);
902         buffer_view_->draw(pain);
903 }
904
905
906 void GuiWorkArea::showCursor(int x, int y, int h,
907         bool l_shape, bool rtl, bool completable)
908 {
909         if (schedule_redraw_) {
910                 buffer_view_->updateMetrics();
911                 updateScreen();
912                 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
913                 schedule_redraw_ = false;
914                 // Show the cursor immediately after the update.
915                 hideCursor();
916                 toggleCursor();
917                 return;
918         }
919
920         cursor_->update(x, y, h, l_shape, rtl, completable);
921         cursor_->show();
922         viewport()->update(cursor_->rect());
923 }
924
925
926 void GuiWorkArea::removeCursor()
927 {
928         cursor_->hide();
929         //if (!qApp->focusWidget())
930                 viewport()->update(cursor_->rect());
931 }
932
933
934 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
935 {
936         QString const & commit_string = e->commitString();
937         docstring const & preedit_string
938                 = qstring_to_ucs4(e->preeditString());
939
940         if (!commit_string.isEmpty()) {
941
942                 LYXERR(Debug::KEY, "preeditString: " << fromqstr(e->preeditString())
943                         << " commitString: " << fromqstr(e->commitString()));
944
945                 int key = 0;
946
947                 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
948                 for (int i = 0; i != commit_string.size(); ++i) {
949                         QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
950                         keyPressEvent(&ev);
951                 }
952         }
953
954         // Hide the cursor during the kana-kanji transformation.
955         if (preedit_string.empty())
956                 startBlinkingCursor();
957         else
958                 stopBlinkingCursor();
959
960         // last_width : for checking if last preedit string was/wasn't empty.
961         static bool last_width = false;
962         if (!last_width && preedit_string.empty()) {
963                 // if last_width is last length of preedit string.
964                 e->accept();
965                 return;
966         }
967
968         GuiPainter pain(&screen_);
969         buffer_view_->updateMetrics();
970         buffer_view_->draw(pain);
971         FontInfo font = buffer_view_->cursor().getFont().fontInfo();
972         FontMetrics const & fm = theFontMetrics(font);
973         int height = fm.maxHeight();
974         int cur_x = cursor_->rect().left();
975         int cur_y = cursor_->rect().bottom();
976
977         // redraw area of preedit string.
978         update(0, cur_y - height, viewport()->width(),
979                 (height + 1) * preedit_lines_);
980
981         if (preedit_string.empty()) {
982                 last_width = false;
983                 preedit_lines_ = 1;
984                 e->accept();
985                 return;
986         }
987         last_width = true;
988
989         // att : stores an IM attribute.
990         QList<QInputMethodEvent::Attribute> const & att = e->attributes();
991
992         // get attributes of input method cursor.
993         // cursor_pos : cursor position in preedit string.
994         size_t cursor_pos = 0;
995         bool cursor_is_visible = false;
996         for (int i = 0; i != att.size(); ++i) {
997                 if (att.at(i).type == QInputMethodEvent::Cursor) {
998                         cursor_pos = att.at(i).start;
999                         cursor_is_visible = att.at(i).length != 0;
1000                         break;
1001                 }
1002         }
1003
1004         size_t preedit_length = preedit_string.length();
1005
1006         // get position of selection in input method.
1007         // FIXME: isn't there a way to do this simplier?
1008         // rStart : cursor position in selected string in IM.
1009         size_t rStart = 0;
1010         // rLength : selected string length in IM.
1011         size_t rLength = 0;
1012         if (cursor_pos < preedit_length) {
1013                 for (int i = 0; i != att.size(); ++i) {
1014                         if (att.at(i).type == QInputMethodEvent::TextFormat) {
1015                                 if (att.at(i).start <= int(cursor_pos)
1016                                         && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1017                                                 rStart = att.at(i).start;
1018                                                 rLength = att.at(i).length;
1019                                                 if (!cursor_is_visible)
1020                                                         cursor_pos += rLength;
1021                                                 break;
1022                                 }
1023                         }
1024                 }
1025         }
1026         else {
1027                 rStart = cursor_pos;
1028                 rLength = 0;
1029         }
1030
1031         int const right_margin = buffer_view_->rightMargin();
1032         Painter::preedit_style ps;
1033         // Most often there would be only one line:
1034         preedit_lines_ = 1;
1035         for (size_t pos = 0; pos != preedit_length; ++pos) {
1036                 char_type const typed_char = preedit_string[pos];
1037                 // reset preedit string style
1038                 ps = Painter::preedit_default;
1039
1040                 // if we reached the right extremity of the screen, go to next line.
1041                 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1042                         cur_x = right_margin;
1043                         cur_y += height + 1;
1044                         ++preedit_lines_;
1045                 }
1046                 // preedit strings are displayed with dashed underline
1047                 // and partial strings are displayed white on black indicating
1048                 // that we are in selecting mode in the input method.
1049                 // FIXME: rLength == preedit_length is not a changing condition
1050                 // FIXME: should be put out of the loop.
1051                 if (pos >= rStart
1052                         && pos < rStart + rLength
1053                         && !(cursor_pos < rLength && rLength == preedit_length))
1054                         ps = Painter::preedit_selecting;
1055
1056                 if (pos == cursor_pos
1057                         && (cursor_pos < rLength && rLength == preedit_length))
1058                         ps = Painter::preedit_cursor;
1059
1060                 // draw one character and update cur_x.
1061                 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1062         }
1063
1064         // update the preedit string screen area.
1065         update(0, cur_y - preedit_lines_*height, viewport()->width(),
1066                 (height + 1) * preedit_lines_);
1067
1068         // Don't forget to accept the event!
1069         e->accept();
1070 }
1071
1072
1073 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1074 {
1075         QRect cur_r(0,0,0,0);
1076         switch (query) {
1077                 // this is the CJK-specific composition window position.
1078                 case Qt::ImMicroFocus:
1079                         cur_r = cursor_->rect();
1080                         if (preedit_lines_ != 1)
1081                                 cur_r.moveLeft(10);
1082                         cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
1083                         // return lower right of cursor in LyX.
1084                         return cur_r;
1085                 default:
1086                         return QWidget::inputMethodQuery(query);
1087         }
1088 }
1089
1090
1091 void GuiWorkArea::updateWindowTitle()
1092 {
1093         docstring maximize_title;
1094         docstring minimize_title;
1095
1096         Buffer & buf = buffer_view_->buffer();
1097         FileName const fileName = buf.fileName();
1098         if (!fileName.empty()) {
1099                 maximize_title = fileName.displayName(30);
1100                 minimize_title = from_utf8(fileName.onlyFileName());
1101                 if (!buf.isClean()) {
1102                         maximize_title += _(" (changed)");
1103                         minimize_title += char_type('*');
1104                 }
1105                 if (buf.isReadonly())
1106                         maximize_title += _(" (read only)");
1107         }
1108
1109         QString title = windowTitle();
1110         QString new_title = toqstr(maximize_title);
1111         if (title == new_title)
1112                 return;
1113
1114         QWidget::setWindowTitle(new_title);
1115         QWidget::setWindowIconText(toqstr(minimize_title));
1116         titleChanged(this);
1117 }
1118
1119
1120 void GuiWorkArea::setReadOnly(bool)
1121 {
1122         updateWindowTitle();
1123         if (this == lyx_view_->currentWorkArea())
1124                 lyx_view_->updateBufferDependent(false);
1125 }
1126
1127
1128 bool GuiWorkArea::isFullScreen()
1129 {
1130         return lyx_view_ && lyx_view_->isFullScreen();
1131 }
1132
1133
1134 ////////////////////////////////////////////////////////////////////
1135 //
1136 // TabWorkArea 
1137 //
1138 ////////////////////////////////////////////////////////////////////
1139
1140 #ifdef Q_WS_MACX
1141 class NoTabFrameMacStyle : public QMacStyle {
1142 public:
1143         ///
1144         QRect subElementRect(SubElement element, const QStyleOption * option,
1145                              const QWidget * widget = 0) const
1146         {
1147                 QRect rect = QMacStyle::subElementRect(element, option, widget);
1148                 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1149                 
1150                 // The Qt Mac style puts the contents into a 3 pixel wide box
1151                 // which looks very ugly and not like other Mac applications.
1152                 // Hence we remove this here, and moreover the 16 pixel round
1153                 // frame above if the tab bar is hidden.
1154                 if (element == QStyle::SE_TabWidgetTabContents) {
1155                         rect.adjust(- rect.left(), 0, rect.left(), 0);
1156                         if (noBar)
1157                                 rect.setTop(0);
1158                 }
1159
1160                 return rect;
1161         }
1162 };
1163
1164 NoTabFrameMacStyle noTabFrameMacStyle;
1165 #endif
1166
1167
1168 TabWorkArea::TabWorkArea(QWidget * parent)
1169         : QTabWidget(parent), clicked_tab_(-1)
1170 {
1171 #ifdef Q_WS_MACX
1172         setStyle(&noTabFrameMacStyle);
1173 #endif
1174
1175         QPalette pal = palette();
1176         pal.setColor(QPalette::Active, QPalette::Button,
1177                 pal.color(QPalette::Active, QPalette::Window));
1178         pal.setColor(QPalette::Disabled, QPalette::Button,
1179                 pal.color(QPalette::Disabled, QPalette::Window));
1180         pal.setColor(QPalette::Inactive, QPalette::Button,
1181                 pal.color(QPalette::Inactive, QPalette::Window));
1182
1183         QObject::connect(this, SIGNAL(currentChanged(int)),
1184                 this, SLOT(on_currentTabChanged(int)));
1185
1186         QToolButton * closeBufferButton = new QToolButton(this);
1187         closeBufferButton->setPalette(pal);
1188         // FIXME: rename the icon to closebuffer.png
1189         closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1190         closeBufferButton->setText("Close File");
1191         closeBufferButton->setAutoRaise(true);
1192         closeBufferButton->setCursor(Qt::ArrowCursor);
1193         closeBufferButton->setToolTip(qt_("Close File"));
1194         closeBufferButton->setEnabled(true);
1195         QObject::connect(closeBufferButton, SIGNAL(clicked()),
1196                 this, SLOT(closeCurrentBuffer()));
1197         setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1198         
1199         // setup drag'n'drop
1200         QTabBar* tb = new DragTabBar;
1201         connect(tb, SIGNAL(tabMoveRequested(int, int)),
1202                 this, SLOT(moveTab(int, int)));
1203         setTabBar(tb);
1204
1205         // make us responsible for the context menu of the tabbar
1206         tb->setContextMenuPolicy(Qt::CustomContextMenu);
1207         connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1208                 this, SLOT(showContextMenu(const QPoint &)));
1209         
1210         setUsesScrollButtons(true);
1211 }
1212
1213
1214 void TabWorkArea::setFullScreen(bool full_screen)
1215 {
1216         for (int i = 0; i != count(); ++i) {
1217                 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1218                         wa->setFullScreen(full_screen);
1219         }
1220
1221         if (lyxrc.full_screen_tabbar)
1222                 showBar(!full_screen && count()>1);
1223 }
1224
1225
1226 void TabWorkArea::showBar(bool show)
1227 {
1228         tabBar()->setEnabled(show);
1229         tabBar()->setVisible(show);
1230 }
1231
1232
1233 GuiWorkArea * TabWorkArea::currentWorkArea()
1234 {
1235         if (count() == 0)
1236                 return 0;
1237
1238         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget()); 
1239         BOOST_ASSERT(wa);
1240         return wa;
1241 }
1242
1243
1244 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1245 {
1246         for (int i = 0; i != count(); ++i) {
1247                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1248                 BOOST_ASSERT(wa);
1249                 if (&wa->bufferView().buffer() == &buffer)
1250                         return wa;
1251         }
1252         return 0;
1253 }
1254
1255
1256 void TabWorkArea::closeAll()
1257 {
1258         while (count()) {
1259                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1260                 BOOST_ASSERT(wa);
1261                 removeTab(0);
1262                 delete wa;
1263         }
1264 }
1265
1266
1267 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1268 {
1269         BOOST_ASSERT(work_area);
1270         int index = indexOf(work_area);
1271         if (index == -1)
1272                 return false;
1273
1274         if (index == currentIndex())
1275                 // Make sure the work area is up to date.
1276                 on_currentTabChanged(index);
1277         else
1278                 // Switch to the work area.
1279                 setCurrentIndex(index);
1280         work_area->setFocus();
1281
1282         return true;
1283 }
1284
1285
1286 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1287 {
1288         GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1289         wa->setUpdatesEnabled(false);
1290         // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1291         // when hiding it again below).
1292         if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1293                 showBar(count() > 0);
1294         addTab(wa, wa->windowTitle());
1295         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1296                 this, SLOT(updateTabText(GuiWorkArea *)));
1297         if (currentWorkArea() && currentWorkArea()->isFullScreen())
1298                 setFullScreen(true);
1299         else
1300                 // Hide tabbar if there's only one tab.
1301                 showBar(count() > 1);
1302
1303         return wa;
1304 }
1305
1306
1307 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1308 {
1309         BOOST_ASSERT(work_area);
1310         int index = indexOf(work_area);
1311         if (index == -1)
1312                 return false;
1313
1314         work_area->setUpdatesEnabled(false);
1315         removeTab(index);
1316         delete work_area;
1317
1318         if (count()) {
1319                 // make sure the next work area is enabled.
1320                 currentWidget()->setUpdatesEnabled(true);
1321                 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1322                         setFullScreen(true);
1323                 else
1324                         // Hide tabbar if there's only one tab.
1325                         showBar(count() > 1);
1326         } else
1327                 lastWorkAreaRemoved();
1328
1329         return true;
1330 }
1331
1332
1333 void TabWorkArea::on_currentTabChanged(int i)
1334 {
1335         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1336         BOOST_ASSERT(wa);
1337         BufferView & bv = wa->bufferView();
1338         bv.cursor().fixIfBroken();
1339         bv.updateMetrics();
1340         wa->setUpdatesEnabled(true);
1341         wa->redraw();
1342         wa->setFocus();
1343         ///
1344         currentWorkAreaChanged(wa);
1345
1346         LYXERR(Debug::GUI, "currentTabChanged " << i
1347                 << "File" << bv.buffer().absFileName());
1348 }
1349
1350
1351 void TabWorkArea::closeCurrentBuffer()
1352 {
1353         if (clicked_tab_ != -1)
1354                 setCurrentIndex(clicked_tab_);
1355
1356         lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1357 }
1358
1359
1360 void TabWorkArea::closeCurrentTab()
1361 {
1362         if (clicked_tab_ == -1)
1363                 removeWorkArea(currentWorkArea());
1364         else {
1365                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_)); 
1366                 BOOST_ASSERT(wa);
1367                 removeWorkArea(wa);
1368         }
1369 }
1370
1371
1372 void TabWorkArea::updateTabText(GuiWorkArea * wa)
1373 {
1374         int const i = indexOf(wa);
1375         if (i < 0)
1376                 return;
1377         setTabText(i, wa->windowTitle());
1378 }
1379
1380
1381 void TabWorkArea::showContextMenu(const QPoint & pos)
1382 {
1383         // which tab?
1384         clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1385         if (clicked_tab_ != -1) {
1386                 // show tab popup
1387                 QMenu popup;
1388                 popup.addAction(QIcon(":/images/hidetab.png"),
1389                          qt_("Hide tab"), this, SLOT(closeCurrentTab()));
1390                 popup.addAction(QIcon(":/images/closetab.png"),
1391                          qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1392                 popup.exec(tabBar()->mapToGlobal(pos));
1393                 
1394                 clicked_tab_ = -1;
1395         }
1396 }
1397
1398
1399 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1400 {
1401         QWidget * w = widget(fromIndex);
1402         QIcon icon = tabIcon(fromIndex);
1403         QString text = tabText(fromIndex);
1404
1405         setCurrentIndex(fromIndex);
1406         removeTab(fromIndex);
1407         insertTab(toIndex, w, icon, text);
1408         setCurrentIndex(toIndex);
1409 }
1410         
1411
1412 DragTabBar::DragTabBar(QWidget* parent)
1413         : QTabBar(parent)
1414 {
1415         setAcceptDrops(true);
1416 }
1417
1418
1419 #if QT_VERSION < 0x040300
1420 int DragTabBar::tabAt(QPoint const & position) const
1421 {
1422         const int max = count();
1423         for (int i = 0; i < max; ++i) {
1424                 if (tabRect(i).contains(position))
1425                         return i;
1426         }
1427         return -1;
1428 }
1429 #endif
1430
1431
1432 void DragTabBar::mousePressEvent(QMouseEvent * event)
1433 {
1434         if (event->button() == Qt::LeftButton)
1435                 dragStartPos_ = event->pos();
1436         QTabBar::mousePressEvent(event);
1437 }
1438
1439
1440 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1441 {
1442         // If the left button isn't pressed anymore then return
1443         if (!(event->buttons() & Qt::LeftButton))
1444                 return;
1445         
1446         // If the distance is too small then return
1447         if ((event->pos() - dragStartPos_).manhattanLength()
1448             < QApplication::startDragDistance())
1449                 return;
1450
1451         // did we hit something after all?
1452         int tab = tabAt(dragStartPos_);
1453         if (tab == -1)
1454                 return;
1455         
1456         // simulate button release to remove highlight from button
1457         int i = currentIndex();
1458         QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1459                 event->button(), event->buttons(), 0);
1460         QTabBar::mouseReleaseEvent(&me);
1461         setCurrentIndex(i);
1462         
1463         // initiate Drag
1464         QDrag * drag = new QDrag(this);
1465         QMimeData * mimeData = new QMimeData;
1466         // a crude way to distinguish tab-reodering drops from other ones
1467         mimeData->setData("action", "tab-reordering") ;
1468         drag->setMimeData(mimeData);
1469         
1470 #if QT_VERSION >= 0x040300
1471         // get tab pixmap as cursor
1472         QRect r = tabRect(tab);
1473         QPixmap pixmap(r.size());
1474         render(&pixmap, - r.topLeft());
1475         drag->setPixmap(pixmap);
1476         drag->exec();
1477 #else
1478         drag->start(Qt::MoveAction);
1479 #endif
1480         
1481 }
1482
1483
1484 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1485 {
1486         // Only accept if it's an tab-reordering request
1487         QMimeData const * m = event->mimeData();
1488         QStringList formats = m->formats();
1489         if (formats.contains("action") 
1490             && m->data("action") == "tab-reordering")
1491                 event->acceptProposedAction();
1492 }
1493
1494
1495 void DragTabBar::dropEvent(QDropEvent * event)
1496 {
1497         int fromIndex = tabAt(dragStartPos_);
1498         int toIndex = tabAt(event->pos());
1499         
1500         // Tell interested objects that 
1501         if (fromIndex != toIndex)
1502                 tabMoveRequested(fromIndex, toIndex);
1503         event->acceptProposedAction();
1504 }
1505
1506
1507 } // namespace frontend
1508 } // namespace lyx
1509
1510 #include "GuiWorkArea_moc.cpp"