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