AFBClient: use fputs where sensible, more this-> name qualification
[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     fputs("Hangup, the WindowManager vanished\n", stderr);
114     exit(1);
115 }
116
117 constexpr struct afb_wsj1_itf itf = {
118     onHangup, onCall, onEvent,
119 };
120
121 // XXX: I am not sure this is the right thing to do though...
122 std::recursive_mutex dispatch_mutex;
123
124 void dispatch_internal(struct sd_event *loop) {
125     std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
126     TRACE();
127     sd_event_run(loop, -1);
128 }
129
130 /// object will be json_object_put
131 int api_call(struct sd_event *loop, struct afb_wsj1 *wsj1, const char *verb,
132              json_object *object,
133              const std::function<void(bool, json_object *)> &onReply) {
134     TRACE();
135
136     // We need to wrap the actual onReply call once in order to
137     // *look* like a normal functions pointer (std::functions<>
138     // with captures cannot convert to function pointers).
139     // Alternatively we could setup a local struct and use it as
140     // closure, but I think it is cleaner this way.
141     int call_rc = 0;
142     std::atomic<bool> returned{};
143     returned.store(false, std::memory_order_relaxed);
144     std::function<void(bool, json_object *)> wrappedOnReply =
145         [&returned, &call_rc, &onReply](bool ok, json_object *j) {
146             TRACEN(wrappedOnReply);
147             call_rc = ok ? 0 : -EINVAL;
148             // We know it failed, but there may be an explanation in the
149             // json object.
150             {
151                 TRACEN(onReply);
152                 onReply(ok, j);
153             }
154             returned.store(true, std::memory_order_release);
155         };
156
157     // make the actual call, use wrappedOnReply as closure
158     int rc = afb_wsj1_call_j(
159         wsj1, wmAPI, verb, object,
160         [](void *closure, afb_wsj1_msg *msg) {
161             TRACEN(callClosure);
162             auto *onReply =
163                 reinterpret_cast<std::function<void(bool, json_object *)> *>(
164                     closure);
165             (*onReply)(!(afb_wsj1_msg_is_reply_ok(msg) == 0),
166                        afb_wsj1_msg_object_j(msg));
167         },
168         &wrappedOnReply);
169
170     if (rc < 0) {
171         fprintf(
172             stderr, "calling %s/%s(%s) failed: %m\n", wmAPI, verb,
173             json_object_to_json_string_ext(object, JSON_C_TO_STRING_PRETTY));
174         // Call the reply handler regardless with a NULL json_object*
175         onReply(false, nullptr);
176     } else {
177         // We need to dispatch until "returned" got set, this is necessary
178         // if events get triggered by the call (and would be dispatched before
179         // the actual call-reply).
180         while (!returned.load(std::memory_order_consume)) {
181             std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
182             if (!returned.load(std::memory_order_consume)) {
183                 dispatch_internal(loop);
184             }
185         }
186
187         // return the actual API call result
188         rc = call_rc;
189     }
190
191     return rc;
192 }
193
194 }  // namespace
195
196 //       _                 ___                 _   _                 _
197 //   ___| | __ _ ___ ___  |_ _|_ __ ___  _ __ | | (_)_ __ ___  _ __ | |
198 //  / __| |/ _` / __/ __|  | || '_ ` _ \| '_ \| | | | '_ ` _ \| '_ \| |
199 // | (__| | (_| \__ \__ \  | || | | | | | |_) | | | | | | | | | |_) | |
200 //  \___|_|\__,_|___/___/ |___|_| |_| |_| .__/|_| |_|_| |_| |_| .__/|_|
201 //                                      |_|                   |_|
202 AFBClient::Impl::Impl() : wsj1{}, loop{}, labels(), handlers() { TRACE(); }
203
204 AFBClient::Impl::~Impl() {
205     TRACE();
206     afb_wsj1_unref(wsj1);
207     sd_event_unref(loop);
208 }
209
210 int AFBClient::Impl::init(int port, char const *token) {
211     TRACE();
212     char *uribuf = nullptr;
213     int rc = -1;
214
215     if (this->loop != nullptr && this->wsj1 != nullptr) {
216         fputs("AFBClient instance is already initialized!\n", stderr);
217         rc = -EALREADY;
218         goto fail;
219     }
220
221     if ((token == nullptr) || strlen(token) > token_maxlen) {
222         fputs("Token is invalid\n", stderr);
223         rc = -EINVAL;
224         goto fail;
225     }
226
227     for (char const *p = token; *p != 0; p++) {
228         if (isalnum(*p) == 0) {
229             fputs("Token is invalid\n", stderr);
230             rc = -EINVAL;
231             goto fail;
232         }
233     }
234
235     if (port < 1 && port > 0xffff) {
236         fputs("Port is invalid\n", stderr);
237         rc = -EINVAL;
238         goto fail;
239     }
240
241     /* get the default event loop */
242     rc = sd_event_default(&this->loop);
243     if (rc < 0) {
244         fprintf(stderr, "Connection to default event loop failed: %s\n",
245                 strerror(-rc));
246         goto fail;
247     }
248
249     asprintf(&uribuf, "ws://localhost:%d/api?token=%s", port, token);
250
251     /* connect the websocket wsj1 to the uri given by the first argument */
252     this->wsj1 = afb_ws_client_connect_wsj1(
253         this->loop, uribuf, const_cast<struct afb_wsj1_itf *>(&itf), this);
254     if (this->wsj1 == nullptr) {
255         sd_event_unref(this->loop);
256         this->loop = nullptr;
257         fprintf(stderr, "Connection to %s failed: %m\n", uribuf);
258         rc = -errno;
259         goto fail;
260     }
261
262     return 0;
263
264 fail:
265     return rc;
266 }
267
268 int AFBClient::Impl::dispatch() {
269     std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
270     return sd_event_run(this->loop, 1);
271 }
272 }
273
274 int AFBClient::Impl::requestSurface(const char *label) {
275     TRACE();
276
277     if (this->labels.find(label) != this->labels.end()) {
278         fputs("Surface label already known!\n", stderr);
279         return -EINVAL;
280     }
281
282     json_object *jp = json_object_new_object();
283     json_object_object_add(jp, "drawing_name", json_object_new_string(label));
284
285     int rc = -1;
286     /* send the request */
287     int rc2 = api_call(
288         loop, wsj1, "request_surface", jp, [&rc](bool ok, json_object *j) {
289             if (ok) {
290                 int id =
291                     json_object_get_int(json_object_object_get(j, "response"));
292                 char *buf;
293                 asprintf(&buf, "%d", id);
294                 printf("setenv(\"QT_IVI_SURFACE_ID\", %s, 1)\n", buf);
295                 if (setenv("QT_IVI_SURFACE_ID", buf, 1) != 0) {
296                     fprintf(stderr, "putenv failed: %m\n");
297                     rc = -errno;
298                 } else {
299                     rc = 0;  // Single point of success
300                 }
301             } else {
302                 fprintf(stderr, "Could not get surface ID from WM: %s\n",
303                         j != nullptr ? json_object_to_json_string_ext(
304                                            j, JSON_C_TO_STRING_PRETTY)
305                                      : "no-info");
306                 rc = -EINVAL;
307             }
308         });
309
310     if (rc2 < 0) {
311         rc = rc2;
312     }
313
314     if (rc >= 0) {
315         this->labels.insert(this->labels.end(), label);
316     }
317
318     return rc;
319 }
320
321 int AFBClient::Impl::activateSurface(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(
326         loop, wsj1, "activate_surface", j, [](bool ok, json_object *j) {
327             if (!ok) {
328                 fprintf(stderr, "API Call activate_surface() failed: %s\n",
329                         j != nullptr ? json_object_to_json_string_ext(
330                                            j, JSON_C_TO_STRING_PRETTY)
331                                      : "no-info");
332             }
333         });
334 }
335
336 int AFBClient::Impl::deactivateSurface(const char *label) {
337     TRACE();
338     json_object *j = json_object_new_object();
339     json_object_object_add(j, "drawing_name", json_object_new_string(label));
340     return api_call(
341         loop, wsj1, "deactivate_surface", j, [](bool ok, json_object *j) {
342             if (!ok) {
343                 fprintf(stderr, "API Call deactivate_surface() failed: %s\n",
344                         j != nullptr ? json_object_to_json_string_ext(
345                                            j, JSON_C_TO_STRING_PRETTY)
346                                      : "no-info");
347             }
348         });
349 }
350
351 int AFBClient::Impl::endDraw(const char *label) {
352     TRACE();
353     json_object *j = json_object_new_object();
354     json_object_object_add(j, "drawing_name", json_object_new_string(label));
355     return api_call(loop, wsj1, "enddraw", j, [](bool ok, json_object *j) {
356         if (!ok) {
357             fprintf(stderr, "API Call endDraw() failed: %s\n",
358                     j != nullptr ? json_object_to_json_string_ext(
359                                        j, JSON_C_TO_STRING_PRETTY)
360                                  : "no-info");
361         }
362     });
363 }
364
365 void AFBClient::Impl::set_event_handler(
366     enum EventType et, std::function<void(char const *)> func) {
367     TRACE();
368
369     if (et >= 1 && et <= 6) {  // Yeah ... just go with it!
370         this->handlers[et] = std::move(func);
371     }
372 }
373
374 namespace {
375 std::pair<bool, AFBClient::EventType> make_event_type(char const *et) {
376     // Event have the form "$API/$EVENT", just try to find the first / and
377     // get on with it.
378     char const *et2 = strchr(et, '/');
379     if (et2 != nullptr) {
380         et = et2 + 1;
381     }
382
383 #define ET(N, A)                                          \
384     do {                                                  \
385         if (strcasecmp(et, N) == 0)                       \
386             return std::pair<bool, AFBClient::EventType>( \
387                 true, CONCAT(AFBClient::Event_, A));      \
388     } while (false)
389
390     ET("activated", Active);
391     ET("deactivated", Inactive);
392     ET("visible", Visible);
393     ET("invisible", Invisible);
394     ET("syncdraw", SyncDraw);
395     ET("flushdraw", FlushDraw);
396 #undef ET
397
398     return std::pair<bool, AFBClient::EventType>(false,
399                                                  AFBClient::Event_Active);
400 }
401 }  // namespace
402
403 void AFBClient::Impl::event(char const *et, char const *label) {
404     TRACE();
405     auto oet = make_event_type(et);
406     if (!oet.first) {
407         fprintf(stderr, "Unknown event type string '%s'\n", et);
408         return;
409     }
410
411     auto i = this->handlers.find(oet.second);
412     if (i != this->handlers.end()) {
413         if (this->labels.find(label) != this->labels.end()) {
414             i->second(label);
415         }
416     }
417 }
418
419 //       _                    _    _____ ____   ____ _ _            _
420 //   ___| | __ _ ___ ___     / \  |  ___| __ ) / ___| (_) ___ _ __ | |_
421 //  / __| |/ _` / __/ __|   / _ \ | |_  |  _ \| |   | | |/ _ \ '_ \| __|
422 // | (__| | (_| \__ \__ \  / ___ \|  _| | |_) | |___| | |  __/ | | | |_
423 //  \___|_|\__,_|___/___/ /_/   \_\_|   |____/ \____|_|_|\___|_| |_|\__|
424 //
425 int AFBClient::init(int port, char const *token) {
426     return this->d->init(port, token);
427 }
428
429 int AFBClient::dispatch() { return this->d->dispatch(); }
430
431 int AFBClient::requestSurface(const char *label) {
432     return this->d->requestSurface(label);
433 }
434
435 int AFBClient::activateSurface(const char *label) {
436     return this->d->activateSurface(label);
437 }
438
439 int AFBClient::deactivateSurface(const char *label) {
440     return this->d->deactivateSurface(label);
441 }
442
443 int AFBClient::endDraw(const char *label) { return this->d->endDraw(label); }
444
445 void AFBClient::set_event_handler(enum EventType et,
446                                   std::function<void(char const *label)> f) {
447     return this->d->set_event_handler(et, std::move(f));
448 }
449
450 AFBClient &AFBClient::instance() {
451     TRACE();
452     static AFBClient obj;
453     return obj;
454 }
455
456 AFBClient::AFBClient() : d(new Impl) {}
457
458 AFBClient::~AFBClient() { delete d; }