1 /****************************************************************************
3 ** Copyright (C) 2007-2008 Urs Wolfer <uwolfer @ kde.org>
5 ** This file is part of KDE.
7 ** This program is free software; you can redistribute it and/or modify
8 ** it under the terms of the GNU General Public License as published by
9 ** the Free Software Foundation; either version 2 of the License, or
10 ** (at your option) any later version.
12 ** This program is distributed in the hope that it will be useful,
13 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ** GNU General Public License for more details.
17 ** You should have received a copy of the GNU General Public License
18 ** along with this program; see the file COPYING. If not, write to
19 ** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 ** Boston, MA 02110-1301, USA.
22 ****************************************************************************/
29 // Definition of key modifier mask constants
30 #define KMOD_Alt_R 0x01
31 #define KMOD_Alt_L 0x02
32 #define KMOD_Meta_L 0x04
33 #define KMOD_Control_L 0x08
34 #define KMOD_Shift_L 0x10
36 //local cursor width/height in px, should be an odd number
37 const int CURSOR_SIZE = 7;
40 const int TAP_PRESS_TIME = 180;
41 const int DOUBLE_TAP_UP_TIME = 500;
44 VncView::VncView(QWidget *parent, const KUrl &url, RemoteView::Quality quality, int listen_port)
51 m_firstPasswordTry(true),
52 m_dontSendClipboard(false),
53 m_horizontalFactor(1.0),
54 m_verticalFactor(1.0),
55 m_forceLocalCursor(false),
57 listen_port(listen_port),
58 transformation_mode(Qt::FastTransformation)
64 //BlockingQueuedConnection can cause deadlocks when exiting, handled in startQuitting()
65 connect(&vncThread, SIGNAL(imageUpdated(int, int, int, int)), this, SLOT(updateImage(int, int, int, int)), Qt::BlockingQueuedConnection);
66 connect(&vncThread, SIGNAL(gotCut(const QString&)), this, SLOT(setCut(const QString&)), Qt::BlockingQueuedConnection);
67 connect(&vncThread, SIGNAL(passwordRequest()), this, SLOT(requestPassword()), Qt::BlockingQueuedConnection);
68 connect(&vncThread, SIGNAL(outputErrorMessage(QString)), this, SLOT(outputErrorMessage(QString)));
70 //don't miss early connection failures
71 connect(&vncThread, SIGNAL(finished()), this, SLOT(startQuitting()));
73 m_clipboard = QApplication::clipboard();
74 connect(m_clipboard, SIGNAL(selectionChanged()), this, SLOT(clipboardSelectionChanged()));
75 connect(m_clipboard, SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged()));
84 // Disconnect all signals so that we don't get any more callbacks from the client thread
85 vncThread.disconnect();
90 bool VncView::eventFilter(QObject *obj, QEvent *event)
93 if (event->type() == QEvent::KeyPress ||
94 event->type() == QEvent::KeyRelease ||
95 event->type() == QEvent::MouseButtonDblClick ||
96 event->type() == QEvent::MouseButtonPress ||
97 event->type() == QEvent::MouseButtonRelease ||
98 event->type() == QEvent::Wheel ||
99 event->type() == QEvent::MouseMove) {
106 return RemoteView::eventFilter(obj, event);
109 QSize VncView::framebufferSize()
111 return m_frame.size();
114 QSize VncView::sizeHint() const
119 QSize VncView::minimumSizeHint() const
124 void VncView::startQuitting()
129 kDebug(5011) << "about to quit";
131 setStatus(Disconnecting);
137 const bool quitSuccess = vncThread.wait(700);
139 //happens when vncThread wants to call a slot via BlockingQueuedConnection,
140 //needs an event loop in this thread so execution continues after 'emit'
142 if(!loop.processEvents())
143 kDebug(5011) << "BUG: deadlocked, but no events to deliver?";
146 setStatus(Disconnected);
149 bool VncView::isQuitting()
154 bool VncView::start()
156 vncThread.setHost(m_host);
157 vncThread.setPort(m_port);
158 vncThread.setListenPort(listen_port); //if port is != 0, thread will listen for connections
159 vncThread.setQuality(quality);
161 // set local cursor on by default because low quality mostly means slow internet connection
162 if (quality == RemoteView::Low) {
163 showDotCursor(RemoteView::CursorOn);
166 setStatus(Connecting);
172 bool VncView::supportsScaling() const
177 bool VncView::supportsLocalCursor() const
182 void VncView::requestPassword()
184 kDebug(5011) << "request password";
186 setStatus(Authenticating);
188 if (!m_url.password().isNull()) {
189 vncThread.setPassword(m_url.password());
194 settings.beginGroup("hosts");
196 //check for saved password
197 QString password = settings.value(QString("%1/password").arg(m_host), "").toString();
198 if(m_firstPasswordTry and !password.isEmpty()) {
199 kDebug(5011) << "Trying saved password";
200 m_firstPasswordTry = false;
201 vncThread.setPassword(password);
204 m_firstPasswordTry = false;
207 QDialog dialog(this);
208 dialog.setWindowTitle(tr("Password required"));
210 QLineEdit passwordbox;
211 passwordbox.setEchoMode(QLineEdit::Password);
212 passwordbox.setText(password);
213 QCheckBox save_password(tr("Save Password"));
214 save_password.setChecked(!password.isEmpty()); //offer to overwrite saved password
215 QPushButton ok_button(tr("Done"));
216 ok_button.setMaximumWidth(100);
217 connect(&ok_button, SIGNAL(clicked()),
218 &dialog, SLOT(accept()));
222 layout2.addWidget(&passwordbox);
223 if(!m_host.isEmpty()) //don't save incoming connections
224 layout2.addWidget(&save_password);
225 layout1.addLayout(&layout2);
226 layout1.addWidget(&ok_button);
227 dialog.setLayout(&layout1);
229 if(dialog.exec()) { //dialog accepted
230 password = passwordbox.text();
232 if(!m_host.isEmpty() and save_password.isChecked()) {
233 kDebug(5011) << "Saving password for host '" << m_host << "'";
235 settings.setValue(QString("%1/password").arg(m_host), password);
239 vncThread.setPassword(password);
241 vncThread.setPassword(QString()); //null string to exit
245 void VncView::outputErrorMessage(const QString &message)
247 if (message == "INTERNAL:APPLE_VNC_COMPATIBILTY") {
248 setCursor(localDotCursor());
249 m_forceLocalCursor = true;
255 emit errorMessage(i18n("VNC failure"), message);
258 void VncView::updateImage(int x, int y, int w, int h)
260 if(!QApplication::focusWidget()) { //no focus, we're probably minimized
264 //kDebug(5011) << "got update" << width() << height();
271 if (m_horizontalFactor != 1.0 || m_verticalFactor != 1.0) {
272 // If the view is scaled, grow the update rectangle to avoid artifacts
273 int x_extrapixels = 1.0/m_horizontalFactor + 1;
274 int y_extrapixels = 1.0/m_verticalFactor + 1;
278 m_w+=2*x_extrapixels;
279 m_h+=2*y_extrapixels;
282 m_frame = vncThread.image();
284 if (!m_initDone) { //TODO this seems an odd place for initialization
285 setAttribute(Qt::WA_StaticContents);
286 setAttribute(Qt::WA_OpaquePaintEvent);
287 installEventFilter(this);
289 setCursor(((m_dotCursorState == CursorOn) || m_forceLocalCursor) ? localDotCursor() : Qt::BlankCursor);
291 setMouseTracking(true); // get mouse events even when there is no mousebutton pressed
292 setFocusPolicy(Qt::WheelFocus);
293 setStatus(Connected);
296 resize(width(), height());
302 static QSize old_frame_size = QSize();
303 if ((y == 0 && x == 0) && (m_frame.size() != old_frame_size)) {
304 old_frame_size = m_frame.size();
305 kDebug(5011) << "Updating framebuffer size";
307 useFastTransformations(false);
309 emit framebufferSizeChanged(m_frame.width(), m_frame.height());
312 repaint(qRound(m_x * m_horizontalFactor), qRound(m_y * m_verticalFactor), qRound(m_w * m_horizontalFactor), qRound(m_h * m_verticalFactor));
315 void VncView::setViewOnly(bool viewOnly)
317 RemoteView::setViewOnly(viewOnly);
319 m_dontSendClipboard = viewOnly;
322 setCursor(Qt::ArrowCursor);
324 setCursor(m_dotCursorState == CursorOn ? localDotCursor() : Qt::BlankCursor);
327 void VncView::showDotCursor(DotCursorState state)
329 RemoteView::showDotCursor(state);
331 setCursor(state == CursorOn ? localDotCursor() : Qt::BlankCursor);
334 //level should be in [0, 100]
335 void VncView::setZoomLevel(int level)
337 Q_ASSERT(parentWidget() != 0);
339 if(level == -1) { //handle resize
340 resize(m_frame.width()*m_horizontalFactor, m_frame.height()*m_verticalFactor);
344 double magnification;
347 } else if(level >= 90) {
350 const double min_horiz_magnification = double(parentWidget()->width())/m_frame.width();
351 const double min_vert_magnification = double(parentWidget()->height())/m_frame.height();
352 const double fit_screen_magnification = qMin(min_horiz_magnification, min_vert_magnification);
354 //level=90 => magnification=1.0, level=0 => magnification=fit_screen_magnification
355 magnification = (level)/90.0*(1.0 - fit_screen_magnification) + fit_screen_magnification;
358 if(magnification < 0 //remote display smaller than local?
359 or magnification != magnification) //nan
362 m_verticalFactor = m_horizontalFactor = magnification;
363 resize(m_frame.width()*magnification, m_frame.height()*magnification);
366 void VncView::setCut(const QString &text)
368 m_dontSendClipboard = true;
369 m_clipboard->setText(text, QClipboard::Clipboard);
370 m_clipboard->setText(text, QClipboard::Selection);
371 m_dontSendClipboard = false;
374 void VncView::paintEvent(QPaintEvent *event)
376 if (m_frame.isNull() || m_frame.format() == QImage::Format_Invalid) {
377 //no valid image to paint
378 RemoteView::paintEvent(event);
384 const QRect update_rect = event->rect();
385 QPainter painter(this);
386 if (update_rect != rect()) {
387 // kDebug(5011) << "Partial repaint";
388 const int sx = qRound(update_rect.x()/m_horizontalFactor);
389 const int sy = qRound(update_rect.y()/m_verticalFactor);
390 const int sw = qRound(update_rect.width()/m_horizontalFactor);
391 const int sh = qRound(update_rect.height()/m_verticalFactor);
393 painter.drawImage(update_rect,
394 m_frame.copy(sx, sy, sw, sh)
395 .scaled(update_rect.size(), Qt::IgnoreAspectRatio, transformation_mode));
397 //kDebug(5011) << "Full repaint" << width() << height() << m_frame.width() << m_frame.height();
399 painter.drawImage(rect(),
400 m_frame.scaled(size(), Qt::IgnoreAspectRatio, transformation_mode));
403 //draw local cursor ourselves, normal mouse pointer doesn't deal with scrolling
404 if((m_dotCursorState == CursorOn) || m_forceLocalCursor) {
405 #if QT_VERSION >= 0x040500
406 painter.setCompositionMode(QPainter::RasterOp_SourceXorDestination);
408 //rectangle size includes 1px pen width
409 painter.drawRect(cursor_x*m_horizontalFactor - CURSOR_SIZE/2, cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE-1, CURSOR_SIZE-1);
412 RemoteView::paintEvent(event);
415 void VncView::resizeEvent(QResizeEvent *event)
417 RemoteView::resizeEvent(event);
421 bool VncView::event(QEvent *event)
423 switch (event->type()) {
424 case QEvent::KeyPress:
425 case QEvent::KeyRelease:
426 keyEventHandler(static_cast<QKeyEvent*>(event));
429 case QEvent::MouseButtonDblClick:
430 case QEvent::MouseButtonPress:
431 case QEvent::MouseButtonRelease:
432 case QEvent::MouseMove:
433 mouseEventHandler(static_cast<QMouseEvent*>(event));
437 wheelEventHandler(static_cast<QWheelEvent*>(event));
440 case QEvent::WindowActivate: //input panel may have been closed, prevent IM from interfering with hardware keyboard
441 setAttribute(Qt::WA_InputMethodEnabled, false);
444 return RemoteView::event(event);
448 //call with e == 0 to flush held events
449 void VncView::mouseEventHandler(QMouseEvent *e)
451 static bool tap_detected = false;
452 static bool double_tap_detected = false;
453 static bool tap_drag_detected = false;
454 static QTime press_time;
455 static QTime up_time; //used for double clicks/tap&drag, for time after first tap
457 if(!e) { //flush held taps
459 m_buttonMask |= 0x01;
460 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
461 m_buttonMask &= 0xfe;
462 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
463 tap_detected = false;
464 } else if(double_tap_detected and press_time.elapsed() > TAP_PRESS_TIME) { //got tap + another press -> tap & drag
465 m_buttonMask |= 0x01;
466 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
467 double_tap_detected = false;
468 tap_drag_detected = true;
474 if(e->x() < 0 or e->y() < 0) { //QScrollArea tends to send invalid events sometimes...
479 cursor_x = qRound(e->x()/m_horizontalFactor);
480 cursor_y = qRound(e->y()/m_verticalFactor);
481 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask); // plain move event
483 if(!disable_tapping and e->button() == Qt::LeftButton) { //implement touchpad-like input for left button
484 if(e->type() == QEvent::MouseButtonPress or e->type() == QEvent::MouseButtonDblClick) {
486 if(tap_detected and up_time.elapsed() < DOUBLE_TAP_UP_TIME) {
487 tap_detected = false;
488 double_tap_detected = true;
490 QTimer::singleShot(TAP_PRESS_TIME, this, SLOT(mouseEventHandler()));
492 } else if(e->type() == QEvent::MouseButtonRelease) {
493 if(tap_drag_detected) {
494 m_buttonMask &= 0xfe;
495 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
496 tap_drag_detected = false;
497 } else if(double_tap_detected) { //double click
498 double_tap_detected = false;
500 m_buttonMask |= 0x01;
501 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
502 m_buttonMask &= 0xfe;
503 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
504 m_buttonMask |= 0x01;
505 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
506 m_buttonMask &= 0xfe;
507 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
508 } else if(press_time.elapsed() < TAP_PRESS_TIME) { //tap
511 QTimer::singleShot(DOUBLE_TAP_UP_TIME, this, SLOT(mouseEventHandler()));
515 } else { //middle or right button, send directly
516 if ((e->type() == QEvent::MouseButtonPress)) {
517 if (e->button() & Qt::MidButton)
518 m_buttonMask |= 0x02;
519 if (e->button() & Qt::RightButton)
520 m_buttonMask |= 0x04;
521 } else if (e->type() == QEvent::MouseButtonRelease) {
522 if (e->button() & Qt::MidButton)
523 m_buttonMask &= 0xfd;
524 if (e->button() & Qt::RightButton)
525 m_buttonMask &= 0xfb;
527 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
530 //prevent local cursor artifacts
531 static int old_cursor_x = cursor_x;
532 static int old_cursor_y = cursor_y;
533 if(((m_dotCursorState == CursorOn) || m_forceLocalCursor)
534 and (cursor_x != old_cursor_x or cursor_y != old_cursor_y)) {
535 //clear last position
536 repaint(old_cursor_x*m_horizontalFactor - CURSOR_SIZE/2, old_cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE, CURSOR_SIZE);
537 //and refresh new one
538 repaint(cursor_x*m_horizontalFactor - CURSOR_SIZE/2, cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE, CURSOR_SIZE);
540 old_cursor_x = cursor_x; old_cursor_y = cursor_y;
544 void VncView::wheelEventHandler(QWheelEvent *event)
547 if (event->delta() < 0)
552 const int x = qRound(event->x() / m_horizontalFactor);
553 const int y = qRound(event->y() / m_verticalFactor);
555 vncThread.mouseEvent(x, y, eb | m_buttonMask);
556 vncThread.mouseEvent(x, y, m_buttonMask);
559 void VncView::keyEventHandler(QKeyEvent *e)
561 // strip away autorepeating KeyRelease; see bug #206598
562 if (e->isAutoRepeat() && (e->type() == QEvent::KeyRelease)) {
566 // parts of this code are based on http://italc.sourcearchive.com/documentation/1.0.9.1/vncview_8cpp-source.html
567 rfbKeySym k = e->nativeVirtualKey();
569 // we do not handle Key_Backtab separately as the Shift-modifier
570 // is already enabled
571 if (e->key() == Qt::Key_Backtab) {
575 const bool pressed = (e->type() == QEvent::KeyPress);
578 //don't send ISO_Level3_Shift (would break things like Win+0-9)
579 //also enable IM so symbol key works
581 setAttribute(Qt::WA_InputMethodEnabled, pressed);
588 if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L) {
591 } else if (m_mods.contains(k)) {
599 int current_zoom = -1;
600 if(e->key() == Qt::Key_F8)
601 current_zoom = left_zoom;
602 else if(e->key() == Qt::Key_F7)
603 current_zoom = right_zoom;
605 // kDebug(5011) << "got '" << e->text() << "'.";
606 vncThread.keyEvent(k, pressed);
608 kDebug(5011) << "nativeVirtualKey() for '" << e->text() << "' failed.";
612 if(current_zoom == -1)
615 //handle zoom buttons
616 if(current_zoom == 0) { //left click
618 m_buttonMask |= 0x01;
620 m_buttonMask &= 0xfe;
621 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
622 } else if(current_zoom == 1) { //right click
624 m_buttonMask |= 0x04;
626 m_buttonMask &= 0xfb;
627 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
628 } else if(current_zoom == 2) { //middle click
630 m_buttonMask |= 0x02;
632 m_buttonMask &= 0xfd;
633 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
634 } else if(current_zoom == 3 and pressed) { //wheel up
636 vncThread.mouseEvent(cursor_x, cursor_y, eb | m_buttonMask);
637 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
638 } else if(current_zoom == 4 and pressed) { //wheel down
640 vncThread.mouseEvent(cursor_x, cursor_y, eb | m_buttonMask);
641 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
642 } else if(current_zoom == 5) { //page up
643 vncThread.keyEvent(0xff55, pressed);
644 } else if(current_zoom == 6) { //page down
645 vncThread.keyEvent(0xff56, pressed);
649 void VncView::unpressModifiers()
651 const QList<unsigned int> keys = m_mods.keys();
652 QList<unsigned int>::const_iterator it = keys.constBegin();
653 while (it != keys.end()) {
654 vncThread.keyEvent(*it, false);
660 void VncView::clipboardSelectionChanged()
662 if (m_status != Connected)
665 if (m_clipboard->ownsSelection() || m_dontSendClipboard)
668 const QString text = m_clipboard->text(QClipboard::Selection);
670 vncThread.clientCut(text);
673 void VncView::clipboardDataChanged()
675 if (m_status != Connected)
678 if (m_clipboard->ownsClipboard() || m_dontSendClipboard)
681 const QString text = m_clipboard->text(QClipboard::Clipboard);
683 vncThread.clientCut(text);
687 void VncView::sendKey(Qt::Key key)
689 //convert Qt::Key into x11 keysym
701 case Qt::Key_PageDown:
719 case Qt::Key_Backspace:
734 k = 0xffbe + int(key - Qt::Key_F1);
746 case Qt::MetaModifier:
750 case Qt::AltModifier:
753 case Qt::Key_Control:
754 case Qt::ControlModifier:
758 kDebug(5011) << "sendKey(): Unhandled Qt::Key value " << key;
762 if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L || k == XK_Super_L) {
763 if (m_mods.contains(k)) { //release
765 vncThread.keyEvent(k, false);
768 vncThread.keyEvent(k, true);
770 } else { //normal key
771 vncThread.keyEvent(k, true);
772 vncThread.keyEvent(k, false);
776 void VncView::sendKeySequence(QKeySequence keys)
778 Q_ASSERT(keys.count() <= 1); //we can only handle a single combination
780 //to get at individual key presses, we split 'keys' into its components
784 QString k = keys.toString().section('+', pos, pos);
788 //kDebug(5011) << "found key: " << k;
790 key_list.append(Qt::Key_Alt);
791 } else if(k == "Ctrl") {
792 key_list.append(Qt::Key_Control);
793 } else if(k == "Meta") {
794 key_list.append(Qt::Key_Meta);
796 key_list.append(QKeySequence(k)[0]);
802 for(int i = 0; i < key_list.count(); i++)
803 sendKey(Qt::Key(key_list.at(i)));
805 //release modifiers (everything before final key)
806 for(int i = key_list.count()-2; i >= 0; i--)
807 sendKey(Qt::Key(key_list.at(i)));
810 void VncView::reloadSettings()
813 left_zoom = settings.value("left_zoom", 0).toInt();
814 right_zoom = settings.value("right_zoom", 1).toInt();
815 disable_tapping = settings.value("disable_tapping", false).toBool();
817 bool always_show_local_cursor = settings.value("always_show_local_cursor", false).toBool();
818 if(always_show_local_cursor)
819 showDotCursor(CursorOn);
824 //convert commitString into keyevents
825 void VncView::inputMethodEvent(QInputMethodEvent *event)
827 //TODO handle replacements
828 //NOTE for the return key to work Qt needs to enable multiline input, which only works for Q(Plain)TextEdit
830 //kDebug(5011) << event->commitString() << "|" << event->preeditString() << "|" << event->replacementLength() << "|" << event->replacementStart();
831 QString letters = event->commitString();
832 for(int i = 0; i < letters.length(); i++) {
833 char k = letters.at(i).toLatin1();
835 kDebug(5011) << "unhandled key";
838 vncThread.keyEvent(k, true);
839 vncThread.keyEvent(k, false);
843 void VncView::useFastTransformations(bool enabled)
845 if(enabled or zoomFactor() >= 1.0) {
846 transformation_mode = Qt::FastTransformation;
848 transformation_mode = Qt::SmoothTransformation;