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