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