]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.cpp
Create a new EmbeddedWorkArea for dialog embedding purpose and use that in FindAndRep...
[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 {
1228         buffer_ = theBufferList().newBuffer(
1229                 support::FileName::tempName().absFilename() + "_embedded.internal");
1230         LASSERT(buffer_ != 0, /* */);
1231
1232         buffer_->setUnnamed(true);
1233         buffer_->setFullyLoaded(true);
1234         setBuffer(*buffer_);
1235         setUpdatesEnabled(false);
1236         setDialogMode(true);
1237 }
1238
1239 EmbeddedWorkArea::~EmbeddedWorkArea()
1240 {
1241         // No need to destroy buffer and bufferview here, because it is done
1242         // in theBuffeerList() destruction loop at application exit
1243         LYXERR(Debug::DEBUG, "FindAndReplace::~FindAndReplace()");
1244 }
1245
1246
1247
1248
1249 ////////////////////////////////////////////////////////////////////
1250 //
1251 // TabWorkArea
1252 //
1253 ////////////////////////////////////////////////////////////////////
1254
1255 #ifdef Q_WS_MACX
1256 class NoTabFrameMacStyle : public QMacStyle {
1257 public:
1258         ///
1259         QRect subElementRect(SubElement element, const QStyleOption * option,
1260                              const QWidget * widget = 0) const
1261         {
1262                 QRect rect = QMacStyle::subElementRect(element, option, widget);
1263                 bool noBar = static_cast<QTabWidget const *>(widget)->count() <= 1;
1264
1265                 // The Qt Mac style puts the contents into a 3 pixel wide box
1266                 // which looks very ugly and not like other Mac applications.
1267                 // Hence we remove this here, and moreover the 16 pixel round
1268                 // frame above if the tab bar is hidden.
1269                 if (element == QStyle::SE_TabWidgetTabContents) {
1270                         rect.adjust(- rect.left(), 0, rect.left(), 0);
1271                         if (noBar)
1272                                 rect.setTop(0);
1273                 }
1274
1275                 return rect;
1276         }
1277 };
1278
1279 NoTabFrameMacStyle noTabFrameMacStyle;
1280 #endif
1281
1282
1283 TabWorkArea::TabWorkArea(QWidget * parent)
1284         : QTabWidget(parent), clicked_tab_(-1)
1285 {
1286 #ifdef Q_WS_MACX
1287         setStyle(&noTabFrameMacStyle);
1288 #endif
1289
1290         QPalette pal = palette();
1291         pal.setColor(QPalette::Active, QPalette::Button,
1292                 pal.color(QPalette::Active, QPalette::Window));
1293         pal.setColor(QPalette::Disabled, QPalette::Button,
1294                 pal.color(QPalette::Disabled, QPalette::Window));
1295         pal.setColor(QPalette::Inactive, QPalette::Button,
1296                 pal.color(QPalette::Inactive, QPalette::Window));
1297
1298         QObject::connect(this, SIGNAL(currentChanged(int)),
1299                 this, SLOT(on_currentTabChanged(int)));
1300
1301         QToolButton * closeBufferButton = new QToolButton(this);
1302         closeBufferButton->setPalette(pal);
1303         // FIXME: rename the icon to closebuffer.png
1304         closeBufferButton->setIcon(QIcon(":/images/closetab.png"));
1305         closeBufferButton->setText("Close File");
1306         closeBufferButton->setAutoRaise(true);
1307         closeBufferButton->setCursor(Qt::ArrowCursor);
1308         closeBufferButton->setToolTip(qt_("Close File"));
1309         closeBufferButton->setEnabled(true);
1310         QObject::connect(closeBufferButton, SIGNAL(clicked()),
1311                 this, SLOT(closeCurrentBuffer()));
1312         setCornerWidget(closeBufferButton, Qt::TopRightCorner);
1313
1314         // setup drag'n'drop
1315         QTabBar* tb = new DragTabBar;
1316         connect(tb, SIGNAL(tabMoveRequested(int, int)),
1317                 this, SLOT(moveTab(int, int)));
1318         tb->setElideMode(Qt::ElideNone);
1319         setTabBar(tb);
1320
1321         // make us responsible for the context menu of the tabbar
1322         tb->setContextMenuPolicy(Qt::CustomContextMenu);
1323         connect(tb, SIGNAL(customContextMenuRequested(const QPoint &)),
1324                 this, SLOT(showContextMenu(const QPoint &)));
1325
1326         setUsesScrollButtons(true);
1327 }
1328
1329
1330 void TabWorkArea::setFullScreen(bool full_screen)
1331 {
1332         for (int i = 0; i != count(); ++i) {
1333                 if (GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i)))
1334                         wa->setFullScreen(full_screen);
1335         }
1336
1337         if (lyxrc.full_screen_tabbar)
1338                 showBar(!full_screen && count()>1);
1339 }
1340
1341
1342 void TabWorkArea::showBar(bool show)
1343 {
1344         tabBar()->setEnabled(show);
1345         tabBar()->setVisible(show);
1346 }
1347
1348
1349 GuiWorkArea * TabWorkArea::currentWorkArea()
1350 {
1351         if (count() == 0)
1352                 return 0;
1353
1354         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
1355         LASSERT(wa, /**/);
1356         return wa;
1357 }
1358
1359
1360 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1361 {
1362         for (int i = 0; i != count(); ++i) {
1363                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1364                 LASSERT(wa, return 0);
1365                 if (&wa->bufferView().buffer() == &buffer)
1366                         return wa;
1367         }
1368         return 0;
1369 }
1370
1371
1372 void TabWorkArea::closeAll()
1373 {
1374         while (count()) {
1375                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1376                 LASSERT(wa, /**/);
1377                 removeTab(0);
1378                 delete wa;
1379         }
1380 }
1381
1382
1383 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1384 {
1385         LASSERT(work_area, /**/);
1386         int index = indexOf(work_area);
1387         if (index == -1)
1388                 return false;
1389
1390         if (index == currentIndex())
1391                 // Make sure the work area is up to date.
1392                 on_currentTabChanged(index);
1393         else
1394                 // Switch to the work area.
1395                 setCurrentIndex(index);
1396         work_area->setFocus();
1397
1398         return true;
1399 }
1400
1401
1402 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1403 {
1404         GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1405         wa->setUpdatesEnabled(false);
1406         // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1407         // when hiding it again below).
1408         if (!(currentWorkArea() && currentWorkArea()->isFullScreen()))
1409                 showBar(count() > 0);
1410         addTab(wa, wa->windowTitle());
1411         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1412                 this, SLOT(updateTabTexts()));
1413         if (currentWorkArea() && currentWorkArea()->isFullScreen())
1414                 setFullScreen(true);
1415         else
1416                 // Hide tabbar if there's only one tab.
1417                 showBar(count() > 1);
1418
1419         updateTabTexts();
1420
1421         return wa;
1422 }
1423
1424
1425 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1426 {
1427         LASSERT(work_area, return false);
1428         int index = indexOf(work_area);
1429         if (index == -1)
1430                 return false;
1431
1432         work_area->setUpdatesEnabled(false);
1433         removeTab(index);
1434         delete work_area;
1435
1436         if (count()) {
1437                 // make sure the next work area is enabled.
1438                 currentWidget()->setUpdatesEnabled(true);
1439                 if (currentWorkArea() && currentWorkArea()->isFullScreen())
1440                         setFullScreen(true);
1441                 else
1442                         // Hide tabbar if there's only one tab.
1443                         showBar(count() > 1);
1444         } else {
1445                 lastWorkAreaRemoved();
1446         }
1447
1448         updateTabTexts();
1449
1450         return true;
1451 }
1452
1453
1454 void TabWorkArea::on_currentTabChanged(int i)
1455 {
1456         // returns e.g. on application destruction
1457         if (i == -1)
1458                 return;
1459         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1460         LASSERT(wa, return);
1461         BufferView & bv = wa->bufferView();
1462         bv.cursor().fixIfBroken();
1463         bv.updateMetrics();
1464         wa->setUpdatesEnabled(true);
1465         wa->redraw();
1466         wa->setFocus();
1467         ///
1468         currentWorkAreaChanged(wa);
1469
1470         LYXERR(Debug::GUI, "currentTabChanged " << i
1471                 << "File" << bv.buffer().absFileName());
1472 }
1473
1474
1475 void TabWorkArea::closeCurrentBuffer()
1476 {
1477         if (clicked_tab_ != -1)
1478                 setCurrentIndex(clicked_tab_);
1479
1480         lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1481 }
1482
1483
1484 void TabWorkArea::closeCurrentTab()
1485 {
1486         if (clicked_tab_ == -1)
1487                 removeWorkArea(currentWorkArea());
1488         else {
1489                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(clicked_tab_));
1490                 LASSERT(wa, /**/);
1491                 removeWorkArea(wa);
1492         }
1493 }
1494
1495 ///
1496 class DisplayPath {
1497 public:
1498         /// make vector happy
1499         DisplayPath() {}
1500         ///
1501         DisplayPath(int tab, FileName const & filename)
1502                 : tab_(tab)
1503         {
1504                 filename_ = toqstr(filename.onlyFileNameWithoutExt());
1505                 postfix_ = toqstr(filename.absoluteFilePath()).
1506                         split("/", QString::SkipEmptyParts);
1507                 postfix_.pop_back();
1508                 abs_ = toqstr(filename.absoluteFilePath());
1509                 dottedPrefix_ = false;
1510         }
1511
1512         /// Absolute path for debugging.
1513         QString abs() const
1514         {
1515                 return abs_;
1516         }
1517         /// Add the first segment from the postfix or three dots to the prefix.
1518         /// Merge multiple dot tripples. In fact dots are added lazily, i.e. only
1519         /// when really needed.
1520         void shiftPathSegment(bool dotted)
1521         {
1522                 if (postfix_.count() <= 0)
1523                         return;
1524
1525                 if (!dotted) {
1526                         if (dottedPrefix_ && !prefix_.isEmpty())
1527                                 prefix_ += ".../";
1528                         prefix_ += postfix_.front() + "/";
1529                 }
1530                 dottedPrefix_ = dotted && !prefix_.isEmpty();
1531                 postfix_.pop_front();
1532         }
1533         ///
1534         QString displayString() const
1535         {
1536                 if (prefix_.isEmpty())
1537                         return filename_;
1538
1539                 bool dots = dottedPrefix_ || !postfix_.isEmpty();
1540                 return prefix_ + (dots ? ".../" : "") + filename_;
1541         }
1542         ///
1543         QString forecastPathString() const
1544         {
1545                 if (postfix_.count() == 0)
1546                         return displayString();
1547
1548                 return prefix_
1549                         + (dottedPrefix_ ? ".../" : "")
1550                         + postfix_.front() + "/";
1551         }
1552         ///
1553         bool final() const { return postfix_.empty(); }
1554         ///
1555         int tab() const { return tab_; }
1556
1557 private:
1558         ///
1559         QString prefix_;
1560         ///
1561         QStringList postfix_;
1562         ///
1563         QString filename_;
1564         ///
1565         QString abs_;
1566         ///
1567         int tab_;
1568         ///
1569         bool dottedPrefix_;
1570 };
1571
1572
1573 ///
1574 bool operator<(DisplayPath const & a, DisplayPath const & b)
1575 {
1576         return a.displayString() < b.displayString();
1577 }
1578
1579 ///
1580 bool operator==(DisplayPath const & a, DisplayPath const & b)
1581 {
1582         return a.displayString() == b.displayString();
1583 }
1584
1585
1586 void TabWorkArea::updateTabTexts()
1587 {
1588         size_t n = count();
1589         if (n == 0)
1590                 return;
1591         std::list<DisplayPath> paths;
1592         typedef std::list<DisplayPath>::iterator It;
1593
1594         // collect full names first: path into postfix, empty prefix and
1595         // filename without extension
1596         for (size_t i = 0; i < n; ++i) {
1597                 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(i));
1598                 FileName const fn = i_wa->bufferView().buffer().fileName();
1599                 paths.push_back(DisplayPath(i, fn));
1600         }
1601
1602         // go through path segments and see if it helps to make the path more unique
1603         bool somethingChanged = true;
1604         bool allFinal = false;
1605         while (somethingChanged && !allFinal) {
1606                 // adding path segments changes order
1607                 paths.sort();
1608
1609                 LYXERR(Debug::GUI, "updateTabTexts() iteration start");
1610                 somethingChanged = false;
1611                 allFinal = true;
1612
1613                 // find segments which are not unique (i.e. non-atomic)
1614                 It it = paths.begin();
1615                 It segStart = it;
1616                 QString segString = it->displayString();
1617                 for (; it != paths.end(); ++it) {
1618                         // look to the next item
1619                         It next = it;
1620                         ++next;
1621
1622                         // final?
1623                         allFinal = allFinal && it->final();
1624
1625                         LYXERR(Debug::GUI, "it = " << it->abs()
1626                                << " => " << it->displayString());
1627
1628                         // still the same segment?
1629                         QString nextString;
1630                         if ((next != paths.end()
1631                              && (nextString = next->displayString()) == segString))
1632                                 continue;
1633                         LYXERR(Debug::GUI, "segment ended");
1634
1635                         // only a trivial one with one element?
1636                         if (it == segStart) {
1637                                 // start new segment
1638                                 segStart = next;
1639                                 segString = nextString;
1640                                 continue;
1641                         }
1642
1643                         // we found a non-atomic segment segStart <= sit <= it < next.
1644                         // Shift path segments and hope for the best
1645                         // that it makes the path more unique.
1646                         somethingChanged = true;
1647                         It sit = segStart;
1648                         QString dspString = sit->forecastPathString();
1649                         LYXERR(Debug::GUI, "first forecast found for "
1650                                << sit->abs() << " => " << dspString);
1651                         ++sit;
1652                         bool moreUnique = false;
1653                         for (; sit != next; ++sit) {
1654                                 if (sit->forecastPathString() != dspString) {
1655                                         LYXERR(Debug::GUI, "different forecast found for "
1656                                                 << sit->abs() << " => " << sit->forecastPathString());
1657                                         moreUnique = true;
1658                                         break;
1659                                 }
1660                                 LYXERR(Debug::GUI, "same forecast found for "
1661                                         << sit->abs() << " => " << dspString);
1662                         }
1663
1664                         // if the path segment helped, add it. Otherwise add dots
1665                         bool dots = !moreUnique;
1666                         LYXERR(Debug::GUI, "using dots = " << dots);
1667                         for (sit = segStart; sit != next; ++sit) {
1668                                 sit->shiftPathSegment(dots);
1669                                 LYXERR(Debug::GUI, "shifting "
1670                                         << sit->abs() << " => " << sit->displayString());
1671                         }
1672
1673                         // start new segment
1674                         segStart = next;
1675                         segString = nextString;
1676                 }
1677         }
1678
1679         // set new tab titles
1680         for (It it = paths.begin(); it != paths.end(); ++it) {
1681                 GuiWorkArea * i_wa = dynamic_cast<GuiWorkArea *>(widget(it->tab()));
1682                 Buffer & buf = i_wa->bufferView().buffer();
1683                 if (!buf.fileName().empty() && !buf.isClean())
1684                         setTabText(it->tab(), it->displayString() + "*");
1685                 else
1686                         setTabText(it->tab(), it->displayString());
1687         }
1688 }
1689
1690
1691 void TabWorkArea::showContextMenu(const QPoint & pos)
1692 {
1693         // which tab?
1694         clicked_tab_ = static_cast<DragTabBar *>(tabBar())->tabAt(pos);
1695         if (clicked_tab_ == -1)
1696                 return;
1697
1698         // show tab popup
1699         QMenu popup;
1700         popup.addAction(QIcon(":/images/hidetab.png"),
1701                 qt_("Hide tab"), this, SLOT(closeCurrentTab()));
1702         popup.addAction(QIcon(":/images/closetab.png"),
1703                 qt_("Close tab"), this, SLOT(closeCurrentBuffer()));
1704         popup.exec(tabBar()->mapToGlobal(pos));
1705
1706         clicked_tab_ = -1;
1707 }
1708
1709
1710 void TabWorkArea::moveTab(int fromIndex, int toIndex)
1711 {
1712         QWidget * w = widget(fromIndex);
1713         QIcon icon = tabIcon(fromIndex);
1714         QString text = tabText(fromIndex);
1715
1716         setCurrentIndex(fromIndex);
1717         removeTab(fromIndex);
1718         insertTab(toIndex, w, icon, text);
1719         setCurrentIndex(toIndex);
1720 }
1721
1722
1723 DragTabBar::DragTabBar(QWidget* parent)
1724         : QTabBar(parent)
1725 {
1726         setAcceptDrops(true);
1727 }
1728
1729
1730 #if QT_VERSION < 0x040300
1731 int DragTabBar::tabAt(QPoint const & position) const
1732 {
1733         const int max = count();
1734         for (int i = 0; i < max; ++i) {
1735                 if (tabRect(i).contains(position))
1736                         return i;
1737         }
1738         return -1;
1739 }
1740 #endif
1741
1742
1743 void DragTabBar::mousePressEvent(QMouseEvent * event)
1744 {
1745         if (event->button() == Qt::LeftButton)
1746                 dragStartPos_ = event->pos();
1747         QTabBar::mousePressEvent(event);
1748 }
1749
1750
1751 void DragTabBar::mouseMoveEvent(QMouseEvent * event)
1752 {
1753         // If the left button isn't pressed anymore then return
1754         if (!(event->buttons() & Qt::LeftButton))
1755                 return;
1756
1757         // If the distance is too small then return
1758         if ((event->pos() - dragStartPos_).manhattanLength()
1759             < QApplication::startDragDistance())
1760                 return;
1761
1762         // did we hit something after all?
1763         int tab = tabAt(dragStartPos_);
1764         if (tab == -1)
1765                 return;
1766
1767         // simulate button release to remove highlight from button
1768         int i = currentIndex();
1769         QMouseEvent me(QEvent::MouseButtonRelease, dragStartPos_,
1770                 event->button(), event->buttons(), 0);
1771         QTabBar::mouseReleaseEvent(&me);
1772         setCurrentIndex(i);
1773
1774         // initiate Drag
1775         QDrag * drag = new QDrag(this);
1776         QMimeData * mimeData = new QMimeData;
1777         // a crude way to distinguish tab-reodering drops from other ones
1778         mimeData->setData("action", "tab-reordering") ;
1779         drag->setMimeData(mimeData);
1780
1781 #if QT_VERSION >= 0x040300
1782         // get tab pixmap as cursor
1783         QRect r = tabRect(tab);
1784         QPixmap pixmap(r.size());
1785         render(&pixmap, - r.topLeft());
1786         drag->setPixmap(pixmap);
1787         drag->exec();
1788 #else
1789         drag->start(Qt::MoveAction);
1790 #endif
1791
1792 }
1793
1794
1795 void DragTabBar::dragEnterEvent(QDragEnterEvent * event)
1796 {
1797         // Only accept if it's an tab-reordering request
1798         QMimeData const * m = event->mimeData();
1799         QStringList formats = m->formats();
1800         if (formats.contains("action")
1801             && m->data("action") == "tab-reordering")
1802                 event->acceptProposedAction();
1803 }
1804
1805
1806 void DragTabBar::dropEvent(QDropEvent * event)
1807 {
1808         int fromIndex = tabAt(dragStartPos_);
1809         int toIndex = tabAt(event->pos());
1810
1811         // Tell interested objects that
1812         if (fromIndex != toIndex)
1813                 tabMoveRequested(fromIndex, toIndex);
1814         event->acceptProposedAction();
1815 }
1816
1817
1818 } // namespace frontend
1819 } // namespace lyx
1820
1821 #include "moc_GuiWorkArea.cpp"