17 #include <systemd/sd-event.h>
19 #include <json-c/json.h>
22 #include <afb/afb-ws-client.h>
23 #include <afb/afb-wsj1.h>
26 #define UNUSED(x) (void)(x)
29 // ___| | __ _ ___ ___ |_ _|_ __ ___ _ __ | |
30 // / __| |/ _` / __/ __| | || '_ ` _ \| '_ \| |
31 // | (__| | (_| \__ \__ \ | || | | | | | |_) | |
32 // \___|_|\__,_|___/___/ |___|_| |_| |_| .__/|_|
34 class AFBClient::Impl {
35 friend class AFBClient;
37 // This is the AFBClient interface impl
38 int init(int port, char const *token);
42 int requestSurface(const char *label);
43 int activateSurface(const char *label);
44 int deactivateSurface(const char *label);
45 int endDraw(const char *label);
47 void set_event_handler(enum EventType et,
48 std::function<void(char const *label)> f);
53 struct afb_wsj1 *wsj1;
54 struct sd_event *loop;
56 std::set<std::string> labels;
57 std::map<EventType, handler_fun> handlers;
60 void event(char const *et, char const *label);
65 constexpr const int token_maxlen = 20;
66 constexpr const char *const wmAPI = "winman";
72 #define CONCAT_(X, Y) X##Y
73 #define CONCAT(X, Y) CONCAT_(X, Y)
76 ScopeTrace __attribute__((unused)) CONCAT(trace_scope_, __LINE__)(__func__)
78 ScopeTrace __attribute__((unused)) CONCAT(named_trace_scope_, __LINE__)(#N)
81 thread_local static int indent;
83 ScopeTrace(char const *func) : f(func) {
84 fprintf(stderr, "%*s%s -->\n", 2 * indent++, "", this->f);
86 ~ScopeTrace() { fprintf(stderr, "%*s%s <--\n", 2 * --indent, "", this->f); }
88 thread_local int ScopeTrace::indent = 0;
91 /* called when wsj1 receives a method invocation */
92 void onCall(void *closure, const char *api, const char *verb,
93 struct afb_wsj1_msg *msg) {
101 /* called when wsj1 receives an event */
102 void onEvent(void *closure, const char *event, afb_wsj1_msg *msg) {
104 reinterpret_cast<AFBClient::Impl *>(closure)->event(
105 event, json_object_get_string(
106 json_object_object_get(afb_wsj1_msg_object_j(msg), "data")));
109 /* called when wsj1 hangsup */
110 void onHangup(void *closure, afb_wsj1 *wsj1) {
114 printf("ON-HANGUP\n");
119 constexpr static struct afb_wsj1_itf itf = {
120 onHangup, onCall, onEvent,
123 // XXX: I am not sure this is the right thing to do though...
124 std::recursive_mutex dispatch_mutex;
126 void dispatch_internal(struct sd_event *loop) {
127 std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
129 sd_event_run(loop, -1);
132 /// object will be json_object_put
133 int api_call(struct sd_event *loop, struct afb_wsj1 *wsj1, const char *verb,
135 std::function<void(bool, json_object *)> onReply) {
138 // We need to wrap the actual onReply call once in order to
139 // *look* like a normal functions pointer (std::functions<>
140 // with captures cannot convert to function pointers).
141 // Alternatively we could setup a local struct and use it as
142 // closure, but I think it is cleaner this way.
144 std::atomic<bool> returned;
145 returned.store(false, std::memory_order_relaxed);
146 std::function<void(bool, json_object *)> wrappedOnReply =
147 [&returned, &call_rc, &onReply](bool ok, json_object *j) {
148 TRACEN(wrappedOnReply);
149 call_rc = ok ? 0 : -EINVAL;
150 // We know it failed, but there may be an explanation in the
156 returned.store(true, std::memory_order_release);
159 // make the actual call, use wrappedOnReply as closure
160 int rc = afb_wsj1_call_j(
161 wsj1, wmAPI, verb, object,
162 [](void *closure, afb_wsj1_msg *msg) {
165 reinterpret_cast<std::function<void(bool, json_object *)> *>(
167 (*onReply)(!!afb_wsj1_msg_is_reply_ok(msg),
168 afb_wsj1_msg_object_j(msg));
174 stderr, "calling %s/%s(%s) failed: %m\n", wmAPI, verb,
175 json_object_to_json_string_ext(object, JSON_C_TO_STRING_PRETTY));
176 // Call the reply handler regardless with a NULL json_object*
177 onReply(false, nullptr);
179 // We need to dispatch until "returned" got set, this is necessary
180 // if events get triggered by the call (and would be dispatched before
181 // the actual call-reply).
182 while (!returned.load(std::memory_order_consume)) {
183 std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
184 if (!returned.load(std::memory_order_consume)) {
185 dispatch_internal(loop);
189 // return the actual API call result
199 // ___| | __ _ ___ ___ |_ _|_ __ ___ _ __ | | (_)_ __ ___ _ __ | |
200 // / __| |/ _` / __/ __| | || '_ ` _ \| '_ \| | | | '_ ` _ \| '_ \| |
201 // | (__| | (_| \__ \__ \ | || | | | | | |_) | | | | | | | | | |_) | |
202 // \___|_|\__,_|___/___/ |___|_| |_| |_| .__/|_| |_|_| |_| |_| .__/|_|
204 AFBClient::Impl::Impl() : wsj1{}, loop{}, labels(), handlers() { TRACE(); }
206 AFBClient::Impl::~Impl() {
208 afb_wsj1_unref(wsj1);
209 sd_event_unref(loop);
213 int AFBClient::Impl::init(int port, char const *token) {
215 char *uribuf = nullptr;
218 if (!token || strlen(token) > token_maxlen) {
219 fprintf(stderr, "Token is invalid\n");
224 for (char const *p = token; *p; p++) {
226 fprintf(stderr, "Token is invalid\n");
232 if (port < 1 && port > 0xffff) {
233 fprintf(stderr, "Port is invalid\n");
238 /* get the default event loop */
239 rc = sd_event_default(&loop);
241 fprintf(stderr, "Connection to default event loop failed: %s\n",
246 asprintf(&uribuf, "ws://localhost:%d/api?token=%s", port, token);
248 /* connect the websocket wsj1 to the uri given by the first argument */
249 wsj1 = afb_ws_client_connect_wsj1(
250 loop, uribuf, const_cast<struct afb_wsj1_itf *>(&itf), this);
251 if (wsj1 == nullptr) {
252 sd_event_unref(loop);
253 fprintf(stderr, "Connection to %s failed: %m\n", uribuf);
264 int AFBClient::Impl::dispatch() {
265 std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
266 return sd_event_run(loop, 1);
269 int AFBClient::Impl::requestSurface(const char *label) {
272 if (this->labels.find(label) != this->labels.end()) {
273 fprintf(stderr, "Surface label already known!\n");
277 json_object *jp = json_object_new_object();
278 json_object_object_add(jp, "drawing_name", json_object_new_string(label));
281 /* send the request */
283 loop, wsj1, "request_surface", jp, [&rc](bool ok, json_object *j) {
286 json_object_get_int(json_object_object_get(j, "response"));
288 asprintf(&buf, "%d", id);
289 printf("setenv(\"QT_IVI_SURFACE_ID\", %s, 1)\n", buf);
290 if (setenv("QT_IVI_SURFACE_ID", buf, 1) != 0) {
291 fprintf(stderr, "putenv failed: %m\n");
294 rc = 0; // Single point of success
297 fprintf(stderr, "Could not get surface ID from WM: %s\n",
298 j ? json_object_to_json_string_ext(
299 j, JSON_C_TO_STRING_PRETTY)
309 this->labels.insert(this->labels.end(), label);
315 int AFBClient::Impl::activateSurface(const char *label) {
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(loop, wsj1, "activate_surface", j, [](bool ok,
323 stderr, "API Call activate_surface() failed: %s\n",
324 j ? json_object_to_json_string_ext(j, JSON_C_TO_STRING_PRETTY)
330 int AFBClient::Impl::deactivateSurface(const char *label) {
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(loop, wsj1, "deactivate_surface", j, [](bool ok,
338 stderr, "API Call deactivate_surface() failed: %s\n",
339 j ? json_object_to_json_string_ext(j, JSON_C_TO_STRING_PRETTY)
345 int AFBClient::Impl::endDraw(const char *label) {
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) {
352 stderr, "API Call endDraw() failed: %s\n",
353 j ? json_object_to_json_string_ext(j, JSON_C_TO_STRING_PRETTY)
359 void AFBClient::Impl::set_event_handler(
360 enum EventType et, std::function<void(char const *)> func) {
365 if (et >= 1 && et <= 6) { // Yeah ... just go with it!
366 this->handlers[et] = std::move(func);
371 std::pair<bool, AFBClient::EventType> make_event_type(char const *et) {
372 // Event have the form "$API/$EVENT", just try to find the first / and
374 char const *et2 = strchr(et, '/');
381 if (strcasecmp(et, N) == 0) \
382 return std::make_pair<bool, AFBClient::EventType>( \
383 true, CONCAT(AFBClient::Event_, A)); \
386 ET("activated", Active);
387 ET("deactivated", Inactive);
388 ET("visible", Visible);
389 ET("invisible", Invisible);
390 ET("syncdraw", SyncDraw);
391 ET("flushdraw", FlushDraw);
394 return std::make_pair<bool, AFBClient::EventType>(false,
395 AFBClient::Event_Active);
399 void AFBClient::Impl::event(char const *et, char const *label) {
401 auto oet = make_event_type(et);
403 fprintf(stderr, "Unknown event type string '%s'\n", et);
407 auto i = this->handlers.find(oet.second);
408 if (i != this->handlers.end()) {
413 // _ _ _____ ____ ____ _ _ _
414 // ___| | __ _ ___ ___ / \ | ___| __ ) / ___| (_) ___ _ __ | |_
415 // / __| |/ _` / __/ __| / _ \ | |_ | _ \| | | | |/ _ \ '_ \| __|
416 // | (__| | (_| \__ \__ \ / ___ \| _| | |_) | |___| | | __/ | | | |_
417 // \___|_|\__,_|___/___/ /_/ \_\_| |____/ \____|_|_|\___|_| |_|\__|
419 int AFBClient::init(int port, char const *token) {
420 return this->d->init(port, token);
423 int AFBClient::dispatch() { return this->d->dispatch(); }
425 int AFBClient::requestSurface(const char *label) {
426 return this->d->requestSurface(label);
429 int AFBClient::activateSurface(const char *label) {
430 return this->d->activateSurface(label);
433 int AFBClient::deactivateSurface(const char *label) {
434 return this->d->deactivateSurface(label);
437 int AFBClient::endDraw(const char *label) { return this->d->endDraw(label); }
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));
444 AFBClient &AFBClient::instance() {
446 static AFBClient obj;
450 AFBClient::AFBClient() : d(new Impl) {}
452 AFBClient::~AFBClient() { delete d; }