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