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 func);
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 explicit 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 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 const 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) == 0),
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);
211 int AFBClient::Impl::init(int port, char const *token) {
213 char *uribuf = nullptr;
216 if (this->loop != nullptr && this->wsj1 != nullptr) {
217 fputs("AFBClient instance is already initialized!\n", stderr);
222 if ((token == nullptr) || strlen(token) > token_maxlen) {
223 fprintf(stderr, "Token is invalid\n");
228 for (char const *p = token; *p != 0; p++) {
229 if (isalnum(*p) == 0) {
230 fprintf(stderr, "Token is invalid\n");
236 if (port < 1 && port > 0xffff) {
237 fprintf(stderr, "Port is invalid\n");
242 /* get the default event loop */
243 rc = sd_event_default(&loop);
245 fprintf(stderr, "Connection to default event loop failed: %s\n",
250 asprintf(&uribuf, "ws://localhost:%d/api?token=%s", port, token);
252 /* connect the websocket wsj1 to the uri given by the first argument */
253 wsj1 = afb_ws_client_connect_wsj1(
254 loop, uribuf, const_cast<struct afb_wsj1_itf *>(&itf), this);
255 if (wsj1 == nullptr) {
256 sd_event_unref(this->loop);
257 this->loop = nullptr;
258 fprintf(stderr, "Connection to %s failed: %m\n", uribuf);
269 int AFBClient::Impl::dispatch() {
270 std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
271 return sd_event_run(loop, 1);
274 int AFBClient::Impl::requestSurface(const char *label) {
277 if (this->labels.find(label) != this->labels.end()) {
278 fprintf(stderr, "Surface label already known!\n");
282 json_object *jp = json_object_new_object();
283 json_object_object_add(jp, "drawing_name", json_object_new_string(label));
286 /* send the request */
288 loop, wsj1, "request_surface", jp, [&rc](bool ok, json_object *j) {
291 json_object_get_int(json_object_object_get(j, "response"));
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");
299 rc = 0; // Single point of success
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)
315 this->labels.insert(this->labels.end(), label);
321 int AFBClient::Impl::activateSurface(const char *label) {
323 json_object *j = json_object_new_object();
324 json_object_object_add(j, "drawing_name", json_object_new_string(label));
326 loop, wsj1, "activate_surface", j, [](bool ok, json_object *j) {
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)
336 int AFBClient::Impl::deactivateSurface(const char *label) {
338 json_object *j = json_object_new_object();
339 json_object_object_add(j, "drawing_name", json_object_new_string(label));
341 loop, wsj1, "deactivate_surface", j, [](bool ok, json_object *j) {
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)
351 int AFBClient::Impl::endDraw(const char *label) {
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) {
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)
365 void AFBClient::Impl::set_event_handler(
366 enum EventType et, std::function<void(char const *)> func) {
369 if (et >= 1 && et <= 6) { // Yeah ... just go with it!
370 this->handlers[et] = std::move(func);
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
378 char const *et2 = strchr(et, '/');
379 if (et2 != nullptr) {
385 if (strcasecmp(et, N) == 0) \
386 return std::pair<bool, AFBClient::EventType>( \
387 true, CONCAT(AFBClient::Event_, A)); \
390 ET("activated", Active);
391 ET("deactivated", Inactive);
392 ET("visible", Visible);
393 ET("invisible", Invisible);
394 ET("syncdraw", SyncDraw);
395 ET("flushdraw", FlushDraw);
398 return std::pair<bool, AFBClient::EventType>(false,
399 AFBClient::Event_Active);
403 void AFBClient::Impl::event(char const *et, char const *label) {
405 auto oet = make_event_type(et);
407 fprintf(stderr, "Unknown event type string '%s'\n", et);
411 auto i = this->handlers.find(oet.second);
412 if (i != this->handlers.end()) {
413 if (this->labels.find(label) != this->labels.end()) {
419 // _ _ _____ ____ ____ _ _ _
420 // ___| | __ _ ___ ___ / \ | ___| __ ) / ___| (_) ___ _ __ | |_
421 // / __| |/ _` / __/ __| / _ \ | |_ | _ \| | | | |/ _ \ '_ \| __|
422 // | (__| | (_| \__ \__ \ / ___ \| _| | |_) | |___| | | __/ | | | |_
423 // \___|_|\__,_|___/___/ /_/ \_\_| |____/ \____|_|_|\___|_| |_|\__|
425 int AFBClient::init(int port, char const *token) {
426 return this->d->init(port, token);
429 int AFBClient::dispatch() { return this->d->dispatch(); }
431 int AFBClient::requestSurface(const char *label) {
432 return this->d->requestSurface(label);
435 int AFBClient::activateSurface(const char *label) {
436 return this->d->activateSurface(label);
439 int AFBClient::deactivateSurface(const char *label) {
440 return this->d->deactivateSurface(label);
443 int AFBClient::endDraw(const char *label) { return this->d->endDraw(label); }
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));
450 AFBClient &AFBClient::instance() {
452 static AFBClient obj;
456 AFBClient::AFBClient() : d(new Impl) {}
458 AFBClient::~AFBClient() { delete d; }