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