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