5fadc35085ca78423f3398aa9d60de1e428577e1
[staging/windowmanager.git] / AFBClient.cpp
1 #include "AFBClient.h"
2
3 #include <cassert>
4 #include <cctype>
5 #include <cerrno>
6 #include <cstdio>
7 #include <cstdlib>
8 #include <cstring>
9
10 #include <atomic>
11 #include <map>
12 #include <mutex>
13 #include <set>
14
15 #include <unistd.h>
16
17 #include <systemd/sd-event.h>
18
19 #include <json-c/json.h>
20
21 extern "C" {
22 #include <afb/afb-ws-client.h>
23 #include <afb/afb-wsj1.h>
24 }
25
26 #define UNUSED(x) (void)(x)
27
28 //       _                 ___                 _
29 //   ___| | __ _ ___ ___  |_ _|_ __ ___  _ __ | |
30 //  / __| |/ _` / __/ __|  | || '_ ` _ \| '_ \| |
31 // | (__| | (_| \__ \__ \  | || | | | | | |_) | |
32 //  \___|_|\__,_|___/___/ |___|_| |_| |_| .__/|_|
33 //                                      |_|
34 class AFBClient::Impl {
35     friend class AFBClient;
36
37     // This is the AFBClient interface impl
38     int init(int port, char const *token);
39     int dispatch();
40
41     // WM API
42     int requestSurface(const char *label);
43     int activateSurface(const char *label);
44     int deactivateSurface(const char *label);
45     int endDraw(const char *label);
46
47     void set_event_handler(enum EventType et,
48                            std::function<void(char const *label)> f);
49
50     Impl();
51     ~Impl();
52
53     struct afb_wsj1 *wsj1;
54     struct sd_event *loop;
55
56     std::set<std::string> labels;
57     std::map<EventType, handler_fun> handlers;
58
59 public:
60     void event(char const *et, char const *label);
61 };
62
63 namespace {
64
65 constexpr const int token_maxlen = 20;
66 constexpr const char *const wmAPI = "winman";
67
68 #ifdef NDEBUG
69 #define TRACE()
70 #define TRACEN(N)
71 #else
72 #define CONCAT_(X, Y) X##Y
73 #define CONCAT(X, Y) CONCAT_(X, Y)
74
75 #define TRACE() \
76     ScopeTrace __attribute__((unused)) CONCAT(trace_scope_, __LINE__)(__func__)
77 #define TRACEN(N) \
78     ScopeTrace __attribute__((unused)) CONCAT(named_trace_scope_, __LINE__)(#N)
79
80 struct ScopeTrace {
81     thread_local static int indent;
82     char const *f{};
83     ScopeTrace(char const *func) : f(func) {
84         fprintf(stderr, "%*s%s -->\n", 2 * indent++, "", this->f);
85     }
86     ~ScopeTrace() { fprintf(stderr, "%*s%s <--\n", 2 * --indent, "", this->f); }
87 };
88 thread_local int ScopeTrace::indent = 0;
89 #endif
90
91 /* called when wsj1 receives a method invocation */
92 void onCall(void *closure, const char *api, const char *verb,
93             struct afb_wsj1_msg *msg) {
94     TRACE();
95     UNUSED(closure);
96     UNUSED(verb);
97     UNUSED(api);
98     UNUSED(msg);
99 }
100
101 /* called when wsj1 receives an event */
102 void onEvent(void *closure, const char *event, afb_wsj1_msg *msg) {
103     TRACE();
104     reinterpret_cast<AFBClient::Impl *>(closure)->event(
105         event, json_object_get_string(
106                    json_object_object_get(afb_wsj1_msg_object_j(msg), "data")));
107 }
108
109 /* called when wsj1 hangsup */
110 void onHangup(void *closure, afb_wsj1 *wsj1) {
111     TRACE();
112     UNUSED(closure);
113     UNUSED(wsj1);
114     printf("ON-HANGUP\n");
115     fflush(stdout);
116     exit(0);
117 }
118
119 constexpr static struct afb_wsj1_itf itf = {
120     onHangup, onCall, onEvent,
121 };
122
123 // XXX: I am not sure this is the right thing to do though...
124 std::recursive_mutex dispatch_mutex;
125
126 void dispatch_internal(struct sd_event *loop) {
127     std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
128     TRACE();
129     sd_event_run(loop, -1);
130 }
131
132 /// object will be json_object_put
133 int api_call(struct sd_event *loop, struct afb_wsj1 *wsj1, const char *verb,
134              json_object *object,
135              std::function<void(bool, json_object *)> onReply) {
136     TRACE();
137
138     // We need to wrap the actual onReply call once in order to
139     // *look* like a normal functions pointer (std::functions<>
140     // with captures cannot convert to function pointers).
141     // Alternatively we could setup a local struct and use it as
142     // closure, but I think it is cleaner this way.
143     int call_rc = 0;
144     std::atomic<bool> returned;
145     returned.store(false, std::memory_order_relaxed);
146     std::function<void(bool, json_object *)> wrappedOnReply =
147         [&returned, &call_rc, &onReply](bool ok, json_object *j) {
148             TRACEN(wrappedOnReply);
149             call_rc = ok ? 0 : -EINVAL;
150             // We know it failed, but there may be an explanation in the
151             // json object.
152             {
153                 TRACEN(onReply);
154                 onReply(ok, j);
155             }
156             returned.store(true, std::memory_order_release);
157         };
158
159     // make the actual call, use wrappedOnReply as closure
160     int rc = afb_wsj1_call_j(
161         wsj1, wmAPI, verb, object,
162         [](void *closure, afb_wsj1_msg *msg) {
163             TRACEN(callClosure);
164             auto *onReply =
165                 reinterpret_cast<std::function<void(bool, json_object *)> *>(
166                     closure);
167             (*onReply)(!!afb_wsj1_msg_is_reply_ok(msg),
168                        afb_wsj1_msg_object_j(msg));
169         },
170         &wrappedOnReply);
171
172     if (rc < 0) {
173         fprintf(
174             stderr, "calling %s/%s(%s) failed: %m\n", wmAPI, verb,
175             json_object_to_json_string_ext(object, JSON_C_TO_STRING_PRETTY));
176         // Call the reply handler regardless with a NULL json_object*
177         onReply(false, nullptr);
178     } else {
179         // We need to dispatch until "returned" got set, this is necessary
180         // if events get triggered by the call (and would be dispatched before
181         // the actual call-reply).
182         while (!returned.load(std::memory_order_consume)) {
183             std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
184             if (!returned.load(std::memory_order_consume)) {
185                 dispatch_internal(loop);
186             }
187         }
188
189         // return the actual API call result
190         rc = call_rc;
191     }
192
193     return rc;
194 }
195
196 }  // namespace
197
198 //       _                 ___                 _   _                 _
199 //   ___| | __ _ ___ ___  |_ _|_ __ ___  _ __ | | (_)_ __ ___  _ __ | |
200 //  / __| |/ _` / __/ __|  | || '_ ` _ \| '_ \| | | | '_ ` _ \| '_ \| |
201 // | (__| | (_| \__ \__ \  | || | | | | | |_) | | | | | | | | | |_) | |
202 //  \___|_|\__,_|___/___/ |___|_| |_| |_| .__/|_| |_|_| |_| |_| .__/|_|
203 //                                      |_|                   |_|
204 AFBClient::Impl::Impl() : wsj1{}, loop{}, labels(), handlers() { TRACE(); }
205
206 AFBClient::Impl::~Impl() {
207     TRACE();
208     afb_wsj1_unref(wsj1);
209     sd_event_unref(loop);
210     loop = nullptr;
211 }
212
213 int AFBClient::Impl::init(int port, char const *token) {
214     TRACE();
215     char *uribuf = nullptr;
216     int rc = -1;
217
218     if (!token || strlen(token) > token_maxlen) {
219         fprintf(stderr, "Token is invalid\n");
220         rc = -EINVAL;
221         goto fail;
222     }
223
224     for (char const *p = token; *p; p++) {
225         if (!isalnum(*p)) {
226             fprintf(stderr, "Token is invalid\n");
227             rc = -EINVAL;
228             goto fail;
229         }
230     }
231
232     if (port < 1 && port > 0xffff) {
233         fprintf(stderr, "Port is invalid\n");
234         rc = -EINVAL;
235         goto fail;
236     }
237
238     /* get the default event loop */
239     rc = sd_event_default(&loop);
240     if (rc < 0) {
241         fprintf(stderr, "Connection to default event loop failed: %s\n",
242                 strerror(-rc));
243         goto fail;
244     }
245
246     asprintf(&uribuf, "ws://localhost:%d/api?token=%s", port, token);
247
248     /* connect the websocket wsj1 to the uri given by the first argument */
249     wsj1 = afb_ws_client_connect_wsj1(
250         loop, uribuf, const_cast<struct afb_wsj1_itf *>(&itf), this);
251     if (wsj1 == nullptr) {
252         sd_event_unref(loop);
253         fprintf(stderr, "Connection to %s failed: %m\n", uribuf);
254         rc = -errno;
255         goto fail;
256     }
257
258     return 0;
259
260 fail:
261     return rc;
262 }
263
264 int AFBClient::Impl::dispatch() {
265     std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
266     return sd_event_run(loop, 1);
267 }
268
269 int AFBClient::Impl::requestSurface(const char *label) {
270     TRACE();
271
272     if (this->labels.find(label) != this->labels.end()) {
273         fprintf(stderr, "Surface label already known!\n");
274         return -EINVAL;
275     }
276
277     json_object *jp = json_object_new_object();
278     json_object_object_add(jp, "drawing_name", json_object_new_string(label));
279
280     int rc = -1;
281     /* send the request */
282     int rc2 = api_call(
283         loop, wsj1, "request_surface", jp, [&rc](bool ok, json_object *j) {
284             if (ok) {
285                 int id =
286                     json_object_get_int(json_object_object_get(j, "response"));
287                 char *buf;
288                 asprintf(&buf, "%d", id);
289                 printf("setenv(\"QT_IVI_SURFACE_ID\", %s, 1)\n", buf);
290                 if (setenv("QT_IVI_SURFACE_ID", buf, 1) != 0) {
291                     fprintf(stderr, "putenv failed: %m\n");
292                     rc = -errno;
293                 } else {
294                     rc = 0;  // Single point of success
295                 }
296             } else {
297                 fprintf(stderr, "Could not get surface ID from WM: %s\n",
298                         j ? json_object_to_json_string_ext(
299                                 j, JSON_C_TO_STRING_PRETTY)
300                           : "no-info");
301                 rc = -EINVAL;
302             }
303         });
304
305     if (rc2 < 0)
306         rc = rc2;
307
308     if (rc >= 0) {
309         this->labels.insert(this->labels.end(), label);
310     }
311
312     return rc;
313 }
314
315 int AFBClient::Impl::activateSurface(const char *label) {
316     TRACE();
317     json_object *j = json_object_new_object();
318     json_object_object_add(j, "drawing_name", json_object_new_string(label));
319     return api_call(loop, wsj1, "activate_surface", j, [](bool ok,
320                                                           json_object *j) {
321         if (!ok) {
322             fprintf(
323                 stderr, "API Call activate_surface() failed: %s\n",
324                 j ? json_object_to_json_string_ext(j, JSON_C_TO_STRING_PRETTY)
325                   : "no-info");
326         }
327     });
328 }
329
330 int AFBClient::Impl::deactivateSurface(const char *label) {
331     TRACE();
332     json_object *j = json_object_new_object();
333     json_object_object_add(j, "drawing_name", json_object_new_string(label));
334     return api_call(loop, wsj1, "deactivate_surface", j, [](bool ok,
335                                                             json_object *j) {
336         if (!ok) {
337             fprintf(
338                 stderr, "API Call deactivate_surface() failed: %s\n",
339                 j ? json_object_to_json_string_ext(j, JSON_C_TO_STRING_PRETTY)
340                   : "no-info");
341         }
342     });
343 }
344
345 int AFBClient::Impl::endDraw(const char *label) {
346     TRACE();
347     json_object *j = json_object_new_object();
348     json_object_object_add(j, "drawing_name", json_object_new_string(label));
349     return api_call(loop, wsj1, "enddraw", j, [](bool ok, json_object *j) {
350         if (!ok) {
351             fprintf(
352                 stderr, "API Call endDraw() failed: %s\n",
353                 j ? json_object_to_json_string_ext(j, JSON_C_TO_STRING_PRETTY)
354                   : "no-info");
355         }
356     });
357 }
358
359 void AFBClient::Impl::set_event_handler(
360     enum EventType et, std::function<void(char const *)> func) {
361     UNUSED(et);
362     UNUSED(func);
363     TRACE();
364
365     if (et >= 1 && et <= 6) {  // Yeah ... just go with it!
366         this->handlers[et] = std::move(func);
367     }
368 }
369
370 namespace {
371 std::pair<bool, AFBClient::EventType> make_event_type(char const *et) {
372     // Event have the form "$API/$EVENT", just try to find the first / and
373     // get on with it.
374     char const *et2 = strchr(et, '/');
375     if (et2) {
376         et = et2 + 1;
377     }
378
379 #define ET(N, A)                                               \
380     do {                                                       \
381         if (strcasecmp(et, N) == 0)                            \
382             return std::make_pair<bool, AFBClient::EventType>( \
383                 true, CONCAT(AFBClient::Event_, A));           \
384     } while (0)
385
386     ET("activated", Active);
387     ET("deactivated", Inactive);
388     ET("visible", Visible);
389     ET("invisible", Invisible);
390     ET("syncdraw", SyncDraw);
391     ET("flushdraw", FlushDraw);
392 #undef ET
393
394     return std::make_pair<bool, AFBClient::EventType>(false,
395                                                       AFBClient::Event_Active);
396 }
397 }  // namespace
398
399 void AFBClient::Impl::event(char const *et, char const *label) {
400     TRACE();
401     auto oet = make_event_type(et);
402     if (!oet.first) {
403         fprintf(stderr, "Unknown event type string '%s'\n", et);
404         return;
405     }
406
407     auto i = this->handlers.find(oet.second);
408     if (i != this->handlers.end()) {
409         i->second(label);
410     }
411 }
412
413 //       _                    _    _____ ____   ____ _ _            _
414 //   ___| | __ _ ___ ___     / \  |  ___| __ ) / ___| (_) ___ _ __ | |_
415 //  / __| |/ _` / __/ __|   / _ \ | |_  |  _ \| |   | | |/ _ \ '_ \| __|
416 // | (__| | (_| \__ \__ \  / ___ \|  _| | |_) | |___| | |  __/ | | | |_
417 //  \___|_|\__,_|___/___/ /_/   \_\_|   |____/ \____|_|_|\___|_| |_|\__|
418 //
419 int AFBClient::init(int port, char const *token) {
420     return this->d->init(port, token);
421 }
422
423 int AFBClient::dispatch() { return this->d->dispatch(); }
424
425 int AFBClient::requestSurface(const char *label) {
426     return this->d->requestSurface(label);
427 }
428
429 int AFBClient::activateSurface(const char *label) {
430     return this->d->activateSurface(label);
431 }
432
433 int AFBClient::deactivateSurface(const char *label) {
434     return this->d->deactivateSurface(label);
435 }
436
437 int AFBClient::endDraw(const char *label) { return this->d->endDraw(label); }
438
439 void AFBClient::set_event_handler(enum EventType et,
440                                   std::function<void(char const *label)> f) {
441     return this->d->set_event_handler(et, std::move(f));
442 }
443
444 AFBClient &AFBClient::instance() {
445     TRACE();
446     static AFBClient obj;
447     return obj;
448 }
449
450 AFBClient::AFBClient() : d(new Impl) {}
451
452 AFBClient::~AFBClient() { delete d; }