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