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