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