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