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