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