Impl: made wsj1_itf const
[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 constexpr 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(
240         loop, uribuf, const_cast<struct afb_wsj1_itf *>(&itf), nullptr);
241     if (wsj1 == nullptr) {
242         sd_event_unref(loop);
243         fprintf(stderr, "Connection to %s failed: %m\n", uribuf);
244         rc = -errno;
245         goto fail;
246     }
247
248     return 0;
249
250 fail:
251     return rc;
252 }
253
254 int AFBClient::Impl::dispatch() {
255     std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
256     return sd_event_run(loop, 1);
257 }
258
259 int AFBClient::Impl::requestSurface(const char *label) {
260     TRACE();
261     json_object *jp = json_object_new_object();
262     json_object_object_add(jp, "drawing_name", json_object_new_string(label));
263     int rc = -1;
264     /* send the request */
265     int rc2 = api_call(
266         loop, wsj1, "request_surface", jp, [&rc](bool ok, json_object *j) {
267             if (ok) {
268                 int id =
269                     json_object_get_int(json_object_object_get(j, "response"));
270                 char *buf;
271                 asprintf(&buf, "%d", id);
272                 printf("setenv(\"QT_IVI_SURFACE_ID\", %s, 1)\n", buf);
273                 if (setenv("QT_IVI_SURFACE_ID", buf, 1) != 0) {
274                     fprintf(stderr, "putenv failed: %m\n");
275                     rc = -errno;
276                 } else {
277                     rc = 0;  // Single point of success
278                 }
279             } else {
280                 fprintf(stderr, "Could not get surface ID from WM: %s\n",
281                         j ? json_object_to_json_string_ext(
282                                 j, JSON_C_TO_STRING_PRETTY)
283                           : "no-info");
284                 rc = -EINVAL;
285             }
286         });
287
288     return rc2 < 0 ? rc2 : rc;
289 }
290
291 int AFBClient::Impl::activateSurface(const char *label) {
292     TRACE();
293     json_object *j = json_object_new_object();
294     json_object_object_add(j, "drawing_name", json_object_new_string(label));
295     return api_call(loop, wsj1, "activate_surface", j, [](bool ok,
296                                                           json_object *j) {
297         if (!ok) {
298             fprintf(
299                 stderr, "API Call activate_surface() failed: %s\n",
300                 j ? json_object_to_json_string_ext(j, JSON_C_TO_STRING_PRETTY)
301                   : "no-info");
302         }
303     });
304 }
305
306 int AFBClient::Impl::deactivateSurface(const char *label) {
307     TRACE();
308     json_object *j = json_object_new_object();
309     json_object_object_add(j, "drawing_name", json_object_new_string(label));
310     return api_call(loop, wsj1, "deactivate_surface", j, [](bool ok,
311                                                             json_object *j) {
312         if (!ok) {
313             fprintf(
314                 stderr, "API Call deactivate_surface() failed: %s\n",
315                 j ? json_object_to_json_string_ext(j, JSON_C_TO_STRING_PRETTY)
316                   : "no-info");
317         }
318     });
319 }
320
321 int AFBClient::Impl::endDraw(const char *label) {
322     TRACE();
323     json_object *j = json_object_new_object();
324     json_object_object_add(j, "drawing_name", json_object_new_string(label));
325     return api_call(loop, wsj1, "enddraw", j, [](bool ok, json_object *j) {
326         if (!ok) {
327             fprintf(
328                 stderr, "API Call endDraw() failed: %s\n",
329                 j ? json_object_to_json_string_ext(j, JSON_C_TO_STRING_PRETTY)
330                   : "no-info");
331         }
332     });
333 }
334
335 void AFBClient::Impl::set_event_handler(
336     enum EventType et, std::function<void(char const *)> func) {
337     UNUSED(et);
338     UNUSED(func);
339     TRACE();
340     // XXX todo
341 }
342
343 //       _                    _    _____ ____   ____ _ _            _
344 //   ___| | __ _ ___ ___     / \  |  ___| __ ) / ___| (_) ___ _ __ | |_
345 //  / __| |/ _` / __/ __|   / _ \ | |_  |  _ \| |   | | |/ _ \ '_ \| __|
346 // | (__| | (_| \__ \__ \  / ___ \|  _| | |_) | |___| | |  __/ | | | |_
347 //  \___|_|\__,_|___/___/ /_/   \_\_|   |____/ \____|_|_|\___|_| |_|\__|
348 //
349 int AFBClient::init(int port, char const *token) {
350     return this->d->init(port, token);
351 }
352
353 int AFBClient::dispatch() { return this->d->dispatch(); }
354
355 int AFBClient::requestSurface(const char *label) {
356     return this->d->requestSurface(label);
357 }
358
359 int AFBClient::activateSurface(const char *label) {
360     return this->d->activateSurface(label);
361 }
362
363 int AFBClient::deactivateSurface(const char *label) {
364     return this->d->deactivateSurface(label);
365 }
366
367 int AFBClient::endDraw(const char *label) { return this->d->endDraw(label); }
368
369 void AFBClient::set_event_handler(enum EventType et,
370                                   std::function<void(char const *label)> f) {
371     return this->d->set_event_handler(et, std::move(f));
372 }
373
374 AFBClient &AFBClient::instance() {
375     TRACE();
376     static AFBClient obj;
377     return obj;
378 }
379
380 AFBClient::AFBClient() : d(new Impl) {}
381
382 AFBClient::~AFBClient() { delete d; }