]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.cpp
Support full screen in BufferView
[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 "GuiKeySymbol.h"
25 #include "GuiPainter.h"
26 #include "GuiPopupMenu.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 "version.h"
35
36 #include "graphics/GraphicsImage.h"
37 #include "graphics/GraphicsLoader.h"
38
39 #include "support/debug.h"
40 #include "support/gettext.h"
41 #include "support/FileName.h"
42
43 #include "frontends/Application.h"
44 #include "frontends/FontMetrics.h"
45 #include "frontends/WorkAreaManager.h"
46
47 #include <QContextMenuEvent>
48 #include <QInputContext>
49 #include <QHelpEvent>
50 #include <QMainWindow>
51 #include <QPainter>
52 #include <QPalette>
53 #include <QScrollBar>
54 #include <QTabBar>
55 #include <QTimer>
56 #include <QToolButton>
57 #include <QToolTip>
58
59 #include <boost/bind.hpp>
60
61 #ifdef Q_WS_X11
62 #include <QX11Info>
63 extern "C" int XEventsQueued(Display *display, int mode);
64 #endif
65
66 #ifdef Q_WS_WIN
67 int const CursorWidth = 2;
68 #else
69 int const CursorWidth = 1;
70 #endif
71
72 #undef KeyPress
73 #undef NoModifier 
74
75 using namespace std;
76 using namespace lyx::support;
77
78 namespace lyx {
79
80
81 /// return the LyX mouse button state from Qt's
82 static mouse_button::state q_button_state(Qt::MouseButton button)
83 {
84         mouse_button::state b = mouse_button::none;
85         switch (button) {
86                 case Qt::LeftButton:
87                         b = mouse_button::button1;
88                         break;
89                 case Qt::MidButton:
90                         b = mouse_button::button2;
91                         break;
92                 case Qt::RightButton:
93                         b = mouse_button::button3;
94                         break;
95                 default:
96                         break;
97         }
98         return b;
99 }
100
101
102 /// return the LyX mouse button state from Qt's
103 mouse_button::state q_motion_state(Qt::MouseButtons state)
104 {
105         mouse_button::state b = mouse_button::none;
106         if (state & Qt::LeftButton)
107                 b |= mouse_button::button1;
108         if (state & Qt::MidButton)
109                 b |= mouse_button::button2;
110         if (state & Qt::RightButton)
111                 b |= mouse_button::button3;
112         return b;
113 }
114
115
116 namespace frontend {
117
118 class CursorWidget {
119 public:
120         CursorWidget() {}
121
122         void draw(QPainter & painter)
123         {
124                 if (show_ && rect_.isValid()) {
125                         switch (shape_) {
126                         case L_SHAPE:
127                                 painter.fillRect(rect_.x(), rect_.y(), CursorWidth, rect_.height(), color_);
128                                 painter.setPen(color_);
129                                 painter.drawLine(rect_.bottomLeft().x() + CursorWidth, rect_.bottomLeft().y(),
130                                                                                                  rect_.bottomRight().x(), rect_.bottomLeft().y());
131                                 break;
132                         
133                         case REVERSED_L_SHAPE:
134                                 painter.fillRect(rect_.x() + rect_.height() / 3, rect_.y(), CursorWidth, rect_.height(), color_);
135                                 painter.setPen(color_);
136                                 painter.drawLine(rect_.bottomRight().x() - CursorWidth, rect_.bottomLeft().y(),
137                                                                                                          rect_.bottomLeft().x(), rect_.bottomLeft().y());
138                                 break;
139                                         
140                         default:
141                                 painter.fillRect(rect_, color_);
142                                 break;
143                         }
144                 }
145         }
146
147         void update(int x, int y, int h, CursorShape shape)
148         {
149                 color_ = guiApp->colorCache().get(Color_cursor);
150                 shape_ = shape;
151                 switch (shape) {
152                 case L_SHAPE:
153                         rect_ = QRect(x, y, CursorWidth + h / 3, h);
154                         break;
155                 case REVERSED_L_SHAPE:
156                         rect_ = QRect(x - h / 3, y, CursorWidth + h / 3, h);
157                         break;
158                 default: 
159                         rect_ = QRect(x, y, CursorWidth, h);
160                         break;
161                 }
162         }
163
164         void show(bool set_show = true) { show_ = set_show; }
165         void hide() { show_ = false; }
166
167         QRect const & rect() { return rect_; }
168
169 private:
170         ///
171         CursorShape shape_;
172         ///
173         bool show_;
174         ///
175         QColor color_;
176         ///
177         QRect rect_;
178 };
179
180
181 // This is a 'heartbeat' generating synthetic mouse move events when the
182 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
183 SyntheticMouseEvent::SyntheticMouseEvent()
184         : timeout(200), restart_timeout(true),
185           x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
186 {}
187
188
189
190 GuiWorkArea::GuiWorkArea(Buffer & buffer, GuiView & lv)
191         : buffer_view_(new BufferView(buffer)), lyx_view_(&lv),
192           cursor_visible_(false),
193     need_resize_(false), schedule_redraw_(false),
194                 preedit_lines_(1)
195 {
196         buffer.workAreaManager().add(this);
197         // Setup the signals
198         connect(&cursor_timeout_, SIGNAL(timeout()),
199                 this, SLOT(toggleCursor()));
200         
201         int const time = QApplication::cursorFlashTime() / 2;
202         if (time > 0) {
203                 cursor_timeout_.setInterval(time);
204                 cursor_timeout_.start();
205         } else
206                 // let's initialize this just to be safe
207                 cursor_timeout_.setInterval(500);
208
209         screen_ = QPixmap(viewport()->width(), viewport()->height());
210         cursor_ = new frontend::CursorWidget();
211         cursor_->hide();
212
213         setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
214         setAcceptDrops(true);
215         setMouseTracking(true);
216         setMinimumSize(100, 70);
217         updateWindowTitle();
218
219         viewport()->setAutoFillBackground(false);
220         // We don't need double-buffering nor SystemBackground on
221         // the viewport because we have our own backing pixmap.
222         viewport()->setAttribute(Qt::WA_NoSystemBackground);
223
224         setFocusPolicy(Qt::WheelFocus);
225
226         viewport()->setCursor(Qt::IBeamCursor);
227
228         synthetic_mouse_event_.timeout.timeout.connect(
229                 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
230                                         this));
231
232         // Initialize the vertical Scroll Bar
233         QObject::connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
234                 this, SLOT(scrollTo(int)));
235
236         LYXERR(Debug::GUI, "viewport width: " << viewport()->width()
237                 << "  viewport height: " << viewport()->height());
238
239         // Enables input methods for asian languages.
240         // Must be set when creating custom text editing widgets.
241         setAttribute(Qt::WA_InputMethodEnabled, true);
242 }
243
244
245
246 GuiWorkArea::~GuiWorkArea()
247 {
248         buffer_view_->buffer().workAreaManager().remove(this);
249         delete buffer_view_;
250         delete cursor_;
251 }
252
253
254 void GuiWorkArea::close()
255 {
256         lyx_view_->removeWorkArea(this);
257 }
258
259
260 BufferView & GuiWorkArea::bufferView()
261 {
262         return *buffer_view_;
263 }
264
265
266 BufferView const & GuiWorkArea::bufferView() const
267 {
268         return *buffer_view_;
269 }
270
271
272 void GuiWorkArea::stopBlinkingCursor()
273 {
274         cursor_timeout_.stop();
275         hideCursor();
276 }
277
278
279 void GuiWorkArea::startBlinkingCursor()
280 {
281         showCursor();
282         //we're not supposed to cache this value.
283         int const time = QApplication::cursorFlashTime() / 2;
284         if (time <= 0)
285                 return;
286         cursor_timeout_.setInterval(time);
287         cursor_timeout_.start();
288 }
289
290
291 void GuiWorkArea::redraw()
292 {
293         if (!isVisible())
294                 // No need to redraw in this case.
295                 return;
296
297         // No need to do anything if this is the current view. The BufferView
298         // metrics are already up to date.
299         if (lyx_view_ != guiApp->currentView()) {
300                 // FIXME: it would be nice to optimize for the off-screen case.
301                 buffer_view_->updateMetrics();
302                 buffer_view_->cursor().fixIfBroken();
303         }
304
305         // update cursor position, because otherwise it has to wait until
306         // the blinking interval is over
307         if (cursor_visible_) {
308                 hideCursor();
309                 showCursor();
310         }
311         
312         LYXERR(Debug::WORKAREA, "WorkArea::redraw screen");
313         updateScreen();
314         update(0, 0, viewport()->width(), viewport()->height());
315
316         /// \warning: scrollbar updating *must* be done after the BufferView is drawn
317         /// because \c BufferView::updateScrollbar() is called in \c BufferView::draw().
318         updateScrollbar();
319         lyx_view_->updateStatusBar();
320
321         if (lyxerr.debugging(Debug::WORKAREA))
322                 buffer_view_->coordCache().dump();
323 }
324
325
326 void GuiWorkArea::processKeySym(KeySymbol const & key, KeyModifier mod)
327 {
328         // In order to avoid bad surprise in the middle of an operation,
329         // we better stop the blinking cursor...
330         // the cursor gets restarted in GuiView::restartCursor()
331         stopBlinkingCursor();
332
333         theLyXFunc().setLyXView(lyx_view_);
334         theLyXFunc().processKeySym(key, mod);
335         
336 }
337
338
339 void GuiWorkArea::dispatch(FuncRequest const & cmd0, KeyModifier mod)
340 {
341         // Handle drag&drop
342         if (cmd0.action == LFUN_FILE_OPEN) {
343                 lyx_view_->dispatch(cmd0);
344                 return;
345         }
346
347         theLyXFunc().setLyXView(lyx_view_);
348
349         FuncRequest cmd;
350
351         if (cmd0.action == LFUN_MOUSE_PRESS) {
352                 if (mod == ShiftModifier)
353                         cmd = FuncRequest(cmd0, "region-select");
354                 else if (mod == ControlModifier)
355                         cmd = FuncRequest(cmd0, "paragraph-select");
356                 else
357                         cmd = cmd0;
358         }
359         else
360                 cmd = cmd0;
361
362         bool const notJustMovingTheMouse = 
363                 cmd.action != LFUN_MOUSE_MOTION || cmd.button() != mouse_button::none;
364         
365         // In order to avoid bad surprise in the middle of an operation, we better stop
366         // the blinking cursor.
367         if (notJustMovingTheMouse)
368                 stopBlinkingCursor();
369
370         buffer_view_->mouseEventDispatch(cmd);
371
372         // Skip these when selecting
373         if (cmd.action != LFUN_MOUSE_MOTION) {
374                 lyx_view_->updateLayoutList();
375                 lyx_view_->updateToolbars();
376         }
377
378         // GUI tweaks except with mouse motion with no button pressed.
379         if (notJustMovingTheMouse) {
380                 // Slight hack: this is only called currently when we
381                 // clicked somewhere, so we force through the display
382                 // of the new status here.
383                 lyx_view_->clearMessage();
384
385                 // Show the cursor immediately after any operation
386                 startBlinkingCursor();
387         }
388 }
389
390
391 void GuiWorkArea::resizeBufferView()
392 {
393         // WARNING: Please don't put any code that will trigger a repaint here!
394         // We are already inside a paint event.
395         lyx_view_->setBusy(true);
396         buffer_view_->resize(viewport()->width(), viewport()->height());
397         lyx_view_->updateLayoutList();
398         lyx_view_->setBusy(false);
399         need_resize_ = false;
400 }
401
402
403 void GuiWorkArea::showCursor()
404 {
405         if (cursor_visible_)
406                 return;
407
408         CursorShape shape = BAR_SHAPE;
409
410         Font const & realfont = buffer_view_->cursor().real_current_font;
411         BufferParams const & bp = buffer_view_->buffer().params();
412         bool const samelang = realfont.language() == bp.language;
413         bool const isrtl = realfont.isVisibleRightToLeft();
414
415         if (!samelang || isrtl != bp.language->rightToLeft()) {
416                 shape = L_SHAPE;
417                 if (isrtl)
418                         shape = REVERSED_L_SHAPE;
419         }
420
421         // The ERT language hack needs fixing up
422         if (realfont.language() == latex_language)
423                 shape = BAR_SHAPE;
424
425         Font const font = buffer_view_->cursor().getFont();
426         FontMetrics const & fm = theFontMetrics(font);
427         int const asc = fm.maxAscent();
428         int const des = fm.maxDescent();
429         int h = asc + des;
430         int x = 0;
431         int y = 0;
432         buffer_view_->cursor().getPos(x, y);
433         y -= asc;
434
435         // if it doesn't touch the screen, don't try to show it
436         if (y + h < 0 || y >= viewport()->height())
437                 return;
438
439         cursor_visible_ = true;
440         showCursor(x, y, h, shape);
441 }
442
443
444 void GuiWorkArea::hideCursor()
445 {
446         if (!cursor_visible_)
447                 return;
448
449         cursor_visible_ = false;
450         removeCursor();
451 }
452
453
454 void GuiWorkArea::toggleCursor()
455 {
456         if (cursor_visible_)
457                 hideCursor();
458         else
459                 showCursor();
460 }
461
462
463 void GuiWorkArea::updateScrollbar()
464 {
465         ScrollbarParameters const & scroll_ = buffer_view_->scrollbarParameters();
466
467         verticalScrollBar()->setRange(scroll_.min, scroll_.max);
468         verticalScrollBar()->setPageStep(scroll_.page_step);
469         verticalScrollBar()->setSingleStep(scroll_.single_step);
470         // Block the scrollbar signal to prevent recursive signal/slot calling.
471         verticalScrollBar()->blockSignals(true);
472         verticalScrollBar()->setValue(scroll_.position);
473         verticalScrollBar()->setSliderPosition(scroll_.position);
474         verticalScrollBar()->blockSignals(false);
475 }
476
477
478 void GuiWorkArea::scrollTo(int value)
479 {
480         stopBlinkingCursor();
481         buffer_view_->scrollDocView(value);
482
483         if (lyxrc.cursor_follows_scrollbar) {
484                 buffer_view_->setCursorFromScrollbar();
485                 lyx_view_->updateLayoutList();
486         }
487         // Show the cursor immediately after any operation.
488         startBlinkingCursor();
489         QApplication::syncX();
490 }
491
492
493 bool GuiWorkArea::event(QEvent * e)
494 {
495         switch (e->type()) {
496         case QEvent::ToolTip: {
497                 QHelpEvent * helpEvent = static_cast<QHelpEvent *>(e);
498                 if (lyxrc.use_tooltip) {
499                         QPoint pos = helpEvent->pos();
500                         if (pos.x() < viewport()->width()) {
501                                 QString s = toqstr(buffer_view_->toolTip(pos.x(), pos.y()));
502                                 QToolTip::showText(helpEvent->globalPos(), s);
503                         }
504                         else
505                                 QToolTip::hideText();
506                 }
507                 // Don't forget to accept the event!
508                 e->accept();
509                 return true;
510         }
511
512         case QEvent::ShortcutOverride: {
513                 // We catch this event in order to catch the Tab or Shift+Tab key press
514                 // which are otherwise reserved to focus switching between controls
515                 // within a dialog.
516                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
517                 if ((ke->key() != Qt::Key_Tab && ke->key() != Qt::Key_Backtab)
518                         || ke->modifiers() & Qt::ControlModifier)
519                         return QAbstractScrollArea::event(e);
520                 keyPressEvent(ke);
521                 return true;
522         }
523
524         default:
525                 return QAbstractScrollArea::event(e);
526         }
527         return false;
528 }
529
530
531 void GuiWorkArea::contextMenuEvent(QContextMenuEvent * e)
532 {
533         QPoint pos = e->pos();
534         docstring name = buffer_view_->contextMenu(pos.x(), pos.y());
535         if (name.empty()) {
536                 QAbstractScrollArea::contextMenuEvent(e);
537                 return;
538         }
539         QMenu * menu = guiApp->menus().menu(toqstr(name));
540         if (!menu) {
541                 QAbstractScrollArea::contextMenuEvent(e);
542                 return;
543         }
544         // Position the menu to the right.
545         // FIXME: menu position should be different for RTL text.
546         menu->exec(e->globalPos());
547         e->accept();
548 }
549
550
551 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
552 {
553         // Repaint the whole screen.
554         // Note: this is different from redraw() as only the backing pixmap
555         // will be redrawn, which is cheap.
556         viewport()->repaint();
557
558         startBlinkingCursor();
559 }
560
561
562 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
563 {
564         stopBlinkingCursor();
565 }
566
567
568 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
569 {
570         if (dc_event_.active && dc_event_ == *e) {
571                 dc_event_.active = false;
572                 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
573                         q_button_state(e->button()));
574                 dispatch(cmd);
575                 return;
576         }
577
578         inputContext()->reset();
579
580         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
581                 q_button_state(e->button()));
582         dispatch(cmd, q_key_state(e->modifiers()));
583 }
584
585
586 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
587 {
588         if (synthetic_mouse_event_.timeout.running())
589                 synthetic_mouse_event_.timeout.stop();
590
591         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
592                               q_button_state(e->button()));
593         dispatch(cmd);
594 }
595
596
597 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
598 {
599         // we kill the triple click if we move
600         doubleClickTimeout();
601         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
602                 q_motion_state(e->buttons()));
603
604         // If we're above or below the work area...
605         if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
606                 // Make sure only a synthetic event can cause a page scroll,
607                 // so they come at a steady rate:
608                 if (e->y() <= 20)
609                         // _Force_ a scroll up:
610                         cmd.y = -40;
611                 else
612                         cmd.y = viewport()->height();
613                 // Store the event, to be handled when the timeout expires.
614                 synthetic_mouse_event_.cmd = cmd;
615
616                 if (synthetic_mouse_event_.timeout.running())
617                         // Discard the event. Note that it _may_ be handled
618                         // when the timeout expires if
619                         // synthetic_mouse_event_.cmd has not been overwritten.
620                         // Ie, when the timeout expires, we handle the
621                         // most recent event but discard all others that
622                         // occurred after the one used to start the timeout
623                         // in the first place.
624                         return;
625
626                 synthetic_mouse_event_.restart_timeout = true;
627                 synthetic_mouse_event_.timeout.start();
628                 // Fall through to handle this event...
629
630         } else if (synthetic_mouse_event_.timeout.running()) {
631                 // Store the event, to be possibly handled when the timeout
632                 // expires.
633                 // Once the timeout has expired, normal control is returned
634                 // to mouseMoveEvent (restart_timeout = false).
635                 // This results in a much smoother 'feel' when moving the
636                 // mouse back into the work area.
637                 synthetic_mouse_event_.cmd = cmd;
638                 synthetic_mouse_event_.restart_timeout = false;
639                 return;
640         }
641
642         // Has anything changed on-screen since the last QMouseEvent
643         // was received?
644         double const scrollbar_value = verticalScrollBar()->value();
645         if (e->x() == synthetic_mouse_event_.x_old
646                 && e->y() == synthetic_mouse_event_.y_old
647                 && scrollbar_value == synthetic_mouse_event_.scrollbar_value_old) {
648                 // Nothing changed on-screen since the last QMouseEvent.
649                 return;
650         }
651
652         // Yes something has changed. Store the params used to check this.
653         synthetic_mouse_event_.x_old = e->x();
654         synthetic_mouse_event_.y_old = e->y();
655         synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
656
657         // ... and dispatch the event to the LyX core.
658         dispatch(cmd);
659 }
660
661
662 void GuiWorkArea::wheelEvent(QWheelEvent * e)
663 {
664         // Wheel rotation by one notch results in a delta() of 120 (see
665         // documentation of QWheelEvent)
666         double const lines = qApp->wheelScrollLines()
667                 * lyxrc.mouse_wheel_speed
668                 * e->delta() / 120.0;
669         LYXERR(Debug::SCROLLING, "wheelScrollLines = " << qApp->wheelScrollLines()
670                 << " delta = " << e->delta()
671                 << " lines = " << lines);
672         verticalScrollBar()->setValue(verticalScrollBar()->value() -
673                 int(lines *  verticalScrollBar()->singleStep()));
674 }
675
676
677 void GuiWorkArea::generateSyntheticMouseEvent()
678 {
679         // Set things off to generate the _next_ 'pseudo' event.
680         if (synthetic_mouse_event_.restart_timeout)
681                 synthetic_mouse_event_.timeout.start();
682
683         // Has anything changed on-screen since the last timeout signal
684         // was received?
685         double const scrollbar_value = verticalScrollBar()->value();
686         if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
687                 // Yes it has. Store the params used to check this.
688                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
689
690                 // ... and dispatch the event to the LyX core.
691                 dispatch(synthetic_mouse_event_.cmd);
692         }
693 }
694
695
696 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
697 {
698         // do nothing if there are other events
699         // (the auto repeated events come too fast)
700         // \todo FIXME: remove hard coded Qt keys, process the key binding
701 #ifdef Q_WS_X11
702         if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat() 
703                         && (Qt::Key_PageDown || Qt::Key_PageUp)) {
704                 LYXERR(Debug::KEY, "system is busy: scroll key event ignored");
705                 ev->ignore();
706                 return;
707         }
708 #endif
709
710         LYXERR(Debug::KEY, " count: " << ev->count()
711                 << " text: " << fromqstr(ev->text())
712                 << " isAutoRepeat: " << ev->isAutoRepeat() << " key: " << ev->key());
713
714         KeySymbol sym;
715         setKeySymbol(&sym, ev);
716         processKeySym(sym, q_key_state(ev->modifiers()));
717         ev->accept();
718 }
719
720
721 void GuiWorkArea::doubleClickTimeout()
722 {
723         dc_event_.active = false;
724 }
725
726
727 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
728 {
729         dc_event_ = DoubleClick(ev);
730         QTimer::singleShot(QApplication::doubleClickInterval(), this,
731                            SLOT(doubleClickTimeout()));
732         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
733                         ev->x(), ev->y(),
734                         q_button_state(ev->button()));
735         dispatch(cmd);
736 }
737
738
739 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
740 {
741         QAbstractScrollArea::resizeEvent(ev);
742         need_resize_ = true;
743 }
744
745
746 void GuiWorkArea::update(int x, int y, int w, int h)
747 {
748         viewport()->repaint(x, y, w, h);
749 }
750
751
752 void GuiWorkArea::paintEvent(QPaintEvent * ev)
753 {
754         QRect const rc = ev->rect();
755         // LYXERR(Debug::PAINTING, "paintEvent begin: x: " << rc.x()
756         //      << " y: " << rc.y() << " w: " << rc.width() << " h: " << rc.height());
757
758         if (need_resize_) {
759                 screen_ = QPixmap(viewport()->width(), viewport()->height());
760                 resizeBufferView();
761                 
762                 // Update scrollbars which might have changed due different
763                 // BufferView dimension. This is especially important when the 
764                 // BufferView goes from zero-size to the real-size for the first time,
765                 // as the scrollbar paramters are then set for the first time.
766                 updateScrollbar();
767                 BOOST_ASSERT(need_resize_ == false);
768                 
769                 updateScreen();
770                 hideCursor();
771                 showCursor();
772         }
773
774         QPainter pain(viewport());
775         pain.drawPixmap(rc, screen_, rc);
776         cursor_->draw(pain);
777 }
778
779
780 void GuiWorkArea::updateScreen()
781 {
782         GuiPainter pain(&screen_);
783         buffer_view_->draw(pain);
784 }
785
786
787 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
788 {
789         if (schedule_redraw_) {
790                 buffer_view_->updateMetrics();
791                 updateScreen();
792                 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
793                 schedule_redraw_ = false;
794                 // Show the cursor immediately after the update.
795                 hideCursor();
796                 toggleCursor();
797                 return;
798         }
799
800         cursor_->update(x, y, h, shape);
801         cursor_->show();
802         viewport()->update(cursor_->rect());
803 }
804
805
806 void GuiWorkArea::removeCursor()
807 {
808         cursor_->hide();
809         //if (!qApp->focusWidget())
810                 viewport()->update(cursor_->rect());
811 }
812
813
814 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
815 {
816         QString const & commit_string = e->commitString();
817         docstring const & preedit_string
818                 = qstring_to_ucs4(e->preeditString());
819
820         if (!commit_string.isEmpty()) {
821
822                 LYXERR(Debug::KEY, "preeditString: " << fromqstr(e->preeditString())
823                         << " commitString: " << fromqstr(e->commitString()));
824
825                 int key = 0;
826
827                 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
828                 for (int i = 0; i != commit_string.size(); ++i) {
829                         QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
830                         keyPressEvent(&ev);
831                 }
832         }
833
834         // Hide the cursor during the kana-kanji transformation.
835         if (preedit_string.empty())
836                 startBlinkingCursor();
837         else
838                 stopBlinkingCursor();
839
840         // last_width : for checking if last preedit string was/wasn't empty.
841         static bool last_width = false;
842         if (!last_width && preedit_string.empty()) {
843                 // if last_width is last length of preedit string.
844                 e->accept();
845                 return;
846         }
847
848         GuiPainter pain(&screen_);
849         buffer_view_->updateMetrics();
850         buffer_view_->draw(pain);
851         FontInfo font = buffer_view_->cursor().getFont().fontInfo();
852         FontMetrics const & fm = theFontMetrics(font);
853         int height = fm.maxHeight();
854         int cur_x = cursor_->rect().left();
855         int cur_y = cursor_->rect().bottom();
856
857         // redraw area of preedit string.
858         update(0, cur_y - height, viewport()->width(),
859                 (height + 1) * preedit_lines_);
860
861         if (preedit_string.empty()) {
862                 last_width = false;
863                 preedit_lines_ = 1;
864                 e->accept();
865                 return;
866         }
867         last_width = true;
868
869         // att : stores an IM attribute.
870         QList<QInputMethodEvent::Attribute> const & att = e->attributes();
871
872         // get attributes of input method cursor.
873         // cursor_pos : cursor position in preedit string.
874         size_t cursor_pos = 0;
875         bool cursor_is_visible = false;
876         for (int i = 0; i != att.size(); ++i) {
877                 if (att.at(i).type == QInputMethodEvent::Cursor) {
878                         cursor_pos = att.at(i).start;
879                         cursor_is_visible = att.at(i).length != 0;
880                         break;
881                 }
882         }
883
884         size_t preedit_length = preedit_string.length();
885
886         // get position of selection in input method.
887         // FIXME: isn't there a way to do this simplier?
888         // rStart : cursor position in selected string in IM.
889         size_t rStart = 0;
890         // rLength : selected string length in IM.
891         size_t rLength = 0;
892         if (cursor_pos < preedit_length) {
893                 for (int i = 0; i != att.size(); ++i) {
894                         if (att.at(i).type == QInputMethodEvent::TextFormat) {
895                                 if (att.at(i).start <= int(cursor_pos)
896                                         && int(cursor_pos) < att.at(i).start + att.at(i).length) {
897                                                 rStart = att.at(i).start;
898                                                 rLength = att.at(i).length;
899                                                 if (!cursor_is_visible)
900                                                         cursor_pos += rLength;
901                                                 break;
902                                 }
903                         }
904                 }
905         }
906         else {
907                 rStart = cursor_pos;
908                 rLength = 0;
909         }
910
911         int const right_margin = buffer_view_->rightMargin();
912         Painter::preedit_style ps;
913         // Most often there would be only one line:
914         preedit_lines_ = 1;
915         for (size_t pos = 0; pos != preedit_length; ++pos) {
916                 char_type const typed_char = preedit_string[pos];
917                 // reset preedit string style
918                 ps = Painter::preedit_default;
919
920                 // if we reached the right extremity of the screen, go to next line.
921                 if (cur_x + fm.width(typed_char) > viewport()->width() - right_margin) {
922                         cur_x = right_margin;
923                         cur_y += height + 1;
924                         ++preedit_lines_;
925                 }
926                 // preedit strings are displayed with dashed underline
927                 // and partial strings are displayed white on black indicating
928                 // that we are in selecting mode in the input method.
929                 // FIXME: rLength == preedit_length is not a changing condition
930                 // FIXME: should be put out of the loop.
931                 if (pos >= rStart
932                         && pos < rStart + rLength
933                         && !(cursor_pos < rLength && rLength == preedit_length))
934                         ps = Painter::preedit_selecting;
935
936                 if (pos == cursor_pos
937                         && (cursor_pos < rLength && rLength == preedit_length))
938                         ps = Painter::preedit_cursor;
939
940                 // draw one character and update cur_x.
941                 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
942         }
943
944         // update the preedit string screen area.
945         update(0, cur_y - preedit_lines_*height, viewport()->width(),
946                 (height + 1) * preedit_lines_);
947
948         // Don't forget to accept the event!
949         e->accept();
950 }
951
952
953 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
954 {
955         QRect cur_r(0,0,0,0);
956         switch (query) {
957                 // this is the CJK-specific composition window position.
958                 case Qt::ImMicroFocus:
959                         cur_r = cursor_->rect();
960                         if (preedit_lines_ != 1)
961                                 cur_r.moveLeft(10);
962                         cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
963                         // return lower right of cursor in LyX.
964                         return cur_r;
965                 default:
966                         return QWidget::inputMethodQuery(query);
967         }
968 }
969
970
971 void GuiWorkArea::updateWindowTitle()
972 {
973         docstring maximize_title;
974         docstring minimize_title;
975
976         Buffer & buf = buffer_view_->buffer();
977         FileName const fileName = buf.fileName();
978         if (!fileName.empty()) {
979                 maximize_title = fileName.displayName(30);
980                 minimize_title = from_utf8(fileName.onlyFileName());
981                 if (!buf.isClean()) {
982                         maximize_title += _(" (changed)");
983                         minimize_title += char_type('*');
984                 }
985                 if (buf.isReadonly())
986                         maximize_title += _(" (read only)");
987         }
988
989         QString title = windowTitle();
990         QString new_title = toqstr(maximize_title);
991         if (title == new_title)
992                 return;
993
994         QWidget::setWindowTitle(new_title);
995         QWidget::setWindowIconText(toqstr(minimize_title));
996         titleChanged(this);
997 }
998
999
1000 void GuiWorkArea::setReadOnly(bool)
1001 {
1002         updateWindowTitle();
1003         if (this == lyx_view_->currentWorkArea())
1004                 lyx_view_->updateBufferDependent(false);
1005 }
1006
1007
1008 ////////////////////////////////////////////////////////////////////
1009 //
1010 // TabWorkArea 
1011 //
1012 ////////////////////////////////////////////////////////////////////
1013
1014 TabWorkArea::TabWorkArea(QWidget * parent) : QTabWidget(parent)
1015 {
1016         QPalette pal = palette();
1017         pal.setColor(QPalette::Active, QPalette::Button,
1018                 pal.color(QPalette::Active, QPalette::Window));
1019         pal.setColor(QPalette::Disabled, QPalette::Button,
1020                 pal.color(QPalette::Disabled, QPalette::Window));
1021         pal.setColor(QPalette::Inactive, QPalette::Button,
1022                 pal.color(QPalette::Inactive, QPalette::Window));
1023
1024         QToolButton * closeTabButton = new QToolButton(this);
1025     closeTabButton->setPalette(pal);
1026         closeTabButton->setIcon(QIcon(":/images/closetab.png"));
1027         closeTabButton->setText("Close");
1028         closeTabButton->setAutoRaise(true);
1029         closeTabButton->setCursor(Qt::ArrowCursor);
1030         closeTabButton->setToolTip(tr("Close tab"));
1031         closeTabButton->setEnabled(true);
1032
1033         QObject::connect(this, SIGNAL(currentChanged(int)),
1034                 this, SLOT(on_currentTabChanged(int)));
1035         QObject::connect(closeTabButton, SIGNAL(clicked()),
1036                 this, SLOT(closeCurrentTab()));
1037
1038         setCornerWidget(closeTabButton);
1039         setUsesScrollButtons(true);
1040 }
1041
1042
1043 void TabWorkArea::showBar(bool show)
1044 {
1045         tabBar()->setEnabled(show);
1046         tabBar()->setVisible(show);
1047 }
1048
1049
1050 GuiWorkArea * TabWorkArea::currentWorkArea()
1051 {
1052         if (count() == 0)
1053                 return 0;
1054
1055         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget()); 
1056         BOOST_ASSERT(wa);
1057         return wa;
1058 }
1059
1060
1061 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
1062 {
1063         for (int i = 0; i != count(); ++i) {
1064                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1065                 BOOST_ASSERT(wa);
1066                 if (&wa->bufferView().buffer() == &buffer)
1067                         return wa;
1068         }
1069         return 0;
1070 }
1071
1072
1073 void TabWorkArea::closeAll()
1074 {
1075         while (count()) {
1076                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
1077                 BOOST_ASSERT(wa);
1078                 removeTab(0);
1079                 delete wa;
1080         }
1081 }
1082
1083
1084 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
1085 {
1086         BOOST_ASSERT(work_area);
1087         int index = indexOf(work_area);
1088         if (index == -1)
1089                 return false;
1090
1091         if (index == currentIndex())
1092                 // Make sure the work area is up to date.
1093                 on_currentTabChanged(index);
1094         else
1095                 // Switch to the work area.
1096                 setCurrentIndex(index);
1097         work_area->setFocus();
1098
1099         return true;
1100 }
1101
1102
1103 GuiWorkArea * TabWorkArea::addWorkArea(Buffer & buffer, GuiView & view)
1104 {
1105         GuiWorkArea * wa = new GuiWorkArea(buffer, view);
1106         wa->setUpdatesEnabled(false);
1107         // Hide tabbar if there's no tab (avoid a resize and a flashing tabbar
1108         // when hiding it again below).
1109         showBar(count() > 0);
1110         addTab(wa, wa->windowTitle());
1111         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1112                 this, SLOT(updateTabText(GuiWorkArea *)));
1113         // Hide tabbar if there's only one tab.
1114         showBar(count() > 1);
1115         return wa;
1116 }
1117
1118
1119 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
1120 {
1121         BOOST_ASSERT(work_area);
1122         int index = indexOf(work_area);
1123         if (index == -1)
1124                 return false;
1125
1126         work_area->setUpdatesEnabled(false);
1127         removeTab(index);
1128         delete work_area;
1129
1130         if (count()) {
1131                 // make sure the next work area is enabled.
1132                 currentWidget()->setUpdatesEnabled(true);
1133                 // Hide tabbar if there's only one tab.
1134                 showBar(count() > 1);
1135         }
1136         return true;
1137 }
1138
1139
1140 void TabWorkArea::on_currentTabChanged(int i)
1141 {
1142         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
1143         BOOST_ASSERT(wa);
1144         BufferView & bv = wa->bufferView();
1145         bv.cursor().fixIfBroken();
1146         bv.updateMetrics();
1147         wa->setUpdatesEnabled(true);
1148         wa->redraw();
1149         wa->setFocus();
1150         ///
1151         currentWorkAreaChanged(wa);
1152
1153         LYXERR(Debug::GUI, "currentTabChanged " << i
1154                 << "File" << bv.buffer().absFileName());
1155 }
1156
1157
1158 void TabWorkArea::closeCurrentTab()
1159 {
1160         lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
1161 }
1162
1163
1164 void TabWorkArea::updateTabText(GuiWorkArea * wa)
1165 {
1166         int const i = indexOf(wa);
1167         if (i < 0)
1168                 return;
1169         setTabText(i, wa->windowTitle());
1170 }
1171
1172 } // namespace frontend
1173 } // namespace lyx
1174
1175 #include "GuiWorkArea_moc.cpp"