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