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