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>
36 #include <QHBoxLayout>
37 #include <QVBoxLayout>
39 #include <QMouseEvent>
40 #include <QPushButton>
47 // Definition of key modifier mask constants
48 #define KMOD_Alt_R 0x01
49 #define KMOD_Alt_L 0x02
50 #define KMOD_Meta_L 0x04
51 #define KMOD_Control_L 0x08
52 #define KMOD_Shift_L 0x10
54 VncView::VncView(QWidget *parent, const KUrl &url, RemoteView::Quality quality)
62 m_firstPasswordTry(true),
63 m_dontSendClipboard(false),
64 m_horizontalFactor(1.0),
65 m_verticalFactor(1.0),
66 m_forceLocalCursor(false),
67 force_full_repaint(false),
74 connect(&vncThread, SIGNAL(imageUpdated(int, int, int, int)), this, SLOT(updateImage(int, int, int, int)), Qt::BlockingQueuedConnection);
75 connect(&vncThread, SIGNAL(gotCut(const QString&)), this, SLOT(setCut(const QString&)), Qt::BlockingQueuedConnection);
76 connect(&vncThread, SIGNAL(passwordRequest()), this, SLOT(requestPassword()), Qt::BlockingQueuedConnection);
77 connect(&vncThread, SIGNAL(outputErrorMessage(QString)), this, SLOT(outputErrorMessage(QString)));
79 m_clipboard = QApplication::clipboard();
80 connect(m_clipboard, SIGNAL(selectionChanged()), this, SLOT(clipboardSelectionChanged()));
81 connect(m_clipboard, SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged()));
90 // Disconnect all signals so that we don't get any more callbacks from the client thread
91 vncThread.disconnect();
96 void VncView::forceFullRepaint()
98 force_full_repaint = true;
102 bool VncView::eventFilter(QObject *obj, QEvent *event)
105 if (event->type() == QEvent::KeyPress ||
106 event->type() == QEvent::KeyRelease ||
107 event->type() == QEvent::MouseButtonDblClick ||
108 event->type() == QEvent::MouseButtonPress ||
109 event->type() == QEvent::MouseButtonRelease ||
110 event->type() == QEvent::Wheel ||
111 event->type() == QEvent::MouseMove)
114 return RemoteView::eventFilter(obj, event);
117 QSize VncView::framebufferSize()
119 return m_frame.size();
122 QSize VncView::sizeHint() const
127 QSize VncView::minimumSizeHint() const
132 void VncView::scaleResize(int w, int h)
134 RemoteView::scaleResize(w, h);
136 kDebug(5011) << "scaleResize(): " <<w << h;
138 m_verticalFactor = (qreal) h / m_frame.height();
139 m_horizontalFactor = (qreal) w / m_frame.width();
141 m_verticalFactor = m_horizontalFactor = qMin(m_verticalFactor, m_horizontalFactor);
143 const qreal newW = m_frame.width() * m_horizontalFactor;
144 const qreal newH = m_frame.height() * m_verticalFactor;
146 setMaximumSize(newW, newH); //This is a hack to force Qt to center the view in the scroll area
147 //also causes the widget's size to flicker
154 void VncView::startQuitting()
156 kDebug(5011) << "about to quit";
158 const bool connected = status() == RemoteView::Connected;
160 setStatus(Disconnecting);
170 const bool quitSuccess = vncThread.wait(500);
172 kDebug(5011) << "startQuitting(): Quit VNC thread success:" << quitSuccess;
174 setStatus(Disconnected);
177 bool VncView::isQuitting()
182 bool VncView::start()
184 vncThread.setHost(m_host);
185 vncThread.setPort(m_port);
187 vncThread.setQuality(quality);
189 // set local cursor on by default because low quality mostly means slow internet connection
190 if (quality == RemoteView::Low) {
191 showDotCursor(RemoteView::CursorOn);
194 setStatus(Connecting);
200 bool VncView::supportsScaling() const
205 bool VncView::supportsLocalCursor() const
210 void VncView::requestPassword()
212 kDebug(5011) << "request password";
214 setStatus(Authenticating);
216 if (!m_url.password().isNull()) {
217 vncThread.setPassword(m_url.password());
222 settings.beginGroup("hosts");
223 QString password = settings.value(QString("%1/password").arg(m_host), "").toString();
224 //check for saved password
225 if(m_firstPasswordTry and !password.isEmpty()) {
226 kDebug(5011) << "Trying saved password";
227 m_firstPasswordTry = false;
228 vncThread.setPassword(password);
231 m_firstPasswordTry = false;
234 QDialog dialog(this);
235 dialog.setWindowTitle(tr("Password required"));
237 QLineEdit passwordbox;
238 passwordbox.setEchoMode(QLineEdit::Password);
239 passwordbox.setText(password);
240 QCheckBox save_password(tr("Save Password"));
241 save_password.setChecked(!password.isEmpty()); //offer to overwrite saved password
242 QPushButton ok_button(tr("Done"));
243 ok_button.setMaximumWidth(100);
244 connect(&ok_button, SIGNAL(clicked()),
245 &dialog, SLOT(accept()));
249 layout2.addWidget(&passwordbox);
250 layout2.addWidget(&save_password);
251 layout1.addLayout(&layout2);
252 layout1.addWidget(&ok_button);
253 dialog.setLayout(&layout1);
255 if(dialog.exec()) { //dialog accepted
256 password = passwordbox.text();
258 if(save_password.isChecked()) {
259 kDebug(5011) << "Saving password for host '" << m_host << "'";
261 settings.setValue(QString("%1/password").arg(m_host), password);
265 vncThread.setPassword(password);
271 void VncView::outputErrorMessage(const QString &message)
273 kDebug(5011) << message;
275 if (message == "INTERNAL:APPLE_VNC_COMPATIBILTY") {
276 setCursor(localDotCursor());
277 m_forceLocalCursor = true;
283 emit errorMessage(i18n("VNC failure"), message);
286 void VncView::updateImage(int x, int y, int w, int h)
288 if(!QApplication::focusWidget()) { //no focus, we're probably minimized
291 //kDebug(5011) << "got update" << width() << height();
298 if (m_horizontalFactor != 1.0 || m_verticalFactor != 1.0) {
299 // If the view is scaled, grow the update rectangle to avoid artifacts
300 int x_extrapixels = 1.0/m_horizontalFactor+1;
301 int y_extrapixels = 1.0/m_verticalFactor+1;
305 m_w+=2*x_extrapixels;
306 m_h+=2*y_extrapixels;
309 m_frame = vncThread.image();
312 setAttribute(Qt::WA_StaticContents);
313 setAttribute(Qt::WA_OpaquePaintEvent);
314 installEventFilter(this);
316 setCursor(((m_dotCursorState == CursorOn) || m_forceLocalCursor) ? localDotCursor() : Qt::BlankCursor);
318 setMouseTracking(true); // get mouse events even when there is no mousebutton pressed
319 setFocusPolicy(Qt::WheelFocus);
320 setStatus(Connected);
321 // emit framebufferSizeChanged(m_frame.width(), m_frame.height());
326 scaleResize(parentWidget()->width(), parentWidget()->height());
328 scaleResize(width(), height());
335 static QSize old_frame_size = QSize();
336 if ((y == 0 && x == 0) && (m_frame.size() != old_frame_size)) {
337 old_frame_size = m_frame.size();
338 kDebug(5011) << "Updating framebuffer size";
340 //setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
342 scaleResize(parentWidget()->width(), parentWidget()->height());
344 kDebug(5011) << "Resizing: " << m_frame.width() << m_frame.height();
345 resize(m_frame.width(), m_frame.height());
346 //setMaximumSize(m_frame.width(), m_frame.height()); //This is a hack to force Qt to center the view in the scroll area
347 //setMinimumSize(m_frame.width(), m_frame.height());
349 emit framebufferSizeChanged(m_frame.width(), m_frame.height());
353 repaint(qRound(m_x * m_horizontalFactor), qRound(m_y * m_verticalFactor), qRound(m_w * m_horizontalFactor), qRound(m_h * m_verticalFactor));
357 void VncView::setViewOnly(bool viewOnly)
359 RemoteView::setViewOnly(viewOnly);
361 m_dontSendClipboard = viewOnly;
364 setCursor(Qt::ArrowCursor);
366 setCursor(m_dotCursorState == CursorOn ? localDotCursor() : Qt::BlankCursor);
369 void VncView::showDotCursor(DotCursorState state)
371 RemoteView::showDotCursor(state);
373 setCursor(state == CursorOn ? localDotCursor() : Qt::BlankCursor);
376 void VncView::enableScaling(bool scale)
378 RemoteView::enableScaling(scale);
381 //setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
382 //setMinimumSize(1, 1);
384 scaleResize(parentWidget()->width(), parentWidget()->height());
386 scaleResize(width(), height());
388 m_verticalFactor = 1.0;
389 m_horizontalFactor = 1.0;
391 //setMaximumSize(m_frame.width(), m_frame.height()); //This is a hack to force Qt to center the view in the scroll area
392 //setMinimumSize(m_frame.width(), m_frame.height());
393 resize(m_frame.width(), m_frame.height());
397 void VncView::setCut(const QString &text)
399 m_dontSendClipboard = true;
400 m_clipboard->setText(text, QClipboard::Clipboard);
401 m_clipboard->setText(text, QClipboard::Selection);
402 m_dontSendClipboard = false;
405 void VncView::paintEvent(QPaintEvent *event)
407 //kDebug(5011) << "paint event: x: " << m_x << ", y: " << m_y << ", w: " << m_w << ", h: " << m_h;
408 if (m_frame.isNull() || m_frame.format() == QImage::Format_Invalid) {
409 kDebug(5011) << "no valid image to paint";
410 RemoteView::paintEvent(event);
416 QPainter painter(this);
418 if (m_repaint and !force_full_repaint) {
419 // kDebug(5011) << "normal repaint";
420 painter.drawImage(QRect(qRound(m_x*m_horizontalFactor), qRound(m_y*m_verticalFactor),
421 qRound(m_w*m_horizontalFactor), qRound(m_h*m_verticalFactor)),
422 m_frame.copy(m_x, m_y, m_w, m_h).scaled(qRound(m_w*m_horizontalFactor),
423 qRound(m_h*m_verticalFactor),
424 Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
426 //kDebug(5011) << "resize repaint";
427 QRect rect = event->rect();
428 if (!force_full_repaint and (rect.width() != width() || rect.height() != height())) {
429 // kDebug(5011) << "Partial repaint";
430 const int sx = rect.x()/m_horizontalFactor;
431 const int sy = rect.y()/m_verticalFactor;
432 const int sw = rect.width()/m_horizontalFactor;
433 const int sh = rect.height()/m_verticalFactor;
434 painter.drawImage(rect,
435 m_frame.copy(sx, sy, sw, sh).scaled(rect.width(), rect.height(),
436 Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
438 kDebug(5011) << "Full repaint" << width() << height() << m_frame.width() << m_frame.height();
439 painter.drawImage(QRect(0, 0, width(), height()),
440 m_frame.scaled(m_frame.width() * m_horizontalFactor, m_frame.height() * m_verticalFactor,
441 Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
442 force_full_repaint = false;
446 RemoteView::paintEvent(event);
449 void VncView::resizeEvent(QResizeEvent *event)
451 RemoteView::resizeEvent(event);
452 scaleResize(event->size().width(), event->size().height());
456 bool VncView::event(QEvent *event)
458 switch (event->type()) {
459 case QEvent::KeyPress:
460 case QEvent::KeyRelease:
461 // kDebug(5011) << "keyEvent";
462 keyEventHandler(static_cast<QKeyEvent*>(event));
465 case QEvent::MouseButtonDblClick:
466 case QEvent::MouseButtonPress:
467 case QEvent::MouseButtonRelease:
468 case QEvent::MouseMove:
469 // kDebug(5011) << "mouseEvent";
470 mouseEventHandler(static_cast<QMouseEvent*>(event));
474 // kDebug(5011) << "wheelEvent";
475 wheelEventHandler(static_cast<QWheelEvent*>(event));
478 case QEvent::WindowActivate: //input panel may have been closed, prevent IM from interfering with hardware keyboard
479 setAttribute(Qt::WA_InputMethodEnabled, false);
482 return RemoteView::event(event);
486 //call with e == 0 to flush held events
487 void VncView::mouseEventHandler(QMouseEvent *e)
489 static bool tap_detected = false;
490 static bool double_tap_detected = false;
491 static bool tap_drag_detected = false;
492 static QTime press_time;
493 static QTime up_time; //used for double clicks/tap&drag, for time after first tap
495 const int TAP_PRESS_TIME = 180;
496 const int DOUBLE_TAP_UP_TIME = 500;
498 if(!e) { //flush held taps
500 m_buttonMask |= 0x01;
501 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
502 m_buttonMask &= 0xfe;
503 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
504 tap_detected = false;
505 } else if(double_tap_detected and press_time.elapsed() > TAP_PRESS_TIME) { //got tap + another press -> tap & drag
506 m_buttonMask |= 0x01;
507 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
508 double_tap_detected = false;
509 tap_drag_detected = true;
515 if(e->x() < 0 or e->y() < 0) { //QScrollArea tends to send invalid events sometimes...
520 cursor_x = qRound(e->x()/m_horizontalFactor);
521 cursor_y = qRound(e->y()/m_verticalFactor);
522 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask); // plain move event
524 if(disable_tapping) { //only move cursor
529 if(e->type() == QEvent::MouseButtonPress or e->type() == QEvent::MouseButtonDblClick) {
531 if(tap_detected and up_time.elapsed() < DOUBLE_TAP_UP_TIME) {
532 tap_detected = false;
533 double_tap_detected = true;
535 QTimer::singleShot(TAP_PRESS_TIME, this, SLOT(mouseEventHandler()));
537 } else if(e->type() == QEvent::MouseButtonRelease) {
538 if(tap_drag_detected) {
539 m_buttonMask &= 0xfe;
540 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
541 tap_drag_detected = false;
542 } else if(double_tap_detected) { //double click
543 double_tap_detected = false;
545 m_buttonMask |= 0x01;
546 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
547 m_buttonMask &= 0xfe;
548 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
549 m_buttonMask |= 0x01;
550 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
551 m_buttonMask &= 0xfe;
552 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
553 } else if(press_time.elapsed() < TAP_PRESS_TIME) { //tap
556 QTimer::singleShot(DOUBLE_TAP_UP_TIME, this, SLOT(mouseEventHandler()));
562 if (e->type() != QEvent::MouseMove) {
563 if ((e->type() == QEvent::MouseButtonPress)) {
564 if (e->button() & Qt::LeftButton)
565 m_buttonMask |= 0x01;
566 if (e->button() & Qt::MidButton)
567 m_buttonMask |= 0x02;
568 if (e->button() & Qt::RightButton)
569 m_buttonMask |= 0x04;
570 } else if (e->type() == QEvent::MouseButtonRelease) {
571 if (e->button() & Qt::LeftButton)
572 m_buttonMask &= 0xfe;
573 if (e->button() & Qt::MidButton)
574 m_buttonMask &= 0xfd;
575 if (e->button() & Qt::RightButton)
576 m_buttonMask &= 0xfb;
580 void VncView::wheelEventHandler(QWheelEvent *event)
583 if (event->delta() < 0)
588 const int x = qRound(event->x() / m_horizontalFactor);
589 const int y = qRound(event->y() / m_verticalFactor);
591 kDebug(5011) << "Wheelevent";
592 vncThread.mouseEvent(x, y, eb | m_buttonMask);
593 vncThread.mouseEvent(x, y, m_buttonMask);
596 void VncView::keyEventHandler(QKeyEvent *e)
598 // strip away autorepeating KeyRelease; see bug #206598
599 if (e->isAutoRepeat() && (e->type() == QEvent::KeyRelease)) {
603 // parts of this code are based on http://italc.sourcearchive.com/documentation/1.0.9.1/vncview_8cpp-source.html
604 rfbKeySym k = e->nativeVirtualKey();
606 // we do not handle Key_Backtab separately as the Shift-modifier
607 // is already enabled
608 if (e->key() == Qt::Key_Backtab) {
612 const bool pressed = (e->type() == QEvent::KeyPress);
615 if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L) {
618 } else if (m_mods.contains(k)) {
626 int current_zoom = -1;
627 if(e->key() == Qt::Key_F8)
628 current_zoom = left_zoom;
629 else if(e->key() == Qt::Key_F7)
630 current_zoom = right_zoom;
632 // kDebug(5011) << "got '" << e->text() << "'.";
633 vncThread.keyEvent(k, pressed);
635 kDebug(5011) << "nativeVirtualKey() for '" << e->text() << "' failed.";
639 if(current_zoom == -1)
642 //handle zoom buttons
643 if(current_zoom == 0) { //left click
645 m_buttonMask |= 0x01;
647 m_buttonMask &= 0xfe;
648 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
649 } else if(current_zoom == 1) { //right click
651 m_buttonMask |= 0x04;
653 m_buttonMask &= 0xfb;
654 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
655 } else if(current_zoom == 2) { //middle click
657 m_buttonMask |= 0x02;
659 m_buttonMask &= 0xfd;
660 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
661 } else if(current_zoom == 3 and pressed) { //wheel up
663 vncThread.mouseEvent(cursor_x, cursor_y, eb | m_buttonMask);
664 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
665 } else if(current_zoom == 4 and pressed) { //wheel down
667 vncThread.mouseEvent(cursor_x, cursor_y, eb | m_buttonMask);
668 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
669 } else if(current_zoom == 5) { //page up
670 vncThread.keyEvent(0xff55, pressed);
671 } else if(current_zoom == 6) { //page down
672 vncThread.keyEvent(0xff56, pressed);
676 void VncView::unpressModifiers()
678 const QList<unsigned int> keys = m_mods.keys();
679 QList<unsigned int>::const_iterator it = keys.constBegin();
680 while (it != keys.end()) {
681 vncThread.keyEvent(*it, false);
687 void VncView::clipboardSelectionChanged()
691 if (m_status != Connected)
694 if (m_clipboard->ownsSelection() || m_dontSendClipboard)
697 const QString text = m_clipboard->text(QClipboard::Selection);
699 vncThread.clientCut(text);
702 void VncView::clipboardDataChanged()
706 if (m_status != Connected)
709 if (m_clipboard->ownsClipboard() || m_dontSendClipboard)
712 const QString text = m_clipboard->text(QClipboard::Clipboard);
714 vncThread.clientCut(text);
718 void VncView::sendKey(Qt::Key key)
720 int k = 0; //X11 keysym
731 case Qt::Key_PageDown:
737 case Qt::Key_Meta: //TODO: test this.
744 kDebug(5011) << "sendKey(): Unhandled Qt::Key value " << key;
748 if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L || k == XK_Super_L) {
749 if (m_mods.contains(k)) { //release
751 vncThread.keyEvent(k, false);
754 vncThread.keyEvent(k, true);
756 } else { //normal key
757 vncThread.keyEvent(k, true);
758 vncThread.keyEvent(k, false);
762 void VncView::reloadSettings()
765 left_zoom = settings.value("left_zoom", 0).toInt();
766 right_zoom = settings.value("right_zoom", 1).toInt();
767 disable_tapping = settings.value("disable_tapping", false).toBool();
770 //convert commitString into keyevents
771 void VncView::inputMethodEvent(QInputMethodEvent *event)
773 //TODO handle replacements
774 //NOTE for the return key to work Qt needs to enable multiline input, which only works for Q(Plain)TextEdit
776 //kDebug(5011) << event->commitString() << "|" << event->preeditString() << "|" << event->replacementLength() << "|" << event->replacementStart();
777 QString letters = event->commitString();
778 for(int i = 0; i < letters.length(); i++) {
779 char k = letters.at(i).toLatin1(); //works with all 'normal' keys, not umlauts.
781 kDebug(5011) << "unhandled key";
784 vncThread.keyEvent(k, true);
785 vncThread.keyEvent(k, false);
790 #include "moc_vncview.cpp"