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