2 * \file GuiWorkArea.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Abdelrazak Younes
9 * Full author contact details are available in file CREDITS.
14 #include "GuiWorkArea.h"
16 #include "GuiApplication.h"
17 #include "GuiPainter.h"
18 #include "GuiKeySymbol.h"
19 #include "qt_helpers.h"
21 #include "frontends/LyXView.h"
24 #include "BufferView.h"
28 #include "FuncRequest.h"
33 #include "graphics/GraphicsImage.h"
34 #include "graphics/GraphicsLoader.h"
36 #include <QInputContext>
38 #include <QMainWindow>
40 #include <QToolButton>
46 #include <boost/current_function.hpp>
47 #include <boost/bind.hpp>
51 extern "C" int XEventsQueued(Display *display, int mode);
55 int const CursorWidth = 2;
57 int const CursorWidth = 1;
68 using support::FileName;
70 /// return the LyX mouse button state from Qt's
71 static mouse_button::state q_button_state(Qt::MouseButton button)
73 mouse_button::state b = mouse_button::none;
76 b = mouse_button::button1;
79 b = mouse_button::button2;
82 b = mouse_button::button3;
91 /// return the LyX mouse button state from Qt's
92 mouse_button::state q_motion_state(Qt::MouseButtons state)
94 mouse_button::state b = mouse_button::none;
95 if (state & Qt::LeftButton)
96 b |= mouse_button::button1;
97 if (state & Qt::MidButton)
98 b |= mouse_button::button2;
99 if (state & Qt::RightButton)
100 b |= mouse_button::button3;
111 void draw(QPainter & painter)
113 if (show_ && rect_.isValid()) {
116 painter.fillRect(rect_.x(), rect_.y(), CursorWidth, rect_.height(), color_);
117 painter.setPen(color_);
118 painter.drawLine(rect_.bottomLeft().x() + CursorWidth, rect_.bottomLeft().y(),
119 rect_.bottomRight().x(), rect_.bottomLeft().y());
122 case REVERSED_L_SHAPE:
123 painter.fillRect(rect_.x() + rect_.height() / 3, rect_.y(), CursorWidth, rect_.height(), color_);
124 painter.setPen(color_);
125 painter.drawLine(rect_.bottomRight().x() - CursorWidth, rect_.bottomLeft().y(),
126 rect_.bottomLeft().x(), rect_.bottomLeft().y());
130 painter.fillRect(rect_, color_);
136 void update(int x, int y, int h, CursorShape shape)
138 color_ = guiApp->colorCache().get(Color::cursor);
142 rect_ = QRect(x, y, CursorWidth + h / 3, h);
144 case REVERSED_L_SHAPE:
145 rect_ = QRect(x - h / 3, y, CursorWidth + h / 3, h);
148 rect_ = QRect(x, y, CursorWidth, h);
153 void show(bool set_show = true) { show_ = set_show; }
154 void hide() { show_ = false; }
156 QRect const & rect() { return rect_; }
170 // This is a 'heartbeat' generating synthetic mouse move events when the
171 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
172 SyntheticMouseEvent::SyntheticMouseEvent()
173 : timeout(200), restart_timeout(true),
174 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
178 GuiWorkArea::GuiWorkArea(Buffer & buf, LyXView & lv)
179 : WorkArea(buf, lv), need_resize_(false), schedule_redraw_(false),
182 screen_ = QPixmap(viewport()->width(), viewport()->height());
183 cursor_ = new frontend::CursorWidget();
186 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
187 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
188 setAcceptDrops(true);
189 setMouseTracking(true);
190 setMinimumSize(100, 70);
192 viewport()->setAutoFillBackground(false);
193 // We don't need double-buffering nor SystemBackground on
194 // the viewport because we have our own backing pixmap.
195 viewport()->setAttribute(Qt::WA_NoSystemBackground);
197 setFocusPolicy(Qt::WheelFocus);
199 viewport()->setCursor(Qt::IBeamCursor);
201 synthetic_mouse_event_.timeout.timeout.connect(
202 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
205 // Initialize the vertical Scroll Bar
206 QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
207 this, SLOT(adjustViewWithScrollBar(int)));
209 // disable context menu for the scrollbar
210 verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu);
212 // PageStep only depends on the viewport height.
213 verticalScrollBar()->setPageStep(viewport()->height());
215 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
216 << "\n Area width\t" << width()
217 << "\n Area height\t" << height()
218 << "\n viewport width\t" << viewport()->width()
219 << "\n viewport height\t" << viewport()->height()
222 // Enables input methods for asian languages.
223 // Must be set when creating custom text editing widgets.
224 setAttribute(Qt::WA_InputMethodEnabled, true);
228 void GuiWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
230 if (verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOn)
231 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
233 verticalScrollBar()->setTracking(false);
235 // do what cursor movement does (some grey)
237 int scroll_max_ = std::max(0, h - height());
239 verticalScrollBar()->setRange(0, scroll_max_);
240 verticalScrollBar()->setSliderPosition(scroll_pos);
241 verticalScrollBar()->setSingleStep(scroll_line_step);
242 verticalScrollBar()->setValue(scroll_pos);
244 verticalScrollBar()->setTracking(true);
248 void GuiWorkArea::adjustViewWithScrollBar(int action)
250 stopBlinkingCursor();
251 if (action == QAbstractSlider::SliderPageStepAdd)
252 buffer_view_->scrollDown(viewport()->height());
253 else if (action == QAbstractSlider::SliderPageStepSub)
254 buffer_view_->scrollUp(viewport()->height());
256 buffer_view_->scrollDocView(verticalScrollBar()->sliderPosition());
258 if (lyxrc.cursor_follows_scrollbar) {
259 buffer_view_->setCursorFromScrollbar();
260 lyx_view_->updateLayoutChoice();
262 // Show the cursor immediately after any operation.
263 startBlinkingCursor();
264 QApplication::syncX();
268 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
270 // Repaint the whole screen.
271 // Note: this is different from redraw() as only the backing pixmap
272 // will be redrawn, which is cheap.
273 viewport()->repaint();
275 startBlinkingCursor();
279 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
281 stopBlinkingCursor();
285 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
287 if (dc_event_.active && dc_event_ == *e) {
288 dc_event_.active = false;
289 FuncRequest cmd(LFUN_MOUSE_TRIPLE, e->x(), e->y(),
290 q_button_state(e->button()));
295 inputContext()->reset();
297 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
298 q_button_state(e->button()));
299 dispatch(cmd, q_key_state(e->modifiers()));
303 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
305 if (synthetic_mouse_event_.timeout.running())
306 synthetic_mouse_event_.timeout.stop();
308 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
309 q_button_state(e->button()));
314 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
316 // we kill the triple click if we move
317 doubleClickTimeout();
318 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
319 q_motion_state(e->buttons()));
321 // If we're above or below the work area...
322 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
323 // Make sure only a synthetic event can cause a page scroll,
324 // so they come at a steady rate:
326 // _Force_ a scroll up:
329 cmd.y = viewport()->height();
330 // Store the event, to be handled when the timeout expires.
331 synthetic_mouse_event_.cmd = cmd;
333 if (synthetic_mouse_event_.timeout.running())
334 // Discard the event. Note that it _may_ be handled
335 // when the timeout expires if
336 // synthetic_mouse_event_.cmd has not been overwritten.
337 // Ie, when the timeout expires, we handle the
338 // most recent event but discard all others that
339 // occurred after the one used to start the timeout
340 // in the first place.
343 synthetic_mouse_event_.restart_timeout = true;
344 synthetic_mouse_event_.timeout.start();
345 // Fall through to handle this event...
348 } else if (synthetic_mouse_event_.timeout.running()) {
349 // Store the event, to be possibly handled when the timeout
351 // Once the timeout has expired, normal control is returned
352 // to mouseMoveEvent (restart_timeout = false).
353 // This results in a much smoother 'feel' when moving the
354 // mouse back into the work area.
355 synthetic_mouse_event_.cmd = cmd;
356 synthetic_mouse_event_.restart_timeout = false;
360 // Has anything changed on-screen since the last QMouseEvent
362 double const scrollbar_value = verticalScrollBar()->value();
363 if (e->x() != synthetic_mouse_event_.x_old ||
364 e->y() != synthetic_mouse_event_.y_old ||
365 scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
366 // Yes it has. Store the params used to check this.
367 synthetic_mouse_event_.x_old = e->x();
368 synthetic_mouse_event_.y_old = e->y();
369 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
371 // ... and dispatch the event to the LyX core.
377 void GuiWorkArea::wheelEvent(QWheelEvent * e)
379 // Wheel rotation by one notch results in a delta() of 120 (see
380 // documentation of QWheelEvent)
381 int const lines = qApp->wheelScrollLines() * e->delta() / 120;
382 verticalScrollBar()->setValue(verticalScrollBar()->value() -
383 lines * verticalScrollBar()->singleStep());
384 adjustViewWithScrollBar();
388 void GuiWorkArea::generateSyntheticMouseEvent()
390 // Set things off to generate the _next_ 'pseudo' event.
391 if (synthetic_mouse_event_.restart_timeout)
392 synthetic_mouse_event_.timeout.start();
394 // Has anything changed on-screen since the last timeout signal
396 double const scrollbar_value = verticalScrollBar()->value();
397 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
398 // Yes it has. Store the params used to check this.
399 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
401 // ... and dispatch the event to the LyX core.
402 dispatch(synthetic_mouse_event_.cmd);
407 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
409 // do nothing if there are other events
410 // (the auto repeated events come too fast)
411 // \todo FIXME: remove hard coded Qt keys, process the key binding
413 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
414 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
416 << BOOST_CURRENT_FUNCTION << endl
417 << "system is busy: scroll key event ignored" << endl;
423 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
424 << " count=" << ev->count()
425 << " text=" << fromqstr(ev->text())
426 << " isAutoRepeat=" << ev->isAutoRepeat()
427 << " key=" << ev->key()
431 setKeySymbol(&sym, ev);
432 processKeySym(sym, q_key_state(ev->modifiers()));
436 void GuiWorkArea::doubleClickTimeout()
438 dc_event_.active = false;
442 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
444 dc_event_ = double_click(ev);
445 QTimer::singleShot(QApplication::doubleClickInterval(), this,
446 SLOT(doubleClickTimeout()));
447 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
449 q_button_state(ev->button()));
454 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
456 QAbstractScrollArea::resizeEvent(ev);
461 void GuiWorkArea::update(int x, int y, int w, int h)
463 viewport()->repaint(x, y, w, h);
467 void GuiWorkArea::paintEvent(QPaintEvent * ev)
469 QRect const rc = ev->rect();
471 LYXERR(Debug::PAINTING) << "paintEvent begin: x: " << rc.x()
473 << " w: " << rc.width()
474 << " h: " << rc.height() << endl;
478 verticalScrollBar()->setPageStep(viewport()->height());
479 screen_ = QPixmap(viewport()->width(), viewport()->height());
482 WorkArea::hideCursor();
483 WorkArea::showCursor();
484 need_resize_ = false;
487 QPainter pain(viewport());
488 pain.drawPixmap(rc, screen_, rc);
493 void GuiWorkArea::expose(int x, int y, int w, int h)
500 void GuiWorkArea::updateScreen()
502 GuiPainter pain(&screen_);
503 verticalScrollBar()->show();
504 buffer_view_->draw(pain);
508 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
510 if (schedule_redraw_) {
511 buffer_view_->updateMetrics(false);
513 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
514 schedule_redraw_ = false;
515 // Show the cursor immediately after the update.
521 cursor_->update(x, y, h, shape);
523 viewport()->update(cursor_->rect());
527 void GuiWorkArea::removeCursor()
530 //if (!qApp->focusWidget())
531 viewport()->update(cursor_->rect());
535 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
537 QString const & commit_string = e->commitString();
538 docstring const & preedit_string
539 = qstring_to_ucs4(e->preeditString());
541 if (!commit_string.isEmpty()) {
543 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
544 << " preeditString =" << fromqstr(e->preeditString())
545 << " commitString =" << fromqstr(e->commitString())
550 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
551 for (int i = 0; i < commit_string.size(); ++i) {
552 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
557 // Hide the cursor during the kana-kanji transformation.
558 if (preedit_string.empty())
559 startBlinkingCursor();
561 stopBlinkingCursor();
563 // last_width : for checking if last preedit string was/wasn't empty.
564 static bool last_width = false;
565 if (!last_width && preedit_string.empty()) {
566 // if last_width is last length of preedit string.
571 GuiPainter pain(&screen_);
572 buffer_view_->updateMetrics(false);
573 buffer_view_->draw(pain);
574 Font font = buffer_view_->cursor().getFont();
575 FontMetrics const & fm = theFontMetrics(font);
576 int height = fm.maxHeight();
577 int cur_x = cursor_->rect().left();
578 int cur_y = cursor_->rect().bottom();
580 // redraw area of preedit string.
581 update(0, cur_y - height, GuiWorkArea::width(),
582 (height + 1) * preedit_lines_);
584 if (preedit_string.empty()) {
592 // att : stores an IM attribute.
593 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
595 // get attributes of input method cursor.
596 // cursor_pos : cursor position in preedit string.
597 size_t cursor_pos = 0;
598 bool cursor_is_visible = false;
599 for (int i = 0; i < att.size(); ++i) {
600 if (att.at(i).type == QInputMethodEvent::Cursor) {
601 cursor_pos = att.at(i).start;
602 cursor_is_visible = att.at(i).length != 0;
607 size_t preedit_length = preedit_string.length();
609 // get position of selection in input method.
610 // FIXME: isn't there a way to do this simplier?
611 // rStart : cursor position in selected string in IM.
613 // rLength : selected string length in IM.
615 if (cursor_pos < preedit_length) {
616 for (int i = 0; i < att.size(); ++i) {
617 if (att.at(i).type == QInputMethodEvent::TextFormat) {
618 if (att.at(i).start <= int(cursor_pos)
619 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
620 rStart = att.at(i).start;
621 rLength = att.at(i).length;
622 if (!cursor_is_visible)
623 cursor_pos += rLength;
634 int const right_margin = rightMargin();
635 Painter::preedit_style ps;
636 // Most often there would be only one line:
638 for (size_t pos = 0; pos != preedit_length; ++pos) {
639 char_type const typed_char = preedit_string[pos];
640 // reset preedit string style
641 ps = Painter::preedit_default;
643 // if we reached the right extremity of the screen, go to next line.
644 if (cur_x + fm.width(typed_char) > GuiWorkArea::width() - right_margin) {
645 cur_x = right_margin;
649 // preedit strings are displayed with dashed underline
650 // and partial strings are displayed white on black indicating
651 // that we are in selecting mode in the input method.
652 // FIXME: rLength == preedit_length is not a changing condition
653 // FIXME: should be put out of the loop.
655 && pos < rStart + rLength
656 && !(cursor_pos < rLength && rLength == preedit_length))
657 ps = Painter::preedit_selecting;
659 if (pos == cursor_pos
660 && (cursor_pos < rLength && rLength == preedit_length))
661 ps = Painter::preedit_cursor;
663 // draw one character and update cur_x.
664 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
667 // update the preedit string screen area.
668 update(0, cur_y - preedit_lines_*height, GuiWorkArea::width(),
669 (height + 1) * preedit_lines_);
671 // Don't forget to accept the event!
676 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
678 QRect cur_r(0,0,0,0);
680 // this is the CJK-specific composition window position.
681 case Qt::ImMicroFocus:
682 cur_r = cursor_->rect();
683 if (preedit_lines_ != 1)
685 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
686 // return lower right of cursor in LyX.
689 return QWidget::inputMethodQuery(query);
694 ////////////////////////////////////////////////////////////////////
698 ////////////////////////////////////////////////////////////////////
700 TabWorkArea::TabWorkArea(QWidget * parent): QTabWidget(parent)
702 QPalette pal = palette();
703 pal.setColor(QPalette::Active, QPalette::Button, pal.color(QPalette::Active, QPalette::Window));
704 pal.setColor(QPalette::Disabled, QPalette::Button, pal.color(QPalette::Disabled, QPalette::Window));
705 pal.setColor(QPalette::Inactive, QPalette::Button, pal.color(QPalette::Inactive, QPalette::Window));
707 QToolButton * closeTabButton = new QToolButton(this);
708 closeTabButton->setPalette(pal);
709 closeTabButton->setIcon(QIcon(":/images/closetab.png"));
710 closeTabButton->setText("Close");
711 closeTabButton->setAutoRaise(true);
712 closeTabButton->setCursor(Qt::ArrowCursor);
713 closeTabButton->setToolTip(tr("Close tab"));
714 closeTabButton->setEnabled(true);
716 QObject::connect(this, SIGNAL(currentChanged(int)),
717 this, SLOT(on_currentTabChanged(int)));
718 QObject::connect(closeTabButton, SIGNAL(clicked()),
719 this, SLOT(closeCurrentTab()));
721 setCornerWidget(closeTabButton);
722 #if QT_VERSION >= 0x040200
723 setUsesScrollButtons(true);
728 void TabWorkArea::showBar(bool show)
730 tabBar()->setVisible(show);
734 GuiWorkArea * TabWorkArea::currentWorkArea()
739 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(currentWidget());
745 GuiWorkArea * TabWorkArea::workArea(Buffer & buffer)
747 for (int i = 0; i != count(); ++i) {
748 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
750 if (&wa->bufferView().buffer() == &buffer)
757 void TabWorkArea::closeAll()
760 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
768 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
770 BOOST_ASSERT(work_area);
771 int index = indexOf(work_area);
775 if (index == currentIndex())
776 // Make sure the work area is up to date.
777 on_currentTabChanged(index);
779 // Switch to the work area.
780 setCurrentIndex(index);
781 work_area->setFocus();
787 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
789 BOOST_ASSERT(work_area);
790 int index = indexOf(work_area);
794 work_area->setUpdatesEnabled(false);
799 // make sure the next work area is enabled.
800 currentWidget()->setUpdatesEnabled(true);
801 // Hide tabbar if there's only one tab.
802 showBar(count() > 1);
808 void TabWorkArea::on_currentTabChanged(int i)
810 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
812 BufferView & bv = wa->bufferView();
813 bv.updateMetrics(false);
814 bv.cursor().fixIfBroken();
815 wa->setUpdatesEnabled(true);
819 currentWorkAreaChanged(wa);
821 LYXERR(Debug::GUI) << "currentTabChanged " << i
822 << "File" << bv.buffer().absFileName() << endl;
826 void TabWorkArea::closeCurrentTab()
828 lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
831 } // namespace frontend
834 #include "GuiWorkArea_moc.cpp"