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