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