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