trying to pinpoint crash on exit
[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 <QBitmap>
34 #include <QCheckBox>
35 #include <QDialog>
36 #include <QImage>
37 #include <QHBoxLayout>
38 #include <QVBoxLayout>
39 #include <QPainter>
40 #include <QMouseEvent>
41 #include <QPushButton>
42 #include <QEvent>
43 #include <QSettings>
44 #include <QTime>
45 #include <QTimer>
46
47
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
54
55 //local cursor width/height in px, should be an odd number
56 const int cursor_size = 7;
57
58 VncView::VncView(QWidget *parent, const KUrl &url, RemoteView::Quality quality)
59         : RemoteView(parent),
60         m_initDone(false),
61         m_buttonMask(0),
62         cursor_x(0),
63         cursor_y(0),
64         m_repaint(false),
65         m_quitFlag(false),
66         m_firstPasswordTry(true),
67         m_dontSendClipboard(false),
68         m_horizontalFactor(1.0),
69         m_verticalFactor(1.0),
70         m_forceLocalCursor(false),
71         force_full_repaint(false),
72         quality(quality)
73 {
74     m_url = url;
75     m_host = url.host();
76     m_port = url.port();
77
78     connect(&vncThread, SIGNAL(imageUpdated(int, int, int, int)), this, SLOT(updateImage(int, int, int, int)), Qt::BlockingQueuedConnection);
79     connect(&vncThread, SIGNAL(gotCut(const QString&)), this, SLOT(setCut(const QString&)), Qt::BlockingQueuedConnection);
80     connect(&vncThread, SIGNAL(passwordRequest()), this, SLOT(requestPassword()), Qt::BlockingQueuedConnection);
81     connect(&vncThread, SIGNAL(outputErrorMessage(QString)), this, SLOT(outputErrorMessage(QString)));
82
83     m_clipboard = QApplication::clipboard();
84     connect(m_clipboard, SIGNAL(selectionChanged()), this, SLOT(clipboardSelectionChanged()));
85     connect(m_clipboard, SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged()));
86
87     reloadSettings();
88 }
89
90 VncView::~VncView()
91 {
92     unpressModifiers();
93
94     // Disconnect all signals so that we don't get any more callbacks from the client thread
95     vncThread.disconnect();
96
97     startQuitting();
98 }
99
100 void VncView::forceFullRepaint()
101 {
102         force_full_repaint = true;
103         repaint();
104 }
105
106 bool VncView::eventFilter(QObject *obj, QEvent *event)
107 {
108     if (m_viewOnly) {
109         if (event->type() == QEvent::KeyPress ||
110                 event->type() == QEvent::KeyRelease ||
111                 event->type() == QEvent::MouseButtonDblClick ||
112                 event->type() == QEvent::MouseButtonPress ||
113                 event->type() == QEvent::MouseButtonRelease ||
114                 event->type() == QEvent::Wheel ||
115                 event->type() == QEvent::MouseMove)
116             return true;
117     }
118     return RemoteView::eventFilter(obj, event);
119 }
120
121 QSize VncView::framebufferSize()
122 {
123     return m_frame.size();
124 }
125
126 QSize VncView::sizeHint() const
127 {
128     return size();
129 }
130
131 QSize VncView::minimumSizeHint() const
132 {
133     return size();
134 }
135
136 void VncView::scaleResize(int w, int h)
137 {
138     RemoteView::scaleResize(w, h);
139     
140     kDebug(5011) << "scaleResize(): " <<w << h;
141     if (m_scale) {
142         m_verticalFactor = (qreal) h / m_frame.height();
143         m_horizontalFactor = (qreal) w / m_frame.width();
144
145         m_verticalFactor = m_horizontalFactor = qMin(m_verticalFactor, m_horizontalFactor);
146
147         const qreal newW = m_frame.width() * m_horizontalFactor;
148         const qreal newH = m_frame.height() * m_verticalFactor;
149         /*
150         setMaximumSize(newW, newH); //This is a hack to force Qt to center the view in the scroll area
151         //also causes the widget's size to flicker
152         */
153         resize(newW, newH);
154     } 
155 }
156
157
158 void VncView::startQuitting()
159 {
160     kDebug(5011) << "about to quit";
161
162     const bool connected = status() == RemoteView::Connected;
163
164     setStatus(Disconnecting);
165
166     m_quitFlag = true;
167
168     if (connected) {
169                 kDebug(5011) << "stopping vncThread";
170         vncThread.stop();
171     }
172
173     vncThread.quit();
174
175     const bool quitSuccess = vncThread.wait(700);
176
177     kDebug(5011) << "startQuitting(): 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     setStatus(Authenticating);
220
221     if (!m_url.password().isNull()) {
222         vncThread.setPassword(m_url.password());
223         return;
224     }
225
226         QSettings settings;
227         settings.beginGroup("hosts");
228         QString password = settings.value(QString("%1/password").arg(m_host), "").toString();
229         //check for saved password
230         if(m_firstPasswordTry and !password.isEmpty()) {
231                 kDebug(5011) << "Trying saved password";
232                 m_firstPasswordTry = false;
233                 vncThread.setPassword(password);
234                 return;
235         }
236         m_firstPasswordTry = false;
237
238         //build dialog
239         QDialog dialog(this);
240         dialog.setWindowTitle(tr("Password required"));
241
242         QLineEdit passwordbox;
243         passwordbox.setEchoMode(QLineEdit::Password);
244         passwordbox.setText(password);
245         QCheckBox save_password(tr("Save Password"));
246         save_password.setChecked(!password.isEmpty()); //offer to overwrite saved password
247         QPushButton ok_button(tr("Done"));
248         ok_button.setMaximumWidth(100);
249         connect(&ok_button, SIGNAL(clicked()),
250                 &dialog, SLOT(accept()));
251
252         QHBoxLayout layout1;
253         QVBoxLayout layout2;
254         layout2.addWidget(&passwordbox);
255         layout2.addWidget(&save_password);
256         layout1.addLayout(&layout2);
257         layout1.addWidget(&ok_button);
258         dialog.setLayout(&layout1);
259
260         if(dialog.exec()) { //dialog accepted
261                 password = passwordbox.text();
262
263                 if(save_password.isChecked()) {
264                         kDebug(5011) << "Saving password for host '" << m_host << "'";
265
266                         settings.setValue(QString("%1/password").arg(m_host), password);
267                         settings.sync();
268                 }
269
270                 vncThread.setPassword(password);
271         } else {
272                 startQuitting();
273         }
274 }
275
276 void VncView::outputErrorMessage(const QString &message)
277 {
278     kDebug(5011) << message;
279
280     if (message == "INTERNAL:APPLE_VNC_COMPATIBILTY") {
281         setCursor(localDotCursor());
282         m_forceLocalCursor = true;
283         return;
284     }
285
286     startQuitting();
287
288     emit errorMessage(i18n("VNC failure"), message);
289 }
290
291 void VncView::updateImage(int x, int y, int w, int h)
292 {
293         if(!QApplication::focusWidget()) { //no focus, we're probably minimized
294                 return;
295         }
296      //kDebug(5011) << "got update" << width() << height();
297
298      /*
299      static unsigned int frames = 0;
300      static unsigned int updates = 0;
301      static QTime time = QTime::currentTime();
302      updates++;
303      if(updates % 100 == 0)
304              kDebug(5011) << "u/s: " << updates/double(time.elapsed()) * 1000.0;
305 if(x == 0 and y == 0) {
306         frames++;
307      if(frames % 100 == 0)
308              kDebug(5011) << "f/s: " << frames/double(time.elapsed()) * 1000.0;
309 }
310 */
311
312     m_x = x;
313     m_y = y;
314     m_w = w;
315     m_h = h;
316
317
318         //with scaled view, artefacts occur because of rounding errors
319         //we'll try to only update chunks of screen space that correspond to integer pixel sizes in m_frame
320         //put this into paintEvent
321         /*
322         int frame_x = x/m_horizontalFactor;
323         int frame_w = w/m_horizontalFactor;
324         int frame_y = y/m_verticalFactor;
325         int frame_h = h/m_verticalFactor;
326         
327         m_x = frame_x*m_horizontalFactor;
328         m_y = frame_y*m_verticalFactor;
329
330         m_w = (frame_w+2)*m_horizontalFactor;
331         m_h = (frame_h+2)*m_verticalFactor;
332         kDebug(5011)<< "update);
333         */
334
335
336     if (m_horizontalFactor != 1.0 || m_verticalFactor != 1.0) {
337         // If the view is scaled, grow the update rectangle to avoid artifacts
338         int x_extrapixels = 1.0/m_horizontalFactor + 1;
339         int y_extrapixels = 1.0/m_verticalFactor + 1;
340
341         m_x-=x_extrapixels;
342         m_y-=y_extrapixels;
343         m_w+=2*x_extrapixels;
344         m_h+=2*y_extrapixels;
345     }
346
347     m_frame = vncThread.image();
348
349     if (!m_initDone) {
350         setAttribute(Qt::WA_StaticContents);
351         setAttribute(Qt::WA_OpaquePaintEvent);
352         installEventFilter(this);
353
354         setCursor(((m_dotCursorState == CursorOn) || m_forceLocalCursor) ? localDotCursor() : Qt::BlankCursor);
355
356         setMouseTracking(true); // get mouse events even when there is no mousebutton pressed
357         setFocusPolicy(Qt::WheelFocus);
358         setStatus(Connected);
359 //         emit framebufferSizeChanged(m_frame.width(), m_frame.height());
360         emit connected();
361         
362         if (m_scale) {
363             if (parentWidget())
364                 scaleResize(parentWidget()->width(), parentWidget()->height());
365             else
366                 scaleResize(width(), height());
367         } 
368         
369         m_initDone = true;
370
371     }
372
373         static QSize old_frame_size = QSize();
374     if ((y == 0 && x == 0) && (m_frame.size() != old_frame_size)) {
375             old_frame_size = m_frame.size();
376         kDebug(5011) << "Updating framebuffer size";
377         if (m_scale) {
378             //setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
379             if (parentWidget())
380                 scaleResize(parentWidget()->width(), parentWidget()->height());
381         } else {
382             kDebug(5011) << "Resizing: " << m_frame.width() << m_frame.height();
383             resize(m_frame.width(), m_frame.height());
384             //setMaximumSize(m_frame.width(), m_frame.height()); //This is a hack to force Qt to center the view in the scroll area
385             //setMinimumSize(m_frame.width(), m_frame.height());
386         }
387         emit framebufferSizeChanged(m_frame.width(), m_frame.height());
388     }
389
390     m_repaint = true;
391     repaint(qRound(m_x * m_horizontalFactor), qRound(m_y * m_verticalFactor), qRound(m_w * m_horizontalFactor), qRound(m_h * m_verticalFactor));
392     m_repaint = false;
393 }
394
395 void VncView::setViewOnly(bool viewOnly)
396 {
397     RemoteView::setViewOnly(viewOnly);
398
399     m_dontSendClipboard = viewOnly;
400
401     if (viewOnly)
402         setCursor(Qt::ArrowCursor);
403     else
404         setCursor(m_dotCursorState == CursorOn ? localDotCursor() : Qt::BlankCursor);
405 }
406
407 void VncView::showDotCursor(DotCursorState state)
408 {
409     RemoteView::showDotCursor(state);
410
411     setCursor(state == CursorOn ? localDotCursor() : Qt::BlankCursor);
412 }
413
414 void VncView::enableScaling(bool scale)
415 {
416     RemoteView::enableScaling(scale);
417 }
418
419 //level should be in [0, 100]
420 void VncView::setZoomLevel(int level)
421 {
422         Q_ASSERT(parentWidget() != 0);
423
424
425         double factor; //actual magnification
426         if(level > 95) {
427                 factor = 2.0;
428         } else if(level > 90) {
429                 factor = 1.0;
430         } else {
431                 const double min_horiz_factor = double(parentWidget()->width())/m_frame.width();
432                 const double min_vert_factor = double(parentWidget()->height())/m_frame.height();
433                 const double fit_screen_factor = qMin(min_horiz_factor, min_vert_factor);
434
435                 //level=900 => factor=1.0, level=0 => factor=fit_screen_factor
436                 factor = (level)/90.0*(1.0 - fit_screen_factor) + fit_screen_factor;
437         }
438
439         if(factor < 0) {
440                 //remote display smaller than local?
441                 kDebug(5011) << "remote display smaller than local?";
442                 factor = 1.0;
443         }
444
445         m_verticalFactor = m_horizontalFactor = factor;
446         resize(m_frame.width()*factor, m_frame.height()*factor);
447 }
448
449 void VncView::setCut(const QString &text)
450 {
451     m_dontSendClipboard = true;
452     m_clipboard->setText(text, QClipboard::Clipboard);
453     m_clipboard->setText(text, QClipboard::Selection);
454     m_dontSendClipboard = false;
455 }
456
457 void VncView::paintEvent(QPaintEvent *event)
458 {
459      //kDebug(5011) << "paint event: x: " << m_x << ", y: " << m_y << ", w: " << m_w << ", h: " << m_h;
460     if (m_frame.isNull() || m_frame.format() == QImage::Format_Invalid) {
461         kDebug(5011) << "no valid image to paint";
462         RemoteView::paintEvent(event);
463         return;
464     }
465
466     event->accept();
467
468     QPainter painter(this);
469
470         Qt::TransformationMode transformation_mode = Qt::SmoothTransformation;
471         if( m_horizontalFactor >= 1.0 )
472                 transformation_mode = Qt::FastTransformation;
473
474     if (m_repaint and !force_full_repaint) {
475 //         kDebug(5011) << "normal repaint";
476         painter.drawImage(QRect(qRound(m_x*m_horizontalFactor), qRound(m_y*m_verticalFactor),
477                                 qRound(m_w*m_horizontalFactor), qRound(m_h*m_verticalFactor)), 
478                           m_frame.copy(m_x, m_y, m_w, m_h).scaled(qRound(m_w*m_horizontalFactor), 
479                                                                   qRound(m_h*m_verticalFactor),
480                                                                   Qt::IgnoreAspectRatio, transformation_mode));
481     } else {
482          //kDebug(5011) << "resize repaint";
483         QRect rect = event->rect();
484         if (!force_full_repaint and (rect.width() != width() || rect.height() != height())) {
485           //   kDebug(5011) << "Partial repaint";
486             const int sx = rect.x()/m_horizontalFactor;
487             const int sy = rect.y()/m_verticalFactor;
488             const int sw = rect.width()/m_horizontalFactor;
489             const int sh = rect.height()/m_verticalFactor;
490             painter.drawImage(rect, 
491                               m_frame.copy(sx, sy, sw, sh).scaled(rect.width(), rect.height(),
492                                                                   Qt::IgnoreAspectRatio, transformation_mode));
493         } else {
494              kDebug(5011) << "Full repaint" << width() << height() << m_frame.width() << m_frame.height();
495             painter.drawImage(QRect(0, 0, width(), height()), 
496                               m_frame.scaled(m_frame.width() * m_horizontalFactor, m_frame.height() * m_verticalFactor,
497                                              Qt::IgnoreAspectRatio, transformation_mode));
498                         force_full_repaint = false;
499         }
500     }
501
502         //draw local cursor ourselves, normal mouse pointer doesn't deal with scrolling
503         if((m_dotCursorState == CursorOn) || m_forceLocalCursor) {
504 #if QT_VERSION >= 0x040500
505                 painter.setCompositionMode(QPainter::RasterOp_SourceXorDestination);
506 #endif
507                 //rectangle size includes 1px pen width
508                 painter.drawRect(cursor_x*m_horizontalFactor - cursor_size/2, cursor_y*m_verticalFactor - cursor_size/2, cursor_size-1, cursor_size-1);
509         }
510
511     RemoteView::paintEvent(event);
512 }
513
514 void VncView::resizeEvent(QResizeEvent *event)
515 {
516     RemoteView::resizeEvent(event);
517         /*
518     scaleResize(event->size().width(), event->size().height());
519     forceFullRepaint();
520         */
521 }
522
523 bool VncView::event(QEvent *event)
524 {
525     switch (event->type()) {
526     case QEvent::KeyPress:
527     case QEvent::KeyRelease:
528 //         kDebug(5011) << "keyEvent";
529         keyEventHandler(static_cast<QKeyEvent*>(event));
530         return true;
531         break;
532     case QEvent::MouseButtonDblClick:
533     case QEvent::MouseButtonPress:
534     case QEvent::MouseButtonRelease:
535     case QEvent::MouseMove:
536 //         kDebug(5011) << "mouseEvent";
537         mouseEventHandler(static_cast<QMouseEvent*>(event));
538         return true;
539         break;
540     case QEvent::Wheel:
541 //         kDebug(5011) << "wheelEvent";
542         wheelEventHandler(static_cast<QWheelEvent*>(event));
543         return true;
544         break;
545     case QEvent::WindowActivate: //input panel may have been closed, prevent IM from interfering with hardware keyboard
546         setAttribute(Qt::WA_InputMethodEnabled, false);
547         //fall through
548     default:
549         return RemoteView::event(event);
550     }
551 }
552
553 //call with e == 0 to flush held events
554 void VncView::mouseEventHandler(QMouseEvent *e)
555 {
556         static bool tap_detected = false;
557         static bool double_tap_detected = false;
558         static bool tap_drag_detected = false;
559         static QTime press_time;
560         static QTime up_time; //used for double clicks/tap&drag, for time after first tap
561
562         const int TAP_PRESS_TIME = 180;
563         const int DOUBLE_TAP_UP_TIME = 500;
564
565         if(!e) { //flush held taps
566                 if(tap_detected) {
567                         m_buttonMask |= 0x01;
568                         vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
569                         m_buttonMask &= 0xfe;
570                         vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
571                         tap_detected = false;
572                 } else if(double_tap_detected and press_time.elapsed() > TAP_PRESS_TIME) { //got tap + another press -> tap & drag
573                         m_buttonMask |= 0x01;
574                         vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
575                         double_tap_detected = false;
576                         tap_drag_detected = true;
577                 }
578                         
579                 return;
580         }
581
582         if(e->x() < 0 or e->y() < 0) { //QScrollArea tends to send invalid events sometimes...
583                 e->ignore();
584                 return;
585         }
586
587         cursor_x = qRound(e->x()/m_horizontalFactor);
588         cursor_y = qRound(e->y()/m_verticalFactor);
589         vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask); // plain move event
590
591         if(!disable_tapping and e->button() == Qt::LeftButton) { //implement touchpad-like input for left button
592                 if(e->type() == QEvent::MouseButtonPress or e->type() == QEvent::MouseButtonDblClick) {
593                         press_time.start();
594                         if(tap_detected and up_time.elapsed() < DOUBLE_TAP_UP_TIME) {
595                                 tap_detected = false;
596                                 double_tap_detected = true;
597
598                                 QTimer::singleShot(TAP_PRESS_TIME, this, SLOT(mouseEventHandler()));
599                         }
600                 } else if(e->type() == QEvent::MouseButtonRelease) {
601                         if(tap_drag_detected) {
602                                 m_buttonMask &= 0xfe;
603                                 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
604                                 tap_drag_detected = false;
605                         } else if(double_tap_detected) { //double click
606                                 double_tap_detected = false;
607
608                                 m_buttonMask |= 0x01;
609                                 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
610                                 m_buttonMask &= 0xfe;
611                                 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
612                                 m_buttonMask |= 0x01;
613                                 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
614                                 m_buttonMask &= 0xfe;
615                                 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
616                         } else if(press_time.elapsed() < TAP_PRESS_TIME) { //tap
617                                 up_time.start();
618                                 tap_detected = true;
619                                 QTimer::singleShot(DOUBLE_TAP_UP_TIME, this, SLOT(mouseEventHandler()));
620                         }
621
622                 }
623         } else { //middle or right button, send directly
624                 if ((e->type() == QEvent::MouseButtonPress)) {
625                     if (e->button() & Qt::MidButton)
626                         m_buttonMask |= 0x02;
627                     if (e->button() & Qt::RightButton)
628                         m_buttonMask |= 0x04;
629                 } else if (e->type() == QEvent::MouseButtonRelease) {
630                     if (e->button() & Qt::MidButton)
631                         m_buttonMask &= 0xfd;
632                     if (e->button() & Qt::RightButton)
633                         m_buttonMask &= 0xfb;
634                 }
635                 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
636         }
637
638         //prevent local cursor artifacts
639         static int old_cursor_x = cursor_x;
640         static int old_cursor_y = cursor_y;
641         if(((m_dotCursorState == CursorOn) || m_forceLocalCursor)
642         and (cursor_x != old_cursor_x or cursor_y != old_cursor_y)) {
643                 //clear last position
644                 repaint(old_cursor_x*m_horizontalFactor - cursor_size/2, old_cursor_y*m_verticalFactor - cursor_size/2, cursor_size, cursor_size);
645                 //and refresh new one
646                 repaint(cursor_x*m_horizontalFactor - cursor_size/2, cursor_y*m_verticalFactor - cursor_size/2, cursor_size, cursor_size);
647
648                 old_cursor_x = cursor_x; old_cursor_y = cursor_y;
649         }
650 }
651
652 void VncView::wheelEventHandler(QWheelEvent *event)
653 {
654     int eb = 0;
655     if (event->delta() < 0)
656         eb |= 0x10;
657     else
658         eb |= 0x8;
659
660     const int x = qRound(event->x() / m_horizontalFactor);
661     const int y = qRound(event->y() / m_verticalFactor);
662
663     vncThread.mouseEvent(x, y, eb | m_buttonMask);
664     vncThread.mouseEvent(x, y, m_buttonMask);
665 }
666
667 void VncView::keyEventHandler(QKeyEvent *e)
668 {
669     // strip away autorepeating KeyRelease; see bug #206598
670     if (e->isAutoRepeat() && (e->type() == QEvent::KeyRelease)) {
671         return;
672     }
673
674 // parts of this code are based on http://italc.sourcearchive.com/documentation/1.0.9.1/vncview_8cpp-source.html
675     rfbKeySym k = e->nativeVirtualKey();
676
677     // we do not handle Key_Backtab separately as the Shift-modifier
678     // is already enabled
679     if (e->key() == Qt::Key_Backtab) {
680         k = XK_Tab;
681     }
682
683     const bool pressed = (e->type() == QEvent::KeyPress);
684
685 #ifdef Q_WS_MAEMO_5
686     //don't send ISO_Level3_Shift (would break things like Win+0-9)
687     //also enable IM so symbol key works
688     if(k == 0xfe03) {
689             setAttribute(Qt::WA_InputMethodEnabled, pressed);
690             e->ignore();
691             return;
692     }
693 #endif
694
695     // handle modifiers
696     if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L) {
697         if (pressed) {
698             m_mods[k] = true;
699         } else if (m_mods.contains(k)) {
700             m_mods.remove(k);
701         } else {
702             unpressModifiers();
703         }
704     }
705
706
707         int current_zoom = -1;
708         if(e->key() == Qt::Key_F8)
709                 current_zoom = left_zoom;
710         else if(e->key() == Qt::Key_F7)
711                 current_zoom = right_zoom;
712         else if (k) {
713         //      kDebug(5011) << "got '" << e->text() << "'.";
714                 vncThread.keyEvent(k, pressed);
715         } else {
716                 kDebug(5011) << "nativeVirtualKey() for '" << e->text() << "' failed.";
717                 return;
718         }       
719         
720         if(current_zoom == -1)
721                 return;
722
723         //handle zoom buttons
724         if(current_zoom == 0) { //left click
725                 if(pressed)
726                         m_buttonMask |= 0x01;
727                 else
728                         m_buttonMask &= 0xfe;
729                 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
730         } else if(current_zoom == 1) { //right click
731                 if(pressed)
732                         m_buttonMask |= 0x04;
733                 else
734                         m_buttonMask &= 0xfb;
735                 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
736         } else if(current_zoom == 2) { //middle click
737                 if(pressed)
738                         m_buttonMask |= 0x02;
739                 else
740                         m_buttonMask &= 0xfd;
741                 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
742         } else if(current_zoom == 3 and pressed) { //wheel up
743                 int eb = 0x8;
744                 vncThread.mouseEvent(cursor_x, cursor_y, eb | m_buttonMask);
745                 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
746         } else if(current_zoom == 4 and pressed) { //wheel down
747                 int eb = 0x10;
748                 vncThread.mouseEvent(cursor_x, cursor_y, eb | m_buttonMask);
749                 vncThread.mouseEvent(cursor_x, cursor_y, m_buttonMask);
750         } else if(current_zoom == 5) { //page up
751                 vncThread.keyEvent(0xff55, pressed);
752         } else if(current_zoom == 6) { //page down
753                 vncThread.keyEvent(0xff56, pressed);
754         }
755 }
756
757 void VncView::unpressModifiers()
758 {
759     const QList<unsigned int> keys = m_mods.keys();
760     QList<unsigned int>::const_iterator it = keys.constBegin();
761     while (it != keys.end()) {
762         vncThread.keyEvent(*it, false);
763         it++;
764     }
765     m_mods.clear();
766 }
767
768 void VncView::clipboardSelectionChanged()
769 {
770     if (m_status != Connected)
771         return;
772
773     if (m_clipboard->ownsSelection() || m_dontSendClipboard)
774         return;
775
776     const QString text = m_clipboard->text(QClipboard::Selection);
777
778     vncThread.clientCut(text);
779 }
780
781 void VncView::clipboardDataChanged()
782 {
783     if (m_status != Connected)
784         return;
785
786     if (m_clipboard->ownsClipboard() || m_dontSendClipboard)
787         return;
788
789     const QString text = m_clipboard->text(QClipboard::Clipboard);
790
791     vncThread.clientCut(text);
792 }
793
794 //fake key events
795 void VncView::sendKey(Qt::Key key)
796 {
797         //convert Qt::Key into x11 keysym
798         int k = 0;
799         switch(key) {
800         case Qt::Key_Escape:
801                 k = 0xff1b;
802                 break;
803         case Qt::Key_Tab:
804                 k = 0xff09;
805                 break;
806         case Qt::Key_PageUp:
807                 k = 0xff55;
808                 break;
809         case Qt::Key_PageDown:
810                 k = 0xff56;
811                 break;
812         case Qt::Key_Return:
813                 k = 0xff0d;
814                 break;
815         case Qt::Key_Insert:
816                 k = 0xff63;
817                 break;
818         case Qt::Key_Delete:
819                 k = 0xffff;
820                 break;
821         case Qt::Key_Home:
822                 k = 0xff50;
823                 break;
824         case Qt::Key_End:
825                 k = 0xff57;
826                 break;
827         case Qt::Key_Backspace:
828                 k = 0xff08;
829                 break;
830         case Qt::Key_F1:
831         case Qt::Key_F2:
832         case Qt::Key_F3:
833         case Qt::Key_F4:
834         case Qt::Key_F5:
835         case Qt::Key_F6:
836         case Qt::Key_F7:
837         case Qt::Key_F8:
838         case Qt::Key_F9:
839         case Qt::Key_F10:
840         case Qt::Key_F11:
841         case Qt::Key_F12:
842                 k = 0xffbe + int(key - Qt::Key_F1);
843                 break;
844         case Qt::Key_Pause:
845                 k = 0xff13;
846                 break;
847         case Qt::Key_Print:
848                 k = 0xff61;
849                 break;
850         case Qt::Key_Menu:
851                 k = 0xff67;
852                 break;
853         case Qt::Key_Meta:
854         case Qt::MetaModifier:
855                 k = XK_Super_L;
856                 break;
857         case Qt::Key_Alt:
858         case Qt::AltModifier:
859                 k = XK_Alt_L;
860                 break;
861         case Qt::Key_Control:
862         case Qt::ControlModifier:
863                 k = XK_Control_L;
864                 break;
865         default:
866                 kDebug(5011) << "sendKey(): Unhandled Qt::Key value " << key;
867                 return;
868         }
869
870         if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L || k == XK_Super_L) {
871                 if (m_mods.contains(k)) { //release
872                         m_mods.remove(k);
873                         vncThread.keyEvent(k, false);
874                 } else { //press
875                         m_mods[k] = true;
876                         vncThread.keyEvent(k, true);
877                 }
878         } else { //normal key
879                 vncThread.keyEvent(k, true);
880                 vncThread.keyEvent(k, false);
881         }
882 }
883
884 void VncView::sendKeySequence(QKeySequence keys)
885 {
886         Q_ASSERT(keys.count() <= 1); //we can only handle a single combination
887
888         //to get at individual key presses, we split 'keys' into its components
889         QList<int> key_list;
890         for(int i = 0; ; i++) {
891                 QString k = keys.toString().section('+', i, i);
892                 if(k.isEmpty())
893                         break;
894                 //kDebug(5011) << "found key: " << k;
895                 if(k == "Alt") {
896                         key_list.append(Qt::Key_Alt);
897                 } else if(k == "Ctrl") {
898                         key_list.append(Qt::Key_Control);
899                 } else if(k == "Meta") {
900                         key_list.append(Qt::Key_Meta);
901                 } else {
902                         key_list.append(QKeySequence(k)[0]);
903                 }
904         }
905         
906         for(int i = 0; i < key_list.count(); i++)
907                 sendKey(Qt::Key(key_list.at(i)));
908
909         //release modifiers (everything before final key)
910         for(int i = key_list.count()-2; i >= 0; i--)
911                 sendKey(Qt::Key(key_list.at(i)));
912 }
913
914 void VncView::reloadSettings()
915 {
916         QSettings settings;
917         left_zoom = settings.value("left_zoom", 0).toInt();
918         right_zoom = settings.value("right_zoom", 1).toInt();
919         disable_tapping = settings.value("disable_tapping", false).toBool();
920
921         bool always_show_local_cursor = settings.value("always_show_local_cursor", false).toBool();
922         if(always_show_local_cursor)
923                 showDotCursor(CursorOn);
924
925         enableScaling(true);
926 }
927
928 //convert commitString into keyevents
929 void VncView::inputMethodEvent(QInputMethodEvent *event)
930 {
931         //TODO handle replacements
932         //NOTE for the return key to work Qt needs to enable multiline input, which only works for Q(Plain)TextEdit
933
934         //kDebug(5011) << event->commitString() << "|" << event->preeditString() << "|" << event->replacementLength() << "|" << event->replacementStart();
935         QString letters = event->commitString();
936         for(int i = 0; i < letters.length(); i++) {
937                 char k = letters.at(i).toLatin1(); //works with all 'normal' keys, not umlauts.
938                 if(!k) {
939                         kDebug(5011) << "unhandled key";
940                         continue;
941                 }
942                 vncThread.keyEvent(k, true);
943                 vncThread.keyEvent(k, false);
944         }
945 }
946
947
948 #include "moc_vncview.cpp"