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