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)
120 return RemoteView::eventFilter(obj, event);
123 QSize VncView::framebufferSize()
125 return m_frame.size();
128 QSize VncView::sizeHint() const
133 QSize VncView::minimumSizeHint() const
138 void VncView::startQuitting()
143 kDebug(5011) << "about to quit";
145 //const bool connected = status() == RemoteView::Connected;
147 setStatus(Disconnecting);
151 //if(connected) //remove if things work without it
154 const bool quitSuccess = vncThread.wait(700);
156 //happens when vncThread wants to call a slot via BlockingQueuedConnection,
157 //needs an event loop in this thread so execution continues after 'emit'
159 if(!loop.processEvents())
160 kDebug(5011) << "BUG: deadlocked, but no events to deliver?";
163 setStatus(Disconnected);
166 bool VncView::isQuitting()
171 bool VncView::start()
173 vncThread.setHost(m_host);
174 vncThread.setPort(m_port);
175 vncThread.setListenPort(listen_port); //if port is != 0, thread will listen for connections
176 vncThread.setQuality(quality);
178 // set local cursor on by default because low quality mostly means slow internet connection
179 if (quality == RemoteView::Low) {
180 showDotCursor(RemoteView::CursorOn);
183 setStatus(Connecting);
189 bool VncView::supportsScaling() const
194 bool VncView::supportsLocalCursor() const
199 void VncView::requestPassword()
201 kDebug(5011) << "request password";
203 setStatus(Authenticating);
205 if (!m_url.password().isNull()) {
206 vncThread.setPassword(m_url.password());
211 settings.beginGroup("hosts");
212 QString password = settings.value(QString("%1/password").arg(m_host), "").toString();
213 //check for saved password
214 if(m_firstPasswordTry and !password.isEmpty()) {
215 kDebug(5011) << "Trying saved password";
216 m_firstPasswordTry = false;
217 vncThread.setPassword(password);
220 m_firstPasswordTry = false;
223 QDialog dialog(this);
224 dialog.setWindowTitle(tr("Password required"));
226 QLineEdit passwordbox;
227 passwordbox.setEchoMode(QLineEdit::Password);
228 passwordbox.setText(password);
229 QCheckBox save_password(tr("Save Password"));
230 save_password.setChecked(!password.isEmpty()); //offer to overwrite saved password
231 QPushButton ok_button(tr("Done"));
232 ok_button.setMaximumWidth(100);
233 connect(&ok_button, SIGNAL(clicked()),
234 &dialog, SLOT(accept()));
238 layout2.addWidget(&passwordbox);
239 if(!m_host.isEmpty()) //don't save incomming connections
240 layout2.addWidget(&save_password);
241 layout1.addLayout(&layout2);
242 layout1.addWidget(&ok_button);
243 dialog.setLayout(&layout1);
245 if(dialog.exec()) { //dialog accepted
246 password = passwordbox.text();
248 if(!m_host.isEmpty() and save_password.isChecked()) {
249 kDebug(5011) << "Saving password for host '" << m_host << "'";
251 settings.setValue(QString("%1/password").arg(m_host), password);
255 vncThread.setPassword(password);
257 vncThread.setPassword(QString()); //null string to exit
261 void VncView::outputErrorMessage(const QString &message)
263 if (message == "INTERNAL:APPLE_VNC_COMPATIBILTY") {
264 setCursor(localDotCursor());
265 m_forceLocalCursor = true;
271 emit errorMessage(i18n("VNC failure"), message);
274 void VncView::updateImage(int x, int y, int w, int h)
276 if(!QApplication::focusWidget()) { //no focus, we're probably minimized
280 //kDebug(5011) << "got update" << width() << height();
287 if (m_horizontalFactor != 1.0 || m_verticalFactor != 1.0) {
288 // If the view is scaled, grow the update rectangle to avoid artifacts
289 int x_extrapixels = 1.0/m_horizontalFactor + 1;
290 int y_extrapixels = 1.0/m_verticalFactor + 1;
294 m_w+=2*x_extrapixels;
295 m_h+=2*y_extrapixels;
298 m_frame = vncThread.image();
300 if (!m_initDone) { //TODO this seems an odd place for initialization
301 setAttribute(Qt::WA_StaticContents);
302 setAttribute(Qt::WA_OpaquePaintEvent);
303 installEventFilter(this);
305 setCursor(((m_dotCursorState == CursorOn) || m_forceLocalCursor) ? localDotCursor() : Qt::BlankCursor);
307 setMouseTracking(true); // get mouse events even when there is no mousebutton pressed
308 setFocusPolicy(Qt::WheelFocus);
309 setStatus(Connected);
312 resize(width(), height());
318 static QSize old_frame_size = QSize();
319 if ((y == 0 && x == 0) && (m_frame.size() != old_frame_size)) {
320 old_frame_size = m_frame.size();
321 kDebug(5011) << "Updating framebuffer size";
323 useFastTransformations(false);
325 emit framebufferSizeChanged(m_frame.width(), m_frame.height());
328 repaint(qRound(m_x * m_horizontalFactor), qRound(m_y * m_verticalFactor), qRound(m_w * m_horizontalFactor), qRound(m_h * m_verticalFactor));
331 void VncView::setViewOnly(bool viewOnly)
333 RemoteView::setViewOnly(viewOnly);
335 m_dontSendClipboard = viewOnly;
338 setCursor(Qt::ArrowCursor);
340 setCursor(m_dotCursorState == CursorOn ? localDotCursor() : Qt::BlankCursor);
343 void VncView::showDotCursor(DotCursorState state)
345 RemoteView::showDotCursor(state);
347 setCursor(state == CursorOn ? localDotCursor() : Qt::BlankCursor);
350 //level should be in [0, 100]
351 void VncView::setZoomLevel(int level)
353 Q_ASSERT(parentWidget() != 0);
355 if(level == -1) { //handle resize
356 resize(m_frame.width()*m_horizontalFactor, m_frame.height()*m_verticalFactor);
360 double magnification;
363 } else if(level >= 90) {
366 const double min_horiz_magnification = double(parentWidget()->width())/m_frame.width();
367 const double min_vert_magnification = double(parentWidget()->height())/m_frame.height();
368 const double fit_screen_magnification = qMin(min_horiz_magnification, min_vert_magnification);
370 //level=90 => magnification=1.0, level=0 => magnification=fit_screen_magnification
371 magnification = (level)/90.0*(1.0 - fit_screen_magnification) + fit_screen_magnification;
374 if(magnification < 0 //remote display smaller than local?
375 or magnification != magnification) //nan
378 m_verticalFactor = m_horizontalFactor = magnification;
379 resize(m_frame.width()*magnification, m_frame.height()*magnification);
382 void VncView::setCut(const QString &text)
384 m_dontSendClipboard = true;
385 m_clipboard->setText(text, QClipboard::Clipboard);
386 m_clipboard->setText(text, QClipboard::Selection);
387 m_dontSendClipboard = false;
390 void VncView::paintEvent(QPaintEvent *event)
392 if (m_frame.isNull() || m_frame.format() == QImage::Format_Invalid) {
393 //no valid image to paint
394 RemoteView::paintEvent(event);
400 const QRect update_rect = event->rect();
401 QPainter painter(this);
402 if (update_rect != rect()) {
403 // kDebug(5011) << "Partial repaint";
404 const int sx = qRound(update_rect.x()/m_horizontalFactor);
405 const int sy = qRound(update_rect.y()/m_verticalFactor);
406 const int sw = qRound(update_rect.width()/m_horizontalFactor);
407 const int sh = qRound(update_rect.height()/m_verticalFactor);
409 painter.drawImage(update_rect,
410 m_frame.copy(sx, sy, sw, sh)
411 .scaled(update_rect.size(), Qt::IgnoreAspectRatio, transformation_mode));
413 //kDebug(5011) << "Full repaint" << width() << height() << m_frame.width() << m_frame.height();
415 painter.drawImage(rect(),
416 m_frame.scaled(size(), Qt::IgnoreAspectRatio, transformation_mode));
419 //draw local cursor ourselves, normal mouse pointer doesn't deal with scrolling
420 if((m_dotCursorState == CursorOn) || m_forceLocalCursor) {
421 #if QT_VERSION >= 0x040500
422 painter.setCompositionMode(QPainter::RasterOp_SourceXorDestination);
424 //rectangle size includes 1px pen width
425 painter.drawRect(cursor_x*m_horizontalFactor - CURSOR_SIZE/2, cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE-1, CURSOR_SIZE-1);
428 RemoteView::paintEvent(event);
431 void VncView::resizeEvent(QResizeEvent *event)
433 RemoteView::resizeEvent(event);
437 bool VncView::event(QEvent *event)
439 switch (event->type()) {
440 case QEvent::KeyPress:
441 case QEvent::KeyRelease:
442 // kDebug(5011) << "keyEvent";
443 keyEventHandler(static_cast<QKeyEvent*>(event));
446 case QEvent::MouseButtonDblClick:
447 case QEvent::MouseButtonPress:
448 case QEvent::MouseButtonRelease:
449 case QEvent::MouseMove:
450 // kDebug(5011) << "mouseEvent";
451 mouseEventHandler(static_cast<QMouseEvent*>(event));
455 // kDebug(5011) << "wheelEvent";
456 wheelEventHandler(static_cast<QWheelEvent*>(event));
459 case QEvent::WindowActivate: //input panel may have been closed, prevent IM from interfering with hardware keyboard
460 setAttribute(Qt::WA_InputMethodEnabled, false);
463 return RemoteView::event(event);
467 //call with e == 0 to flush held events
468 void VncView::mouseEventHandler(QMouseEvent *e)
470 static bool tap_detected = false;
471 static bool double_tap_detected = false;
472 static bool tap_drag_detected = false;
473 static QTime press_time;
474 static QTime up_time; //used for double clicks/tap&drag, for time after first tap
476 if(!e) { //flush held taps
478 m_buttonMask |= 0x01;
479 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
480 m_buttonMask &= 0xfe;
481 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
482 tap_detected = false;
483 } else if(double_tap_detected and press_time.elapsed() > TAP_PRESS_TIME) { //got tap + another press -> tap & drag
484 m_buttonMask |= 0x01;
485 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
486 double_tap_detected = false;
487 tap_drag_detected = true;
493 if(e->x() < 0 or e->y() < 0) { //QScrollArea tends to send invalid events sometimes...
498 cursor_x = qRound(e->x()/m_horizontalFactor);
499 cursor_y = qRound(e->y()/m_verticalFactor);
500 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask); // plain move event
502 if(!disable_tapping and e->button() == Qt::LeftButton) { //implement touchpad-like input for left button
503 if(e->type() == QEvent::MouseButtonPress or e->type() == QEvent::MouseButtonDblClick) {
505 if(tap_detected and up_time.elapsed() < DOUBLE_TAP_UP_TIME) {
506 tap_detected = false;
507 double_tap_detected = true;
509 QTimer::singleShot(TAP_PRESS_TIME, this, SLOT(mouseEventHandler()));
511 } else if(e->type() == QEvent::MouseButtonRelease) {
512 if(tap_drag_detected) {
513 m_buttonMask &= 0xfe;
514 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
515 tap_drag_detected = false;
516 } else if(double_tap_detected) { //double click
517 double_tap_detected = false;
519 m_buttonMask |= 0x01;
520 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
521 m_buttonMask &= 0xfe;
522 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
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 } else if(press_time.elapsed() < TAP_PRESS_TIME) { //tap
530 QTimer::singleShot(DOUBLE_TAP_UP_TIME, this, SLOT(mouseEventHandler()));
534 } else { //middle or right button, send directly
535 if ((e->type() == QEvent::MouseButtonPress)) {
536 if (e->button() & Qt::MidButton)
537 m_buttonMask |= 0x02;
538 if (e->button() & Qt::RightButton)
539 m_buttonMask |= 0x04;
540 } else if (e->type() == QEvent::MouseButtonRelease) {
541 if (e->button() & Qt::MidButton)
542 m_buttonMask &= 0xfd;
543 if (e->button() & Qt::RightButton)
544 m_buttonMask &= 0xfb;
546 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
549 //prevent local cursor artifacts
550 static int old_cursor_x = cursor_x;
551 static int old_cursor_y = cursor_y;
552 if(((m_dotCursorState == CursorOn) || m_forceLocalCursor)
553 and (cursor_x != old_cursor_x or cursor_y != old_cursor_y)) {
554 //clear last position
555 repaint(old_cursor_x*m_horizontalFactor - CURSOR_SIZE/2, old_cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE, CURSOR_SIZE);
556 //and refresh new one
557 repaint(cursor_x*m_horizontalFactor - CURSOR_SIZE/2, cursor_y*m_verticalFactor - CURSOR_SIZE/2, CURSOR_SIZE, CURSOR_SIZE);
559 old_cursor_x = cursor_x; old_cursor_y = cursor_y;
563 void VncView::wheelEventHandler(QWheelEvent *event)
566 if (event->delta() < 0)
571 const int x = qRound(event->x() / m_horizontalFactor);
572 const int y = qRound(event->y() / m_verticalFactor);
574 vncThread.mouseEvent(x, y, eb | m_buttonMask);
575 vncThread.mouseEvent(x, y, m_buttonMask);
578 void VncView::keyEventHandler(QKeyEvent *e)
580 // strip away autorepeating KeyRelease; see bug #206598
581 if (e->isAutoRepeat() && (e->type() == QEvent::KeyRelease)) {
585 // parts of this code are based on http://italc.sourcearchive.com/documentation/1.0.9.1/vncview_8cpp-source.html
586 rfbKeySym k = e->nativeVirtualKey();
588 // we do not handle Key_Backtab separately as the Shift-modifier
589 // is already enabled
590 if (e->key() == Qt::Key_Backtab) {
594 const bool pressed = (e->type() == QEvent::KeyPress);
597 //don't send ISO_Level3_Shift (would break things like Win+0-9)
598 //also enable IM so symbol key works
600 setAttribute(Qt::WA_InputMethodEnabled, pressed);
607 if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L) {
610 } else if (m_mods.contains(k)) {
618 int current_zoom = -1;
619 if(e->key() == Qt::Key_F8)
620 current_zoom = left_zoom;
621 else if(e->key() == Qt::Key_F7)
622 current_zoom = right_zoom;
624 // kDebug(5011) << "got '" << e->text() << "'.";
625 vncThread.keyEvent(k, pressed);
627 kDebug(5011) << "nativeVirtualKey() for '" << e->text() << "' failed.";
631 if(current_zoom == -1)
634 //handle zoom buttons
635 if(current_zoom == 0) { //left click
637 m_buttonMask |= 0x01;
639 m_buttonMask &= 0xfe;
640 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
641 } else if(current_zoom == 1) { //right click
643 m_buttonMask |= 0x04;
645 m_buttonMask &= 0xfb;
646 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
647 } else if(current_zoom == 2) { //middle click
649 m_buttonMask |= 0x02;
651 m_buttonMask &= 0xfd;
652 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
653 } else if(current_zoom == 3 and pressed) { //wheel up
655 vncThread.mouseEvent(cursor_x, cursor_y, eb | m_buttonMask);
656 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
657 } else if(current_zoom == 4 and pressed) { //wheel down
659 vncThread.mouseEvent(cursor_x, cursor_y, eb | m_buttonMask);
660 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
661 } else if(current_zoom == 5) { //page up
662 vncThread.keyEvent(0xff55, pressed);
663 } else if(current_zoom == 6) { //page down
664 vncThread.keyEvent(0xff56, pressed);
668 void VncView::unpressModifiers()
670 const QList<unsigned int> keys = m_mods.keys();
671 QList<unsigned int>::const_iterator it = keys.constBegin();
672 while (it != keys.end()) {
673 vncThread.keyEvent(*it, false);
679 void VncView::clipboardSelectionChanged()
681 if (m_status != Connected)
684 if (m_clipboard->ownsSelection() || m_dontSendClipboard)
687 const QString text = m_clipboard->text(QClipboard::Selection);
689 vncThread.clientCut(text);
692 void VncView::clipboardDataChanged()
694 if (m_status != Connected)
697 if (m_clipboard->ownsClipboard() || m_dontSendClipboard)
700 const QString text = m_clipboard->text(QClipboard::Clipboard);
702 vncThread.clientCut(text);
706 void VncView::sendKey(Qt::Key key)
708 //convert Qt::Key into x11 keysym
720 case Qt::Key_PageDown:
738 case Qt::Key_Backspace:
753 k = 0xffbe + int(key - Qt::Key_F1);
765 case Qt::MetaModifier:
769 case Qt::AltModifier:
772 case Qt::Key_Control:
773 case Qt::ControlModifier:
777 kDebug(5011) << "sendKey(): Unhandled Qt::Key value " << key;
781 if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L || k == XK_Super_L) {
782 if (m_mods.contains(k)) { //release
784 vncThread.keyEvent(k, false);
787 vncThread.keyEvent(k, true);
789 } else { //normal key
790 vncThread.keyEvent(k, true);
791 vncThread.keyEvent(k, false);
795 void VncView::sendKeySequence(QKeySequence keys)
797 Q_ASSERT(keys.count() <= 1); //we can only handle a single combination
799 //to get at individual key presses, we split 'keys' into its components
803 QString k = keys.toString().section('+', pos, pos);
807 //kDebug(5011) << "found key: " << k;
809 key_list.append(Qt::Key_Alt);
810 } else if(k == "Ctrl") {
811 key_list.append(Qt::Key_Control);
812 } else if(k == "Meta") {
813 key_list.append(Qt::Key_Meta);
815 key_list.append(QKeySequence(k)[0]);
821 for(int i = 0; i < key_list.count(); i++)
822 sendKey(Qt::Key(key_list.at(i)));
824 //release modifiers (everything before final key)
825 for(int i = key_list.count()-2; i >= 0; i--)
826 sendKey(Qt::Key(key_list.at(i)));
829 void VncView::reloadSettings()
832 left_zoom = settings.value("left_zoom", 0).toInt();
833 right_zoom = settings.value("right_zoom", 1).toInt();
834 disable_tapping = settings.value("disable_tapping", false).toBool();
836 bool always_show_local_cursor = settings.value("always_show_local_cursor", false).toBool();
837 if(always_show_local_cursor)
838 showDotCursor(CursorOn);
843 //convert commitString into keyevents
844 void VncView::inputMethodEvent(QInputMethodEvent *event)
846 //TODO handle replacements
847 //NOTE for the return key to work Qt needs to enable multiline input, which only works for Q(Plain)TextEdit
849 //kDebug(5011) << event->commitString() << "|" << event->preeditString() << "|" << event->replacementLength() << "|" << event->replacementStart();
850 QString letters = event->commitString();
851 for(int i = 0; i < letters.length(); i++) {
852 char k = letters.at(i).toLatin1(); //works with all 'normal' keys, not umlauts.
854 kDebug(5011) << "unhandled key";
857 vncThread.keyEvent(k, true);
858 vncThread.keyEvent(k, false);
862 void VncView::useFastTransformations(bool enabled)
864 if(enabled or zoomFactor() >= 1.0) {
865 transformation_mode = Qt::FastTransformation;
867 transformation_mode = Qt::SmoothTransformation;
872 #include "moc_vncview.cpp"