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),
74 force_full_repaint(false),
76 listen_port(listen_port)
82 //BlockingQueuedConnection can cause deadlocks when exiting, handled in startQuitting()
83 connect(&vncThread, SIGNAL(imageUpdated(int, int, int, int)), this, SLOT(updateImage(int, int, int, int)), Qt::BlockingQueuedConnection);
84 connect(&vncThread, SIGNAL(gotCut(const QString&)), this, SLOT(setCut(const QString&)), Qt::BlockingQueuedConnection);
85 connect(&vncThread, SIGNAL(passwordRequest()), this, SLOT(requestPassword()), Qt::BlockingQueuedConnection);
86 connect(&vncThread, SIGNAL(outputErrorMessage(QString)), this, SLOT(outputErrorMessage(QString)));
88 //don't miss early connection failures
89 connect(&vncThread, SIGNAL(finished()), this, SLOT(startQuitting()));
91 m_clipboard = QApplication::clipboard();
92 connect(m_clipboard, SIGNAL(selectionChanged()), this, SLOT(clipboardSelectionChanged()));
93 connect(m_clipboard, SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged()));
102 // Disconnect all signals so that we don't get any more callbacks from the client thread
103 vncThread.disconnect();
108 void VncView::forceFullRepaint()
110 force_full_repaint = true;
114 bool VncView::eventFilter(QObject *obj, QEvent *event)
117 if (event->type() == QEvent::KeyPress ||
118 event->type() == QEvent::KeyRelease ||
119 event->type() == QEvent::MouseButtonDblClick ||
120 event->type() == QEvent::MouseButtonPress ||
121 event->type() == QEvent::MouseButtonRelease ||
122 event->type() == QEvent::Wheel ||
123 event->type() == QEvent::MouseMove)
126 return RemoteView::eventFilter(obj, event);
129 QSize VncView::framebufferSize()
131 return m_frame.size();
134 QSize VncView::sizeHint() const
139 QSize VncView::minimumSizeHint() const
144 void VncView::startQuitting()
149 kDebug(5011) << "about to quit";
151 //const bool connected = status() == RemoteView::Connected;
153 setStatus(Disconnecting);
157 //if(connected) //remove if things work without it
160 const bool quitSuccess = vncThread.wait(700);
162 //happens when vncThread wants to call a slot via BlockingQueuedConnection,
163 //needs an event loop in this thread so execution continues after 'emit'
165 if(!loop.processEvents())
166 kDebug(5011) << "BUG: deadlocked, but no events to deliver?";
169 setStatus(Disconnected);
172 bool VncView::isQuitting()
177 bool VncView::start()
179 vncThread.setHost(m_host);
180 vncThread.setPort(m_port);
181 vncThread.setListenPort(listen_port); //if port is != 0, thread will listen for connections
182 vncThread.setQuality(quality);
184 // set local cursor on by default because low quality mostly means slow internet connection
185 if (quality == RemoteView::Low) {
186 showDotCursor(RemoteView::CursorOn);
189 setStatus(Connecting);
195 bool VncView::supportsScaling() const
200 bool VncView::supportsLocalCursor() const
205 void VncView::requestPassword()
207 kDebug(5011) << "request password";
209 setStatus(Authenticating);
211 if (!m_url.password().isNull()) {
212 vncThread.setPassword(m_url.password());
217 settings.beginGroup("hosts");
218 QString password = settings.value(QString("%1/password").arg(m_host), "").toString();
219 //check for saved password
220 if(m_firstPasswordTry and !password.isEmpty()) {
221 kDebug(5011) << "Trying saved password";
222 m_firstPasswordTry = false;
223 vncThread.setPassword(password);
226 m_firstPasswordTry = false;
229 QDialog dialog(this);
230 dialog.setWindowTitle(tr("Password required"));
232 QLineEdit passwordbox;
233 passwordbox.setEchoMode(QLineEdit::Password);
234 passwordbox.setText(password);
235 QCheckBox save_password(tr("Save Password"));
236 save_password.setChecked(!password.isEmpty()); //offer to overwrite saved password
237 QPushButton ok_button(tr("Done"));
238 ok_button.setMaximumWidth(100);
239 connect(&ok_button, SIGNAL(clicked()),
240 &dialog, SLOT(accept()));
244 layout2.addWidget(&passwordbox);
245 if(!m_host.isEmpty()) //don't save incomming connections
246 layout2.addWidget(&save_password);
247 layout1.addLayout(&layout2);
248 layout1.addWidget(&ok_button);
249 dialog.setLayout(&layout1);
251 if(dialog.exec()) { //dialog accepted
252 password = passwordbox.text();
254 if(!m_host.isEmpty() and save_password.isChecked()) {
255 kDebug(5011) << "Saving password for host '" << m_host << "'";
257 settings.setValue(QString("%1/password").arg(m_host), password);
261 vncThread.setPassword(password);
263 vncThread.setPassword(QString()); //null string to exit
267 void VncView::outputErrorMessage(const QString &message)
269 if (message == "INTERNAL:APPLE_VNC_COMPATIBILTY") {
270 setCursor(localDotCursor());
271 m_forceLocalCursor = true;
277 emit errorMessage(i18n("VNC failure"), message);
280 void VncView::updateImage(int x, int y, int w, int h)
282 if(!QApplication::focusWidget()) { //no focus, we're probably minimized
286 //kDebug(5011) << "got update" << width() << height();
293 if (m_horizontalFactor != 1.0 || m_verticalFactor != 1.0) {
294 // If the view is scaled, grow the update rectangle to avoid artifacts
295 int x_extrapixels = 1.0/m_horizontalFactor + 1;
296 int y_extrapixels = 1.0/m_verticalFactor + 1;
300 m_w+=2*x_extrapixels;
301 m_h+=2*y_extrapixels;
304 m_frame = vncThread.image();
306 if (!m_initDone) { //TODO this seems an odd place for initialization
307 setAttribute(Qt::WA_StaticContents);
308 setAttribute(Qt::WA_OpaquePaintEvent);
309 installEventFilter(this);
311 setCursor(((m_dotCursorState == CursorOn) || m_forceLocalCursor) ? localDotCursor() : Qt::BlankCursor);
313 setMouseTracking(true); // get mouse events even when there is no mousebutton pressed
314 setFocusPolicy(Qt::WheelFocus);
315 setStatus(Connected);
318 resize(width(), height());
324 static QSize old_frame_size = QSize();
325 if ((y == 0 && x == 0) && (m_frame.size() != old_frame_size)) {
326 old_frame_size = m_frame.size();
327 kDebug(5011) << "Updating framebuffer size";
329 emit framebufferSizeChanged(m_frame.width(), m_frame.height());
332 repaint(qRound(m_x * m_horizontalFactor), qRound(m_y * m_verticalFactor), qRound(m_w * m_horizontalFactor), qRound(m_h * m_verticalFactor));
335 void VncView::setViewOnly(bool viewOnly)
337 RemoteView::setViewOnly(viewOnly);
339 m_dontSendClipboard = viewOnly;
342 setCursor(Qt::ArrowCursor);
344 setCursor(m_dotCursorState == CursorOn ? localDotCursor() : Qt::BlankCursor);
347 void VncView::showDotCursor(DotCursorState state)
349 RemoteView::showDotCursor(state);
351 setCursor(state == CursorOn ? localDotCursor() : Qt::BlankCursor);
354 //level should be in [0, 100]
355 void VncView::setZoomLevel(int level)
357 Q_ASSERT(parentWidget() != 0);
359 if(level == -1) { //handle resize
360 resize(m_frame.width()*m_horizontalFactor, m_frame.height()*m_verticalFactor);
364 double magnification;
367 } else if(level >= 90) {
370 const double min_horiz_magnification = double(parentWidget()->width())/m_frame.width();
371 const double min_vert_magnification = double(parentWidget()->height())/m_frame.height();
372 const double fit_screen_magnification = qMin(min_horiz_magnification, min_vert_magnification);
374 //level=90 => magnification=1.0, level=0 => magnification=fit_screen_magnification
375 magnification = (level)/90.0*(1.0 - fit_screen_magnification) + fit_screen_magnification;
378 if(magnification < 0 //remote display smaller than local?
379 or magnification != magnification) //nan
382 m_verticalFactor = m_horizontalFactor = magnification;
383 resize(m_frame.width()*magnification, m_frame.height()*magnification);
386 void VncView::setCut(const QString &text)
388 m_dontSendClipboard = true;
389 m_clipboard->setText(text, QClipboard::Clipboard);
390 m_clipboard->setText(text, QClipboard::Selection);
391 m_dontSendClipboard = false;
394 void VncView::paintEvent(QPaintEvent *event)
396 //kDebug(5011) << "paint event: x: " << m_x << ", y: " << m_y << ", w: " << m_w << ", h: " << m_h;
397 if (m_frame.isNull() || m_frame.format() == QImage::Format_Invalid) {
398 kDebug(5011) << "no valid image to paint";
399 RemoteView::paintEvent(event);
405 Qt::TransformationMode transformation_mode = Qt::SmoothTransformation;
406 if( m_horizontalFactor >= 1.0 )
407 transformation_mode = Qt::FastTransformation;
409 const QRect update_rect = event->rect();
410 QPainter painter(this);
411 if (!force_full_repaint and (update_rect.width() != width() || update_rect.height() != height())) {
412 // kDebug(5011) << "Partial repaint";
413 const int sx = qRound(update_rect.x()/m_horizontalFactor);
414 const int sy = qRound(update_rect.y()/m_verticalFactor);
415 const int sw = qRound(update_rect.width()/m_horizontalFactor);
416 const int sh = qRound(update_rect.height()/m_verticalFactor);
418 painter.drawImage(update_rect,
419 m_frame.copy(sx, sy, sw, sh).scaled(update_rect.size(), Qt::IgnoreAspectRatio, transformation_mode));
421 kDebug(5011) << "Full repaint" << width() << height() << m_frame.width() << m_frame.height();
423 painter.drawImage(rect(),
424 m_frame.scaled(size(), Qt::IgnoreAspectRatio, transformation_mode));
425 force_full_repaint = false;
428 //draw local cursor ourselves, normal mouse pointer doesn't deal with scrolling
429 if((m_dotCursorState == CursorOn) || m_forceLocalCursor) {
430 #if QT_VERSION >= 0x040500
431 painter.setCompositionMode(QPainter::RasterOp_SourceXorDestination);
433 //rectangle size includes 1px pen width
434 painter.drawRect(cursor_x*m_horizontalFactor - CURSOR_SIZE/2, cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE-1, CURSOR_SIZE-1);
437 RemoteView::paintEvent(event);
440 void VncView::resizeEvent(QResizeEvent *event)
442 RemoteView::resizeEvent(event);
446 bool VncView::event(QEvent *event)
448 switch (event->type()) {
449 case QEvent::KeyPress:
450 case QEvent::KeyRelease:
451 // kDebug(5011) << "keyEvent";
452 keyEventHandler(static_cast<QKeyEvent*>(event));
455 case QEvent::MouseButtonDblClick:
456 case QEvent::MouseButtonPress:
457 case QEvent::MouseButtonRelease:
458 case QEvent::MouseMove:
459 // kDebug(5011) << "mouseEvent";
460 mouseEventHandler(static_cast<QMouseEvent*>(event));
464 // kDebug(5011) << "wheelEvent";
465 wheelEventHandler(static_cast<QWheelEvent*>(event));
468 case QEvent::WindowActivate: //input panel may have been closed, prevent IM from interfering with hardware keyboard
469 setAttribute(Qt::WA_InputMethodEnabled, false);
472 return RemoteView::event(event);
476 //call with e == 0 to flush held events
477 void VncView::mouseEventHandler(QMouseEvent *e)
479 static bool tap_detected = false;
480 static bool double_tap_detected = false;
481 static bool tap_drag_detected = false;
482 static QTime press_time;
483 static QTime up_time; //used for double clicks/tap&drag, for time after first tap
485 if(!e) { //flush held taps
487 m_buttonMask |= 0x01;
488 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
489 m_buttonMask &= 0xfe;
490 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
491 tap_detected = false;
492 } else if(double_tap_detected and press_time.elapsed() > TAP_PRESS_TIME) { //got tap + another press -> tap & drag
493 m_buttonMask |= 0x01;
494 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
495 double_tap_detected = false;
496 tap_drag_detected = true;
502 if(e->x() < 0 or e->y() < 0) { //QScrollArea tends to send invalid events sometimes...
507 cursor_x = qRound(e->x()/m_horizontalFactor);
508 cursor_y = qRound(e->y()/m_verticalFactor);
509 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask); // plain move event
511 if(!disable_tapping and e->button() == Qt::LeftButton) { //implement touchpad-like input for left button
512 if(e->type() == QEvent::MouseButtonPress or e->type() == QEvent::MouseButtonDblClick) {
514 if(tap_detected and up_time.elapsed() < DOUBLE_TAP_UP_TIME) {
515 tap_detected = false;
516 double_tap_detected = true;
518 QTimer::singleShot(TAP_PRESS_TIME, this, SLOT(mouseEventHandler()));
520 } else if(e->type() == QEvent::MouseButtonRelease) {
521 if(tap_drag_detected) {
522 m_buttonMask &= 0xfe;
523 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
524 tap_drag_detected = false;
525 } else if(double_tap_detected) { //double click
526 double_tap_detected = false;
528 m_buttonMask |= 0x01;
529 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
530 m_buttonMask &= 0xfe;
531 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
532 m_buttonMask |= 0x01;
533 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
534 m_buttonMask &= 0xfe;
535 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
536 } else if(press_time.elapsed() < TAP_PRESS_TIME) { //tap
539 QTimer::singleShot(DOUBLE_TAP_UP_TIME, this, SLOT(mouseEventHandler()));
543 } else { //middle or right button, send directly
544 if ((e->type() == QEvent::MouseButtonPress)) {
545 if (e->button() & Qt::MidButton)
546 m_buttonMask |= 0x02;
547 if (e->button() & Qt::RightButton)
548 m_buttonMask |= 0x04;
549 } else if (e->type() == QEvent::MouseButtonRelease) {
550 if (e->button() & Qt::MidButton)
551 m_buttonMask &= 0xfd;
552 if (e->button() & Qt::RightButton)
553 m_buttonMask &= 0xfb;
555 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
558 //prevent local cursor artifacts
559 static int old_cursor_x = cursor_x;
560 static int old_cursor_y = cursor_y;
561 if(((m_dotCursorState == CursorOn) || m_forceLocalCursor)
562 and (cursor_x != old_cursor_x or cursor_y != old_cursor_y)) {
563 //clear last position
564 repaint(old_cursor_x*m_horizontalFactor - CURSOR_SIZE/2, old_cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE, CURSOR_SIZE);
565 //and refresh new one
566 repaint(cursor_x*m_horizontalFactor - CURSOR_SIZE/2, cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE, CURSOR_SIZE);
568 old_cursor_x = cursor_x; old_cursor_y = cursor_y;
572 void VncView::wheelEventHandler(QWheelEvent *event)
575 if (event->delta() < 0)
580 const int x = qRound(event->x() / m_horizontalFactor);
581 const int y = qRound(event->y() / m_verticalFactor);
583 vncThread.mouseEvent(x, y, eb | m_buttonMask);
584 vncThread.mouseEvent(x, y, m_buttonMask);
587 void VncView::keyEventHandler(QKeyEvent *e)
589 // strip away autorepeating KeyRelease; see bug #206598
590 if (e->isAutoRepeat() && (e->type() == QEvent::KeyRelease)) {
594 // parts of this code are based on http://italc.sourcearchive.com/documentation/1.0.9.1/vncview_8cpp-source.html
595 rfbKeySym k = e->nativeVirtualKey();
597 // we do not handle Key_Backtab separately as the Shift-modifier
598 // is already enabled
599 if (e->key() == Qt::Key_Backtab) {
603 const bool pressed = (e->type() == QEvent::KeyPress);
606 //don't send ISO_Level3_Shift (would break things like Win+0-9)
607 //also enable IM so symbol key works
609 setAttribute(Qt::WA_InputMethodEnabled, pressed);
616 if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L) {
619 } else if (m_mods.contains(k)) {
627 int current_zoom = -1;
628 if(e->key() == Qt::Key_F8)
629 current_zoom = left_zoom;
630 else if(e->key() == Qt::Key_F7)
631 current_zoom = right_zoom;
633 // kDebug(5011) << "got '" << e->text() << "'.";
634 vncThread.keyEvent(k, pressed);
636 kDebug(5011) << "nativeVirtualKey() for '" << e->text() << "' failed.";
640 if(current_zoom == -1)
643 //handle zoom buttons
644 if(current_zoom == 0) { //left click
646 m_buttonMask |= 0x01;
648 m_buttonMask &= 0xfe;
649 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
650 } else if(current_zoom == 1) { //right click
652 m_buttonMask |= 0x04;
654 m_buttonMask &= 0xfb;
655 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
656 } else if(current_zoom == 2) { //middle click
658 m_buttonMask |= 0x02;
660 m_buttonMask &= 0xfd;
661 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
662 } else if(current_zoom == 3 and pressed) { //wheel up
664 vncThread.mouseEvent(cursor_x, cursor_y, eb | m_buttonMask);
665 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
666 } else if(current_zoom == 4 and pressed) { //wheel down
668 vncThread.mouseEvent(cursor_x, cursor_y, eb | m_buttonMask);
669 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
670 } else if(current_zoom == 5) { //page up
671 vncThread.keyEvent(0xff55, pressed);
672 } else if(current_zoom == 6) { //page down
673 vncThread.keyEvent(0xff56, pressed);
677 void VncView::unpressModifiers()
679 const QList<unsigned int> keys = m_mods.keys();
680 QList<unsigned int>::const_iterator it = keys.constBegin();
681 while (it != keys.end()) {
682 vncThread.keyEvent(*it, false);
688 void VncView::clipboardSelectionChanged()
690 if (m_status != Connected)
693 if (m_clipboard->ownsSelection() || m_dontSendClipboard)
696 const QString text = m_clipboard->text(QClipboard::Selection);
698 vncThread.clientCut(text);
701 void VncView::clipboardDataChanged()
703 if (m_status != Connected)
706 if (m_clipboard->ownsClipboard() || m_dontSendClipboard)
709 const QString text = m_clipboard->text(QClipboard::Clipboard);
711 vncThread.clientCut(text);
715 void VncView::sendKey(Qt::Key key)
717 //convert Qt::Key into x11 keysym
729 case Qt::Key_PageDown:
747 case Qt::Key_Backspace:
762 k = 0xffbe + int(key - Qt::Key_F1);
774 case Qt::MetaModifier:
778 case Qt::AltModifier:
781 case Qt::Key_Control:
782 case Qt::ControlModifier:
786 kDebug(5011) << "sendKey(): Unhandled Qt::Key value " << key;
790 if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L || k == XK_Super_L) {
791 if (m_mods.contains(k)) { //release
793 vncThread.keyEvent(k, false);
796 vncThread.keyEvent(k, true);
798 } else { //normal key
799 vncThread.keyEvent(k, true);
800 vncThread.keyEvent(k, false);
804 void VncView::sendKeySequence(QKeySequence keys)
806 Q_ASSERT(keys.count() <= 1); //we can only handle a single combination
808 //to get at individual key presses, we split 'keys' into its components
812 QString k = keys.toString().section('+', pos, pos);
816 //kDebug(5011) << "found key: " << k;
818 key_list.append(Qt::Key_Alt);
819 } else if(k == "Ctrl") {
820 key_list.append(Qt::Key_Control);
821 } else if(k == "Meta") {
822 key_list.append(Qt::Key_Meta);
824 key_list.append(QKeySequence(k)[0]);
830 for(int i = 0; i < key_list.count(); i++)
831 sendKey(Qt::Key(key_list.at(i)));
833 //release modifiers (everything before final key)
834 for(int i = key_list.count()-2; i >= 0; i--)
835 sendKey(Qt::Key(key_list.at(i)));
838 void VncView::reloadSettings()
841 left_zoom = settings.value("left_zoom", 0).toInt();
842 right_zoom = settings.value("right_zoom", 1).toInt();
843 disable_tapping = settings.value("disable_tapping", false).toBool();
845 bool always_show_local_cursor = settings.value("always_show_local_cursor", false).toBool();
846 if(always_show_local_cursor)
847 showDotCursor(CursorOn);
852 //convert commitString into keyevents
853 void VncView::inputMethodEvent(QInputMethodEvent *event)
855 //TODO handle replacements
856 //NOTE for the return key to work Qt needs to enable multiline input, which only works for Q(Plain)TextEdit
858 //kDebug(5011) << event->commitString() << "|" << event->preeditString() << "|" << event->replacementLength() << "|" << event->replacementStart();
859 QString letters = event->commitString();
860 for(int i = 0; i < letters.length(); i++) {
861 char k = letters.at(i).toLatin1(); //works with all 'normal' keys, not umlauts.
863 kDebug(5011) << "unhandled key";
866 vncThread.keyEvent(k, true);
867 vncThread.keyEvent(k, false);
872 #include "moc_vncview.cpp"