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