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