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