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