imported project
[presencevnc] / src / vncview.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2007-2008 Urs Wolfer <uwolfer @ kde.org>
4 **
5 ** This file is part of KDE.
6 **
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.
11 **
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.
16 **
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.
21 **
22 ****************************************************************************/
23
24 #include "vncview.h"
25
26 #include <QMessageBox>
27 #include <QInputDialog>
28 #define KMessageBox QMessageBox
29 #define error(parent, message, caption) \
30 critical(parent, caption, message)
31
32 #include <QApplication>
33 #include <QImage>
34 #include <QPainter>
35 #include <QMouseEvent>
36 #include <QEvent>
37 #include <QTime>
38 #include <QTimer>
39
40 // Definition of key modifier mask constants
41 #define KMOD_Alt_R      0x01
42 #define KMOD_Alt_L      0x02
43 #define KMOD_Meta_L     0x04
44 #define KMOD_Control_L  0x08
45 #define KMOD_Shift_L    0x10
46
47 VncView::VncView(QWidget *parent, const KUrl &url, RemoteView::Quality quality)
48         : RemoteView(parent),
49         m_initDone(false),
50         m_buttonMask(0),
51         cursor_x(0),
52         cursor_y(0),
53         m_repaint(false),
54         m_quitFlag(false),
55         m_firstPasswordTry(true),
56         m_authenticaionCanceled(false),
57         m_dontSendClipboard(false),
58         m_horizontalFactor(1.0),
59         m_verticalFactor(1.0),
60         m_forceLocalCursor(false),
61         force_full_repaint(false),
62         quality(quality)
63 {
64     m_url = url;
65     m_host = url.host();
66     m_port = url.port();
67
68     connect(&vncThread, SIGNAL(imageUpdated(int, int, int, int)), this, SLOT(updateImage(int, int, int, int)), Qt::BlockingQueuedConnection);
69     connect(&vncThread, SIGNAL(gotCut(const QString&)), this, SLOT(setCut(const QString&)), Qt::BlockingQueuedConnection);
70     connect(&vncThread, SIGNAL(passwordRequest()), this, SLOT(requestPassword()), Qt::BlockingQueuedConnection);
71     connect(&vncThread, SIGNAL(outputErrorMessage(QString)), this, SLOT(outputErrorMessage(QString)));
72
73     m_clipboard = QApplication::clipboard();
74     connect(m_clipboard, SIGNAL(selectionChanged()), this, SLOT(clipboardSelectionChanged()));
75     connect(m_clipboard, SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged()));
76 }
77
78 VncView::~VncView()
79 {
80     unpressModifiers();
81
82     // Disconnect all signals so that we don't get any more callbacks from the client thread
83     disconnect(&vncThread, SIGNAL(imageUpdated(int, int, int, int)), this, SLOT(updateImage(int, int, int, int)));
84     disconnect(&vncThread, SIGNAL(gotCut(const QString&)), this, SLOT(setCut(const QString&)));
85     disconnect(&vncThread, SIGNAL(passwordRequest()), this, SLOT(requestPassword()));
86     disconnect(&vncThread, SIGNAL(outputErrorMessage(QString)), this, SLOT(outputErrorMessage(QString)));
87
88     startQuitting();
89 }
90
91 void VncView::forceFullRepaint()
92 {
93         force_full_repaint = true;
94         repaint();
95 }
96
97 bool VncView::eventFilter(QObject *obj, QEvent *event)
98 {
99     if (m_viewOnly) {
100         if (event->type() == QEvent::KeyPress ||
101                 event->type() == QEvent::KeyRelease ||
102                 event->type() == QEvent::MouseButtonDblClick ||
103                 event->type() == QEvent::MouseButtonPress ||
104                 event->type() == QEvent::MouseButtonRelease ||
105                 event->type() == QEvent::Wheel ||
106                 event->type() == QEvent::MouseMove)
107             return true;
108     }
109     return RemoteView::eventFilter(obj, event);
110 }
111
112 QSize VncView::framebufferSize()
113 {
114     return m_frame.size();
115 }
116
117 QSize VncView::sizeHint() const
118 {
119     return size();
120 }
121
122 QSize VncView::minimumSizeHint() const
123 {
124     return size();
125 }
126
127 void VncView::scaleResize(int w, int h)
128 {
129     RemoteView::scaleResize(w, h);
130     
131     kDebug(5011) << "scaleResize(): " <<w << h;
132     if (m_scale) {
133         m_verticalFactor = (qreal) h / m_frame.height();
134         m_horizontalFactor = (qreal) w / m_frame.width();
135
136         m_verticalFactor = m_horizontalFactor = qMin(m_verticalFactor, m_horizontalFactor);
137
138         const qreal newW = m_frame.width() * m_horizontalFactor;
139         const qreal newH = m_frame.height() * m_verticalFactor;
140         /*
141         setMaximumSize(newW, newH); //This is a hack to force Qt to center the view in the scroll area
142         //also causes the widget's size to flicker
143         */
144         resize(newW, newH);
145     } 
146 }
147
148 void VncView::updateConfiguration()
149 {
150     RemoteView::updateConfiguration();
151
152     // Update the scaling mode in case KeepAspectRatio changed
153     if(parentWidget())
154             scaleResize(parentWidget()->width(), parentWidget()->height());
155     else
156         scaleResize(width(), height());
157 }
158
159 void VncView::startQuitting()
160 {
161     kDebug(5011) << "about to quit";
162
163     const bool connected = status() == RemoteView::Connected;
164
165     setStatus(Disconnecting);
166
167     m_quitFlag = true;
168
169     if (connected) {
170         vncThread.stop();
171     }
172
173     vncThread.quit();
174
175     const bool quitSuccess = vncThread.wait(500);
176
177     kDebug(5011) << "Quit VNC thread success:" << quitSuccess;
178
179     setStatus(Disconnected);
180 }
181
182 bool VncView::isQuitting()
183 {
184     return m_quitFlag;
185 }
186
187 bool VncView::start()
188 {
189     vncThread.setHost(m_host);
190     vncThread.setPort(m_port);
191
192     vncThread.setQuality(quality);
193
194     // set local cursor on by default because low quality mostly means slow internet connection
195     if (quality == RemoteView::Low) {
196         showDotCursor(RemoteView::CursorOn);
197     }
198
199     setStatus(Connecting);
200
201     vncThread.start();
202     return true;
203 }
204
205 bool VncView::supportsScaling() const
206 {
207     return true;
208 }
209
210 bool VncView::supportsLocalCursor() const
211 {
212     return true;
213 }
214
215 void VncView::requestPassword()
216 {
217     kDebug(5011) << "request password";
218
219     if (m_authenticaionCanceled) {
220         startQuitting();
221         return;
222     }
223
224     setStatus(Authenticating);
225
226     if (!m_url.password().isNull()) {
227         vncThread.setPassword(m_url.password());
228         return;
229     }
230
231     bool ok;
232     QString password = QInputDialog::getText(this, //krazy:exclude=qclasses
233                                              tr("Password required"),
234                                              tr("Please enter the password for the remote desktop:"),
235                                              QLineEdit::Password, QString(), &ok);
236     m_firstPasswordTry = false;
237     if (ok)
238         vncThread.setPassword(password);
239     else
240         m_authenticaionCanceled = true;
241 }
242
243 void VncView::outputErrorMessage(const QString &message)
244 {
245     kDebug(5011) << message;
246
247     if (message == "INTERNAL:APPLE_VNC_COMPATIBILTY") {
248         setCursor(localDotCursor());
249         m_forceLocalCursor = true;
250         return;
251     }
252
253     startQuitting();
254
255     emit errorMessage(i18n("VNC failure"), message);
256 }
257
258 void VncView::updateImage(int x, int y, int w, int h)
259 {
260 //     kDebug(5011) << "got update" << width() << height();
261
262     m_x = x;
263     m_y = y;
264     m_w = w;
265     m_h = h;
266
267     if (m_horizontalFactor != 1.0 || m_verticalFactor != 1.0) {
268         // If the view is scaled, grow the update rectangle to avoid artifacts
269         m_x-=1;
270         m_y-=1;
271         m_w+=2;
272         m_h+=2;
273     }
274
275     m_frame = vncThread.image();
276
277     if (!m_initDone) {
278         setAttribute(Qt::WA_StaticContents);
279         setAttribute(Qt::WA_OpaquePaintEvent);
280         installEventFilter(this);
281
282         setCursor(((m_dotCursorState == CursorOn) || m_forceLocalCursor) ? localDotCursor() : Qt::BlankCursor);
283
284         setMouseTracking(true); // get mouse events even when there is no mousebutton pressed
285         setFocusPolicy(Qt::WheelFocus);
286         setStatus(Connected);
287 //         emit framebufferSizeChanged(m_frame.width(), m_frame.height());
288         emit connected();
289         
290         if (m_scale) {
291             if (parentWidget())
292                 scaleResize(parentWidget()->width(), parentWidget()->height());
293             else
294                 scaleResize(width(), height());
295         } 
296         
297         m_initDone = true;
298
299     }
300
301         static QSize old_frame_size = QSize();
302     if ((y == 0 && x == 0) && (m_frame.size() != old_frame_size)) {
303             old_frame_size = m_frame.size();
304         kDebug(5011) << "Updating framebuffer size";
305         if (m_scale) {
306             //setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
307             if (parentWidget())
308                 scaleResize(parentWidget()->width(), parentWidget()->height());
309         } else {
310             kDebug(5011) << "Resizing: " << m_frame.width() << m_frame.height();
311             resize(m_frame.width(), m_frame.height());
312             //setMaximumSize(m_frame.width(), m_frame.height()); //This is a hack to force Qt to center the view in the scroll area
313             //setMinimumSize(m_frame.width(), m_frame.height());
314         }
315         emit framebufferSizeChanged(m_frame.width(), m_frame.height());
316     }
317
318     m_repaint = true;
319     repaint(qRound(m_x * m_horizontalFactor), qRound(m_y * m_verticalFactor), qRound(m_w * m_horizontalFactor), qRound(m_h * m_verticalFactor));
320     m_repaint = false;
321 }
322
323 void VncView::setViewOnly(bool viewOnly)
324 {
325     RemoteView::setViewOnly(viewOnly);
326
327     m_dontSendClipboard = viewOnly;
328
329     if (viewOnly)
330         setCursor(Qt::ArrowCursor);
331     else
332         setCursor(m_dotCursorState == CursorOn ? localDotCursor() : Qt::BlankCursor);
333 }
334
335 void VncView::showDotCursor(DotCursorState state)
336 {
337     RemoteView::showDotCursor(state);
338
339     setCursor(state == CursorOn ? localDotCursor() : Qt::BlankCursor);
340 }
341
342 void VncView::enableScaling(bool scale)
343 {
344     RemoteView::enableScaling(scale);
345
346     if (scale) {
347         //setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
348         //setMinimumSize(1, 1);
349         if (parentWidget())
350             scaleResize(parentWidget()->width(), parentWidget()->height());
351             else
352                 scaleResize(width(), height());
353     } else {
354         m_verticalFactor = 1.0;
355         m_horizontalFactor = 1.0;
356
357         //setMaximumSize(m_frame.width(), m_frame.height()); //This is a hack to force Qt to center the view in the scroll area
358         //setMinimumSize(m_frame.width(), m_frame.height());
359         resize(m_frame.width(), m_frame.height());
360     }
361 }
362
363 void VncView::setCut(const QString &text)
364 {
365     m_dontSendClipboard = true;
366     m_clipboard->setText(text, QClipboard::Clipboard);
367     m_clipboard->setText(text, QClipboard::Selection);
368     m_dontSendClipboard = false;
369 }
370
371 void VncView::paintEvent(QPaintEvent *event)
372 {
373 //     kDebug(5011) << "paint event: x: " << m_x << ", y: " << m_y << ", w: " << m_w << ", h: " << m_h;
374     if (m_frame.isNull() || m_frame.format() == QImage::Format_Invalid) {
375         kDebug(5011) << "no valid image to paint";
376         RemoteView::paintEvent(event);
377         return;
378     }
379
380     event->accept();
381
382     QPainter painter(this);
383
384     if (m_repaint) {
385 //         kDebug(5011) << "normal repaint";
386         painter.drawImage(QRect(qRound(m_x*m_horizontalFactor), qRound(m_y*m_verticalFactor),
387                                 qRound(m_w*m_horizontalFactor), qRound(m_h*m_verticalFactor)), 
388                           m_frame.copy(m_x, m_y, m_w, m_h).scaled(qRound(m_w*m_horizontalFactor), 
389                                                                   qRound(m_h*m_verticalFactor),
390                                                                   Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
391     } else {
392          kDebug(5011) << "resize repaint";
393         QRect rect = event->rect();
394         if (!force_full_repaint and (rect.width() != width() || rect.height() != height())) {
395              kDebug(5011) << "Partial repaint";
396             const int sx = rect.x()/m_horizontalFactor;
397             const int sy = rect.y()/m_verticalFactor;
398             const int sw = rect.width()/m_horizontalFactor;
399             const int sh = rect.height()/m_verticalFactor;
400             painter.drawImage(rect, 
401                               m_frame.copy(sx, sy, sw, sh).scaled(rect.width(), rect.height(),
402                                                                   Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
403         } else {
404              kDebug(5011) << "Full repaint" << width() << height() << m_frame.width() << m_frame.height();
405             painter.drawImage(QRect(0, 0, width(), height()), 
406                               m_frame.scaled(m_frame.width() * m_horizontalFactor, m_frame.height() * m_verticalFactor,
407                                              Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
408             force_full_repaint = false;
409         }
410     }
411
412     RemoteView::paintEvent(event);
413 }
414
415 void VncView::resizeEvent(QResizeEvent *event)
416 {
417     RemoteView::resizeEvent(event);
418     scaleResize(event->size().width(), event->size().height());
419     forceFullRepaint();
420 }
421
422 bool VncView::event(QEvent *event)
423 {
424     switch (event->type()) {
425     case QEvent::KeyPress:
426     case QEvent::KeyRelease:
427 //         kDebug(5011) << "keyEvent";
428         keyEventHandler(static_cast<QKeyEvent*>(event));
429         return true;
430         break;
431     case QEvent::MouseButtonDblClick:
432     case QEvent::MouseButtonPress:
433     case QEvent::MouseButtonRelease:
434     case QEvent::MouseMove:
435 //         kDebug(5011) << "mouseEvent";
436         mouseEventHandler(static_cast<QMouseEvent*>(event));
437         return true;
438         break;
439     case QEvent::Wheel:
440 //         kDebug(5011) << "wheelEvent";
441         wheelEventHandler(static_cast<QWheelEvent*>(event));
442         return true;
443         break;
444     default:
445         return RemoteView::event(event);
446     }
447 }
448
449
450 void VncView::mouseEventHandler(QMouseEvent *e)
451 {
452         static bool tap_detected = false;
453         static bool double_tap_detected = false;
454         static bool tap_drag_detected = false;
455         static QTime press_time;
456         static QTime up_time; //used for double clicks/tap&drag, for time after first tap
457 static QTime foo;
458
459         if(!e) { //flush held taps
460                 if(tap_detected) {
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() > 200) { //got tap + another press -> tap & drag
467                         m_buttonMask |= 0x01;
468                         vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
469                         foo.start();
470                         double_tap_detected = false;
471                         tap_drag_detected = true;
472                 }
473                         
474                 return;
475         }
476
477         if(e->x() < 0 or e->y() < 0) { //QScrollArea tends to send invalid events sometimes...
478                 e->ignore();
479                 return;
480         }
481
482         cursor_x = qRound(e->x()/m_horizontalFactor);
483         cursor_y = qRound(e->y()/m_verticalFactor);
484         vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask); // plain move event
485
486         if(e->type() == QEvent::MouseButtonPress or e->type() == QEvent::MouseButtonDblClick) {
487                 press_time.start();
488                 if(tap_detected and up_time.elapsed() < 500) {
489                         tap_detected = false;
490                         double_tap_detected = true;
491
492                         QTimer::singleShot(200, this, SLOT(mouseEventHandler()));
493                 }
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;
501
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() < 200) { //tap
511                         up_time.start();
512                         tap_detected = true;
513                         QTimer::singleShot(500, this, SLOT(mouseEventHandler()));
514                 }
515
516         }
517
518 /* for reference:
519     if (e->type() != QEvent::MouseMove) {
520         if ((e->type() == QEvent::MouseButtonPress)) {
521             if (e->button() & Qt::LeftButton)
522                 m_buttonMask |= 0x01;
523             if (e->button() & Qt::MidButton)
524                 m_buttonMask |= 0x02;
525             if (e->button() & Qt::RightButton)
526                 m_buttonMask |= 0x04;
527         } else if (e->type() == QEvent::MouseButtonRelease) {
528             if (e->button() & Qt::LeftButton)
529                 m_buttonMask &= 0xfe;
530             if (e->button() & Qt::MidButton)
531                 m_buttonMask &= 0xfd;
532             if (e->button() & Qt::RightButton)
533                 m_buttonMask &= 0xfb;
534         */
535 }
536
537 void VncView::wheelEventHandler(QWheelEvent *event)
538 {
539     int eb = 0;
540     if (event->delta() < 0)
541         eb |= 0x10;
542     else
543         eb |= 0x8;
544
545     const int x = qRound(event->x() / m_horizontalFactor);
546     const int y = qRound(event->y() / m_verticalFactor);
547
548         kDebug(5011) << "Wheelevent";
549     vncThread.mouseEvent(x, y, eb | m_buttonMask);
550     vncThread.mouseEvent(x, y, m_buttonMask);
551 }
552
553 void VncView::keyEventHandler(QKeyEvent *e)
554 {
555     // strip away autorepeating KeyRelease; see bug #206598
556     if (e->isAutoRepeat() && (e->type() == QEvent::KeyRelease))
557         return;
558
559 // parts of this code are based on http://italc.sourcearchive.com/documentation/1.0.9.1/vncview_8cpp-source.html
560     rfbKeySym k = e->nativeVirtualKey();
561
562     // we do not handle Key_Backtab separately as the Shift-modifier
563     // is already enabled
564     if (e->key() == Qt::Key_Backtab) {
565         k = XK_Tab;
566     }
567
568     const bool pressed = (e->type() == QEvent::KeyPress);
569
570     // handle modifiers
571     if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L) {
572         if (pressed) {
573             m_mods[k] = true;
574         } else if (m_mods.contains(k)) {
575             m_mods.remove(k);
576         } else {
577             unpressModifiers();
578         }
579     }
580
581
582     //handle clicks via zoom buttons
583     if(e->key() == Qt::Key_F8) {
584         if(pressed)
585                 m_buttonMask |= 0x01;
586         else
587                 m_buttonMask &= 0xfe;
588         vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
589         kDebug(5011) << "left zoom";
590     } else if(e->key() == Qt::Key_F7) {
591         if(pressed)
592                 m_buttonMask |= 0x04;
593         else
594                 m_buttonMask &= 0xfb;
595         vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
596         kDebug(5011) << "right zoom";
597     } else if (k) {
598         vncThread.keyEvent(k, pressed);
599     }
600 }
601
602 void VncView::unpressModifiers()
603 {
604     const QList<unsigned int> keys = m_mods.keys();
605     QList<unsigned int>::const_iterator it = keys.constBegin();
606     while (it != keys.end()) {
607         vncThread.keyEvent(*it, false);
608         it++;
609     }
610     m_mods.clear();
611 }
612
613 void VncView::clipboardSelectionChanged()
614 {
615     kDebug(5011);
616
617     if (m_status != Connected)
618         return;
619
620     if (m_clipboard->ownsSelection() || m_dontSendClipboard)
621         return;
622
623     const QString text = m_clipboard->text(QClipboard::Selection);
624
625     vncThread.clientCut(text);
626 }
627
628 void VncView::clipboardDataChanged()
629 {
630     kDebug(5011);
631
632     if (m_status != Connected)
633         return;
634
635     if (m_clipboard->ownsClipboard() || m_dontSendClipboard)
636         return;
637
638     const QString text = m_clipboard->text(QClipboard::Clipboard);
639
640     vncThread.clientCut(text);
641 }
642
643 #include "moc_vncview.cpp"