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