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, handler_fun f);
52 struct afb_wsj1 *wsj1;
53 struct sd_event *loop;
55 std::set<std::string> labels;
56 std::map<EventType, handler_fun> handlers;
59 void event(char const *et, char const *label);
64 constexpr const int token_maxlen = 20;
65 constexpr const char *const wmAPI = "winman";
71 #define CONCAT_(X, Y) X##Y
72 #define CONCAT(X, Y) CONCAT_(X, Y)
75 ScopeTrace __attribute__((unused)) CONCAT(trace_scope_, __LINE__)(__func__)
77 ScopeTrace __attribute__((unused)) CONCAT(named_trace_scope_, __LINE__)(#N)
80 thread_local static int indent;
82 ScopeTrace(char const *func) : f(func) {
83 fprintf(stderr, "%*s%s -->\n", 2 * indent++, "", this->f);
85 ~ScopeTrace() { fprintf(stderr, "%*s%s <--\n", 2 * --indent, "", this->f); }
87 thread_local int ScopeTrace::indent = 0;
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) {
100 /* called when wsj1 receives an event */
101 void onEvent(void *closure, const char *event, afb_wsj1_msg *msg) {
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")));
108 /* called when wsj1 hangsup */
109 void onHangup(void *closure, afb_wsj1 *wsj1) {
113 printf("ON-HANGUP\n");
118 constexpr static struct afb_wsj1_itf itf = {
119 onHangup, onCall, onEvent,
122 // XXX: I am not sure this is the right thing to do though...
123 std::recursive_mutex dispatch_mutex;
125 void dispatch_internal(struct sd_event *loop) {
126 std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
128 sd_event_run(loop, -1);
131 /// object will be json_object_put
132 int api_call(struct sd_event *loop, struct afb_wsj1 *wsj1, const char *verb,
134 std::function<void(bool, json_object *)> onReply) {
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.
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
155 returned.store(true, std::memory_order_release);
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) {
164 reinterpret_cast<std::function<void(bool, json_object *)> *>(
166 (*onReply)(!!afb_wsj1_msg_is_reply_ok(msg),
167 afb_wsj1_msg_object_j(msg));
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);
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);
188 // return the actual API call result
198 // ___| | __ _ ___ ___ |_ _|_ __ ___ _ __ | | (_)_ __ ___ _ __ | |
199 // / __| |/ _` / __/ __| | || '_ ` _ \| '_ \| | | | '_ ` _ \| '_ \| |
200 // | (__| | (_| \__ \__ \ | || | | | | | |_) | | | | | | | | | |_) | |
201 // \___|_|\__,_|___/___/ |___|_| |_| |_| .__/|_| |_|_| |_| |_| .__/|_|
203 AFBClient::Impl::Impl() : wsj1{}, loop{}, labels(), handlers() { TRACE(); }
205 AFBClient::Impl::~Impl() {
207 afb_wsj1_unref(wsj1);
208 sd_event_unref(loop);
212 int AFBClient::Impl::init(int port, char const *token) {
214 char *uribuf = nullptr;
217 if (!token || strlen(token) > token_maxlen) {
218 fprintf(stderr, "Token is invalid\n");
223 for (char const *p = token; *p; p++) {
225 fprintf(stderr, "Token is invalid\n");
231 if (port < 1 && port > 0xffff) {
232 fprintf(stderr, "Port is invalid\n");
237 /* get the default event loop */
238 rc = sd_event_default(&loop);
240 fprintf(stderr, "Connection to default event loop failed: %s\n",
245 asprintf(&uribuf, "ws://localhost:%d/api?token=%s", port, token);
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);
263 int AFBClient::Impl::dispatch() {
264 std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
265 return sd_event_run(loop, 1);
268 int AFBClient::Impl::requestSurface(const char *label) {
271 if (this->labels.find(label) != this->labels.end()) {
272 fprintf(stderr, "Surface label already known!\n");
276 json_object *jp = json_object_new_object();
277 json_object_object_add(jp, "drawing_name", json_object_new_string(label));
280 /* send the request */
282 loop, wsj1, "request_surface", jp, [&rc](bool ok, json_object *j) {
285 json_object_get_int(json_object_object_get(j, "response"));
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");
293 rc = 0; // Single point of success
296 fprintf(stderr, "Could not get surface ID from WM: %s\n",
297 j ? json_object_to_json_string_ext(
298 j, JSON_C_TO_STRING_PRETTY)
308 this->labels.insert(this->labels.end(), label);
314 int AFBClient::Impl::activateSurface(const char *label) {
316 json_object *j = json_object_new_object();
317 json_object_object_add(j, "drawing_name", json_object_new_string(label));
318 return api_call(loop, wsj1, "activate_surface", j, [](bool ok,
322 stderr, "API Call activate_surface() failed: %s\n",
323 j ? json_object_to_json_string_ext(j, JSON_C_TO_STRING_PRETTY)
329 int AFBClient::Impl::deactivateSurface(const char *label) {
331 json_object *j = json_object_new_object();
332 json_object_object_add(j, "drawing_name", json_object_new_string(label));
333 return api_call(loop, wsj1, "deactivate_surface", j, [](bool ok,
337 stderr, "API Call deactivate_surface() failed: %s\n",
338 j ? json_object_to_json_string_ext(j, JSON_C_TO_STRING_PRETTY)
344 int AFBClient::Impl::endDraw(const char *label) {
346 json_object *j = json_object_new_object();
347 json_object_object_add(j, "drawing_name", json_object_new_string(label));
348 return api_call(loop, wsj1, "enddraw", j, [](bool ok, json_object *j) {
351 stderr, "API Call endDraw() failed: %s\n",
352 j ? json_object_to_json_string_ext(j, JSON_C_TO_STRING_PRETTY)
358 void AFBClient::Impl::set_event_handler(
359 enum EventType et, std::function<void(char const *)> func) {
362 if (et >= 1 && et <= 6) { // Yeah ... just go with it!
363 this->handlers[et] = std::move(func);
368 std::pair<bool, AFBClient::EventType> make_event_type(char const *et) {
369 // Event have the form "$API/$EVENT", just try to find the first / and
371 char const *et2 = strchr(et, '/');
378 if (strcasecmp(et, N) == 0) \
379 return std::make_pair<bool, AFBClient::EventType>( \
380 true, CONCAT(AFBClient::Event_, A)); \
383 ET("activated", Active);
384 ET("deactivated", Inactive);
385 ET("visible", Visible);
386 ET("invisible", Invisible);
387 ET("syncdraw", SyncDraw);
388 ET("flushdraw", FlushDraw);
391 return std::make_pair<bool, AFBClient::EventType>(false,
392 AFBClient::Event_Active);
396 void AFBClient::Impl::event(char const *et, char const *label) {
398 auto oet = make_event_type(et);
400 fprintf(stderr, "Unknown event type string '%s'\n", et);
404 auto i = this->handlers.find(oet.second);
405 if (i != this->handlers.end()) {
410 // _ _ _____ ____ ____ _ _ _
411 // ___| | __ _ ___ ___ / \ | ___| __ ) / ___| (_) ___ _ __ | |_
412 // / __| |/ _` / __/ __| / _ \ | |_ | _ \| | | | |/ _ \ '_ \| __|
413 // | (__| | (_| \__ \__ \ / ___ \| _| | |_) | |___| | | __/ | | | |_
414 // \___|_|\__,_|___/___/ /_/ \_\_| |____/ \____|_|_|\___|_| |_|\__|
416 int AFBClient::init(int port, char const *token) {
417 return this->d->init(port, token);
420 int AFBClient::dispatch() { return this->d->dispatch(); }
422 int AFBClient::requestSurface(const char *label) {
423 return this->d->requestSurface(label);
426 int AFBClient::activateSurface(const char *label) {
427 return this->d->activateSurface(label);
430 int AFBClient::deactivateSurface(const char *label) {
431 return this->d->deactivateSurface(label);
434 int AFBClient::endDraw(const char *label) { return this->d->endDraw(label); }
436 void AFBClient::set_event_handler(enum EventType et,
437 std::function<void(char const *label)> f) {
438 return this->d->set_event_handler(et, std::move(f));
441 AFBClient &AFBClient::instance() {
443 static AFBClient obj;
447 AFBClient::AFBClient() : d(new Impl) {}
449 AFBClient::~AFBClient() { delete d; }