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