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 ****************************************************************************/
26 //for mouse button masks
27 #include "rfb/rfbproto.h"
32 // Definition of key modifier mask constants
33 #define KMOD_Alt_R 0x01
34 #define KMOD_Alt_L 0x02
35 #define KMOD_Meta_L 0x04
36 #define KMOD_Control_L 0x08
37 #define KMOD_Shift_L 0x10
39 //local cursor width/height in px, should be an odd number
40 const int CURSOR_SIZE = 7;
43 const int TAP_PRESS_TIME = 180;
44 const int DOUBLE_TAP_UP_TIME = 500;
47 VncView::VncView(QWidget *parent, const KUrl &url, RemoteView::Quality quality, int listen_port)
54 m_firstPasswordTry(true),
55 m_dontSendClipboard(false),
56 m_horizontalFactor(1.0),
57 m_verticalFactor(1.0),
58 m_forceLocalCursor(false),
60 listen_port(listen_port),
61 transformation_mode(Qt::FastTransformation),
68 //BlockingQueuedConnection can cause deadlocks when exiting, handled in startQuitting()
69 connect(&vncThread, SIGNAL(imageUpdated(int, int, int, int)), this, SLOT(updateImage(int, int, int, int)), Qt::BlockingQueuedConnection);
70 connect(&vncThread, SIGNAL(gotCut(const QString&)), this, SLOT(setCut(const QString&)), Qt::BlockingQueuedConnection);
71 connect(&vncThread, SIGNAL(passwordRequest()), this, SLOT(requestPassword()), Qt::BlockingQueuedConnection);
72 connect(&vncThread, SIGNAL(outputErrorMessage(QString)), this, SLOT(outputErrorMessage(QString)));
74 //don't miss early connection failures
75 connect(&vncThread, SIGNAL(finished()), this, SLOT(startQuitting()));
77 m_clipboard = QApplication::clipboard();
78 connect(m_clipboard, SIGNAL(selectionChanged()), this, SLOT(clipboardSelectionChanged()));
79 connect(m_clipboard, SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged()));
88 // Disconnect all signals so that we don't get any more callbacks from the client thread
89 vncThread.disconnect();
94 bool VncView::eventFilter(QObject *obj, QEvent *event)
97 if (event->type() == QEvent::KeyPress ||
98 event->type() == QEvent::KeyRelease ||
99 event->type() == QEvent::MouseButtonDblClick ||
100 event->type() == QEvent::MouseButtonPress ||
101 event->type() == QEvent::MouseButtonRelease ||
102 event->type() == QEvent::Wheel ||
103 event->type() == QEvent::MouseMove) {
110 return RemoteView::eventFilter(obj, event);
113 QSize VncView::framebufferSize()
115 return m_frame.size();
118 QSize VncView::sizeHint() const
123 QSize VncView::minimumSizeHint() const
128 void VncView::startQuitting()
133 kDebug(5011) << "about to quit";
135 setStatus(Disconnecting);
141 const bool quitSuccess = vncThread.wait(700);
143 //happens when vncThread wants to call a slot via BlockingQueuedConnection,
144 //needs an event loop in this thread so execution continues after 'emit'
146 if(!loop.processEvents())
147 kDebug(5011) << "BUG: deadlocked, but no events to deliver?";
150 setStatus(Disconnected);
153 bool VncView::isQuitting()
158 bool VncView::start()
160 vncThread.setHost(m_host);
161 vncThread.setPort(m_port);
162 vncThread.setListenPort(listen_port); //if port is != 0, thread will listen for connections
163 vncThread.setQuality(quality);
165 // set local cursor on by default because low quality mostly means slow internet connection
166 if (quality == RemoteView::Low) {
167 showDotCursor(RemoteView::CursorOn);
170 setStatus(Connecting);
176 bool VncView::supportsScaling() const
181 bool VncView::supportsLocalCursor() const
186 void VncView::requestPassword()
188 kDebug(5011) << "request password";
190 setStatus(Authenticating);
192 if (!m_url.password().isNull()) {
193 vncThread.setPassword(m_url.password());
198 settings.beginGroup("hosts");
200 //check for saved password
201 QString password = settings.value(QString("%1/password").arg(m_host), "").toString();
202 if(m_firstPasswordTry and !password.isEmpty()) {
203 kDebug(5011) << "Trying saved password";
204 m_firstPasswordTry = false;
205 vncThread.setPassword(password);
208 m_firstPasswordTry = false;
211 QDialog dialog(this);
212 dialog.setWindowTitle(tr("Password required"));
214 QLineEdit passwordbox;
215 passwordbox.setEchoMode(QLineEdit::Password);
216 passwordbox.setText(password);
217 QCheckBox save_password(tr("Save Password"));
218 save_password.setChecked(!password.isEmpty()); //offer to overwrite saved password
219 QPushButton ok_button(tr("Done"));
220 ok_button.setMaximumWidth(100);
221 connect(&ok_button, SIGNAL(clicked()),
222 &dialog, SLOT(accept()));
226 layout2.addWidget(&passwordbox);
227 if(!m_host.isEmpty()) //don't save incoming connections
228 layout2.addWidget(&save_password);
229 layout1.addLayout(&layout2);
230 layout1.addWidget(&ok_button);
231 dialog.setLayout(&layout1);
233 if(dialog.exec()) { //dialog accepted
234 password = passwordbox.text();
236 if(!m_host.isEmpty() and save_password.isChecked()) {
237 kDebug(5011) << "Saving password for host '" << m_host << "'";
239 settings.setValue(QString("%1/password").arg(m_host), password);
243 vncThread.setPassword(password);
245 vncThread.setPassword(QString()); //null string to exit
249 void VncView::outputErrorMessage(const QString &message)
251 if (message == "INTERNAL:APPLE_VNC_COMPATIBILTY") {
252 setCursor(localDotCursor());
253 m_forceLocalCursor = true;
259 emit errorMessage(i18n("VNC failure"), message);
262 void VncView::updateImage(int x, int y, int w, int h)
264 //don't update if window is out of focus / display is off
265 if(!QApplication::focusWidget() || display_off) {
269 //kDebug(5011) << "got update" << width() << height();
276 if (m_horizontalFactor != 1.0 || m_verticalFactor != 1.0) {
277 // If the view is scaled, grow the update rectangle to avoid artifacts
278 int x_extrapixels = 1.0/m_horizontalFactor + 1;
279 int y_extrapixels = 1.0/m_verticalFactor + 1;
283 m_w+=2*x_extrapixels;
284 m_h+=2*y_extrapixels;
287 m_frame = vncThread.image();
289 if (!m_initDone) { //TODO this seems an odd place for initialization
290 setAttribute(Qt::WA_StaticContents);
291 setAttribute(Qt::WA_OpaquePaintEvent);
292 installEventFilter(this);
294 setCursor(((m_dotCursorState == CursorOn) || m_forceLocalCursor) ? localDotCursor() : Qt::BlankCursor);
296 setMouseTracking(true); // get mouse events even when there is no mousebutton pressed
297 setFocusPolicy(Qt::WheelFocus);
298 setStatus(Connected);
301 resize(width(), height());
306 static QSize old_frame_size = QSize();
307 if ((y == 0 && x == 0) && (m_frame.size() != old_frame_size)) {
308 old_frame_size = m_frame.size();
309 kDebug(5011) << "Updating framebuffer size";
311 useFastTransformations(false);
313 emit framebufferSizeChanged(m_frame.width(), m_frame.height());
316 repaint(qRound(m_x * m_horizontalFactor), qRound(m_y * m_verticalFactor), qRound(m_w * m_horizontalFactor), qRound(m_h * m_verticalFactor));
319 void VncView::setViewOnly(bool viewOnly)
321 RemoteView::setViewOnly(viewOnly);
323 m_dontSendClipboard = viewOnly;
326 showDotCursor(CursorOff);
327 setCursor(Qt::ArrowCursor);
329 setCursor(m_dotCursorState == CursorOn ? localDotCursor() : Qt::BlankCursor);
333 void VncView::showDotCursor(DotCursorState state)
335 RemoteView::showDotCursor(state);
337 setCursor(state == CursorOn ? localDotCursor() : Qt::BlankCursor);
340 //level should be in [0, 100]
341 void VncView::setZoomLevel(int level)
343 Q_ASSERT(parentWidget() != 0);
345 if(level == -1) { //handle resize
346 resize(m_frame.width()*m_horizontalFactor, m_frame.height()*m_verticalFactor);
350 double magnification;
353 } else if(level >= 90) {
356 const double min_horiz_magnification = double(parentWidget()->width())/m_frame.width();
357 const double min_vert_magnification = double(parentWidget()->height())/m_frame.height();
358 const double fit_screen_magnification = qMin(min_horiz_magnification, min_vert_magnification);
360 //level=90 => magnification=1.0, level=0 => magnification=fit_screen_magnification
361 magnification = (level)/90.0*(1.0 - fit_screen_magnification) + fit_screen_magnification;
364 if(magnification < 0 //remote display smaller than local?
365 or magnification != magnification) //nan
368 m_verticalFactor = m_horizontalFactor = magnification;
369 resize(m_frame.width()*magnification, m_frame.height()*magnification);
372 void VncView::setCut(const QString &text)
374 m_dontSendClipboard = true;
375 m_clipboard->setText(text, QClipboard::Clipboard);
376 m_clipboard->setText(text, QClipboard::Selection);
377 m_dontSendClipboard = false;
380 void VncView::paintEvent(QPaintEvent *event)
382 if (m_frame.isNull() || m_frame.format() == QImage::Format_Invalid) {
383 //no valid image to paint
384 RemoteView::paintEvent(event);
390 //split update region into smaller non-intersecting rectangles and only paint those
391 QPainter painter(this);
392 foreach(const QRect& update_rect, event->region().rects()) {
393 const int sx = qRound(update_rect.x()/m_horizontalFactor);
394 const int sy = qRound(update_rect.y()/m_verticalFactor);
395 const int sw = qRound(update_rect.width()/m_horizontalFactor);
396 const int sh = qRound(update_rect.height()/m_verticalFactor);
398 //kDebug(5011) << "Partial repaint, widget x,y,w,h:" << update_rect.x() << update_rect.y() << update_rect.width() << update_rect.height() << "orig: " << sx << sy << sw << sh;
400 painter.drawImage(update_rect,
401 m_frame.copy(sx, sy, sw, sh)
402 .scaled(update_rect.size(), Qt::IgnoreAspectRatio, transformation_mode));
405 //draw local cursor ourselves, normal mouse pointer doesn't deal with scrolling
406 if((m_dotCursorState == CursorOn) || m_forceLocalCursor) {
407 #if QT_VERSION >= 0x040500
408 painter.setCompositionMode(QPainter::RasterOp_SourceXorDestination);
410 //rectangle size includes 1px pen width
411 painter.drawRect(cursor_x*m_horizontalFactor - CURSOR_SIZE/2, cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE-1, CURSOR_SIZE-1);
414 RemoteView::paintEvent(event);
417 void VncView::resizeEvent(QResizeEvent *event)
419 RemoteView::resizeEvent(event);
423 bool VncView::event(QEvent *event)
425 switch (event->type()) {
426 case QEvent::KeyPress:
427 case QEvent::KeyRelease:
428 keyEventHandler(static_cast<QKeyEvent*>(event));
431 case QEvent::MouseButtonDblClick:
432 case QEvent::MouseButtonPress:
433 case QEvent::MouseButtonRelease:
434 case QEvent::MouseMove:
435 mouseEventHandler(static_cast<QMouseEvent*>(event));
439 wheelEventHandler(static_cast<QWheelEvent*>(event));
442 case QEvent::WindowActivate: //input panel may have been closed, prevent IM from interfering with hardware keyboard
443 setAttribute(Qt::WA_InputMethodEnabled, false);
446 return RemoteView::event(event);
450 //call with e == 0 to flush held events
451 void VncView::mouseEventHandler(QMouseEvent *e)
453 static bool tap_detected = false;
454 static bool double_tap_detected = false;
455 static bool tap_drag_detected = false;
456 static QTime press_time;
457 static QTime up_time; //used for double clicks/tap&drag, for time after first tap
460 if(!e) { //flush held taps
462 m_buttonMask |= rfbButton1Mask;
463 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
464 m_buttonMask &= ~rfbButton1Mask;
465 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
466 tap_detected = false;
467 } else if(double_tap_detected and press_time.elapsed() > TAP_PRESS_TIME) { //got tap + another press -> tap & drag
468 m_buttonMask |= rfbButton1Mask;
469 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
470 double_tap_detected = false;
471 tap_drag_detected = true;
477 if(e->x() < 0 or e->y() < 0) { //QScrollArea tends to send invalid events sometimes...
482 cursor_x = qRound(e->x()/m_horizontalFactor);
483 cursor_y = qRound(e->y()/m_verticalFactor);
484 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask); // plain move event
486 if(!disable_tapping and e->button() == Qt::LeftButton) { //implement touchpad-like input for left button
487 if(e->type() == QEvent::MouseButtonPress or e->type() == QEvent::MouseButtonDblClick) {
489 if(tap_detected and up_time.elapsed() < DOUBLE_TAP_UP_TIME) {
490 tap_detected = false;
491 double_tap_detected = true;
493 QTimer::singleShot(TAP_PRESS_TIME, this, SLOT(mouseEventHandler()));
495 } else if(e->type() == QEvent::MouseButtonRelease) {
496 if(tap_drag_detected) { //end tap & drag
497 m_buttonMask &= ~rfbButton1Mask;
498 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
499 tap_drag_detected = false;
500 } else if(double_tap_detected) { //double click
501 double_tap_detected = false;
503 m_buttonMask |= rfbButton1Mask;
504 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
505 m_buttonMask &= ~rfbButton1Mask;
506 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
507 m_buttonMask |= rfbButton1Mask;
508 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
509 m_buttonMask &= ~rfbButton1Mask;
510 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
511 } else if(press_time.elapsed() < TAP_PRESS_TIME) { //tap
514 QTimer::singleShot(DOUBLE_TAP_UP_TIME, this, SLOT(mouseEventHandler()));
518 } else { //middle or right button, send directly
519 if ((e->type() == QEvent::MouseButtonPress)) {
520 if (e->button() & Qt::MidButton)
521 m_buttonMask |= rfbButton2Mask;
522 if (e->button() & Qt::RightButton)
523 m_buttonMask |= rfbButton3Mask;
524 } else if (e->type() == QEvent::MouseButtonRelease) {
525 if (e->button() & Qt::MidButton)
526 m_buttonMask &= ~rfbButton2Mask;
527 if (e->button() & Qt::RightButton)
528 m_buttonMask &= ~rfbButton3Mask;
530 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
533 //prevent local cursor artifacts
534 static int old_cursor_x = cursor_x;
535 static int old_cursor_y = cursor_y;
536 if(((m_dotCursorState == CursorOn) || m_forceLocalCursor)
537 and (cursor_x != old_cursor_x or cursor_y != old_cursor_y)) {
538 //clear last position
539 repaint(old_cursor_x*m_horizontalFactor - CURSOR_SIZE/2, old_cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE, CURSOR_SIZE);
540 //and refresh new one
541 repaint(cursor_x*m_horizontalFactor - CURSOR_SIZE/2, cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE, CURSOR_SIZE);
543 old_cursor_x = cursor_x;
544 old_cursor_y = cursor_y;
548 void VncView::wheelEventHandler(QWheelEvent *event)
551 if (event->delta() < 0)
552 eb |= rfbWheelDownMask;
554 eb |= rfbWheelUpMask;
556 const int x = qRound(event->x() / m_horizontalFactor);
557 const int y = qRound(event->y() / m_verticalFactor);
559 vncThread.mouseEvent(x, y, m_buttonMask | eb);
560 vncThread.mouseEvent(x, y, m_buttonMask);
563 void VncView::keyEventHandler(QKeyEvent *e)
565 // strip away autorepeating KeyRelease; see bug #206598
566 if (e->isAutoRepeat() && (e->type() == QEvent::KeyRelease)) {
570 // parts of this code are based on http://italc.sourcearchive.com/documentation/1.0.9.1/vncview_8cpp-source.html
571 rfbKeySym k = e->nativeVirtualKey();
573 // we do not handle Key_Backtab separately as the Shift-modifier
574 // is already enabled
575 if (e->key() == Qt::Key_Backtab) {
579 const bool pressed = (e->type() == QEvent::KeyPress);
582 //don't send ISO_Level3_Shift (would break things like Win+0-9)
583 //also enable IM so symbol key works
585 setAttribute(Qt::WA_InputMethodEnabled, pressed);
592 if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L) {
595 } else if (m_mods.contains(k)) {
603 int current_zoom = -1;
604 if(e->key() == Qt::Key_F8)
605 current_zoom = left_zoom;
606 else if(e->key() == Qt::Key_F7)
607 current_zoom = right_zoom;
609 // kDebug(5011) << "got '" << e->text() << "'.";
610 vncThread.keyEvent(k, pressed);
612 kDebug(5011) << "nativeVirtualKey() for '" << e->text() << "' failed.";
616 if(current_zoom == -1)
619 //handle zoom buttons
620 if(current_zoom == 0) { //left click
622 m_buttonMask |= rfbButton1Mask;
624 m_buttonMask &= ~rfbButton1Mask;
625 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
626 } else if(current_zoom == 1) { //right click
628 m_buttonMask |= rfbButton3Mask;
630 m_buttonMask &= ~rfbButton3Mask;
631 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
632 } else if(current_zoom == 2) { //middle click
634 m_buttonMask |= rfbButton2Mask;
636 m_buttonMask &= ~rfbButton2Mask;
637 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
638 } else if(current_zoom == 3 and pressed) { //wheel up
639 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask | rfbWheelUpMask);
640 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
641 } else if(current_zoom == 4 and pressed) { //wheel down
642 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask | rfbWheelDownMask);
643 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
644 } else if(current_zoom == 5) { //page up
645 vncThread.keyEvent(0xff55, pressed);
646 } else if(current_zoom == 6) { //page down
647 vncThread.keyEvent(0xff56, pressed);
651 void VncView::unpressModifiers()
653 const QList<unsigned int> keys = m_mods.keys();
654 QList<unsigned int>::const_iterator it = keys.constBegin();
655 while (it != keys.end()) {
656 vncThread.keyEvent(*it, false);
662 void VncView::clipboardSelectionChanged()
664 if (m_status != Connected)
667 if (m_clipboard->ownsSelection() || m_dontSendClipboard)
670 const QString text = m_clipboard->text(QClipboard::Selection);
672 vncThread.clientCut(text);
675 void VncView::clipboardDataChanged()
677 if (m_status != Connected)
680 if (m_clipboard->ownsClipboard() || m_dontSendClipboard)
683 const QString text = m_clipboard->text(QClipboard::Clipboard);
685 vncThread.clientCut(text);
689 void VncView::sendKey(Qt::Key key)
691 //convert Qt::Key into x11 keysym
703 case Qt::Key_PageDown:
721 case Qt::Key_Backspace:
736 k = 0xffbe + int(key - Qt::Key_F1);
748 case Qt::MetaModifier:
752 case Qt::AltModifier:
755 case Qt::Key_Control:
756 case Qt::ControlModifier:
760 kDebug(5011) << "sendKey(): Unhandled Qt::Key value " << key;
764 if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L || k == XK_Super_L) {
765 if (m_mods.contains(k)) { //release
767 vncThread.keyEvent(k, false);
770 vncThread.keyEvent(k, true);
772 } else { //normal key
773 vncThread.keyEvent(k, true);
774 vncThread.keyEvent(k, false);
778 void VncView::sendKeySequence(QKeySequence keys)
780 Q_ASSERT(keys.count() <= 1); //we can only handle a single combination
782 //to get at individual key presses, we split 'keys' into its components
786 QString k = keys.toString().section('+', pos, pos);
790 //kDebug(5011) << "found key: " << k;
792 key_list.append(Qt::Key_Alt);
793 } else if(k == "Ctrl") {
794 key_list.append(Qt::Key_Control);
795 } else if(k == "Meta") {
796 key_list.append(Qt::Key_Meta);
798 key_list.append(QKeySequence(k)[0]);
804 for(int i = 0; i < key_list.count(); i++)
805 sendKey(Qt::Key(key_list.at(i)));
807 //release modifiers (everything before final key)
808 for(int i = key_list.count()-2; i >= 0; i--)
809 sendKey(Qt::Key(key_list.at(i)));
812 void VncView::reloadSettings()
815 left_zoom = settings.value("left_zoom", 0).toInt();
816 right_zoom = settings.value("right_zoom", 1).toInt();
817 disable_tapping = settings.value("disable_tapping", false).toBool();
819 bool always_show_local_cursor = settings.value("always_show_local_cursor", false).toBool();
820 if(always_show_local_cursor)
821 showDotCursor(CursorOn);
826 //convert commitString into keyevents
827 void VncView::inputMethodEvent(QInputMethodEvent *event)
829 //TODO handle replacements
830 //NOTE for the return key to work Qt needs to enable multiline input, which only works for Q(Plain)TextEdit
832 //kDebug(5011) << event->commitString() << "|" << event->preeditString() << "|" << event->replacementLength() << "|" << event->replacementStart();
833 QString letters = event->commitString();
834 for(int i = 0; i < letters.length(); i++) {
835 char k = letters.at(i).toLatin1();
837 kDebug(5011) << "unhandled key";
840 vncThread.keyEvent(k, true);
841 vncThread.keyEvent(k, false);
845 void VncView::useFastTransformations(bool enabled)
847 if(enabled or zoomFactor() >= 1.0) {
848 transformation_mode = Qt::FastTransformation;
850 transformation_mode = Qt::SmoothTransformation;