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