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