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