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),
76 transformation_mode(Qt::FastTransformation)
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 bool VncView::eventFilter(QObject *obj, QEvent *event)
111 if (event->type() == QEvent::KeyPress ||
112 event->type() == QEvent::KeyRelease ||
113 event->type() == QEvent::MouseButtonDblClick ||
114 event->type() == QEvent::MouseButtonPress ||
115 event->type() == QEvent::MouseButtonRelease ||
116 event->type() == QEvent::Wheel ||
117 event->type() == QEvent::MouseMove) {
124 return RemoteView::eventFilter(obj, event);
127 QSize VncView::framebufferSize()
129 return m_frame.size();
132 QSize VncView::sizeHint() const
137 QSize VncView::minimumSizeHint() const
142 void VncView::startQuitting()
147 kDebug(5011) << "about to quit";
149 //const bool connected = status() == RemoteView::Connected;
151 setStatus(Disconnecting);
155 //if(connected) //remove if things work without it
158 const bool quitSuccess = vncThread.wait(700);
160 //happens when vncThread wants to call a slot via BlockingQueuedConnection,
161 //needs an event loop in this thread so execution continues after 'emit'
163 if(!loop.processEvents())
164 kDebug(5011) << "BUG: deadlocked, but no events to deliver?";
167 setStatus(Disconnected);
170 bool VncView::isQuitting()
175 bool VncView::start()
177 vncThread.setHost(m_host);
178 vncThread.setPort(m_port);
179 vncThread.setListenPort(listen_port); //if port is != 0, thread will listen for connections
180 vncThread.setQuality(quality);
182 // set local cursor on by default because low quality mostly means slow internet connection
183 if (quality == RemoteView::Low) {
184 showDotCursor(RemoteView::CursorOn);
187 setStatus(Connecting);
193 bool VncView::supportsScaling() const
198 bool VncView::supportsLocalCursor() const
203 void VncView::requestPassword()
205 kDebug(5011) << "request password";
207 setStatus(Authenticating);
209 if (!m_url.password().isNull()) {
210 vncThread.setPassword(m_url.password());
215 settings.beginGroup("hosts");
216 QString password = settings.value(QString("%1/password").arg(m_host), "").toString();
217 //check for saved password
218 if(m_firstPasswordTry and !password.isEmpty()) {
219 kDebug(5011) << "Trying saved password";
220 m_firstPasswordTry = false;
221 vncThread.setPassword(password);
224 m_firstPasswordTry = false;
227 QDialog dialog(this);
228 dialog.setWindowTitle(tr("Password required"));
230 QLineEdit passwordbox;
231 passwordbox.setEchoMode(QLineEdit::Password);
232 passwordbox.setText(password);
233 QCheckBox save_password(tr("Save Password"));
234 save_password.setChecked(!password.isEmpty()); //offer to overwrite saved password
235 QPushButton ok_button(tr("Done"));
236 ok_button.setMaximumWidth(100);
237 connect(&ok_button, SIGNAL(clicked()),
238 &dialog, SLOT(accept()));
242 layout2.addWidget(&passwordbox);
243 if(!m_host.isEmpty()) //don't save incomming connections
244 layout2.addWidget(&save_password);
245 layout1.addLayout(&layout2);
246 layout1.addWidget(&ok_button);
247 dialog.setLayout(&layout1);
249 if(dialog.exec()) { //dialog accepted
250 password = passwordbox.text();
252 if(!m_host.isEmpty() and save_password.isChecked()) {
253 kDebug(5011) << "Saving password for host '" << m_host << "'";
255 settings.setValue(QString("%1/password").arg(m_host), password);
259 vncThread.setPassword(password);
261 vncThread.setPassword(QString()); //null string to exit
265 void VncView::outputErrorMessage(const QString &message)
267 if (message == "INTERNAL:APPLE_VNC_COMPATIBILTY") {
268 setCursor(localDotCursor());
269 m_forceLocalCursor = true;
275 emit errorMessage(i18n("VNC failure"), message);
278 void VncView::updateImage(int x, int y, int w, int h)
280 if(!QApplication::focusWidget()) { //no focus, we're probably minimized
284 //kDebug(5011) << "got update" << width() << height();
291 if (m_horizontalFactor != 1.0 || m_verticalFactor != 1.0) {
292 // If the view is scaled, grow the update rectangle to avoid artifacts
293 int x_extrapixels = 1.0/m_horizontalFactor + 1;
294 int y_extrapixels = 1.0/m_verticalFactor + 1;
298 m_w+=2*x_extrapixels;
299 m_h+=2*y_extrapixels;
302 m_frame = vncThread.image();
304 if (!m_initDone) { //TODO this seems an odd place for initialization
305 setAttribute(Qt::WA_StaticContents);
306 setAttribute(Qt::WA_OpaquePaintEvent);
307 installEventFilter(this);
309 setCursor(((m_dotCursorState == CursorOn) || m_forceLocalCursor) ? localDotCursor() : Qt::BlankCursor);
311 setMouseTracking(true); // get mouse events even when there is no mousebutton pressed
312 setFocusPolicy(Qt::WheelFocus);
313 setStatus(Connected);
316 resize(width(), height());
322 static QSize old_frame_size = QSize();
323 if ((y == 0 && x == 0) && (m_frame.size() != old_frame_size)) {
324 old_frame_size = m_frame.size();
325 kDebug(5011) << "Updating framebuffer size";
327 useFastTransformations(false);
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 if (m_frame.isNull() || m_frame.format() == QImage::Format_Invalid) {
397 //no valid image to paint
398 RemoteView::paintEvent(event);
404 const QRect update_rect = event->rect();
405 QPainter painter(this);
406 if (update_rect != rect()) {
407 // kDebug(5011) << "Partial repaint";
408 const int sx = qRound(update_rect.x()/m_horizontalFactor);
409 const int sy = qRound(update_rect.y()/m_verticalFactor);
410 const int sw = qRound(update_rect.width()/m_horizontalFactor);
411 const int sh = qRound(update_rect.height()/m_verticalFactor);
413 painter.drawImage(update_rect,
414 m_frame.copy(sx, sy, sw, sh)
415 .scaled(update_rect.size(), Qt::IgnoreAspectRatio, transformation_mode));
417 //kDebug(5011) << "Full repaint" << width() << height() << m_frame.width() << m_frame.height();
419 painter.drawImage(rect(),
420 m_frame.scaled(size(), Qt::IgnoreAspectRatio, transformation_mode));
423 //draw local cursor ourselves, normal mouse pointer doesn't deal with scrolling
424 if((m_dotCursorState == CursorOn) || m_forceLocalCursor) {
425 #if QT_VERSION >= 0x040500
426 painter.setCompositionMode(QPainter::RasterOp_SourceXorDestination);
428 //rectangle size includes 1px pen width
429 painter.drawRect(cursor_x*m_horizontalFactor - CURSOR_SIZE/2, cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE-1, CURSOR_SIZE-1);
432 RemoteView::paintEvent(event);
435 void VncView::resizeEvent(QResizeEvent *event)
437 RemoteView::resizeEvent(event);
441 bool VncView::event(QEvent *event)
443 switch (event->type()) {
444 case QEvent::KeyPress:
445 case QEvent::KeyRelease:
446 // kDebug(5011) << "keyEvent";
447 keyEventHandler(static_cast<QKeyEvent*>(event));
450 case QEvent::MouseButtonDblClick:
451 case QEvent::MouseButtonPress:
452 case QEvent::MouseButtonRelease:
453 case QEvent::MouseMove:
454 // kDebug(5011) << "mouseEvent";
455 mouseEventHandler(static_cast<QMouseEvent*>(event));
459 // kDebug(5011) << "wheelEvent";
460 wheelEventHandler(static_cast<QWheelEvent*>(event));
463 case QEvent::WindowActivate: //input panel may have been closed, prevent IM from interfering with hardware keyboard
464 setAttribute(Qt::WA_InputMethodEnabled, false);
467 return RemoteView::event(event);
471 //call with e == 0 to flush held events
472 void VncView::mouseEventHandler(QMouseEvent *e)
474 static bool tap_detected = false;
475 static bool double_tap_detected = false;
476 static bool tap_drag_detected = false;
477 static QTime press_time;
478 static QTime up_time; //used for double clicks/tap&drag, for time after first tap
480 if(!e) { //flush held taps
482 m_buttonMask |= 0x01;
483 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
484 m_buttonMask &= 0xfe;
485 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
486 tap_detected = false;
487 } else if(double_tap_detected and press_time.elapsed() > TAP_PRESS_TIME) { //got tap + another press -> tap & drag
488 m_buttonMask |= 0x01;
489 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
490 double_tap_detected = false;
491 tap_drag_detected = true;
497 if(e->x() < 0 or e->y() < 0) { //QScrollArea tends to send invalid events sometimes...
502 cursor_x = qRound(e->x()/m_horizontalFactor);
503 cursor_y = qRound(e->y()/m_verticalFactor);
504 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask); // plain move event
506 if(!disable_tapping and e->button() == Qt::LeftButton) { //implement touchpad-like input for left button
507 if(e->type() == QEvent::MouseButtonPress or e->type() == QEvent::MouseButtonDblClick) {
509 if(tap_detected and up_time.elapsed() < DOUBLE_TAP_UP_TIME) {
510 tap_detected = false;
511 double_tap_detected = true;
513 QTimer::singleShot(TAP_PRESS_TIME, this, SLOT(mouseEventHandler()));
515 } else if(e->type() == QEvent::MouseButtonRelease) {
516 if(tap_drag_detected) {
517 m_buttonMask &= 0xfe;
518 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
519 tap_drag_detected = false;
520 } else if(double_tap_detected) { //double click
521 double_tap_detected = false;
523 m_buttonMask |= 0x01;
524 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
525 m_buttonMask &= 0xfe;
526 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
527 m_buttonMask |= 0x01;
528 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
529 m_buttonMask &= 0xfe;
530 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
531 } else if(press_time.elapsed() < TAP_PRESS_TIME) { //tap
534 QTimer::singleShot(DOUBLE_TAP_UP_TIME, this, SLOT(mouseEventHandler()));
538 } else { //middle or right button, send directly
539 if ((e->type() == QEvent::MouseButtonPress)) {
540 if (e->button() & Qt::MidButton)
541 m_buttonMask |= 0x02;
542 if (e->button() & Qt::RightButton)
543 m_buttonMask |= 0x04;
544 } else if (e->type() == QEvent::MouseButtonRelease) {
545 if (e->button() & Qt::MidButton)
546 m_buttonMask &= 0xfd;
547 if (e->button() & Qt::RightButton)
548 m_buttonMask &= 0xfb;
550 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
553 //prevent local cursor artifacts
554 static int old_cursor_x = cursor_x;
555 static int old_cursor_y = cursor_y;
556 if(((m_dotCursorState == CursorOn) || m_forceLocalCursor)
557 and (cursor_x != old_cursor_x or cursor_y != old_cursor_y)) {
558 //clear last position
559 repaint(old_cursor_x*m_horizontalFactor - CURSOR_SIZE/2, old_cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE, CURSOR_SIZE);
560 //and refresh new one
561 repaint(cursor_x*m_horizontalFactor - CURSOR_SIZE/2, cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE, CURSOR_SIZE);
563 old_cursor_x = cursor_x; old_cursor_y = cursor_y;
567 void VncView::wheelEventHandler(QWheelEvent *event)
570 if (event->delta() < 0)
575 const int x = qRound(event->x() / m_horizontalFactor);
576 const int y = qRound(event->y() / m_verticalFactor);
578 vncThread.mouseEvent(x, y, eb | m_buttonMask);
579 vncThread.mouseEvent(x, y, m_buttonMask);
582 void VncView::keyEventHandler(QKeyEvent *e)
584 // strip away autorepeating KeyRelease; see bug #206598
585 if (e->isAutoRepeat() && (e->type() == QEvent::KeyRelease)) {
589 // parts of this code are based on http://italc.sourcearchive.com/documentation/1.0.9.1/vncview_8cpp-source.html
590 rfbKeySym k = e->nativeVirtualKey();
592 // we do not handle Key_Backtab separately as the Shift-modifier
593 // is already enabled
594 if (e->key() == Qt::Key_Backtab) {
598 const bool pressed = (e->type() == QEvent::KeyPress);
601 //don't send ISO_Level3_Shift (would break things like Win+0-9)
602 //also enable IM so symbol key works
604 setAttribute(Qt::WA_InputMethodEnabled, pressed);
611 if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L) {
614 } else if (m_mods.contains(k)) {
622 int current_zoom = -1;
623 if(e->key() == Qt::Key_F8)
624 current_zoom = left_zoom;
625 else if(e->key() == Qt::Key_F7)
626 current_zoom = right_zoom;
628 // kDebug(5011) << "got '" << e->text() << "'.";
629 vncThread.keyEvent(k, pressed);
631 kDebug(5011) << "nativeVirtualKey() for '" << e->text() << "' failed.";
635 if(current_zoom == -1)
638 //handle zoom buttons
639 if(current_zoom == 0) { //left click
641 m_buttonMask |= 0x01;
643 m_buttonMask &= 0xfe;
644 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
645 } else if(current_zoom == 1) { //right click
647 m_buttonMask |= 0x04;
649 m_buttonMask &= 0xfb;
650 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
651 } else if(current_zoom == 2) { //middle click
653 m_buttonMask |= 0x02;
655 m_buttonMask &= 0xfd;
656 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
657 } else if(current_zoom == 3 and pressed) { //wheel up
659 vncThread.mouseEvent(cursor_x, cursor_y, eb | m_buttonMask);
660 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
661 } else if(current_zoom == 4 and pressed) { //wheel down
663 vncThread.mouseEvent(cursor_x, cursor_y, eb | m_buttonMask);
664 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
665 } else if(current_zoom == 5) { //page up
666 vncThread.keyEvent(0xff55, pressed);
667 } else if(current_zoom == 6) { //page down
668 vncThread.keyEvent(0xff56, pressed);
672 void VncView::unpressModifiers()
674 const QList<unsigned int> keys = m_mods.keys();
675 QList<unsigned int>::const_iterator it = keys.constBegin();
676 while (it != keys.end()) {
677 vncThread.keyEvent(*it, false);
683 void VncView::clipboardSelectionChanged()
685 if (m_status != Connected)
688 if (m_clipboard->ownsSelection() || m_dontSendClipboard)
691 const QString text = m_clipboard->text(QClipboard::Selection);
693 vncThread.clientCut(text);
696 void VncView::clipboardDataChanged()
698 if (m_status != Connected)
701 if (m_clipboard->ownsClipboard() || m_dontSendClipboard)
704 const QString text = m_clipboard->text(QClipboard::Clipboard);
706 vncThread.clientCut(text);
710 void VncView::sendKey(Qt::Key key)
712 //convert Qt::Key into x11 keysym
724 case Qt::Key_PageDown:
742 case Qt::Key_Backspace:
757 k = 0xffbe + int(key - Qt::Key_F1);
769 case Qt::MetaModifier:
773 case Qt::AltModifier:
776 case Qt::Key_Control:
777 case Qt::ControlModifier:
781 kDebug(5011) << "sendKey(): Unhandled Qt::Key value " << key;
785 if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L || k == XK_Super_L) {
786 if (m_mods.contains(k)) { //release
788 vncThread.keyEvent(k, false);
791 vncThread.keyEvent(k, true);
793 } else { //normal key
794 vncThread.keyEvent(k, true);
795 vncThread.keyEvent(k, false);
799 void VncView::sendKeySequence(QKeySequence keys)
801 Q_ASSERT(keys.count() <= 1); //we can only handle a single combination
803 //to get at individual key presses, we split 'keys' into its components
807 QString k = keys.toString().section('+', pos, pos);
811 //kDebug(5011) << "found key: " << k;
813 key_list.append(Qt::Key_Alt);
814 } else if(k == "Ctrl") {
815 key_list.append(Qt::Key_Control);
816 } else if(k == "Meta") {
817 key_list.append(Qt::Key_Meta);
819 key_list.append(QKeySequence(k)[0]);
825 for(int i = 0; i < key_list.count(); i++)
826 sendKey(Qt::Key(key_list.at(i)));
828 //release modifiers (everything before final key)
829 for(int i = key_list.count()-2; i >= 0; i--)
830 sendKey(Qt::Key(key_list.at(i)));
833 void VncView::reloadSettings()
836 left_zoom = settings.value("left_zoom", 0).toInt();
837 right_zoom = settings.value("right_zoom", 1).toInt();
838 disable_tapping = settings.value("disable_tapping", false).toBool();
840 bool always_show_local_cursor = settings.value("always_show_local_cursor", false).toBool();
841 if(always_show_local_cursor)
842 showDotCursor(CursorOn);
847 //convert commitString into keyevents
848 void VncView::inputMethodEvent(QInputMethodEvent *event)
850 //TODO handle replacements
851 //NOTE for the return key to work Qt needs to enable multiline input, which only works for Q(Plain)TextEdit
853 //kDebug(5011) << event->commitString() << "|" << event->preeditString() << "|" << event->replacementLength() << "|" << event->replacementStart();
854 QString letters = event->commitString();
855 for(int i = 0; i < letters.length(); i++) {
856 char k = letters.at(i).toLatin1(); //works with all 'normal' keys, not umlauts.
858 kDebug(5011) << "unhandled key";
861 vncThread.keyEvent(k, true);
862 vncThread.keyEvent(k, false);
866 void VncView::useFastTransformations(bool enabled)
868 if(enabled or zoomFactor() >= 1.0) {
869 transformation_mode = Qt::FastTransformation;
871 transformation_mode = Qt::SmoothTransformation;
876 #include "moc_vncview.cpp"