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