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