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