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