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 #include <QMessageBox>
27 #include <QInputDialog>
28 #define KMessageBox QMessageBox
29 #define error(parent, message, caption) \
30 critical(parent, caption, message)
32 #include <QApplication>
37 #include <QHBoxLayout>
38 #include <QVBoxLayout>
40 #include <QMouseEvent>
41 #include <QPushButton>
48 // Definition of key modifier mask constants
49 #define KMOD_Alt_R 0x01
50 #define KMOD_Alt_L 0x02
51 #define KMOD_Meta_L 0x04
52 #define KMOD_Control_L 0x08
53 #define KMOD_Shift_L 0x10
55 //local cursor width/height in px, should be an odd number
56 const int CURSOR_SIZE = 7;
58 const int TAP_PRESS_TIME = 180;
59 const int DOUBLE_TAP_UP_TIME = 500;
62 VncView::VncView(QWidget *parent, const KUrl &url, RemoteView::Quality quality, int listen_port)
69 m_firstPasswordTry(true),
70 m_dontSendClipboard(false),
71 m_horizontalFactor(1.0),
72 m_verticalFactor(1.0),
73 m_forceLocalCursor(false),
75 listen_port(listen_port)
81 //BlockingQueuedConnection can cause deadlocks when exiting, handled in startQuitting()
82 connect(&vncThread, SIGNAL(imageUpdated(int, int, int, int)), this, SLOT(updateImage(int, int, int, int)), Qt::BlockingQueuedConnection);
83 connect(&vncThread, SIGNAL(gotCut(const QString&)), this, SLOT(setCut(const QString&)), Qt::BlockingQueuedConnection);
84 connect(&vncThread, SIGNAL(passwordRequest()), this, SLOT(requestPassword()), Qt::BlockingQueuedConnection);
85 connect(&vncThread, SIGNAL(outputErrorMessage(QString)), this, SLOT(outputErrorMessage(QString)));
87 //don't miss early connection failures
88 connect(&vncThread, SIGNAL(finished()), this, SLOT(startQuitting()));
90 m_clipboard = QApplication::clipboard();
91 connect(m_clipboard, SIGNAL(selectionChanged()), this, SLOT(clipboardSelectionChanged()));
92 connect(m_clipboard, SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged()));
101 // Disconnect all signals so that we don't get any more callbacks from the client thread
102 vncThread.disconnect();
107 bool VncView::eventFilter(QObject *obj, QEvent *event)
110 if (event->type() == QEvent::KeyPress ||
111 event->type() == QEvent::KeyRelease ||
112 event->type() == QEvent::MouseButtonDblClick ||
113 event->type() == QEvent::MouseButtonPress ||
114 event->type() == QEvent::MouseButtonRelease ||
115 event->type() == QEvent::Wheel ||
116 event->type() == QEvent::MouseMove)
119 return RemoteView::eventFilter(obj, event);
122 QSize VncView::framebufferSize()
124 return m_frame.size();
127 QSize VncView::sizeHint() const
132 QSize VncView::minimumSizeHint() const
137 void VncView::startQuitting()
142 kDebug(5011) << "about to quit";
144 //const bool connected = status() == RemoteView::Connected;
146 setStatus(Disconnecting);
150 //if(connected) //remove if things work without it
153 const bool quitSuccess = vncThread.wait(700);
155 //happens when vncThread wants to call a slot via BlockingQueuedConnection,
156 //needs an event loop in this thread so execution continues after 'emit'
158 if(!loop.processEvents())
159 kDebug(5011) << "BUG: deadlocked, but no events to deliver?";
162 setStatus(Disconnected);
165 bool VncView::isQuitting()
170 bool VncView::start()
172 vncThread.setHost(m_host);
173 vncThread.setPort(m_port);
174 vncThread.setListenPort(listen_port); //if port is != 0, thread will listen for connections
175 vncThread.setQuality(quality);
177 // set local cursor on by default because low quality mostly means slow internet connection
178 if (quality == RemoteView::Low) {
179 showDotCursor(RemoteView::CursorOn);
182 setStatus(Connecting);
188 bool VncView::supportsScaling() const
193 bool VncView::supportsLocalCursor() const
198 void VncView::requestPassword()
200 kDebug(5011) << "request password";
202 setStatus(Authenticating);
204 if (!m_url.password().isNull()) {
205 vncThread.setPassword(m_url.password());
210 settings.beginGroup("hosts");
211 QString password = settings.value(QString("%1/password").arg(m_host), "").toString();
212 //check for saved password
213 if(m_firstPasswordTry and !password.isEmpty()) {
214 kDebug(5011) << "Trying saved password";
215 m_firstPasswordTry = false;
216 vncThread.setPassword(password);
219 m_firstPasswordTry = false;
222 QDialog dialog(this);
223 dialog.setWindowTitle(tr("Password required"));
225 QLineEdit passwordbox;
226 passwordbox.setEchoMode(QLineEdit::Password);
227 passwordbox.setText(password);
228 QCheckBox save_password(tr("Save Password"));
229 save_password.setChecked(!password.isEmpty()); //offer to overwrite saved password
230 QPushButton ok_button(tr("Done"));
231 ok_button.setMaximumWidth(100);
232 connect(&ok_button, SIGNAL(clicked()),
233 &dialog, SLOT(accept()));
237 layout2.addWidget(&passwordbox);
238 if(!m_host.isEmpty()) //don't save incomming connections
239 layout2.addWidget(&save_password);
240 layout1.addLayout(&layout2);
241 layout1.addWidget(&ok_button);
242 dialog.setLayout(&layout1);
244 if(dialog.exec()) { //dialog accepted
245 password = passwordbox.text();
247 if(!m_host.isEmpty() and save_password.isChecked()) {
248 kDebug(5011) << "Saving password for host '" << m_host << "'";
250 settings.setValue(QString("%1/password").arg(m_host), password);
254 vncThread.setPassword(password);
256 vncThread.setPassword(QString()); //null string to exit
260 void VncView::outputErrorMessage(const QString &message)
262 if (message == "INTERNAL:APPLE_VNC_COMPATIBILTY") {
263 setCursor(localDotCursor());
264 m_forceLocalCursor = true;
270 emit errorMessage(i18n("VNC failure"), message);
273 void VncView::updateImage(int x, int y, int w, int h)
275 if(!QApplication::focusWidget()) { //no focus, we're probably minimized
279 //kDebug(5011) << "got update" << width() << height();
286 if (m_horizontalFactor != 1.0 || m_verticalFactor != 1.0) {
287 // If the view is scaled, grow the update rectangle to avoid artifacts
288 int x_extrapixels = 1.0/m_horizontalFactor + 1;
289 int y_extrapixels = 1.0/m_verticalFactor + 1;
293 m_w+=2*x_extrapixels;
294 m_h+=2*y_extrapixels;
297 m_frame = vncThread.image();
299 if (!m_initDone) { //TODO this seems an odd place for initialization
300 setAttribute(Qt::WA_StaticContents);
301 setAttribute(Qt::WA_OpaquePaintEvent);
302 installEventFilter(this);
304 setCursor(((m_dotCursorState == CursorOn) || m_forceLocalCursor) ? localDotCursor() : Qt::BlankCursor);
306 setMouseTracking(true); // get mouse events even when there is no mousebutton pressed
307 setFocusPolicy(Qt::WheelFocus);
308 setStatus(Connected);
311 resize(width(), height());
317 static QSize old_frame_size = QSize();
318 if ((y == 0 && x == 0) && (m_frame.size() != old_frame_size)) {
319 old_frame_size = m_frame.size();
320 kDebug(5011) << "Updating framebuffer size";
322 emit framebufferSizeChanged(m_frame.width(), m_frame.height());
325 repaint(qRound(m_x * m_horizontalFactor), qRound(m_y * m_verticalFactor), qRound(m_w * m_horizontalFactor), qRound(m_h * m_verticalFactor));
328 void VncView::setViewOnly(bool viewOnly)
330 RemoteView::setViewOnly(viewOnly);
332 m_dontSendClipboard = viewOnly;
335 setCursor(Qt::ArrowCursor);
337 setCursor(m_dotCursorState == CursorOn ? localDotCursor() : Qt::BlankCursor);
340 void VncView::showDotCursor(DotCursorState state)
342 RemoteView::showDotCursor(state);
344 setCursor(state == CursorOn ? localDotCursor() : Qt::BlankCursor);
347 //level should be in [0, 100]
348 void VncView::setZoomLevel(int level)
350 Q_ASSERT(parentWidget() != 0);
352 if(level == -1) { //handle resize
353 resize(m_frame.width()*m_horizontalFactor, m_frame.height()*m_verticalFactor);
357 double magnification;
360 } else if(level >= 90) {
363 const double min_horiz_magnification = double(parentWidget()->width())/m_frame.width();
364 const double min_vert_magnification = double(parentWidget()->height())/m_frame.height();
365 const double fit_screen_magnification = qMin(min_horiz_magnification, min_vert_magnification);
367 //level=90 => magnification=1.0, level=0 => magnification=fit_screen_magnification
368 magnification = (level)/90.0*(1.0 - fit_screen_magnification) + fit_screen_magnification;
371 if(magnification < 0 //remote display smaller than local?
372 or magnification != magnification) //nan
375 m_verticalFactor = m_horizontalFactor = magnification;
376 resize(m_frame.width()*magnification, m_frame.height()*magnification);
379 void VncView::setCut(const QString &text)
381 m_dontSendClipboard = true;
382 m_clipboard->setText(text, QClipboard::Clipboard);
383 m_clipboard->setText(text, QClipboard::Selection);
384 m_dontSendClipboard = false;
387 void VncView::paintEvent(QPaintEvent *event)
389 //kDebug(5011) << "paint event: x: " << m_x << ", y: " << m_y << ", w: " << m_w << ", h: " << m_h;
390 if (m_frame.isNull() || m_frame.format() == QImage::Format_Invalid) {
391 kDebug(5011) << "no valid image to paint";
392 RemoteView::paintEvent(event);
398 Qt::TransformationMode transformation_mode = Qt::SmoothTransformation;
399 if( m_horizontalFactor >= 1.0 )
400 transformation_mode = Qt::FastTransformation;
402 const QRect update_rect = event->rect();
403 QPainter painter(this);
404 if (update_rect != rect()) {
405 // kDebug(5011) << "Partial repaint";
406 const int sx = qRound(update_rect.x()/m_horizontalFactor);
407 const int sy = qRound(update_rect.y()/m_verticalFactor);
408 const int sw = qRound(update_rect.width()/m_horizontalFactor);
409 const int sh = qRound(update_rect.height()/m_verticalFactor);
411 painter.drawImage(update_rect,
412 m_frame.copy(sx, sy, sw, sh).scaled(update_rect.size(), Qt::IgnoreAspectRatio, transformation_mode));
414 kDebug(5011) << "Full repaint" << width() << height() << m_frame.width() << m_frame.height();
416 painter.drawImage(rect(),
417 m_frame.scaled(size(), Qt::IgnoreAspectRatio, transformation_mode));
420 //draw local cursor ourselves, normal mouse pointer doesn't deal with scrolling
421 if((m_dotCursorState == CursorOn) || m_forceLocalCursor) {
422 #if QT_VERSION >= 0x040500
423 painter.setCompositionMode(QPainter::RasterOp_SourceXorDestination);
425 //rectangle size includes 1px pen width
426 painter.drawRect(cursor_x*m_horizontalFactor - CURSOR_SIZE/2, cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE-1, CURSOR_SIZE-1);
429 RemoteView::paintEvent(event);
432 void VncView::resizeEvent(QResizeEvent *event)
434 RemoteView::resizeEvent(event);
438 bool VncView::event(QEvent *event)
440 switch (event->type()) {
441 case QEvent::KeyPress:
442 case QEvent::KeyRelease:
443 // kDebug(5011) << "keyEvent";
444 keyEventHandler(static_cast<QKeyEvent*>(event));
447 case QEvent::MouseButtonDblClick:
448 case QEvent::MouseButtonPress:
449 case QEvent::MouseButtonRelease:
450 case QEvent::MouseMove:
451 // kDebug(5011) << "mouseEvent";
452 mouseEventHandler(static_cast<QMouseEvent*>(event));
456 // kDebug(5011) << "wheelEvent";
457 wheelEventHandler(static_cast<QWheelEvent*>(event));
460 case QEvent::WindowActivate: //input panel may have been closed, prevent IM from interfering with hardware keyboard
461 setAttribute(Qt::WA_InputMethodEnabled, false);
464 return RemoteView::event(event);
468 //call with e == 0 to flush held events
469 void VncView::mouseEventHandler(QMouseEvent *e)
471 static bool tap_detected = false;
472 static bool double_tap_detected = false;
473 static bool tap_drag_detected = false;
474 static QTime press_time;
475 static QTime up_time; //used for double clicks/tap&drag, for time after first tap
477 if(!e) { //flush held taps
479 m_buttonMask |= 0x01;
480 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
481 m_buttonMask &= 0xfe;
482 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
483 tap_detected = false;
484 } else if(double_tap_detected and press_time.elapsed() > TAP_PRESS_TIME) { //got tap + another press -> tap & drag
485 m_buttonMask |= 0x01;
486 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
487 double_tap_detected = false;
488 tap_drag_detected = true;
494 if(e->x() < 0 or e->y() < 0) { //QScrollArea tends to send invalid events sometimes...
499 cursor_x = qRound(e->x()/m_horizontalFactor);
500 cursor_y = qRound(e->y()/m_verticalFactor);
501 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask); // plain move event
503 if(!disable_tapping and e->button() == Qt::LeftButton) { //implement touchpad-like input for left button
504 if(e->type() == QEvent::MouseButtonPress or e->type() == QEvent::MouseButtonDblClick) {
506 if(tap_detected and up_time.elapsed() < DOUBLE_TAP_UP_TIME) {
507 tap_detected = false;
508 double_tap_detected = true;
510 QTimer::singleShot(TAP_PRESS_TIME, this, SLOT(mouseEventHandler()));
512 } else if(e->type() == QEvent::MouseButtonRelease) {
513 if(tap_drag_detected) {
514 m_buttonMask &= 0xfe;
515 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
516 tap_drag_detected = false;
517 } else if(double_tap_detected) { //double click
518 double_tap_detected = false;
520 m_buttonMask |= 0x01;
521 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
522 m_buttonMask &= 0xfe;
523 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
524 m_buttonMask |= 0x01;
525 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
526 m_buttonMask &= 0xfe;
527 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
528 } else if(press_time.elapsed() < TAP_PRESS_TIME) { //tap
531 QTimer::singleShot(DOUBLE_TAP_UP_TIME, this, SLOT(mouseEventHandler()));
535 } else { //middle or right button, send directly
536 if ((e->type() == QEvent::MouseButtonPress)) {
537 if (e->button() & Qt::MidButton)
538 m_buttonMask |= 0x02;
539 if (e->button() & Qt::RightButton)
540 m_buttonMask |= 0x04;
541 } else if (e->type() == QEvent::MouseButtonRelease) {
542 if (e->button() & Qt::MidButton)
543 m_buttonMask &= 0xfd;
544 if (e->button() & Qt::RightButton)
545 m_buttonMask &= 0xfb;
547 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
550 //prevent local cursor artifacts
551 static int old_cursor_x = cursor_x;
552 static int old_cursor_y = cursor_y;
553 if(((m_dotCursorState == CursorOn) || m_forceLocalCursor)
554 and (cursor_x != old_cursor_x or cursor_y != old_cursor_y)) {
555 //clear last position
556 repaint(old_cursor_x*m_horizontalFactor - CURSOR_SIZE/2, old_cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE, CURSOR_SIZE);
557 //and refresh new one
558 repaint(cursor_x*m_horizontalFactor - CURSOR_SIZE/2, cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE, CURSOR_SIZE);
560 old_cursor_x = cursor_x; old_cursor_y = cursor_y;
564 void VncView::wheelEventHandler(QWheelEvent *event)
567 if (event->delta() < 0)
572 const int x = qRound(event->x() / m_horizontalFactor);
573 const int y = qRound(event->y() / m_verticalFactor);
575 vncThread.mouseEvent(x, y, eb | m_buttonMask);
576 vncThread.mouseEvent(x, y, m_buttonMask);
579 void VncView::keyEventHandler(QKeyEvent *e)
581 // strip away autorepeating KeyRelease; see bug #206598
582 if (e->isAutoRepeat() && (e->type() == QEvent::KeyRelease)) {
586 // parts of this code are based on http://italc.sourcearchive.com/documentation/1.0.9.1/vncview_8cpp-source.html
587 rfbKeySym k = e->nativeVirtualKey();
589 // we do not handle Key_Backtab separately as the Shift-modifier
590 // is already enabled
591 if (e->key() == Qt::Key_Backtab) {
595 const bool pressed = (e->type() == QEvent::KeyPress);
598 //don't send ISO_Level3_Shift (would break things like Win+0-9)
599 //also enable IM so symbol key works
601 setAttribute(Qt::WA_InputMethodEnabled, pressed);
608 if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L) {
611 } else if (m_mods.contains(k)) {
619 int current_zoom = -1;
620 if(e->key() == Qt::Key_F8)
621 current_zoom = left_zoom;
622 else if(e->key() == Qt::Key_F7)
623 current_zoom = right_zoom;
625 // kDebug(5011) << "got '" << e->text() << "'.";
626 vncThread.keyEvent(k, pressed);
628 kDebug(5011) << "nativeVirtualKey() for '" << e->text() << "' failed.";
632 if(current_zoom == -1)
635 //handle zoom buttons
636 if(current_zoom == 0) { //left click
638 m_buttonMask |= 0x01;
640 m_buttonMask &= 0xfe;
641 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
642 } else if(current_zoom == 1) { //right click
644 m_buttonMask |= 0x04;
646 m_buttonMask &= 0xfb;
647 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
648 } else if(current_zoom == 2) { //middle click
650 m_buttonMask |= 0x02;
652 m_buttonMask &= 0xfd;
653 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
654 } else if(current_zoom == 3 and pressed) { //wheel up
656 vncThread.mouseEvent(cursor_x, cursor_y, eb | m_buttonMask);
657 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
658 } else if(current_zoom == 4 and pressed) { //wheel down
660 vncThread.mouseEvent(cursor_x, cursor_y, eb | m_buttonMask);
661 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
662 } else if(current_zoom == 5) { //page up
663 vncThread.keyEvent(0xff55, pressed);
664 } else if(current_zoom == 6) { //page down
665 vncThread.keyEvent(0xff56, pressed);
669 void VncView::unpressModifiers()
671 const QList<unsigned int> keys = m_mods.keys();
672 QList<unsigned int>::const_iterator it = keys.constBegin();
673 while (it != keys.end()) {
674 vncThread.keyEvent(*it, false);
680 void VncView::clipboardSelectionChanged()
682 if (m_status != Connected)
685 if (m_clipboard->ownsSelection() || m_dontSendClipboard)
688 const QString text = m_clipboard->text(QClipboard::Selection);
690 vncThread.clientCut(text);
693 void VncView::clipboardDataChanged()
695 if (m_status != Connected)
698 if (m_clipboard->ownsClipboard() || m_dontSendClipboard)
701 const QString text = m_clipboard->text(QClipboard::Clipboard);
703 vncThread.clientCut(text);
707 void VncView::sendKey(Qt::Key key)
709 //convert Qt::Key into x11 keysym
721 case Qt::Key_PageDown:
739 case Qt::Key_Backspace:
754 k = 0xffbe + int(key - Qt::Key_F1);
766 case Qt::MetaModifier:
770 case Qt::AltModifier:
773 case Qt::Key_Control:
774 case Qt::ControlModifier:
778 kDebug(5011) << "sendKey(): Unhandled Qt::Key value " << key;
782 if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L || k == XK_Super_L) {
783 if (m_mods.contains(k)) { //release
785 vncThread.keyEvent(k, false);
788 vncThread.keyEvent(k, true);
790 } else { //normal key
791 vncThread.keyEvent(k, true);
792 vncThread.keyEvent(k, false);
796 void VncView::sendKeySequence(QKeySequence keys)
798 Q_ASSERT(keys.count() <= 1); //we can only handle a single combination
800 //to get at individual key presses, we split 'keys' into its components
804 QString k = keys.toString().section('+', pos, pos);
808 //kDebug(5011) << "found key: " << k;
810 key_list.append(Qt::Key_Alt);
811 } else if(k == "Ctrl") {
812 key_list.append(Qt::Key_Control);
813 } else if(k == "Meta") {
814 key_list.append(Qt::Key_Meta);
816 key_list.append(QKeySequence(k)[0]);
822 for(int i = 0; i < key_list.count(); i++)
823 sendKey(Qt::Key(key_list.at(i)));
825 //release modifiers (everything before final key)
826 for(int i = key_list.count()-2; i >= 0; i--)
827 sendKey(Qt::Key(key_list.at(i)));
830 void VncView::reloadSettings()
833 left_zoom = settings.value("left_zoom", 0).toInt();
834 right_zoom = settings.value("right_zoom", 1).toInt();
835 disable_tapping = settings.value("disable_tapping", false).toBool();
837 bool always_show_local_cursor = settings.value("always_show_local_cursor", false).toBool();
838 if(always_show_local_cursor)
839 showDotCursor(CursorOn);
844 //convert commitString into keyevents
845 void VncView::inputMethodEvent(QInputMethodEvent *event)
847 //TODO handle replacements
848 //NOTE for the return key to work Qt needs to enable multiline input, which only works for Q(Plain)TextEdit
850 //kDebug(5011) << event->commitString() << "|" << event->preeditString() << "|" << event->replacementLength() << "|" << event->replacementStart();
851 QString letters = event->commitString();
852 for(int i = 0; i < letters.length(); i++) {
853 char k = letters.at(i).toLatin1(); //works with all 'normal' keys, not umlauts.
855 kDebug(5011) << "unhandled key";
858 vncThread.keyEvent(k, true);
859 vncThread.keyEvent(k, false);
864 #include "moc_vncview.cpp"