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