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