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