AFBClient: fix some clang-tidy issues
[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, handler_fun func);
48
49     Impl();
50     ~Impl();
51
52     struct afb_wsj1 *wsj1;
53     struct sd_event *loop;
54
55     std::set<std::string> labels;
56     std::map<EventType, handler_fun> handlers;
57
58 public:
59     void event(char const *et, char const *label);
60 };
61
62 namespace {
63
64 constexpr const int token_maxlen = 20;
65 constexpr const char *const wmAPI = "winman";
66
67 #ifdef NDEBUG
68 #define TRACE()
69 #define TRACEN(N)
70 #else
71 #define CONCAT_(X, Y) X##Y
72 #define CONCAT(X, Y) CONCAT_(X, Y)
73
74 #define TRACE() \
75     ScopeTrace __attribute__((unused)) CONCAT(trace_scope_, __LINE__)(__func__)
76 #define TRACEN(N) \
77     ScopeTrace __attribute__((unused)) CONCAT(named_trace_scope_, __LINE__)(#N)
78
79 struct ScopeTrace {
80     thread_local static int indent;
81     char const *f{};
82     explicit ScopeTrace(char const *func) : f(func) {
83         fprintf(stderr, "%*s%s -->\n", 2 * indent++, "", this->f);
84     }
85     ~ScopeTrace() { fprintf(stderr, "%*s%s <--\n", 2 * --indent, "", this->f); }
86 };
87 thread_local int ScopeTrace::indent = 0;
88 #endif
89
90 /* called when wsj1 receives a method invocation */
91 void onCall(void *closure, const char *api, const char *verb,
92             struct afb_wsj1_msg *msg) {
93     TRACE();
94     UNUSED(closure);
95     UNUSED(verb);
96     UNUSED(api);
97     UNUSED(msg);
98 }
99
100 /* called when wsj1 receives an event */
101 void onEvent(void *closure, const char *event, afb_wsj1_msg *msg) {
102     TRACE();
103     reinterpret_cast<AFBClient::Impl *>(closure)->event(
104         event, json_object_get_string(
105                    json_object_object_get(afb_wsj1_msg_object_j(msg), "data")));
106 }
107
108 /* called when wsj1 hangsup */
109 void onHangup(void *closure, afb_wsj1 *wsj1) {
110     TRACE();
111     UNUSED(closure);
112     UNUSED(wsj1);
113     printf("ON-HANGUP\n");
114     fflush(stdout);
115     exit(0);
116 }
117
118 constexpr struct afb_wsj1_itf itf = {
119     onHangup, onCall, onEvent,
120 };
121
122 // XXX: I am not sure this is the right thing to do though...
123 std::recursive_mutex dispatch_mutex;
124
125 void dispatch_internal(struct sd_event *loop) {
126     std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
127     TRACE();
128     sd_event_run(loop, -1);
129 }
130
131 /// object will be json_object_put
132 int api_call(struct sd_event *loop, struct afb_wsj1 *wsj1, const char *verb,
133              json_object *object,
134              const std::function<void(bool, json_object *)> &onReply) {
135     TRACE();
136
137     // We need to wrap the actual onReply call once in order to
138     // *look* like a normal functions pointer (std::functions<>
139     // with captures cannot convert to function pointers).
140     // Alternatively we could setup a local struct and use it as
141     // closure, but I think it is cleaner this way.
142     int call_rc = 0;
143     std::atomic<bool> returned{};
144     returned.store(false, std::memory_order_relaxed);
145     std::function<void(bool, json_object *)> wrappedOnReply =
146         [&returned, &call_rc, &onReply](bool ok, json_object *j) {
147             TRACEN(wrappedOnReply);
148             call_rc = ok ? 0 : -EINVAL;
149             // We know it failed, but there may be an explanation in the
150             // json object.
151             {
152                 TRACEN(onReply);
153                 onReply(ok, j);
154             }
155             returned.store(true, std::memory_order_release);
156         };
157
158     // make the actual call, use wrappedOnReply as closure
159     int rc = afb_wsj1_call_j(
160         wsj1, wmAPI, verb, object,
161         [](void *closure, afb_wsj1_msg *msg) {
162             TRACEN(callClosure);
163             auto *onReply =
164                 reinterpret_cast<std::function<void(bool, json_object *)> *>(
165                     closure);
166             (*onReply)(!(afb_wsj1_msg_is_reply_ok(msg) == 0),
167                        afb_wsj1_msg_object_j(msg));
168         },
169         &wrappedOnReply);
170
171     if (rc < 0) {
172         fprintf(
173             stderr, "calling %s/%s(%s) failed: %m\n", wmAPI, verb,
174             json_object_to_json_string_ext(object, JSON_C_TO_STRING_PRETTY));
175         // Call the reply handler regardless with a NULL json_object*
176         onReply(false, nullptr);
177     } else {
178         // We need to dispatch until "returned" got set, this is necessary
179         // if events get triggered by the call (and would be dispatched before
180         // the actual call-reply).
181         while (!returned.load(std::memory_order_consume)) {
182             std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
183             if (!returned.load(std::memory_order_consume)) {
184                 dispatch_internal(loop);
185             }
186         }
187
188         // return the actual API call result
189         rc = call_rc;
190     }
191
192     return rc;
193 }
194
195 }  // namespace
196
197 //       _                 ___                 _   _                 _
198 //   ___| | __ _ ___ ___  |_ _|_ __ ___  _ __ | | (_)_ __ ___  _ __ | |
199 //  / __| |/ _` / __/ __|  | || '_ ` _ \| '_ \| | | | '_ ` _ \| '_ \| |
200 // | (__| | (_| \__ \__ \  | || | | | | | |_) | | | | | | | | | |_) | |
201 //  \___|_|\__,_|___/___/ |___|_| |_| |_| .__/|_| |_|_| |_| |_| .__/|_|
202 //                                      |_|                   |_|
203 AFBClient::Impl::Impl() : wsj1{}, loop{}, labels(), handlers() { TRACE(); }
204
205 AFBClient::Impl::~Impl() {
206     TRACE();
207     afb_wsj1_unref(wsj1);
208     sd_event_unref(loop);
209     loop = nullptr;
210 }
211
212 int AFBClient::Impl::init(int port, char const *token) {
213     TRACE();
214     char *uribuf = nullptr;
215     int rc = -1;
216
217     if ((token == nullptr) || strlen(token) > token_maxlen) {
218         fprintf(stderr, "Token is invalid\n");
219         rc = -EINVAL;
220         goto fail;
221     }
222
223     for (char const *p = token; *p != 0; p++) {
224         if (isalnum(*p) == 0) {
225             fprintf(stderr, "Token is invalid\n");
226             rc = -EINVAL;
227             goto fail;
228         }
229     }
230
231     if (port < 1 && port > 0xffff) {
232         fprintf(stderr, "Port is invalid\n");
233         rc = -EINVAL;
234         goto fail;
235     }
236
237     /* get the default event loop */
238     rc = sd_event_default(&loop);
239     if (rc < 0) {
240         fprintf(stderr, "Connection to default event loop failed: %s\n",
241                 strerror(-rc));
242         goto fail;
243     }
244
245     asprintf(&uribuf, "ws://localhost:%d/api?token=%s", port, token);
246
247     /* connect the websocket wsj1 to the uri given by the first argument */
248     wsj1 = afb_ws_client_connect_wsj1(
249         loop, uribuf, const_cast<struct afb_wsj1_itf *>(&itf), this);
250     if (wsj1 == nullptr) {
251         sd_event_unref(loop);
252         fprintf(stderr, "Connection to %s failed: %m\n", uribuf);
253         rc = -errno;
254         goto fail;
255     }
256
257     return 0;
258
259 fail:
260     return rc;
261 }
262
263 int AFBClient::Impl::dispatch() {
264     std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
265     return sd_event_run(loop, 1);
266 }
267
268 int AFBClient::Impl::requestSurface(const char *label) {
269     TRACE();
270
271     if (this->labels.find(label) != this->labels.end()) {
272         fprintf(stderr, "Surface label already known!\n");
273         return -EINVAL;
274     }
275
276     json_object *jp = json_object_new_object();
277     json_object_object_add(jp, "drawing_name", json_object_new_string(label));
278
279     int rc = -1;
280     /* send the request */
281     int rc2 = api_call(
282         loop, wsj1, "request_surface", jp, [&rc](bool ok, json_object *j) {
283             if (ok) {
284                 int id =
285                     json_object_get_int(json_object_object_get(j, "response"));
286                 char *buf;
287                 asprintf(&buf, "%d", id);
288                 printf("setenv(\"QT_IVI_SURFACE_ID\", %s, 1)\n", buf);
289                 if (setenv("QT_IVI_SURFACE_ID", buf, 1) != 0) {
290                     fprintf(stderr, "putenv failed: %m\n");
291                     rc = -errno;
292                 } else {
293                     rc = 0;  // Single point of success
294                 }
295             } else {
296                 fprintf(stderr, "Could not get surface ID from WM: %s\n",
297                         j != nullptr ? json_object_to_json_string_ext(
298                                            j, JSON_C_TO_STRING_PRETTY)
299                                      : "no-info");
300                 rc = -EINVAL;
301             }
302         });
303
304     if (rc2 < 0) {
305         rc = rc2;
306     }
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(
320         loop, wsj1, "activate_surface", j, [](bool ok, json_object *j) {
321             if (!ok) {
322                 fprintf(stderr, "API Call activate_surface() failed: %s\n",
323                         j != nullptr ? json_object_to_json_string_ext(
324                                            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(
335         loop, wsj1, "deactivate_surface", j, [](bool ok, json_object *j) {
336             if (!ok) {
337                 fprintf(stderr, "API Call deactivate_surface() failed: %s\n",
338                         j != nullptr ? json_object_to_json_string_ext(
339                                            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(stderr, "API Call endDraw() failed: %s\n",
352                     j != nullptr ? json_object_to_json_string_ext(
353                                        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     TRACE();
362
363     if (et >= 1 && et <= 6) {  // Yeah ... just go with it!
364         this->handlers[et] = std::move(func);
365     }
366 }
367
368 namespace {
369 std::pair<bool, AFBClient::EventType> make_event_type(char const *et) {
370     // Event have the form "$API/$EVENT", just try to find the first / and
371     // get on with it.
372     char const *et2 = strchr(et, '/');
373     if (et2 != nullptr) {
374         et = et2 + 1;
375     }
376
377 #define ET(N, A)                                          \
378     do {                                                  \
379         if (strcasecmp(et, N) == 0)                       \
380             return std::pair<bool, AFBClient::EventType>( \
381                 true, CONCAT(AFBClient::Event_, A));      \
382     } while (false)
383
384     ET("activated", Active);
385     ET("deactivated", Inactive);
386     ET("visible", Visible);
387     ET("invisible", Invisible);
388     ET("syncdraw", SyncDraw);
389     ET("flushdraw", FlushDraw);
390 #undef ET
391
392     return std::pair<bool, AFBClient::EventType>(false,
393                                                  AFBClient::Event_Active);
394 }
395 }  // namespace
396
397 void AFBClient::Impl::event(char const *et, char const *label) {
398     TRACE();
399     auto oet = make_event_type(et);
400     if (!oet.first) {
401         fprintf(stderr, "Unknown event type string '%s'\n", et);
402         return;
403     }
404
405     auto i = this->handlers.find(oet.second);
406     if (i != this->handlers.end()) {
407         if (this->labels.find(label) != this->labels.end()) {
408             i->second(label);
409         }
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; }