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