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 "support/filetools.h" // LibFileSearch
35 #include "graphics/GraphicsImage.h"
36 #include "graphics/GraphicsLoader.h"
38 #include <QInputContext>
40 #include <QMainWindow>
42 #include <QPushButton>
47 #include <boost/bind.hpp>
48 #include <boost/current_function.hpp>
52 extern "C" int XEventsQueued(Display *display, int mode);
56 int const CursorWidth = 2;
58 int const CursorWidth = 1;
69 using support::FileName;
71 /// return the LyX mouse button state from Qt's
72 static mouse_button::state q_button_state(Qt::MouseButton button)
74 mouse_button::state b = mouse_button::none;
77 b = mouse_button::button1;
80 b = mouse_button::button2;
83 b = mouse_button::button3;
92 /// return the LyX mouse button state from Qt's
93 mouse_button::state q_motion_state(Qt::MouseButtons state)
95 mouse_button::state b = mouse_button::none;
96 if (state & Qt::LeftButton)
97 b |= mouse_button::button1;
98 if (state & Qt::MidButton)
99 b |= mouse_button::button2;
100 if (state & Qt::RightButton)
101 b |= mouse_button::button3;
112 void draw(QPainter & painter)
114 if (show_ && rect_.isValid()) {
117 painter.fillRect(rect_.x(), rect_.y(), CursorWidth, rect_.height(), color_);
118 painter.setPen(color_);
119 painter.drawLine(rect_.bottomLeft().x() + CursorWidth, rect_.bottomLeft().y(),
120 rect_.bottomRight().x(), rect_.bottomLeft().y());
123 case REVERSED_L_SHAPE:
124 painter.fillRect(rect_.x() + rect_.height() / 3, rect_.y(), CursorWidth, rect_.height(), color_);
125 painter.setPen(color_);
126 painter.drawLine(rect_.bottomRight().x() - CursorWidth, rect_.bottomLeft().y(),
127 rect_.bottomLeft().x(), rect_.bottomLeft().y());
131 painter.fillRect(rect_, color_);
137 void update(int x, int y, int h, CursorShape shape)
139 color_ = guiApp->colorCache().get(Color::cursor);
143 rect_ = QRect(x, y, CursorWidth + h / 3, h);
145 case REVERSED_L_SHAPE:
146 rect_ = QRect(x - h / 3, y, CursorWidth + h / 3, h);
149 rect_ = QRect(x, y, CursorWidth, h);
154 void show(bool set_show = true) { show_ = set_show; }
155 void hide() { show_ = false; }
157 QRect const & rect() { return rect_; }
171 // This is a 'heartbeat' generating synthetic mouse move events when the
172 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
173 SyntheticMouseEvent::SyntheticMouseEvent()
174 : timeout(200), restart_timeout(true),
175 x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
179 GuiWorkArea::GuiWorkArea(Buffer & buf, LyXView & lv)
180 : WorkArea(buf, lv), need_resize_(false), schedule_redraw_(false),
183 screen_ = QPixmap(viewport()->width(), viewport()->height());
184 cursor_ = new frontend::CursorWidget();
187 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
188 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
189 setAcceptDrops(true);
190 setMouseTracking(true);
191 setMinimumSize(100, 70);
193 viewport()->setAutoFillBackground(false);
194 // We don't need double-buffering nor SystemBackground on
195 // the viewport because we have our own backing pixmap.
196 viewport()->setAttribute(Qt::WA_NoSystemBackground);
198 setFocusPolicy(Qt::WheelFocus);
200 viewport()->setCursor(Qt::IBeamCursor);
202 synthetic_mouse_event_.timeout.timeout.connect(
203 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
206 // Initialize the vertical Scroll Bar
207 QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
208 this, SLOT(adjustViewWithScrollBar(int)));
210 // disable context menu for the scrollbar
211 verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu);
213 // PageStep only depends on the viewport height.
214 verticalScrollBar()->setPageStep(viewport()->height());
216 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
217 << "\n Area width\t" << width()
218 << "\n Area height\t" << height()
219 << "\n viewport width\t" << viewport()->width()
220 << "\n viewport height\t" << viewport()->height()
223 // Enables input methods for asian languages.
224 // Must be set when creating custom text editing widgets.
225 setAttribute(Qt::WA_InputMethodEnabled, true);
229 void GuiWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
231 if (verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOn)
232 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
234 verticalScrollBar()->setTracking(false);
236 // do what cursor movement does (some grey)
238 int scroll_max_ = std::max(0, h - height());
240 verticalScrollBar()->setRange(0, scroll_max_);
241 verticalScrollBar()->setSliderPosition(scroll_pos);
242 verticalScrollBar()->setSingleStep(scroll_line_step);
243 verticalScrollBar()->setValue(scroll_pos);
245 verticalScrollBar()->setTracking(true);
249 void GuiWorkArea::adjustViewWithScrollBar(int action)
251 stopBlinkingCursor();
252 if (action == QAbstractSlider::SliderPageStepAdd)
253 buffer_view_->scrollDown(viewport()->height());
254 else if (action == QAbstractSlider::SliderPageStepSub)
255 buffer_view_->scrollUp(viewport()->height());
257 buffer_view_->scrollDocView(verticalScrollBar()->sliderPosition());
259 if (lyxrc.cursor_follows_scrollbar) {
260 buffer_view_->setCursorFromScrollbar();
261 lyx_view_->updateLayoutChoice();
263 // Show the cursor immediately after any operation.
264 startBlinkingCursor();
265 QApplication::syncX();
269 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
271 // Repaint the whole screen.
272 // Note: this is different from redraw() as only the backing pixmap
273 // will be redrawn, which is cheap.
274 viewport()->repaint();
276 startBlinkingCursor();
280 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
282 stopBlinkingCursor();
286 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
288 if (dc_event_.active && dc_event_ == *e) {
289 dc_event_.active = false;
290 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
292 q_button_state(e->button()));
297 inputContext()->reset();
299 FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
300 q_button_state(e->button()));
301 dispatch(cmd, q_key_state(e->modifiers()));
305 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
307 if (synthetic_mouse_event_.timeout.running())
308 synthetic_mouse_event_.timeout.stop();
310 FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
311 q_button_state(e->button()));
316 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
318 // we kill the triple click if we move
319 doubleClickTimeout();
320 FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
321 q_motion_state(e->buttons()));
323 // If we're above or below the work area...
324 if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
325 // Make sure only a synthetic event can cause a page scroll,
326 // so they come at a steady rate:
328 // _Force_ a scroll up:
331 cmd.y = viewport()->height();
332 // Store the event, to be handled when the timeout expires.
333 synthetic_mouse_event_.cmd = cmd;
335 if (synthetic_mouse_event_.timeout.running())
336 // Discard the event. Note that it _may_ be handled
337 // when the timeout expires if
338 // synthetic_mouse_event_.cmd has not been overwritten.
339 // Ie, when the timeout expires, we handle the
340 // most recent event but discard all others that
341 // occurred after the one used to start the timeout
342 // in the first place.
345 synthetic_mouse_event_.restart_timeout = true;
346 synthetic_mouse_event_.timeout.start();
347 // Fall through to handle this event...
350 } else if (synthetic_mouse_event_.timeout.running()) {
351 // Store the event, to be possibly handled when the timeout
353 // Once the timeout has expired, normal control is returned
354 // to mouseMoveEvent (restart_timeout = false).
355 // This results in a much smoother 'feel' when moving the
356 // mouse back into the work area.
357 synthetic_mouse_event_.cmd = cmd;
358 synthetic_mouse_event_.restart_timeout = false;
362 // Has anything changed on-screen since the last QMouseEvent
364 double const scrollbar_value = verticalScrollBar()->value();
365 if (e->x() != synthetic_mouse_event_.x_old ||
366 e->y() != synthetic_mouse_event_.y_old ||
367 scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
368 // Yes it has. Store the params used to check this.
369 synthetic_mouse_event_.x_old = e->x();
370 synthetic_mouse_event_.y_old = e->y();
371 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
373 // ... and dispatch the event to the LyX core.
379 void GuiWorkArea::wheelEvent(QWheelEvent * e)
381 // Wheel rotation by one notch results in a delta() of 120 (see
382 // documentation of QWheelEvent)
383 int const lines = qApp->wheelScrollLines() * e->delta() / 120;
384 verticalScrollBar()->setValue(verticalScrollBar()->value() -
385 lines * verticalScrollBar()->singleStep());
386 adjustViewWithScrollBar();
390 void GuiWorkArea::generateSyntheticMouseEvent()
392 // Set things off to generate the _next_ 'pseudo' event.
393 if (synthetic_mouse_event_.restart_timeout)
394 synthetic_mouse_event_.timeout.start();
396 // Has anything changed on-screen since the last timeout signal
398 double const scrollbar_value = verticalScrollBar()->value();
399 if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
400 // Yes it has. Store the params used to check this.
401 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
403 // ... and dispatch the event to the LyX core.
404 dispatch(synthetic_mouse_event_.cmd);
409 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
411 // do nothing if there are other events
412 // (the auto repeated events come too fast)
413 // \todo FIXME: remove hard coded Qt keys, process the key binding
415 if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat()
416 && (Qt::Key_PageDown || Qt::Key_PageUp)) {
418 << BOOST_CURRENT_FUNCTION << endl
419 << "system is busy: scroll key event ignored" << endl;
425 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
426 << " count=" << ev->count()
427 << " text=" << fromqstr(ev->text())
428 << " isAutoRepeat=" << ev->isAutoRepeat()
429 << " key=" << ev->key()
433 setKeySymbol(&sym, ev);
434 processKeySym(sym, q_key_state(ev->modifiers()));
438 void GuiWorkArea::doubleClickTimeout()
440 dc_event_.active = false;
444 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
446 dc_event_ = double_click(ev);
447 QTimer::singleShot(QApplication::doubleClickInterval(), this,
448 SLOT(doubleClickTimeout()));
449 FuncRequest cmd(LFUN_MOUSE_DOUBLE,
451 q_button_state(ev->button()));
456 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
458 QAbstractScrollArea::resizeEvent(ev);
463 void GuiWorkArea::update(int x, int y, int w, int h)
465 viewport()->repaint(x, y, w, h);
469 void GuiWorkArea::paintEvent(QPaintEvent * ev)
471 QRect const rc = ev->rect();
473 LYXERR(Debug::PAINTING) << "paintEvent begin: x: " << rc.x()
475 << " w: " << rc.width()
476 << " h: " << rc.height() << endl;
480 verticalScrollBar()->setPageStep(viewport()->height());
481 screen_ = QPixmap(viewport()->width(), viewport()->height());
484 WorkArea::hideCursor();
485 WorkArea::showCursor();
486 need_resize_ = false;
489 QPainter pain(viewport());
490 pain.drawPixmap(rc, screen_, rc);
495 void GuiWorkArea::expose(int x, int y, int w, int h)
502 void GuiWorkArea::updateScreen()
504 GuiPainter pain(&screen_);
505 verticalScrollBar()->show();
506 buffer_view_->draw(pain);
510 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
512 if (schedule_redraw_) {
513 buffer_view_->updateMetrics(false);
515 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
516 schedule_redraw_ = false;
517 // Show the cursor immediately after the update.
523 cursor_->update(x, y, h, shape);
525 viewport()->update(cursor_->rect());
529 void GuiWorkArea::removeCursor()
532 //if (!qApp->focusWidget())
533 viewport()->update(cursor_->rect());
537 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
539 QString const & commit_string = e->commitString();
540 docstring const & preedit_string
541 = qstring_to_ucs4(e->preeditString());
543 if (!commit_string.isEmpty()) {
545 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
546 << " preeditString =" << fromqstr(e->preeditString())
547 << " commitString =" << fromqstr(e->commitString())
552 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
553 for (int i = 0; i < commit_string.size(); ++i) {
554 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
559 // Hide the cursor during the kana-kanji transformation.
560 if (preedit_string.empty())
561 startBlinkingCursor();
563 stopBlinkingCursor();
565 // last_width : for checking if last preedit string was/wasn't empty.
566 static bool last_width = false;
567 if (!last_width && preedit_string.empty()) {
568 // if last_width is last length of preedit string.
573 GuiPainter pain(&screen_);
574 buffer_view_->updateMetrics(false);
575 buffer_view_->draw(pain);
576 Font font = buffer_view_->cursor().getFont();
577 FontMetrics const & fm = theFontMetrics(font);
578 int height = fm.maxHeight();
579 int cur_x = cursor_->rect().left();
580 int cur_y = cursor_->rect().bottom();
582 // redraw area of preedit string.
583 update(0, cur_y - height, GuiWorkArea::width(),
584 (height + 1) * preedit_lines_);
586 if (preedit_string.empty()) {
594 // att : stores an IM attribute.
595 QList<QInputMethodEvent::Attribute> const & att = e->attributes();
597 // get attributes of input method cursor.
598 // cursor_pos : cursor position in preedit string.
599 size_t cursor_pos = 0;
600 bool cursor_is_visible = false;
601 for (int i = 0; i < att.size(); ++i) {
602 if (att.at(i).type == QInputMethodEvent::Cursor) {
603 cursor_pos = att.at(i).start;
604 cursor_is_visible = att.at(i).length != 0;
609 size_t preedit_length = preedit_string.length();
611 // get position of selection in input method.
612 // FIXME: isn't there a way to do this simplier?
613 // rStart : cursor position in selected string in IM.
615 // rLength : selected string length in IM.
617 if (cursor_pos < preedit_length) {
618 for (int i = 0; i < att.size(); ++i) {
619 if (att.at(i).type == QInputMethodEvent::TextFormat) {
620 if (att.at(i).start <= int(cursor_pos)
621 && int(cursor_pos) < att.at(i).start + att.at(i).length) {
622 rStart = att.at(i).start;
623 rLength = att.at(i).length;
624 if (!cursor_is_visible)
625 cursor_pos += rLength;
636 int const right_margin = rightMargin();
637 Painter::preedit_style ps;
638 // Most often there would be only one line:
640 for (size_t pos = 0; pos != preedit_length; ++pos) {
641 char_type const typed_char = preedit_string[pos];
642 // reset preedit string style
643 ps = Painter::preedit_default;
645 // if we reached the right extremity of the screen, go to next line.
646 if (cur_x + fm.width(typed_char) > GuiWorkArea::width() - right_margin) {
647 cur_x = right_margin;
651 // preedit strings are displayed with dashed underline
652 // and partial strings are displayed white on black indicating
653 // that we are in selecting mode in the input method.
654 // FIXME: rLength == preedit_length is not a changing condition
655 // FIXME: should be put out of the loop.
657 && pos < rStart + rLength
658 && !(cursor_pos < rLength && rLength == preedit_length))
659 ps = Painter::preedit_selecting;
661 if (pos == cursor_pos
662 && (cursor_pos < rLength && rLength == preedit_length))
663 ps = Painter::preedit_cursor;
665 // draw one character and update cur_x.
666 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
669 // update the preedit string screen area.
670 update(0, cur_y - preedit_lines_*height, GuiWorkArea::width(),
671 (height + 1) * preedit_lines_);
673 // Don't forget to accept the event!
678 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
680 QRect cur_r(0,0,0,0);
682 // this is the CJK-specific composition window position.
683 case Qt::ImMicroFocus:
684 cur_r = cursor_->rect();
685 if (preedit_lines_ != 1)
687 cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
688 // return lower right of cursor in LyX.
691 return QWidget::inputMethodQuery(query);
695 ////////////////////////////////////////////////////////////////////
696 // TabWorkArea implementation.
697 ////////////////////////////////////////////////////////////////////
698 TabWorkArea::TabWorkArea(QWidget * parent): QTabWidget(parent)
700 QPushButton * closeTabButton = new QPushButton(this);
701 FileName const file = support::libFileSearch("images", "closetab", "png");
703 QPixmap pm(toqstr(file.absFilename()));
704 closeTabButton->setIcon(QIcon(pm));
705 closeTabButton->setMaximumSize(pm.size());
706 closeTabButton->setFlat(true);
708 closeTabButton->setText("Close");
710 closeTabButton->setCursor(Qt::ArrowCursor);
711 closeTabButton->setToolTip(tr("Close tab"));
712 closeTabButton->setEnabled(true);
714 QObject::connect(this, SIGNAL(currentChanged(int)),
715 this, SLOT(on_currentTabChanged(int)));
716 QObject::connect(closeTabButton, SIGNAL(clicked()),
717 this, SLOT(closeCurrentTab()));
719 setCornerWidget(closeTabButton);
720 #if QT_VERSION >= 0x040200
721 setUsesScrollButtons(true);
726 void TabWorkArea::showBar(bool show)
728 tabBar()->setVisible(show);
732 void TabWorkArea::closeAll()
735 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
743 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
745 BOOST_ASSERT(work_area);
746 int index = indexOf(work_area);
750 if (index == currentIndex())
751 // Make sure the work area is up to date.
752 on_currentTabChanged(index);
754 // Switch to the work area.
755 setCurrentIndex(index);
756 work_area->setFocus();
762 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
764 BOOST_ASSERT(work_area);
765 int index = indexOf(work_area);
769 work_area->setUpdatesEnabled(false);
774 // make sure the next work area is enabled.
775 currentWidget()->setUpdatesEnabled(true);
776 // Hide tabbar if there's only one tab.
777 showBar(count() > 1);
783 void TabWorkArea::on_currentTabChanged(int i)
785 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
787 BufferView & bv = wa->bufferView();
788 bv.updateMetrics(false);
789 bv.cursor().fixIfBroken();
790 wa->setUpdatesEnabled(true);
794 currentWorkAreaChanged(wa);
796 LYXERR(Debug::GUI) << "currentTabChanged " << i
797 << "File" << bv.buffer().fileName() << endl;
801 void TabWorkArea::closeCurrentTab()
803 lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
806 } // namespace frontend
809 #include "GuiWorkArea_moc.cpp"