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