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