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