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