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