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