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