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