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 showDotCursor(CursorOff);
323 setCursor(Qt::ArrowCursor);
325 setCursor(m_dotCursorState == CursorOn ? localDotCursor() : Qt::BlankCursor);
329 void VncView::showDotCursor(DotCursorState state)
331 RemoteView::showDotCursor(state);
333 setCursor(state == CursorOn ? localDotCursor() : Qt::BlankCursor);
336 //level should be in [0, 100]
337 void VncView::setZoomLevel(int level)
339 Q_ASSERT(parentWidget() != 0);
341 if(level == -1) { //handle resize
342 resize(m_frame.width()*m_horizontalFactor, m_frame.height()*m_verticalFactor);
346 double magnification;
349 } else if(level >= 90) {
352 const double min_horiz_magnification = double(parentWidget()->width())/m_frame.width();
353 const double min_vert_magnification = double(parentWidget()->height())/m_frame.height();
354 const double fit_screen_magnification = qMin(min_horiz_magnification, min_vert_magnification);
356 //level=90 => magnification=1.0, level=0 => magnification=fit_screen_magnification
357 magnification = (level)/90.0*(1.0 - fit_screen_magnification) + fit_screen_magnification;
360 if(magnification < 0 //remote display smaller than local?
361 or magnification != magnification) //nan
364 m_verticalFactor = m_horizontalFactor = magnification;
365 resize(m_frame.width()*magnification, m_frame.height()*magnification);
368 void VncView::setCut(const QString &text)
370 m_dontSendClipboard = true;
371 m_clipboard->setText(text, QClipboard::Clipboard);
372 m_clipboard->setText(text, QClipboard::Selection);
373 m_dontSendClipboard = false;
376 void VncView::paintEvent(QPaintEvent *event)
378 if (m_frame.isNull() || m_frame.format() == QImage::Format_Invalid) {
379 //no valid image to paint
380 RemoteView::paintEvent(event);
386 const QRect update_rect = event->rect();
387 QPainter painter(this);
388 if (update_rect != rect()) {
389 // kDebug(5011) << "Partial repaint";
390 const int sx = qRound(update_rect.x()/m_horizontalFactor);
391 const int sy = qRound(update_rect.y()/m_verticalFactor);
392 const int sw = qRound(update_rect.width()/m_horizontalFactor);
393 const int sh = qRound(update_rect.height()/m_verticalFactor);
395 painter.drawImage(update_rect,
396 m_frame.copy(sx, sy, sw, sh)
397 .scaled(update_rect.size(), Qt::IgnoreAspectRatio, transformation_mode));
399 //kDebug(5011) << "Full repaint" << width() << height() << m_frame.width() << m_frame.height();
401 painter.drawImage(rect(),
402 m_frame.scaled(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
459 if(!e) { //flush held taps
461 m_buttonMask |= 0x01;
462 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
463 m_buttonMask &= 0xfe;
464 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
465 tap_detected = false;
466 } else if(double_tap_detected and press_time.elapsed() > TAP_PRESS_TIME) { //got tap + another press -> tap & drag
467 m_buttonMask |= 0x01;
468 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
469 double_tap_detected = false;
470 tap_drag_detected = true;
476 if(e->x() < 0 or e->y() < 0) { //QScrollArea tends to send invalid events sometimes...
481 cursor_x = qRound(e->x()/m_horizontalFactor);
482 cursor_y = qRound(e->y()/m_verticalFactor);
483 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask); // plain move event
485 if(!disable_tapping and e->button() == Qt::LeftButton) { //implement touchpad-like input for left button
486 if(e->type() == QEvent::MouseButtonPress or e->type() == QEvent::MouseButtonDblClick) {
488 if(tap_detected and up_time.elapsed() < DOUBLE_TAP_UP_TIME) {
489 tap_detected = false;
490 double_tap_detected = true;
492 QTimer::singleShot(TAP_PRESS_TIME, this, SLOT(mouseEventHandler()));
494 } else if(e->type() == QEvent::MouseButtonRelease) {
495 if(tap_drag_detected) {
496 m_buttonMask &= 0xfe;
497 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
498 tap_drag_detected = false;
499 } else if(double_tap_detected) { //double click
500 double_tap_detected = false;
502 m_buttonMask |= 0x01;
503 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
504 m_buttonMask &= 0xfe;
505 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
506 m_buttonMask |= 0x01;
507 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
508 m_buttonMask &= 0xfe;
509 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
510 } else if(press_time.elapsed() < TAP_PRESS_TIME) { //tap
513 QTimer::singleShot(DOUBLE_TAP_UP_TIME, this, SLOT(mouseEventHandler()));
517 } else { //middle or right button, send directly
518 if ((e->type() == QEvent::MouseButtonPress)) {
519 if (e->button() & Qt::MidButton)
520 m_buttonMask |= 0x02;
521 if (e->button() & Qt::RightButton)
522 m_buttonMask |= 0x04;
523 } else if (e->type() == QEvent::MouseButtonRelease) {
524 if (e->button() & Qt::MidButton)
525 m_buttonMask &= 0xfd;
526 if (e->button() & Qt::RightButton)
527 m_buttonMask &= 0xfb;
529 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
532 //prevent local cursor artifacts
533 static int old_cursor_x = cursor_x;
534 static int old_cursor_y = cursor_y;
535 if(((m_dotCursorState == CursorOn) || m_forceLocalCursor)
536 and (cursor_x != old_cursor_x or cursor_y != old_cursor_y)) {
537 //clear last position
538 repaint(old_cursor_x*m_horizontalFactor - CURSOR_SIZE/2, old_cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE, CURSOR_SIZE);
539 //and refresh new one
540 repaint(cursor_x*m_horizontalFactor - CURSOR_SIZE/2, cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE, CURSOR_SIZE);
542 old_cursor_x = cursor_x; old_cursor_y = cursor_y;
546 void VncView::wheelEventHandler(QWheelEvent *event)
549 if (event->delta() < 0)
554 const int x = qRound(event->x() / m_horizontalFactor);
555 const int y = qRound(event->y() / m_verticalFactor);
557 vncThread.mouseEvent(x, y, eb | m_buttonMask);
558 vncThread.mouseEvent(x, y, m_buttonMask);
561 void VncView::keyEventHandler(QKeyEvent *e)
563 // strip away autorepeating KeyRelease; see bug #206598
564 if (e->isAutoRepeat() && (e->type() == QEvent::KeyRelease)) {
568 // parts of this code are based on http://italc.sourcearchive.com/documentation/1.0.9.1/vncview_8cpp-source.html
569 rfbKeySym k = e->nativeVirtualKey();
571 // we do not handle Key_Backtab separately as the Shift-modifier
572 // is already enabled
573 if (e->key() == Qt::Key_Backtab) {
577 const bool pressed = (e->type() == QEvent::KeyPress);
580 //don't send ISO_Level3_Shift (would break things like Win+0-9)
581 //also enable IM so symbol key works
583 setAttribute(Qt::WA_InputMethodEnabled, pressed);
590 if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L) {
593 } else if (m_mods.contains(k)) {
601 int current_zoom = -1;
602 if(e->key() == Qt::Key_F8)
603 current_zoom = left_zoom;
604 else if(e->key() == Qt::Key_F7)
605 current_zoom = right_zoom;
607 // kDebug(5011) << "got '" << e->text() << "'.";
608 vncThread.keyEvent(k, pressed);
610 kDebug(5011) << "nativeVirtualKey() for '" << e->text() << "' failed.";
614 if(current_zoom == -1)
617 //handle zoom buttons
618 if(current_zoom == 0) { //left click
620 m_buttonMask |= 0x01;
622 m_buttonMask &= 0xfe;
623 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
624 } else if(current_zoom == 1) { //right click
626 m_buttonMask |= 0x04;
628 m_buttonMask &= 0xfb;
629 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
630 } else if(current_zoom == 2) { //middle click
632 m_buttonMask |= 0x02;
634 m_buttonMask &= 0xfd;
635 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
636 } else if(current_zoom == 3 and pressed) { //wheel up
638 vncThread.mouseEvent(cursor_x, cursor_y, eb | m_buttonMask);
639 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
640 } else if(current_zoom == 4 and pressed) { //wheel down
642 vncThread.mouseEvent(cursor_x, cursor_y, eb | m_buttonMask);
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;