78f09714ff0ed3ee1c61f77b4ecfbaf6ae5456ce
[presencevnc] / src / vncclientthread.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 "vncclientthread.h"
25
26 #include <QMutexLocker>
27 #include <QTimer>
28
29 static QString outputErrorMessageString;
30
31 rfbBool VncClientThread::newclient(rfbClient *cl)
32 {
33     VncClientThread *t = (VncClientThread*)rfbClientGetClientData(cl, 0);
34     Q_ASSERT(t);
35
36     const int width = cl->width, height = cl->height, depth = cl->format.bitsPerPixel;
37     const int size = width * height * (depth / 8);
38     if (t->frameBuffer)
39         delete [] t->frameBuffer; // do not leak if we get a new framebuffer size
40     t->frameBuffer = new uint8_t[size];
41     cl->frameBuffer = t->frameBuffer;
42     memset(cl->frameBuffer, '\0', size);
43     cl->format.bitsPerPixel = 32;
44     cl->format.redShift = 16;
45     cl->format.greenShift = 8;
46     cl->format.blueShift = 0;
47     cl->format.redMax = 0xff;
48     cl->format.greenMax = 0xff;
49     cl->format.blueMax = 0xff;
50
51     switch (t->quality()) {
52     case RemoteView::High:
53         cl->appData.useBGR233 = 0;
54         cl->appData.encodingsString = "copyrect hextile raw";
55         cl->appData.compressLevel = 0;
56         cl->appData.qualityLevel = 9;
57         break;
58     case RemoteView::Medium:
59         cl->appData.useBGR233 = 0;
60         cl->appData.encodingsString = "tight zrle ultra copyrect hextile zlib corre rre raw";
61         cl->appData.compressLevel = 5;
62         cl->appData.qualityLevel = 7;
63         break;
64     case RemoteView::Low:
65     case RemoteView::Unknown:
66     default:
67         cl->appData.useBGR233 = 1;
68         cl->appData.encodingsString = "tight zrle ultra copyrect hextile zlib corre rre raw";
69         cl->appData.compressLevel = 9;
70         cl->appData.qualityLevel = 1;
71     }
72
73     SetFormatAndEncodings(cl);
74
75     return true;
76 }
77
78 void VncClientThread::updatefb(rfbClient* cl, int x, int y, int w, int h)
79 {
80     //kDebug(5011) << "updated client: x: " << x << ", y: " << y << ", w: " << w << ", h: " << h;
81
82     const int width = cl->width, height = cl->height;
83
84     const QImage img(cl->frameBuffer, width, height, QImage::Format_RGB32);
85
86     if (img.isNull()) {
87         kDebug(5011) << "image not loaded";
88     }
89
90     VncClientThread *t = (VncClientThread*)rfbClientGetClientData(cl, 0);
91     Q_ASSERT(t);
92
93     t->setImage(img);
94
95     t->emitUpdated(x, y, w, h);
96 }
97
98 void VncClientThread::cuttext(rfbClient* cl, const char *text, int textlen)
99 {
100     const QString cutText = QString::fromUtf8(text, textlen);
101     kDebug(5011) << "cuttext: " << cutText;
102
103     if (!cutText.isEmpty()) {
104         VncClientThread *t = (VncClientThread*)rfbClientGetClientData(cl, 0);
105         Q_ASSERT(t);
106
107         t->emitGotCut(cutText);
108     }
109 }
110
111 char *VncClientThread::passwdHandler(rfbClient *cl)
112 {
113     kDebug(5011) << "password request" << kBacktrace();
114
115     VncClientThread *t = (VncClientThread*)rfbClientGetClientData(cl, 0);
116     Q_ASSERT(t);
117
118     t->m_passwordError = true;
119     t->passwordRequest();
120
121     return strdup(t->password().toLocal8Bit());
122 }
123
124 void VncClientThread::setPassword(const QString &password)
125 {
126     if(password.isNull()) //cancelled, don't retry
127         m_passwordError = false;
128
129     m_password = password;
130 }
131
132 void VncClientThread::outputHandler(const char *format, ...)
133 {
134     va_list args;
135     va_start(args, format);
136
137     QString message;
138     message.vsprintf(format, args);
139
140     va_end(args);
141
142     message = message.trimmed();
143
144     kDebug(5011) << message;
145
146     if ((message.contains("Couldn't convert ")) ||
147             (message.contains("Unable to connect to VNC server")))
148         outputErrorMessageString = i18n("Server not found.");
149
150     if ((message.contains("VNC connection failed: Authentication failed, too many tries")) ||
151             (message.contains("VNC connection failed: Too many authentication failures")))
152         outputErrorMessageString = i18n("VNC authentication failed because of too many authentication tries.");
153
154     if (message.contains("VNC connection failed: Authentication failed"))
155         outputErrorMessageString = i18n("VNC authentication failed.");
156
157     if (message.contains("VNC server closed connection"))
158         outputErrorMessageString = i18n("VNC server closed connection.");
159
160     // internal messages, not displayed to user
161     if (message.contains("VNC server supports protocol version 3.889")) // see http://bugs.kde.org/162640
162         outputErrorMessageString = "INTERNAL:APPLE_VNC_COMPATIBILTY";
163 }
164
165 VncClientThread::VncClientThread(QObject *parent)
166     : QThread(parent)
167     , frameBuffer(0)
168 {
169     QMutexLocker locker(&mutex);
170     m_stopped = false;
171
172     QTimer *outputErrorMessagesCheckTimer = new QTimer(this);
173     outputErrorMessagesCheckTimer->setInterval(500);
174     connect(outputErrorMessagesCheckTimer, SIGNAL(timeout()), this, SLOT(checkOutputErrorMessage()));
175     outputErrorMessagesCheckTimer->start();
176 }
177
178 VncClientThread::~VncClientThread()
179 {
180     stop();
181
182     const bool quitSuccess = wait(1000);
183
184     if(!quitSuccess)
185         kDebug(5011) << "~VncClientThread(): Quit failed";
186
187     delete [] frameBuffer;
188     //cl is free()d when event loop exits.
189 }
190
191 void VncClientThread::checkOutputErrorMessage()
192 {
193     if (!outputErrorMessageString.isEmpty()) {
194         kDebug(5011) << outputErrorMessageString;
195         QString errorMessage = outputErrorMessageString;
196         outputErrorMessageString.clear();
197         // show authentication failure error only after the 3rd unsuccessful try
198         if ((errorMessage != i18n("VNC authentication failed.")) || m_passwordError)
199             outputErrorMessage(errorMessage);
200     }
201 }
202
203 void VncClientThread::setHost(const QString &host)
204 {
205     QMutexLocker locker(&mutex);
206     m_host = host;
207 }
208
209 void VncClientThread::setPort(int port)
210 {
211     QMutexLocker locker(&mutex);
212     m_port = port;
213 }
214
215 void VncClientThread::setQuality(RemoteView::Quality quality)
216 {
217     m_quality = quality;
218 }
219
220 RemoteView::Quality VncClientThread::quality() const
221 {
222     return m_quality;
223 }
224
225 void VncClientThread::setImage(const QImage &img)
226 {
227     QMutexLocker locker(&mutex);
228     m_image = img;
229 }
230
231 const QImage VncClientThread::image(int x, int y, int w, int h)
232 {
233     QMutexLocker locker(&mutex);
234
235     if (w == 0) // full image requested
236         return m_image;
237     else
238         return m_image.copy(x, y, w, h);
239 }
240
241 void VncClientThread::emitUpdated(int x, int y, int w, int h)
242 {
243     emit imageUpdated(x, y, w, h);
244 }
245
246 void VncClientThread::emitGotCut(const QString &text)
247 {
248     emit gotCut(text);
249 }
250
251 void VncClientThread::stop()
252 {
253     if(m_stopped)
254         return;
255
256     //also abort listening for connections, should be safe without locking
257     if(listen_port)
258         cl->listenSpecified = false;
259
260     QMutexLocker locker(&mutex);
261     m_stopped = true;
262 }
263
264 void VncClientThread::run()
265 {
266     QMutexLocker locker(&mutex);
267
268     int passwd_failures = 0;
269     while (!m_stopped) { // try to connect as long as the server allows
270         m_passwordError = false;
271         outputErrorMessageString.clear(); //don't deliver error messages of old instances...
272
273         rfbClientLog = outputHandler;
274         rfbClientErr = outputHandler;
275         cl = rfbGetClient(8, 3, 4); // bitsPerSample, samplesPerPixel, bytesPerPixel
276         cl->MallocFrameBuffer = newclient;
277         cl->canHandleNewFBSize = true;
278         cl->GetPassword = passwdHandler;
279         cl->GotFrameBufferUpdate = updatefb;
280         cl->GotXCutText = cuttext;
281         rfbClientSetClientData(cl, 0, this);
282
283         cl->serverHost = strdup(m_host.toUtf8().constData());
284
285         if (m_port < 0 || !m_port) // port is invalid or empty...
286             m_port = 5900; // fallback: try an often used VNC port
287
288         if (m_port >= 0 && m_port < 100) // the user most likely used the short form (e.g. :1)
289             m_port += 5900;
290         cl->serverPort = m_port;
291
292         cl->listenSpecified = rfbBool(listen_port > 0);
293         cl->listenPort = listen_port;
294
295         kDebug(5011) << "--------------------- trying init ---------------------";
296
297         if (rfbInitClient(cl, 0, 0))
298             break;
299
300         //init failed...
301         if (m_passwordError) {
302             passwd_failures++;
303             if(passwd_failures < 3)
304                 continue; //that's ok, try again
305         }
306
307         //stop connecting
308         m_stopped = true;
309         return; //no cleanup necessary, cl was free()d by rfbInitClient()
310     }
311
312     locker.unlock();
313
314     // Main VNC event loop
315     while (!m_stopped) {
316         const int i = WaitForMessage(cl, 500);
317         if(m_stopped or i < 0)
318             break;
319
320         if (i)
321             if (!HandleRFBServerMessage(cl))
322                 break;
323
324         locker.relock();
325
326         while (!m_eventQueue.isEmpty()) {
327             ClientEvent* clientEvent = m_eventQueue.dequeue();
328             clientEvent->fire(cl);
329             delete clientEvent;
330         }
331
332         locker.unlock();
333     }
334
335     // Cleanup allocated resources
336     locker.relock();
337     rfbClientCleanup(cl);
338     m_stopped = true;
339 }
340
341 ClientEvent::~ClientEvent()
342 {
343 }
344
345 void PointerClientEvent::fire(rfbClient* cl)
346 {
347     SendPointerEvent(cl, m_x, m_y, m_buttonMask);
348 }
349
350 void KeyClientEvent::fire(rfbClient* cl)
351 {
352     SendKeyEvent(cl, m_key, m_pressed);
353 }
354
355 void ClientCutEvent::fire(rfbClient* cl)
356 {
357     SendClientCutText(cl, text.toUtf8().data(), text.size());
358 }
359
360 void VncClientThread::mouseEvent(int x, int y, int buttonMask)
361 {
362     QMutexLocker lock(&mutex);
363     if (m_stopped)
364         return;
365
366     m_eventQueue.enqueue(new PointerClientEvent(x, y, buttonMask));
367 }
368
369 void VncClientThread::keyEvent(int key, bool pressed)
370 {
371     QMutexLocker lock(&mutex);
372     if (m_stopped)
373         return;
374
375     m_eventQueue.enqueue(new KeyClientEvent(key, pressed));
376 }
377
378 void VncClientThread::clientCut(const QString &text)
379 {
380     QMutexLocker lock(&mutex);
381     if (m_stopped)
382         return;
383
384     m_eventQueue.enqueue(new ClientCutEvent(text));
385 }