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