imported project
[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;
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->passwordRequest();
119     t->m_passwordError = true;
120
121     return strdup(t->password().toLocal8Bit());
122 }
123
124 void VncClientThread::outputHandler(const char *format, ...)
125 {
126     va_list args;
127     va_start(args, format);
128
129     QString message;
130     message.vsprintf(format, args);
131
132     va_end(args);
133
134     message = message.trimmed();
135
136     kDebug(5011) << message;
137
138     if ((message.contains("Couldn't convert ")) ||
139             (message.contains("Unable to connect to VNC server")))
140         outputErrorMessageString = i18n("Server not found.");
141
142     if ((message.contains("VNC connection failed: Authentication failed, too many tries")) ||
143             (message.contains("VNC connection failed: Too many authentication failures")))
144         outputErrorMessageString = i18n("VNC authentication failed because of too many authentication tries.");
145
146     if (message.contains("VNC connection failed: Authentication failed"))
147         outputErrorMessageString = i18n("VNC authentication failed.");
148
149     if (message.contains("VNC server closed connection"))
150         outputErrorMessageString = i18n("VNC server closed connection.");
151
152     // internal messages, not displayed to user
153     if (message.contains("VNC server supports protocol version 3.889")) // see http://bugs.kde.org/162640
154         outputErrorMessageString = "INTERNAL:APPLE_VNC_COMPATIBILTY";
155 }
156
157 VncClientThread::VncClientThread(QObject *parent)
158         : QThread(parent)
159         , frameBuffer(0)
160 {
161     QMutexLocker locker(&mutex);
162     m_stopped = false;
163
164     QTimer *outputErrorMessagesCheckTimer = new QTimer(this);
165     outputErrorMessagesCheckTimer->setInterval(500);
166     connect(outputErrorMessagesCheckTimer, SIGNAL(timeout()), this, SLOT(checkOutputErrorMessage()));
167     outputErrorMessagesCheckTimer->start();
168 }
169
170 VncClientThread::~VncClientThread()
171 {
172     stop();
173
174     const bool quitSuccess = wait(500);
175
176     kDebug(5011) << "Quit VNC thread success:" << quitSuccess;
177     
178     delete [] frameBuffer;
179 }
180
181 void VncClientThread::checkOutputErrorMessage()
182 {
183     if (!outputErrorMessageString.isEmpty()) {
184         kDebug(5011) << outputErrorMessageString;
185         QString errorMessage = outputErrorMessageString;
186         outputErrorMessageString.clear();
187         // show authentication failure error only after the 3rd unsuccessful try
188         if ((errorMessage != i18n("VNC authentication failed.")) || m_passwordError)
189             outputErrorMessage(errorMessage);
190     }
191 }
192
193 void VncClientThread::setHost(const QString &host)
194 {
195     QMutexLocker locker(&mutex);
196     m_host = host;
197 }
198
199 void VncClientThread::setPort(int port)
200 {
201     QMutexLocker locker(&mutex);
202     m_port = port;
203 }
204
205 void VncClientThread::setQuality(RemoteView::Quality quality)
206 {
207     m_quality = quality;
208 }
209
210 RemoteView::Quality VncClientThread::quality() const
211 {
212     return m_quality;
213 }
214
215 void VncClientThread::setImage(const QImage &img)
216 {
217     QMutexLocker locker(&mutex);
218     m_image = img;
219 }
220
221 const QImage VncClientThread::image(int x, int y, int w, int h)
222 {
223     QMutexLocker locker(&mutex);
224
225     if (w == 0) // full image requested
226         return m_image;
227     else
228         return m_image.copy(x, y, w, h);
229 }
230
231 void VncClientThread::emitUpdated(int x, int y, int w, int h)
232 {
233     emit imageUpdated(x, y, w, h);
234 }
235
236 void VncClientThread::emitGotCut(const QString &text)
237 {
238     emit gotCut(text);
239 }
240
241 void VncClientThread::stop()
242 {
243     QMutexLocker locker(&mutex);
244     m_stopped = true;
245 }
246
247 void VncClientThread::run()
248 {
249     QMutexLocker locker(&mutex);
250
251     while (!m_stopped) { // try to connect as long as the server allows
252         m_passwordError = false;
253
254         rfbClientLog = outputHandler;
255         rfbClientErr = outputHandler;
256         cl = rfbGetClient(8, 3, 4);
257         cl->MallocFrameBuffer = newclient;
258         cl->canHandleNewFBSize = true;
259         cl->GetPassword = passwdHandler;
260         cl->GotFrameBufferUpdate = updatefb;
261         cl->GotXCutText = cuttext;
262         rfbClientSetClientData(cl, 0, this);
263
264         cl->serverHost = strdup(m_host.toUtf8().constData());
265
266         if (m_port < 0 || !m_port) // port is invalid or empty...
267             m_port = 5900; // fallback: try an often used VNC port
268
269         if (m_port >= 0 && m_port < 100) // the user most likely used the short form (e.g. :1)
270             m_port += 5900;
271         cl->serverPort = m_port;
272
273         kDebug(5011) << "--------------------- trying init ---------------------";
274
275         if (rfbInitClient(cl, 0, 0))
276             break;
277
278         if (m_passwordError)
279             continue;
280
281         return;
282     }
283
284     locker.unlock();
285
286     // Main VNC event loop
287     while (!m_stopped) {
288         const int i = WaitForMessage(cl, 500);
289         if (i < 0)
290             break;
291         if (i)
292             if (!HandleRFBServerMessage(cl))
293                 break;
294
295         locker.relock();
296
297         while (!m_eventQueue.isEmpty()) {
298             ClientEvent* clientEvent = m_eventQueue.dequeue();
299             clientEvent->fire(cl);
300             delete clientEvent;
301         }
302
303         locker.unlock();
304     }
305
306     // Cleanup allocated resources
307     locker.relock();
308     rfbClientCleanup(cl);
309     m_stopped = true;
310 }
311
312 ClientEvent::~ClientEvent()
313 {
314 }
315
316 void PointerClientEvent::fire(rfbClient* cl)
317 {
318     SendPointerEvent(cl, m_x, m_y, m_buttonMask);
319 }
320
321 void KeyClientEvent::fire(rfbClient* cl)
322 {
323     SendKeyEvent(cl, m_key, m_pressed);
324 }
325
326 void ClientCutEvent::fire(rfbClient* cl)
327 {
328     SendClientCutText(cl, text.toUtf8().data(), text.size());
329 }
330
331 void VncClientThread::mouseEvent(int x, int y, int buttonMask)
332 {
333     QMutexLocker lock(&mutex);
334     if (m_stopped)
335         return;
336
337     m_eventQueue.enqueue(new PointerClientEvent(x, y, buttonMask));
338 }
339
340 void VncClientThread::keyEvent(int key, bool pressed)
341 {
342     QMutexLocker lock(&mutex);
343     if (m_stopped)
344         return;
345
346     m_eventQueue.enqueue(new KeyClientEvent(key, pressed));
347 }
348
349 void VncClientThread::clientCut(const QString &text)
350 {
351     QMutexLocker lock(&mutex);
352     if (m_stopped)
353         return;
354
355     m_eventQueue.enqueue(new ClientCutEvent(text));
356 }
357
358 #include "moc_vncclientthread.cpp"