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