]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.cpp
have pointing cursor when hovering something clickable
[lyx.git] / src / frontends / qt4 / GuiWorkArea.cpp
1 /**
2  * \file GuiWorkArea.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  * \author Abdelrazak Younes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "GuiWorkArea.h"
15
16 #include "ColorCache.h"
17 #include "FontLoader.h"
18 #include "Menus.h"
19
20 #include "Buffer.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
24 #include "CoordCache.h"
25 #include "Cursor.h"
26 #include "Font.h"
27 #include "FuncRequest.h"
28 #include "GuiApplication.h"
29 #include "GuiCompleter.h"
30 #include "GuiKeySymbol.h"
31 #include "GuiPainter.h"
32 #include "GuiView.h"
33 #include "KeySymbol.h"
34 #include "Language.h"
35 #include "LyX.h"
36 #include "LyXRC.h"
37 #include "LyXVC.h"
38 #include "qt_helpers.h"
39 #include "Text.h"
40 #include "TextMetrics.h"
41 #include "version.h"
42
43 #include "graphics/GraphicsImage.h"
44 #include "graphics/GraphicsLoader.h"
45
46 #include "support/convert.h"
47 #include "support/debug.h"
48 #include "support/gettext.h"
49 #include "support/FileName.h"
50
51 #include "frontends/Application.h"
52 #include "frontends/FontMetrics.h"
53 #include "frontends/WorkAreaManager.h"
54
55 #include <QContextMenuEvent>
56 #include <QInputContext>
57 #include <QHelpEvent>
58 #ifdef Q_WS_MACX
59 #include <QMacStyle>
60 #endif
61 #include <QMainWindow>
62 #include <QMenu>
63 #include <QPainter>
64 #include <QPalette>
65 #include <QPixmapCache>
66 #include <QScrollBar>
67 #include <QTimer>
68 #include <QToolButton>
69 #include <QToolTip>
70 #include <QMenuBar>
71
72 #include "support/bind.h"
73
74 #include <cmath>
75
76 #ifdef Q_WS_WIN
77 int const CursorWidth = 2;
78 #else
79 int const CursorWidth = 1;
80 #endif
81 int const TabIndicatorWidth = 3;
82
83 #undef KeyPress
84 #undef NoModifier
85
86 using namespace std;
87 using namespace lyx::support;
88
89 namespace lyx {
90
91
92 /// return the LyX mouse button state from Qt's
93 static mouse_button::state q_button_state(Qt::MouseButton button)
94 {
95         mouse_button::state b = mouse_button::none;
96         switch (button) {
97                 case Qt::LeftButton:
98                         b = mouse_button::button1;
99                         break;
100                 case Qt::MidButton:
101                         b = mouse_button::button2;
102                         break;
103                 case Qt::RightButton:
104                         b = mouse_button::button3;
105                         break;
106                 default:
107                         break;
108         }
109         return b;
110 }
111
112
113 /// return the LyX mouse button state from Qt's
114 mouse_button::state q_motion_state(Qt::MouseButtons state)
115 {
116         mouse_button::state b = mouse_button::none;
117         if (state & Qt::LeftButton)
118                 b |= mouse_button::button1;
119         if (state & Qt::MidButton)
120                 b |= mouse_button::button2;
121         if (state & Qt::RightButton)
122                 b |= mouse_button::button3;
123         return b;
124 }
125
126
127 namespace frontend {
128
129 class CursorWidget {
130 public:
131         CursorWidget() {}
132
133         void draw(QPainter & painter)
134         {
135                 if (!show_ || !rect_.isValid())
136                         return;
137
138                 int y = rect_.top();
139                 int l = x_ - rect_.left();
140                 int r = rect_.right() - x_;
141                 int bot = rect_.bottom();
142
143                 // draw vertica linel
144                 painter.fillRect(x_, y, CursorWidth, rect_.height(), color_);
145
146                 // draw RTL/LTR indication
147                 painter.setPen(color_);
148                 if (l_shape_) {
149                         if (rtl_)
150                                 painter.drawLine(x_, bot, x_ - l, bot);
151                         else
152                                 painter.drawLine(x_, bot, x_ + CursorWidth + r, bot);
153                 }
154
155                 // draw completion triangle
156                 if (completable_) {
157                         int m = y + rect_.height() / 2;
158                         int d = TabIndicatorWidth - 1;
159                         if (rtl_) {
160                                 painter.drawLine(x_ - 1, m - d, x_ - 1 - d, m);
161                                 painter.drawLine(x_ - 1, m + d, x_ - 1 - d, m);
162                         } else {
163                                 painter.drawLine(x_ + CursorWidth, m - d, x_ + CursorWidth + d, m);
164                                 painter.drawLine(x_ + CursorWidth, m + d, x_ + CursorWidth + d, m);
165                         }
166                 }
167         }
168
169         void update(int x, int y, int h, bool l_shape,
170                 bool rtl, bool completable)
171         {
172                 color_ = guiApp->colorCache().get(Color_cursor);
173                 l_shape_ = l_shape;
174                 rtl_ = rtl;
175                 completable_ = completable;
176                 x_ = x;
177
178                 // extension to left and right
179                 int l = 0;
180                 int r = 0;
181
182                 // RTL/LTR indication
183                 if (l_shape_) {
184                         if (rtl)
185                                 l += h / 3;
186                         else
187                                 r += h / 3;
188                 }
189
190                 // completion triangle
191                 if (completable_) {
192                         if (rtl)
193                                 l = max(l, TabIndicatorWidth);
194                         else
195                                 r = max(r, TabIndicatorWidth);
196                 }
197
198                 // compute overall rectangle
199                 rect_ = QRect(x - l, y, CursorWidth + r + l, h);
200         }
201
202         void show(bool set_show = true) { show_ = set_show; }
203         void hide() { show_ = false; }
204
205         QRect const & rect() { return rect_; }
206
207 private:
208         /// cursor is in RTL or LTR text
209         bool rtl_;
210         /// indication for RTL or LTR
211         bool l_shape_;
212         /// triangle to show that a completion is available
213         bool completable_;
214         ///
215         bool show_;
216         ///
217         QColor color_;
218         /// rectangle, possibly with l_shape and completion triangle
219         QRect rect_;
220         /// x position (were the vertical line is drawn)
221         int x_;
222 };
223
224
225 // This is a 'heartbeat' generating synthetic mouse move events when the
226 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
227 SyntheticMouseEvent::SyntheticMouseEvent()
228         : timeout(200), restart_timeout(true)
229 {}
230
231
232 GuiWorkArea::GuiWorkArea(QWidget *)
233         : buffer_view_(0), lyx_view_(0),
234         cursor_visible_(false),
235         need_resize_(false), schedule_redraw_(false),
236         preedit_lines_(1), completer_(new GuiCompleter(this, this)),
237         context_target_pos_()
238 {
239 }
240
241
242 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & gv)
243         : buffer_view_(0), read_only_(buffer.isReadonly()), lyx_view_(0),
244         cursor_visible_(false),
245         need_resize_(false), schedule_redraw_(false),
246         preedit_lines_(1), completer_(new GuiCompleter(this, this)),
247         context_target_pos_()
248 {
249         setGuiView(gv);
250         setBuffer(buffer);
251         init();
252 }
253
254
255 void GuiWorkArea::init()
256 {
257         // Setup the signals
258         connect(&cursor_timeout_, SIGNAL(timeout()),
259                 this, SLOT(toggleCursor()));
260
261         int const time = QApplication::cursorFlashTime() / 2;
262         if (time > 0) {
263                 cursor_timeout_.setInterval(time);
264                 cursor_timeout_.start();
265         } else {
266                 // let's initialize this just to be safe
267                 cursor_timeout_.setInterval(500);
268         }
269
270         screen_ = QPixmap(viewport()->width(), viewport()->height());
271         // With Qt4.5 a mouse event will happen before the first paint event
272         // so make sure that the buffer view has an up to date metrics.
273         buffer_view_->resize(viewport()->width(), viewport()->height());
274         cursor_ = new frontend::CursorWidget();
275         cursor_->hide();
276
277         setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
278         setAcceptDrops(true);
279         setMouseTracking(true);
280         setMinimumSize(100, 70);
281         setFrameStyle(QFrame::NoFrame);
282         updateWindowTitle();
283
284         viewport()->setAutoFillBackground(false);
285         // We don't need double-buffering nor SystemBackground on
286         // the viewport because we have our own backing pixmap.
287         viewport()->setAttribute(Qt::WA_NoSystemBackground);
288
289         setFocusPolicy(Qt::StrongFocus);
290
291         setCursorShape(Qt::IBeamCursor);
292
293         synthetic_mouse_event_.timeout.timeout.connect(
294                 bind(&GuiWorkArea::generateSyntheticMouseEvent,
295                                         this));
296
297         // Initialize the vertical Scroll Bar
298         QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
299                 this, SLOT(scrollTo(int)));
300
301         LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
302                 << "  viewport height: " << viewport()->height());
303
304         // Enables input methods for asian languages.
305         // Must be set when creating custom text editing widgets.
306         setAttribute(Qt::WA_InputMethodEnabled, true);
307
308         dialog_mode_ = false;
309 }
310
311
312 GuiWorkArea::~GuiWorkArea()
313 {
314         buffer_view_->buffer().workAreaManager().remove(this);
315         delete buffer_view_;
316         delete cursor_;
317         // Completer has a QObject parent and is thus automatically destroyed.
318         // See #4758.
319         // delete completer_;
320 }
321
322
323 Qt::CursorShape GuiWorkArea::cursorShape() const
324 {
325         return viewport()->cursor().shape();
326 }
327
328 void GuiWorkArea::setCursorShape(Qt::CursorShape shape)
329 {
330         viewport()->setCursor(shape);
331 }
332
333 void GuiWorkArea::setGuiView(GuiView & gv)
334 {
335         lyx_view_ = &gv;
336 }
337
338
339 void GuiWorkArea::setBuffer(Buffer & buffer)
340 {
341         delete buffer_view_;
342         buffer_view_ = new BufferView(buffer);
343         buffer.workAreaManager().add(this);
344
345         // HACK: Prevents an additional redraw when the scrollbar pops up
346         // which regularily happens on documents with more than one page.
347         // The policy  should be set to "Qt::ScrollBarAsNeeded" soon.
348         // Since we have no geometry information yet, we assume that
349         // a document needs a scrollbar if there is more then four
350         // paragraph in the outermost text.
351         if (buffer.text().paragraphs().size() > 4)
352                 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
353         QTimer::singleShot(50, this, SLOT(fixVerticalScrollBar()));
354 }
355
356
357 void GuiWorkArea::fixVerticalScrollBar()
358 {
359         if (!isFullScreen())
360                 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
361 }
362
363
364 void GuiWorkArea::close()
365 {
366         lyx_view_->removeWorkArea(this);
367 }
368
369
370 void GuiWorkArea::setFullScreen(bool full_screen)
371 {
372         buffer_view_->setFullScreen(full_screen);
373         setFrameStyle(QFrame::NoFrame);
374         if (full_screen) {
375                 setFrameStyle(QFrame::NoFrame);
376                 if (lyxrc.full_screen_scrollbar)
377                         setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
378         } else
379                 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
380 }
381
382
383 BufferView & GuiWorkArea::bufferView()
384 {
385         return *buffer_view_;
386 }
387
388
389 BufferView const & GuiWorkArea::bufferView() const
390 {
391         return *buffer_view_;
392 }
393
394
395 void GuiWorkArea::stopBlinkingCursor()
396 {
397         cursor_timeout_.stop();
398         hideCursor();
399 }
400
401
402 void GuiWorkArea::startBlinkingCursor()
403 {
404         // do not show the cursor if the view is busy
405         if (view().busy())
406                 return;
407
408         Point p;
409         int h = 0;
410         buffer_view_->cursorPosAndHeight(p, h);
411         // Don't start blinking if the cursor isn't on screen.
412         if (!buffer_view_->cursorInView(p, h))
413                 return;
414
415         showCursor();
416
417         //we're not supposed to cache this value.
418         int const time = QApplication::cursorFlashTime() / 2;
419         if (time <= 0)
420                 return;
421         cursor_timeout_.setInterval(time);
422         cursor_timeout_.start();
423 }
424
425
426 void GuiWorkArea::redraw(bool update_metrics)
427 {
428         if (!isVisible())
429                 // No need to redraw in this case.
430                 return;
431
432         // No need to do anything if this is the current view. The BufferView
433         // metrics are already up to date.
434         if (update_metrics || lyx_view_ != guiApp->currentView()
435                 || lyx_view_->currentWorkArea() != this) {
436                 // FIXME: it would be nice to optimize for the off-screen case.
437                 buffer_view_->updateMetrics();
438                 buffer_view_->cursor().fixIfBroken();
439         }
440
441         // update cursor position, because otherwise it has to wait until
442         // the blinking interval is over
443         if (cursor_visible_) {
444                 hideCursor();
445                 showCursor();
446         }
447
448         LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
449         updateScreen();
450         update(0, 0, viewport()->width(), viewport()->height());
451
452         /// \warning: scrollbar updating *must* be done after the BufferView is drawn
453         /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
454         updateScrollbar();
455         lyx_view_->updateStatusBar();
456
457         if (lyxerr.debugging(Debug::WORKAREA))
458                 buffer_view_->coordCache().dump();
459
460         setReadOnly(buffer_view_->buffer().isReadonly());
461 }
462
463
464 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
465 {
466         if (lyx_view_->isFullScreen() && lyx_view_->menuBar()->isVisible()
467                 && lyxrc.full_screen_menubar) {
468                 // FIXME HACK: we should not have to do this here. See related comment
469                 // in GuiView::event() (QEvent::ShortcutOverride)
470                 lyx_view_->menuBar()->hide();
471         }
472
473         // In order to avoid bad surprise in the middle of an operation,
474         // we better stop the blinking cursor...
475         // the cursor gets restarted in GuiView::restartCursor()
476         stopBlinkingCursor();
477         guiApp->processKeySym(key, mod);
478 }
479
480
481 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
482 {
483         // Handle drag&drop
484         if (cmd0.action() == LFUN_FILE_OPEN) {
485                 DispatchResult dr;
486                 lyx_view_->dispatch(cmd0, dr);
487                 return;
488         }
489
490         FuncRequest cmd;
491
492         if (cmd0.action() == LFUN_MOUSE_PRESS) {
493                 if (mod == ShiftModifier)
494                         cmd = FuncRequest(cmd0, "region-select");
495                 else if (mod == ControlModifier)
496                         cmd = FuncRequest(cmd0, "paragraph-select");
497                 else
498                         cmd = cmd0;
499         }
500         else
501                 cmd = cmd0;
502
503         bool const notJustMovingTheMouse =
504                 cmd.action() != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
505
506         // In order to avoid bad surprise in the middle of an operation, we better stop
507         // the blinking cursor.
508         if (notJustMovingTheMouse)
509                 stopBlinkingCursor();
510
511         buffer_view_->mouseEventDispatch(cmd);
512
513         // Skip these when selecting
514         if (cmd.action() != LFUN_MOUSE_MOTION) {
515                 completer_->updateVisibility(false, false);
516                 lyx_view_->updateDialogs();
517                 lyx_view_->updateStatusBar();
518         }
519
520         // GUI tweaks except with mouse motion with no button pressed.
521         if (notJustMovingTheMouse) {
522                 // Slight hack: this is only called currently when we
523                 // clicked somewhere, so we force through the display
524                 // of the new status here.
525                 lyx_view_->clearMessage();
526
527                 // Show the cursor immediately after any operation
528                 startBlinkingCursor();
529         }
530
531         setCursorShape(buffer_view_->clickableInset() 
532                 ? Qt::PointingHandCursor : Qt::IBeamCursor);
533 }
534
535
536 void GuiWorkArea::resizeBufferView()
537 {
538         // WARNING: Please don't put any code that will trigger a repaint here!
539         // We are already inside a paint event.
540         lyx_view_->setBusy(true);
541         Point p;
542         int h = 0;
543         buffer_view_->cursorPosAndHeight(p, h);
544         bool const cursor_in_view = buffer_view_->cursorInView(p, h);
545         buffer_view_->resize(viewport()->width(), viewport()->height());
546         if (cursor_in_view)
547                 buffer_view_->scrollToCursor();
548         updateScreen();
549
550         // Update scrollbars which might have changed due different
551         // BufferView dimension. This is especially important when the
552         // BufferView goes from zero-size to the real-size for the first time,
553         // as the scrollbar paramters are then set for the first time.
554         updateScrollbar();
555
556         lyx_view_->updateLayoutList();
557         lyx_view_->setBusy(false);
558         need_resize_ = false;
559 }
560
561
562 void GuiWorkArea::showCursor()
563 {
564         if (cursor_visible_)
565                 return;
566
567         Point p;
568         int h = 0;
569         buffer_view_->cursorPosAndHeight(p, h);
570         if (!buffer_view_->cursorInView(p, h))
571                 return;
572
573         // RTL or not RTL
574         bool l_shape = false;
575         Font const & realfont = buffer_view_->cursor().real_current_font;
576         BufferParams const & bp = buffer_view_->buffer().params();
577         bool const samelang = realfont.language() == bp.language;
578         bool const isrtl = realfont.isVisibleRightToLeft();
579
580         if (!samelang || isrtl != bp.language->rightToLeft())
581                 l_shape = true;
582
583         // The ERT language hack needs fixing up
584         if (realfont.language() == latex_language)
585                 l_shape = false;
586
587         // show cursor on screen
588         Cursor & cur = buffer_view_->cursor();
589         bool completable = cur.inset().showCompletionCursor()
590                 && completer_->completionAvailable()
591                 && !completer_->popupVisible()
592                 && !completer_->inlineVisible();
593         cursor_visible_ = true;
594         showCursor(p.x_, p.y_, h, l_shape, isrtl, completable);
595 }
596
597
598 void GuiWorkArea::hideCursor()
599 {
600         if (!cursor_visible_)
601                 return;
602
603         cursor_visible_ = false;
604         removeCursor();
605 }
606
607
608 void GuiWorkArea::toggleCursor()
609 {
610         if (cursor_visible_)
611                 hideCursor();
612         else
613                 showCursor();
614 }
615
616
617 void GuiWorkArea::updateScrollbar()
618 {
619         ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
620         // WARNING: don't touch at the scrollbar value like this:
621         //   verticalScrollBar()->setValue(scroll_.position);
622         // because this would cause a recursive signal/slot calling with
623         // GuiWorkArea::scrollTo
624         verticalScrollBar()->setRange(scroll_.min, scroll_.max);
625         verticalScrollBar()->setPageStep(scroll_.page_step);
626         verticalScrollBar()->setSingleStep(scroll_.single_step);
627         verticalScrollBar()->setSliderPosition(scroll_.position);
628 }
629
630
631 void GuiWorkArea::scrollTo(int value)
632 {
633         stopBlinkingCursor();
634         buffer_view_->scrollDocView(value, true);
635
636         if (lyxrc.cursor_follows_scrollbar) {
637                 buffer_view_->setCursorFromScrollbar();
638                 lyx_view_->updateLayoutList();
639         }
640         // Show the cursor immediately after any operation.
641         startBlinkingCursor();
642         QApplication::syncX();
643 }
644
645
646 bool GuiWorkArea::event(QEvent * e)
647 {
648         switch (e->type()) {
649         case QEvent::ToolTip: {
650                 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
651                 if (lyxrc.use_tooltip) {
652                         QPoint pos = helpEvent->pos();
653                         if (pos.x() < viewport()->width()) {
654                                 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
655                                 QToolTip::showText(helpEvent->globalPos(), s);
656                         }
657                         else
658                                 QToolTip::hideText();
659                 }
660                 // Don't forget to accept the event!
661                 e->accept();
662                 return true;
663         }
664
665         case QEvent::ShortcutOverride: {
666                 // We catch this event in order to catch the Tab or Shift+Tab key press
667                 // which are otherwise reserved to focus switching between controls
668                 // within a dialog.
669                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
670                 if ((ke->key() == Qt::Key_Tab && ke->modifiers() == Qt::NoModifier)
671                         || (ke->key() == Qt::Key_Backtab && (
672                                 ke->modifiers() == Qt::ShiftModifier
673                                 || ke->modifiers() == Qt::NoModifier))) {
674                         keyPressEvent(ke);
675                         return true;
676                 }
677                 return QAbstractScrollArea::event(e);
678         }
679
680         default:
681                 return QAbstractScrollArea::event(e);
682         }
683         return false;
684 }
685
686
687 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
688 {
689         QPoint pos;
690         if (e->reason() == QContextMenuEvent::Mouse)
691                 // the position is set on mouse press
692                 pos = context_target_pos_;
693         else
694                 pos = e->pos();
695         Cursor const & cur = buffer_view_->cursor();
696         if (e->reason() == QContextMenuEvent::Keyboard && cur.inTexted()) {
697                 // Do not access the context menu of math right in front of before
698                 // the cursor. This does not work when the cursor is in text.
699                 Inset * inset = cur.paragraph().getInset(cur.pos());
700                 if (inset && inset->asInsetMath())
701                         --pos.rx();
702                 else if (cur.pos() > 0) {
703                         Inset * inset = cur.paragraph().getInset(cur.pos() - 1);
704                         if (inset)
705                                 ++pos.rx();
706                 }
707         }
708         docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
709         if (name.empty()) {
710                 QAbstractScrollArea::contextMenuEvent(e);
711                 return;
712         }
713         QMenu * menu = guiApp->menus().menu(toqstr(name), *lyx_view_);
714         if (!menu) {
715                 QAbstractScrollArea::contextMenuEvent(e);
716                 return;
717         }
718         // Position the menu to the right.
719         // FIXME: menu position should be different for RTL text.
720         menu->exec(e->globalPos());
721         e->accept();
722 }
723
724
725 void GuiWorkArea::focusInEvent(QFocusEvent * e)
726 {
727         LYXERR(Debug::DEBUG, "GuiWorkArea::focusInEvent(): " << this << endl);
728         if (lyx_view_->currentWorkArea() != this)
729                 lyx_view_->setCurrentWorkArea(this);
730
731         startBlinkingCursor();
732         QAbstractScrollArea::focusInEvent(e);
733 }
734
735
736 void GuiWorkArea::focusOutEvent(QFocusEvent * e)
737 {
738         LYXERR(Debug::DEBUG, "GuiWorkArea::focusOutEvent(): " << this << endl);
739         stopBlinkingCursor();
740         QAbstractScrollArea::focusOutEvent(e);
741 }
742
743
744 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
745 {
746         if (dc_event_.active && dc_event_ == *e) {
747                 dc_event_.active = false;
748                 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
749                         q_button_state(e->button()));
750                 dispatch(cmd);
751                 e->accept();
752                 return;
753         }
754
755         if (e->button() == Qt::RightButton)
756                 context_target_pos_ = e->pos();
757
758         inputContext()->reset();
759
760         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
761                 q_button_state(e->button()));
762         dispatch(cmd, q_key_state(e->modifiers()));
763         e->accept();
764 }
765
766
767 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
768 {
769         if (synthetic_mouse_event_.timeout.running())
770                 synthetic_mouse_event_.timeout.stop();
771
772         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
773                               q_button_state(e->button()));
774         dispatch(cmd);
775         e->accept();
776 }
777
778
779 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
780 {
781         // we kill the triple click if we move
782         doubleClickTimeout();
783         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
784                 q_motion_state(e->buttons()));
785
786         e->accept();
787
788         // If we're above or below the work area...
789         if ((e->y() <= 20 || e->y() >= viewport()->height() - 20)
790                         && e->buttons() == mouse_button::button1) {
791                 // Make sure only a synthetic event can cause a page scroll,
792                 // so they come at a steady rate:
793                 if (e->y() <= 20)
794                         // _Force_ a scroll up:
795                         cmd.set_y(e->y() - 21);
796                 else
797                         cmd.set_y(e->y() + 21);
798                 // Store the event, to be handled when the timeout expires.
799                 synthetic_mouse_event_.cmd = cmd;
800
801                 if (synthetic_mouse_event_.timeout.running()) {
802                         // Discard the event. Note that it _may_ be handled
803                         // when the timeout expires if
804                         // synthetic_mouse_event_.cmd has not been overwritten.
805                         // Ie, when the timeout expires, we handle the
806                         // most recent event but discard all others that
807                         // occurred after the one used to start the timeout
808                         // in the first place.
809                         return;
810                 }
811                 
812                 synthetic_mouse_event_.restart_timeout = true;
813                 synthetic_mouse_event_.timeout.start();
814                 // Fall through to handle this event...
815
816         } else if (synthetic_mouse_event_.timeout.running()) {
817                 // Store the event, to be possibly handled when the timeout
818                 // expires.
819                 // Once the timeout has expired, normal control is returned
820                 // to mouseMoveEvent (restart_timeout = false).
821                 // This results in a much smoother 'feel' when moving the
822                 // mouse back into the work area.
823                 synthetic_mouse_event_.cmd = cmd;
824                 synthetic_mouse_event_.restart_timeout = false;
825                 return;
826         }
827         dispatch(cmd);
828 }
829
830
831 void GuiWorkArea::wheelEvent(QWheelEvent * ev)
832 {
833         // Wheel rotation by one notch results in a delta() of 120 (see
834         // documentation of QWheelEvent)
835         double const delta = ev->delta() / 120.0;
836         bool zoom = false;
837         switch (lyxrc.scroll_wheel_zoom) {
838         case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
839                 zoom = ev->modifiers() & Qt::ControlModifier;
840                 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::AltModifier));
841                 break;
842         case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
843                 zoom = ev->modifiers() & Qt::ShiftModifier;
844                 zoom &= !(ev->modifiers() & (Qt::ControlModifier | Qt::AltModifier));
845                 break;
846         case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
847                 zoom = ev->modifiers() & Qt::AltModifier;
848                 zoom &= !(ev->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier));
849                 break;
850         case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
851                 break;
852         }
853         if (zoom) {
854                 docstring arg = convert<docstring>(int(5 * delta));
855                 lyx::dispatch(FuncRequest(LFUN_BUFFER_ZOOM_IN, arg));
856                 return;
857         }
858
859         // Take into account the desktop wide settings.
860         int const lines = qApp->wheelScrollLines();
861         int const page_step = verticalScrollBar()->pageStep();
862         // Test if the wheel mouse is set to one screen at a time.
863         int scroll_value = lines > page_step
864                 ? page_step : lines * verticalScrollBar()->singleStep();
865
866         // Take into account the rotation and the user preferences.
867         scroll_value = int(scroll_value * delta * lyxrc.mouse_wheel_speed);
868         LYXERR(Debug::SCROLLING, "wheelScrollLines = " << lines
869                         << " delta = " << delta << " scroll_value = " << scroll_value
870                         << " page_step = " << page_step);
871         // Now scroll.
872         verticalScrollBar()->setValue(verticalScrollBar()->value() - scroll_value);
873
874         ev->accept();
875 }
876
877
878 void GuiWorkArea::generateSyntheticMouseEvent()
879 {
880         int const e_y = synthetic_mouse_event_.cmd.y();
881         int const wh = buffer_view_->workHeight();
882         bool const up = e_y < 0;
883         bool const down = e_y > wh;
884
885         // Set things off to generate the _next_ 'pseudo' event.
886         int step = 50;
887         if (synthetic_mouse_event_.restart_timeout) {
888                 // This is some magic formulae to determine the speed
889                 // of scrolling related to the position of the mouse.
890                 int time = 200;
891                 if (up || down) {
892                         int dist = up ? -e_y : e_y - wh;
893                         time = max(min(200, 250000 / (dist * dist)), 1) ;
894                         
895                         if (time < 40) {
896                                 step = 80000 / (time * time);
897                                 time = 40;
898                         }
899                 }
900                 synthetic_mouse_event_.timeout.setTimeout(time);
901                 synthetic_mouse_event_.timeout.start();
902         }
903
904         // Can we scroll further ?
905         int const value = verticalScrollBar()->value();
906         if (value == verticalScrollBar()->maximum()
907                   || value == verticalScrollBar()->minimum()) {
908                 synthetic_mouse_event_.timeout.stop();
909                 return;
910         }
911
912         // Scroll
913         if (step <= 2 * wh) {
914                 buffer_view_->scroll(up ? -step : step);
915                 buffer_view_->updateMetrics();
916         } else {
917                 buffer_view_->scrollDocView(value + up ? -step : step, false);
918         }
919
920         // In which paragraph do we have to set the cursor ?
921         Cursor & cur = buffer_view_->cursor();
922         TextMetrics const & tm = buffer_view_->textMetrics(cur.text());
923
924         pair<pit_type, const ParagraphMetrics *> p = up ? tm.first() : tm.last();
925         ParagraphMetrics const & pm = *p.second;
926         pit_type const pit = p.first;
927
928         if (pm.rows().empty())
929                 return;
930
931         // Find the row at which we set the cursor.
932         RowList::const_iterator rit = pm.rows().begin();
933         RowList::const_iterator rlast = pm.rows().end();
934         int yy = pm.position() - pm.ascent();
935         for (--rlast; rit != rlast; ++rit) {
936                 int h = rit->height();
937                 if ((up && yy + h > 0)
938                           || (!up && yy + h > wh - defaultRowHeight()))
939                         break;
940                 yy += h;
941         }
942         
943         // Find the position of the cursor
944         bool bound;
945         int x = synthetic_mouse_event_.cmd.x();
946         pos_type const pos = rit->pos() + tm.getColumnNearX(pit, *rit, x, bound);
947
948         // Set the cursor
949         cur.pit() = pit;
950         cur.pos() = pos;
951         cur.boundary(bound);
952
953         buffer_view_->buffer().changed(false);
954         return;
955 }
956
957
958 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
959 {
960         // Do not process here some keys if dialog_mode_ is set
961         if (dialog_mode_
962                 && (ev->modifiers() == Qt::NoModifier
963                     || ev->modifiers() == Qt::ShiftModifier)
964                 && (ev->key() == Qt::Key_Escape
965                     || ev->key() == Qt::Key_Enter
966                     || ev->key() == Qt::Key_Return)
967             ) {
968                 ev->ignore();
969                 return;
970         }
971
972         // intercept some keys if completion popup is visible
973         if (completer_->popupVisible()) {
974                 switch (ev->key()) {
975                 case Qt::Key_Enter:
976                 case Qt::Key_Return:
977                         completer_->activate();
978                         ev->accept();
979                         return;
980                 }
981         }
982
983         // do nothing if there are other events
984         // (the auto repeated events come too fast)
985         // it looks like this is only needed on X11
986 #ifdef Q_WS_X11
987         if (qApp->hasPendingEvents() && ev->isAutoRepeat()) {
988                 LYXERR(Debug::KEY, "system is busy: keyPress event ignored");
989                 ev->ignore();
990                 return;
991         }
992 #endif
993
994         LYXERR(Debug::KEY, " count: " << ev->count() << " text: " << ev->text()
995                 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
996
997         KeySymbol sym;
998         setKeySymbol(&sym, ev);
999         if (sym.isOK()) {
1000                 processKeySym(sym, q_key_state(ev->modifiers()));
1001                 ev->accept();
1002         } else {
1003                 ev->ignore();
1004         }
1005 }
1006
1007
1008 void GuiWorkArea::doubleClickTimeout()
1009 {
1010         dc_event_.active = false;
1011 }
1012
1013
1014 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
1015 {
1016         dc_event_ = DoubleClick(ev);
1017         QTimer::singleShot(QApplication::doubleClickInterval(), this,
1018                            SLOT(doubleClickTimeout()));
1019         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
1020                         ev->x(), ev->y(),
1021                         q_button_state(ev->button()));
1022         dispatch(cmd);
1023         ev->accept();
1024 }
1025
1026
1027 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
1028 {
1029         QAbstractScrollArea::resizeEvent(ev);
1030         need_resize_ = true;
1031         ev->accept();
1032 }
1033
1034
1035 void GuiWorkArea::update(int x, int y, int w, int h)
1036 {
1037         viewport()->repaint(x, y, w, h);
1038 }
1039
1040
1041 void GuiWorkArea::paintEvent(QPaintEvent * ev)
1042 {
1043         QRect const rc = ev->rect();
1044         // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
1045         //      << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
1046
1047         if (need_resize_) {
1048                 screen_ = QPixmap(viewport()->width(), viewport()->height());
1049                 resizeBufferView();
1050                 if (cursor_visible_) {
1051                         hideCursor();
1052                         showCursor();
1053                 }
1054         }
1055
1056         QPainter pain(viewport());
1057         pain.drawPixmap(rc, screen_, rc);
1058         cursor_->draw(pain);
1059         ev->accept();
1060 }
1061
1062
1063 void GuiWorkArea::updateScreen()
1064 {
1065         GuiPainter pain(&screen_);
1066         buffer_view_->draw(pain);
1067 }
1068
1069
1070 void GuiWorkArea::showCursor(int x, int y, int h,
1071         bool l_shape, bool rtl, bool completable)
1072 {
1073         if (schedule_redraw_) {
1074                 // This happens when a graphic conversion is finished. As we don't know
1075                 // the size of the new graphics, it's better the update everything.
1076                 // We can't use redraw() here because this would trigger a infinite
1077                 // recursive loop with showCursor().
1078                 buffer_view_->resize(viewport()->width(), viewport()->height());
1079                 updateScreen();
1080                 updateScrollbar();
1081                 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
1082                 schedule_redraw_ = false;
1083                 // Show the cursor immediately after the update.
1084                 hideCursor();
1085                 toggleCursor();
1086                 return;
1087         }
1088
1089         cursor_->update(x, y, h, l_shape, rtl, completable);
1090         cursor_->show();
1091         viewport()->update(cursor_->rect());
1092 }
1093
1094
1095 void GuiWorkArea::removeCursor()
1096 {
1097         cursor_->hide();
1098         //if (!qApp->focusWidget())
1099                 viewport()->update(cursor_->rect());
1100 }
1101
1102
1103 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
1104 {
1105         QString const & commit_string = e->commitString();
1106         docstring const & preedit_string
1107                 = qstring_to_ucs4(e->preeditString());
1108
1109         if (!commit_string.isEmpty()) {
1110
1111                 LYXERR(Debug::KEY, "preeditString: " << e->preeditString()
1112                         << " commitString: " << e->commitString());
1113
1114                 int key = 0;
1115
1116                 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
1117                 for (int i = 0; i != commit_string.size(); ++i) {
1118                         QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
1119                         keyPressEvent(&ev);
1120                 }
1121         }
1122
1123         // Hide the cursor during the kana-kanji transformation.
1124         if (preedit_string.empty())
1125                 startBlinkingCursor();
1126         else
1127                 stopBlinkingCursor();
1128
1129         // last_width : for checking if last preedit string was/wasn't empty.
1130         static bool last_width = false;
1131         if (!last_width && preedit_string.empty()) {
1132                 // if last_width is last length of preedit string.
1133                 e->accept();
1134                 return;
1135         }
1136
1137         GuiPainter pain(&screen_);
1138         buffer_view_->updateMetrics();
1139         buffer_view_->draw(pain);
1140         FontInfo font = buffer_view_->cursor().getFont().fontInfo();
1141         FontMetrics const & fm = theFontMetrics(font);
1142         int height = fm.maxHeight();
1143         int cur_x = cursor_->rect().left();
1144         int cur_y = cursor_->rect().bottom();
1145
1146         // redraw area of preedit string.
1147         update(0, cur_y - height, viewport()->width(),
1148                 (height + 1) * preedit_lines_);
1149
1150         if (preedit_string.empty()) {
1151                 last_width = false;
1152                 preedit_lines_ = 1;
1153                 e->accept();
1154                 return;
1155         }
1156         last_width = true;
1157
1158         // att : stores an IM attribute.
1159         QList<QInputMethodEvent::Attribute> const & att = e->attributes();
1160
1161         // get attributes of input method cursor.
1162         // cursor_pos : cursor position in preedit string.
1163         size_t cursor_pos = 0;
1164         bool cursor_is_visible = false;
1165         for (int i = 0; i != att.size(); ++i) {
1166                 if (att.at(i).type == QInputMethodEvent::Cursor) {
1167                         cursor_pos = att.at(i).start;
1168                         cursor_is_visible = att.at(i).length != 0;
1169                         break;
1170                 }
1171         }
1172
1173         size_t preedit_length = preedit_string.length();
1174
1175         // get position of selection in input method.
1176         // FIXME: isn't there a way to do this simplier?
1177         // rStart : cursor position in selected string in IM.
1178         size_t rStart = 0;
1179         // rLength : selected string length in IM.
1180         size_t rLength = 0;
1181         if (cursor_pos < preedit_length) {
1182                 for (int i = 0; i != att.size(); ++i) {
1183                         if (att.at(i).type == QInputMethodEvent::TextFormat) {
1184                                 if (att.at(i).start <= int(cursor_pos)
1185                                         && int(cursor_pos) < att.at(i).start + att.at(i).length) {
1186                                                 rStart = att.at(i).start;
1187                                                 rLength = att.at(i).length;
1188                                                 if (!cursor_is_visible)
1189                                                         cursor_pos += rLength;
1190                                                 break;
1191                                 }
1192                         }
1193                 }
1194         }
1195         else {
1196                 rStart = cursor_pos;
1197                 rLength = 0;
1198         }
1199
1200         int const right_margin = buffer_view_->rightMargin();
1201         Painter::preedit_style ps;
1202         // Most often there would be only one line:
1203         preedit_lines_ = 1;
1204         for (size_t pos = 0; pos != preedit_length; ++pos) {
1205                 char_type const typed_char = preedit_string[pos];
1206                 // reset preedit string style
1207                 ps = Painter::preedit_default;
1208
1209                 // if we reached the right extremity of the screen, go to next line.
1210                 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
1211                         cur_x = right_margin;
1212                         cur_y += height + 1;
1213                         ++preedit_lines_;
1214                 }
1215                 // preedit strings are displayed with dashed underline
1216                 // and partial strings are displayed white on black indicating
1217                 // that we are in selecting mode in the input method.
1218                 // FIXME: rLength == preedit_length is not a changing condition
1219                 // FIXME: should be put out of the loop.
1220                 if (pos >= rStart
1221                         && pos < rStart + rLength
1222                         && !(cursor_pos < rLength && rLength == preedit_length))
1223                         ps = Painter::preedit_selecting;
1224
1225                 if (pos == cursor_pos
1226                         && (cursor_pos < rLength && rLength == preedit_length))
1227                         ps = Painter::preedit_cursor;
1228
1229                 // draw one character and update cur_x.
1230                 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
1231         }
1232
1233         // update the preedit string screen area.
1234         update(0, cur_y - preedit_lines_*height, viewport()->width(),
1235                 (height + 1) * preedit_lines_);
1236
1237         // Don't forget to accept the event!
1238         e->accept();
1239 }
1240
1241
1242 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
1243 {
1244         QRect cur_r(0, 0, 0, 0);
1245         switch (query) {
1246                 // this is the CJK-specific composition window position and
1247                 // the context menu position when the menu key is pressed.
1248                 case Qt::ImMicroFocus:
1249                         cur_r = cursor_->rect();
1250                         if (preedit_lines_ != 1)
1251                                 cur_r.moveLeft(10);
1252                         cur_r.moveBottom(cur_r.bottom()
1253                                 + cur_r.height() * (preedit_lines_ - 1));
1254                         // return lower right of cursor in LyX.
1255                         return cur_r;
1256                 default:
1257                         return QWidget::inputMethodQuery(query);
1258         }
1259 }
1260
1261
1262 void GuiWorkArea::updateWindowTitle()
1263 {
1264         docstring maximize_title;
1265         docstring minimize_title;
1266
1267         Buffer & buf = buffer_view_->buffer();
1268         FileName const fileName = buf.fileName();
1269         if (!fileName.empty()) {
1270                 maximize_title = fileName.displayName(30);
1271                 minimize_title = from_utf8(fileName.onlyFileName());
1272                 if (buf.lyxvc().inUse()) {
1273                         if (buf.lyxvc().locking())
1274                                 maximize_title +=  _(" (version control, locking)");
1275                         else
1276                                 maximize_title +=  _(" (version control)");
1277                 }
1278                 if (!buf.isClean()) {
1279                         maximize_title += _(" (changed)");
1280                         minimize_title += char_type('*');
1281                 }
1282                 if (buf.isReadonly())
1283                         maximize_title += _(" (read only)");
1284         }
1285
1286         QString title = windowTitle();
1287         QString new_title = toqstr(maximize_title);
1288         if (title == new_title)
1289                 return;
1290
1291         QWidget::setWindowTitle(new_title);
1292         QWidget::setWindowIconText(toqstr(minimize_title));
1293         titleChanged(this);
1294 }
1295
1296
1297 void GuiWorkArea::setReadOnly(bool read_only)
1298 {
1299         if (read_only_ == read_only)
1300                 return;
1301         read_only_ = read_only;
1302         updateWindowTitle();
1303         if (this == lyx_view_->currentWorkArea())
1304                 lyx_view_->updateDialogs();
1305 }
1306
1307
1308 bool GuiWorkArea::isFullScreen()
1309 {
1310         return lyx_view_ && lyx_view_->isFullScreen();
1311 }
1312
1313
1314 ////////////////////////////////////////////////////////////////////
1315 //
1316 // EmbeddedWorkArea
1317 //
1318 ////////////////////////////////////////////////////////////////////
1319
1320
1321 EmbeddedWorkArea::EmbeddedWorkArea(QWidget * w): GuiWorkArea(w)
1322 {
1323         buffer_ = theBufferList().newBuffer(
1324                 support::FileName::tempName().absFileName() + "_embedded.internal");
1325         buffer_->setUnnamed(true);
1326         buffer_->setFullyLoaded(true);
1327         setBuffer(*buffer_);
1328         setDialogMode(true);
1329 }
1330
1331
1332 EmbeddedWorkArea::~EmbeddedWorkArea()
1333 {
1334         // No need to destroy buffer and bufferview here, because it is done
1335         // in theBufferList() destruction loop at application exit
1336 }
1337
1338
1339 void EmbeddedWorkArea::closeEvent(QCloseEvent * ev)
1340 {
1341         disable();
1342         GuiWorkArea::closeEvent(ev);
1343 }
1344
1345
1346 void EmbeddedWorkArea::hideEvent(QHideEvent * ev)
1347 {
1348         disable();
1349         GuiWorkArea::hideEvent(ev);
1350 }
1351
1352
1353 QSize EmbeddedWorkArea::sizeHint () const
1354 {
1355         // FIXME(?):
1356         // GuiWorkArea sets the size to the screen's viewport
1357         // by returning a value this gets overridden
1358         // EmbeddedWorkArea is now sized to fit in the layout
1359         // of the parent, and has a minimum size set in GuiWorkArea
1360         // which is what we return here
1361         return QSize(100, 70);
1362 }
1363
1364
1365 void EmbeddedWorkArea::disable()
1366 {
1367         stopBlinkingCursor();
1368         if (view().currentWorkArea() != this)
1369                 return;
1370         // No problem if currentMainWorkArea() is 0 (setCurrentWorkArea()
1371         // tolerates it and shows the background logo), what happens if
1372         // an EmbeddedWorkArea is closed after closing all document WAs
1373         view().setCurrentWorkArea(view().currentMainWorkArea());
1374 }
1375
1376 ////////////////////////////////////////////////////////////////////
1377 //
1378 // TabWorkArea
1379 //
1380 ////////////////////////////////////////////////////////////////////
1381
1382 #ifdef Q_WS_MACX
1383 class NoTabFrameMacStyle : public QMacStyle {
1384 public:
1385         ///
1386         QRect subElementRect(SubElement element, const QStyleOption * option,
1387                              const QWidget * widget = 0) const
1388         {
1389                 QRect rect = QMacStyle::subElementRect(element, option, widget);
1390                 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1391
1392                 // The Qt Mac style puts the contents into a 3 pixel wide box
1393                 // which looks very ugly and not like other Mac applications.
1394                 // Hence we remove this here, and moreover the 16 pixel round
1395                 // frame above if the tab bar is hidden.
1396                 if (element == QStyle::SE_TabWidgetTabContents) {
1397                         rect.adjust(- rect.left(), 0, rect.left(), 0);
1398                         if (noBar)
1399                                 rect.setTop(0);
1400                 }
1401
1402                 return rect;
1403         }
1404 };
1405
1406 NoTabFrameMacStyle noTabFrameMacStyle;
1407 #endif
1408
1409
1410 TabWorkArea::TabWorkArea(QWidget * parent)
1411         : QTabWidget(parent), clicked_tab_(-1)
1412 {
1413 #ifdef Q_WS_MACX
1414         setStyle(&noTabFrameMacStyle);
1415 #endif
1416 #if QT_VERSION < 0x040500
1417         lyxrc.single_close_tab_button = true;
1418 #endif
1419
1420         QPalette pal = palette();
1421         pal.setColor(QPalette::Active, QPalette::Button,
1422                 pal.color(QPalette::Active, QPalette::Window));
1423         pal.setColor(QPalette::Disabled, QPalette::Button,
1424                 pal.color(QPalette::Disabled, QPalette::Window));
1425         pal.setColor(QPalette::Inactive, QPalette::Button,
1426                 pal.color(QPalette::Inactive, QPalette::Window));
1427
1428         QObject::connect(this, SIGNAL(currentChanged(int)),
1429                 this, SLOT(on_currentTabChanged(int)));
1430
1431         closeBufferButton = new QToolButton(this);
1432         closeBufferButton->setPalette(pal);
1433         // FIXME: rename the icon to closebuffer.png
1434         closeBufferButton->setIcon(QIcon(getPixmap("images/", "closetab", "png")));
1435         closeBufferButton->setText("Close File");
1436         closeBufferButton->setAutoRaise(true);
1437         closeBufferButton->setCursor(Qt::ArrowCursor);
1438         closeBufferButton->setToolTip(qt_("Close File"));
1439         closeBufferButton->setEnabled(true);
1440         QObject::connect(closeBufferButton, SIGNAL(clicked()),
1441                 this, SLOT(closeCurrentBuffer()));
1442         setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1443
1444         // setup drag'n'drop
1445         QTabBar* tb = new DragTabBar;
1446         connect(tb, SIGNAL(tabMoveRequested(int, int)),
1447                 this, SLOT(moveTab(int, int)));
1448         tb->setElideMode(Qt::ElideNone);
1449         setTabBar(tb);
1450
1451         // make us responsible for the context menu of the tabbar
1452         tb->setContextMenuPolicy(Qt::CustomContextMenu);
1453         connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1454                 this, SLOT(showContextMenu(const QPoint &)));
1455 #if QT_VERSION >= 0x040500
1456         connect(tb, SIGNAL(tabCloseRequested(int)),
1457                 this, SLOT(closeTab(int)));
1458 #endif
1459
1460         setUsesScrollButtons(true);
1461 }
1462
1463
1464 void TabWorkArea::mouseDoubleClickEvent(QMouseEvent * event)
1465 {
1466         if (event->button() != Qt::LeftButton)
1467                 return;
1468
1469         // return early if double click on existing tabs
1470         for (int i = 0; i < count(); ++i)
1471                 if (tabBar()->tabRect(i).contains(event->pos()))
1472                         return;
1473
1474         dispatch(FuncRequest(LFUN_BUFFER_NEW));
1475 }
1476
1477
1478 void TabWorkArea::setFullScreen(bool full_screen)
1479 {
1480         for (int i = 0; i != count(); ++i) {
1481                 if (GuiWorkArea * wa = workArea(i))
1482                         wa->setFullScreen(full_screen);
1483         }
1484
1485         if (lyxrc.full_screen_tabbar)
1486                 showBar(!full_screen && count() > 1);
1487 }
1488
1489
1490 void TabWorkArea::showBar(bool show)
1491 {
1492         tabBar()->setEnabled(show);
1493         tabBar()->setVisible(show);
1494         closeBufferButton->setVisible(show && lyxrc.single_close_tab_button);
1495 #if QT_VERSION >= 0x040500
1496         setTabsClosable(!lyxrc.single_close_tab_button);
1497 #endif
1498 }
1499
1500
1501 GuiWorkArea * TabWorkArea::currentWorkArea()
1502 {
1503         if (count() == 0)
1504                 return 0;
1505
1506         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1507         LASSERT(wa, /**/);
1508         return wa;
1509 }
1510
1511
1512 GuiWorkArea * TabWorkArea::workArea(int index)
1513 {
1514         return dynamic_cast<GuiWorkArea *>(widget(index));
1515 }
1516
1517
1518 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1519 {
1520         // FIXME: this method doesn't work if we have more than work area
1521         // showing the same buffer.
1522         for (int i = 0; i != count(); ++i) {
1523                 GuiWorkArea * wa = workArea(i);
1524                 LASSERT(wa, return 0);
1525                 if (&wa->bufferView().buffer() == &buffer)
1526                         return wa;
1527         }
1528         return 0;
1529 }
1530
1531
1532 void TabWorkArea::closeAll()
1533 {
1534         while (count()) {
1535                 GuiWorkArea * wa = workArea(0);
1536                 LASSERT(wa, /**/);
1537                 removeTab(0);
1538                 delete wa;
1539         }
1540 }
1541
1542
1543 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1544 {
1545         LASSERT(work_area, /**/);
1546         int index = indexOf(work_area);
1547         if (index == -1)
1548                 return false;
1549
1550         if (index == currentIndex())
1551                 // Make sure the work area is up to date.
1552                 on_currentTabChanged(index);
1553         else
1554                 // Switch to the work area.
1555                 setCurrentIndex(index);
1556         work_area->setFocus();
1557
1558         return true;
1559 }
1560
1561
1562 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1563 {
1564         GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1565         wa->setUpdatesEnabled(false);
1566         // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1567         // when hiding it again below).
1568         if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1569                 showBar(count() > 0);
1570         addTab(wa, wa->windowTitle());
1571         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1572                 this, SLOT(updateTabTexts()));
1573         if (currentWorkArea() && currentWorkArea()->isFullScreen())
1574                 setFullScreen(true);
1575         else
1576                 // Hide tabbar if there's only one tab.
1577                 showBar(count() > 1);
1578
1579         updateTabTexts();
1580
1581         return wa;
1582 }
1583
1584
1585 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1586 {
1587         LASSERT(work_area, return false);
1588         int index = indexOf(work_area);
1589         if (index == -1)
1590                 return false;
1591
1592         work_area->setUpdatesEnabled(false);
1593         removeTab(index);
1594         delete work_area;
1595
1596         if (count()) {
1597                 // make sure the next work area is enabled.
1598                 currentWidget()->setUpdatesEnabled(true);
1599                 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1600                         setFullScreen(true);
1601                 else
1602                         // Show tabbar only if there's more than one tab.
1603                         showBar(count() > 1);
1604         } else
1605                 lastWorkAreaRemoved();
1606
1607         updateTabTexts();
1608
1609         return true;
1610 }
1611
1612
1613 void TabWorkArea::on_currentTabChanged(int i)
1614 {
1615         // returns e.g. on application destruction
1616         if (i == -1)
1617                 return;
1618         GuiWorkArea * wa = workArea(i);
1619         LASSERT(wa, return);
1620         wa->setUpdatesEnabled(true);
1621         wa->redraw(true);
1622         wa->setFocus();
1623         ///
1624         currentWorkAreaChanged(wa);
1625
1626         LYXERR(Debug::GUI, "currentTabChanged " << i
1627                 << " File: " << wa->bufferView().buffer().absFileName());
1628 }
1629
1630
1631 void TabWorkArea::closeCurrentBuffer()
1632 {
1633         GuiWorkArea * wa;
1634         if (clicked_tab_ == -1)
1635                 wa = currentWorkArea();
1636         else {
1637                 wa = workArea(clicked_tab_);
1638                 LASSERT(wa, /**/);
1639         }
1640         wa->view().closeWorkArea(wa);
1641 }
1642
1643
1644 void TabWorkArea::hideCurrentTab()
1645 {
1646         GuiWorkArea * wa;
1647         if (clicked_tab_ == -1)
1648                 wa = currentWorkArea();
1649         else {
1650                 wa = workArea(clicked_tab_);
1651                 LASSERT(wa, /**/);
1652         }
1653         wa->view().hideWorkArea(wa);
1654 }
1655
1656
1657 void TabWorkArea::closeTab(int index)
1658 {
1659         on_currentTabChanged(index);
1660         GuiWorkArea * wa;
1661         if (index == -1)
1662                 wa = currentWorkArea();
1663         else {
1664                 wa = workArea(index);
1665                 LASSERT(wa, /**/);
1666         }
1667         wa->view().closeWorkArea(wa);
1668 }
1669
1670
1671 ///
1672 class DisplayPath {
1673 public:
1674         /// make vector happy
1675         DisplayPath() {}
1676         ///
1677         DisplayPath(int tab, FileName const & filename)
1678                 : tab_(tab)
1679         {
1680                 filename_ = (filename.extension() == "lyx") ?
1681                         toqstr(filename.onlyFileNameWithoutExt())
1682                         : toqstr(filename.onlyFileName());
1683                 postfix_ = toqstr(filename.absoluteFilePath()).
1684                         split("/", QString::SkipEmptyParts);
1685                 postfix_.pop_back();
1686                 abs_ = toqstr(filename.absoluteFilePath());
1687                 dottedPrefix_ = false;
1688         }
1689
1690         /// Absolute path for debugging.
1691         QString abs() const
1692         {
1693                 return abs_;
1694         }
1695         /// Add the first segment from the postfix or three dots to the prefix.
1696         /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1697         /// when really needed.
1698         void shiftPathSegment(bool dotted)
1699         {
1700                 if (postfix_.count() <= 0)
1701                         return;
1702
1703                 if (!dotted) {
1704                         if (dottedPrefix_ && !prefix_.isEmpty())
1705                                 prefix_ += ".../";
1706                         prefix_ += postfix_.front() + "/";
1707                 }
1708                 dottedPrefix_ = dotted && !prefix_.isEmpty();
1709                 postfix_.pop_front();
1710         }
1711         ///
1712         QString displayString() const
1713         {
1714                 if (prefix_.isEmpty())
1715                         return filename_;
1716
1717                 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1718                 return prefix_ + (dots ? ".../" : "") + filename_;
1719         }
1720         ///
1721         QString forecastPathString() const
1722         {
1723                 if (postfix_.count() == 0)
1724                         return displayString();
1725
1726                 return prefix_
1727                         + (dottedPrefix_ ? ".../" : "")
1728                         + postfix_.front() + "/";
1729         }
1730         ///
1731         bool final() const { return postfix_.empty(); }
1732         ///
1733         int tab() const { return tab_; }
1734
1735 private:
1736         ///
1737         QString prefix_;
1738         ///
1739         QStringList postfix_;
1740         ///
1741         QString filename_;
1742         ///
1743         QString abs_;
1744         ///
1745         int tab_;
1746         ///
1747         bool dottedPrefix_;
1748 };
1749
1750
1751 ///
1752 bool operator<(DisplayPath const & a, DisplayPath const & b)
1753 {
1754         return a.displayString() < b.displayString();
1755 }
1756
1757 ///
1758 bool operator==(DisplayPath const & a, DisplayPath const & b)
1759 {
1760         return a.displayString() == b.displayString();
1761 }
1762
1763
1764 void TabWorkArea::updateTabTexts()
1765 {
1766         size_t n = count();
1767         if (n == 0)
1768                 return;
1769         std::list<DisplayPath> paths;
1770         typedef std::list<DisplayPath>::iterator It;
1771
1772         // collect full names first: path into postfix, empty prefix and
1773         // filename without extension
1774         for (size_t i = 0; i < n; ++i) {
1775                 GuiWorkArea * i_wa = workArea(i);
1776                 FileName const fn = i_wa->bufferView().buffer().fileName();
1777                 paths.push_back(DisplayPath(i, fn));
1778         }
1779
1780         // go through path segments and see if it helps to make the path more unique
1781         bool somethingChanged = true;
1782         bool allFinal = false;
1783         while (somethingChanged && !allFinal) {
1784                 // adding path segments changes order
1785                 paths.sort();
1786
1787                 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1788                 somethingChanged = false;
1789                 allFinal = true;
1790
1791                 // find segments which are not unique (i.e. non-atomic)
1792                 It it = paths.begin();
1793                 It segStart = it;
1794                 QString segString = it->displayString();
1795                 for (; it != paths.end(); ++it) {
1796                         // look to the next item
1797                         It next = it;
1798                         ++next;
1799
1800                         // final?
1801                         allFinal = allFinal && it->final();
1802
1803                         LYXERR(Debug::GUI, "it = " << it->abs()
1804                                << " => " << it->displayString());
1805
1806                         // still the same segment?
1807                         QString nextString;
1808                         if ((next != paths.end()
1809                              && (nextString = next->displayString()) == segString))
1810                                 continue;
1811                         LYXERR(Debug::GUI, "segment ended");
1812
1813                         // only a trivial one with one element?
1814                         if (it == segStart) {
1815                                 // start new segment
1816                                 segStart = next;
1817                                 segString = nextString;
1818                                 continue;
1819                         }
1820
1821                         // we found a non-atomic segment segStart <= sit <= it < next.
1822                         // Shift path segments and hope for the best
1823                         // that it makes the path more unique.
1824                         somethingChanged = true;
1825                         It sit = segStart;
1826                         QString dspString = sit->forecastPathString();
1827                         LYXERR(Debug::GUI, "first forecast found for "
1828                                << sit->abs() << " => " << dspString);
1829                         ++sit;
1830                         bool moreUnique = false;
1831                         for (; sit != next; ++sit) {
1832                                 if (sit->forecastPathString() != dspString) {
1833                                         LYXERR(Debug::GUI, "different forecast found for "
1834                                                 << sit->abs() << " => " << sit->forecastPathString());
1835                                         moreUnique = true;
1836                                         break;
1837                                 }
1838                                 LYXERR(Debug::GUI, "same forecast found for "
1839                                         << sit->abs() << " => " << dspString);
1840                         }
1841
1842                         // if the path segment helped, add it. Otherwise add dots
1843                         bool dots = !moreUnique;
1844                         LYXERR(Debug::GUI, "using dots = " << dots);
1845                         for (sit = segStart; sit != next; ++sit) {
1846                                 sit->shiftPathSegment(dots);
1847                                 LYXERR(Debug::GUI, "shifting "
1848                                         << sit->abs() << " => " << sit->displayString());
1849                         }
1850
1851                         // start new segment
1852                         segStart = next;
1853                         segString = nextString;
1854                 }
1855         }
1856
1857         // set new tab titles
1858         for (It it = paths.begin(); it != paths.end(); ++it) {
1859                 GuiWorkArea * i_wa = workArea(it->tab());
1860                 Buffer & buf = i_wa->bufferView().buffer();
1861                 if (!buf.fileName().empty() && !buf.isClean())
1862                         setTabText(it->tab(), it->displayString() + "*");
1863                 else
1864                         setTabText(it->tab(), it->displayString());
1865         }
1866 }
1867
1868
1869 void TabWorkArea::showContextMenu(const QPoint & pos)
1870 {
1871         // which tab?
1872         clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1873         if (clicked_tab_ == -1)
1874                 return;
1875
1876         // show tab popup
1877         QMenu popup;
1878         popup.addAction(QIcon(getPixmap("images/", "hidetab", "png")),
1879                 qt_("Hide tab"), this, SLOT(hideCurrentTab()));
1880         popup.addAction(QIcon(getPixmap("images/", "closetab", "png")),
1881                 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1882         popup.exec(tabBar()->mapToGlobal(pos));
1883
1884         clicked_tab_ = -1;
1885 }
1886
1887
1888 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1889 {
1890         QWidget * w = widget(fromIndex);
1891         QIcon icon = tabIcon(fromIndex);
1892         QString text = tabText(fromIndex);
1893
1894         setCurrentIndex(fromIndex);
1895         removeTab(fromIndex);
1896         insertTab(toIndex, w, icon, text);
1897         setCurrentIndex(toIndex);
1898 }
1899
1900
1901 DragTabBar::DragTabBar(QWidget* parent)
1902         : QTabBar(parent)
1903 {
1904         setAcceptDrops(true);
1905 #if QT_VERSION >= 0x040500
1906         setTabsClosable(!lyxrc.single_close_tab_button);
1907 #endif
1908 }
1909
1910
1911 #if QT_VERSION < 0x040300
1912 int DragTabBar::tabAt(QPoint const & position) const
1913 {
1914         const int max = count();
1915         for (int i = 0; i < max; ++i) {
1916                 if (tabRect(i).contains(position))
1917                         return i;
1918         }
1919         return -1;
1920 }
1921 #endif
1922
1923
1924 void DragTabBar::mousePressEvent(QMouseEvent * event)
1925 {
1926         if (event->button() == Qt::LeftButton)
1927                 dragStartPos_ = event->pos();
1928         QTabBar::mousePressEvent(event);
1929 }
1930
1931
1932 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1933 {
1934         // If the left button isn't pressed anymore then return
1935         if (!(event->buttons() & Qt::LeftButton))
1936                 return;
1937
1938         // If the distance is too small then return
1939         if ((event->pos() - dragStartPos_).manhattanLength()
1940             < QApplication::startDragDistance())
1941                 return;
1942
1943         // did we hit something after all?
1944         int tab = tabAt(dragStartPos_);
1945         if (tab == -1)
1946                 return;
1947
1948         // simulate button release to remove highlight from button
1949         int i = currentIndex();
1950         QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1951                 event->button(), event->buttons(), 0);
1952         QTabBar::mouseReleaseEvent(&me);
1953         setCurrentIndex(i);
1954
1955         // initiate Drag
1956         QDrag * drag = new QDrag(this);
1957         QMimeData * mimeData = new QMimeData;
1958         // a crude way to distinguish tab-reodering drops from other ones
1959         mimeData->setData("action", "tab-reordering") ;
1960         drag->setMimeData(mimeData);
1961
1962 #if QT_VERSION >= 0x040300
1963         // get tab pixmap as cursor
1964         QRect r = tabRect(tab);
1965         QPixmap pixmap(r.size());
1966         render(&pixmap, - r.topLeft());
1967         drag->setPixmap(pixmap);
1968         drag->exec();
1969 #else
1970         drag->start(Qt::MoveAction);
1971 #endif
1972
1973 }
1974
1975
1976 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1977 {
1978         // Only accept if it's an tab-reordering request
1979         QMimeData const * m = event->mimeData();
1980         QStringList formats = m->formats();
1981         if (formats.contains("action")
1982             && m->data("action") == "tab-reordering")
1983                 event->acceptProposedAction();
1984 }
1985
1986
1987 void DragTabBar::dropEvent(QDropEvent * event)
1988 {
1989         int fromIndex = tabAt(dragStartPos_);
1990         int toIndex = tabAt(event->pos());
1991
1992         // Tell interested objects that
1993         if (fromIndex != toIndex)
1994                 tabMoveRequested(fromIndex, toIndex);
1995         event->acceptProposedAction();
1996 }
1997
1998
1999 } // namespace frontend
2000 } // namespace lyx
2001
2002 #include "moc_GuiWorkArea.cpp"