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