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