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