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