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