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