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