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;
58 int api_call(const char *verb, json_object *object,
59 const std::function<void(bool, json_object *)> &onReply);
60 void dispatch_internal();
63 void event(char const *et, char const *label);
68 constexpr const int token_maxlen = 20;
69 constexpr const char *const wmAPI = "winman";
75 #define CONCAT_(X, Y) X##Y
76 #define CONCAT(X, Y) CONCAT_(X, Y)
79 ScopeTrace __attribute__((unused)) CONCAT(trace_scope_, __LINE__)(__func__)
81 ScopeTrace __attribute__((unused)) CONCAT(named_trace_scope_, __LINE__)(#N)
84 thread_local static int indent;
86 explicit ScopeTrace(char const *func) : f(func) {
87 fprintf(stderr, "%*s%s -->\n", 2 * indent++, "", this->f);
89 ~ScopeTrace() { fprintf(stderr, "%*s%s <--\n", 2 * --indent, "", this->f); }
91 thread_local int ScopeTrace::indent = 0;
94 /* called when wsj1 receives a method invocation */
95 void onCall(void *closure, const char *api, const char *verb,
96 struct afb_wsj1_msg *msg) {
104 /* called when wsj1 receives an event */
105 void onEvent(void *closure, const char *event, afb_wsj1_msg *msg) {
107 reinterpret_cast<AFBClient::Impl *>(closure)->event(
108 event, json_object_get_string(
109 json_object_object_get(afb_wsj1_msg_object_j(msg), "data")));
112 /* called when wsj1 hangsup */
113 void onHangup(void *closure, afb_wsj1 *wsj1) {
117 fputs("Hangup, the WindowManager vanished\n", stderr);
118 exit(1); // XXX: there should be something ... *better* here.
121 constexpr struct afb_wsj1_itf itf = {
122 onHangup, onCall, onEvent,
125 // XXX: I am not sure this is the right thing to do though...
126 std::recursive_mutex dispatch_mutex;
128 json_object *drawing_name_json_argument(char const *label) {
129 json_object *j = json_object_new_object();
130 json_object_object_add(j, "drawing_name", json_object_new_string(label));
137 // ___| | __ _ ___ ___ |_ _|_ __ ___ _ __ | | (_)_ __ ___ _ __ | |
138 // / __| |/ _` / __/ __| | || '_ ` _ \| '_ \| | | | '_ ` _ \| '_ \| |
139 // | (__| | (_| \__ \__ \ | || | | | | | |_) | | | | | | | | | |_) | |
140 // \___|_|\__,_|___/___/ |___|_| |_| |_| .__/|_| |_|_| |_| |_| .__/|_|
142 AFBClient::Impl::Impl() : wsj1{}, loop{}, labels(), handlers() { TRACE(); }
144 AFBClient::Impl::~Impl() {
146 afb_wsj1_unref(wsj1);
147 sd_event_unref(loop);
150 int AFBClient::Impl::init(int port, char const *token) {
152 char *uribuf = nullptr;
155 if (this->loop != nullptr && this->wsj1 != nullptr) {
156 fputs("AFBClient instance is already initialized!\n", stderr);
161 if ((token == nullptr) || strlen(token) > token_maxlen) {
162 fputs("Token is invalid\n", stderr);
167 for (char const *p = token; *p != 0; p++) {
168 if (isalnum(*p) == 0) {
169 fputs("Token is invalid\n", stderr);
175 if (port < 1 || port > 0xffff) {
176 fputs("Port is invalid\n", stderr);
181 /* get the default event loop */
182 rc = sd_event_default(&this->loop);
184 fprintf(stderr, "Connection to default event loop failed: %s\n",
189 asprintf(&uribuf, "ws://localhost:%d/api?token=%s", port, token);
191 /* connect the websocket wsj1 to the uri given by the first argument */
192 this->wsj1 = afb_ws_client_connect_wsj1(
193 this->loop, uribuf, const_cast<struct afb_wsj1_itf *>(&itf), this);
194 if (this->wsj1 == nullptr) {
195 sd_event_unref(this->loop);
196 this->loop = nullptr;
197 fprintf(stderr, "Connection to %s failed: %m\n", uribuf);
208 int AFBClient::Impl::dispatch() {
209 std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
210 return sd_event_run(this->loop, 1);
213 int AFBClient::Impl::requestSurface(const char *label) {
216 if (this->labels.find(label) != this->labels.end()) {
217 fputs("Surface label already known!\n", stderr);
221 json_object *j = drawing_name_json_argument(label);
224 /* send the request */
226 this->api_call("request_surface", j, [&rc](bool ok, json_object *j) {
229 json_object_get_int(json_object_object_get(j, "response"));
231 asprintf(&buf, "%d", id);
232 printf("setenv(\"QT_IVI_SURFACE_ID\", %s, 1)\n", buf);
233 if (setenv("QT_IVI_SURFACE_ID", buf, 1) != 0) {
234 fprintf(stderr, "putenv failed: %m\n");
237 rc = 0; // Single point of success
240 fprintf(stderr, "Could not get surface ID from WM: %s\n",
241 j != nullptr ? json_object_to_json_string_ext(
242 j, JSON_C_TO_STRING_PRETTY)
253 this->labels.insert(this->labels.end(), label);
259 int AFBClient::Impl::activateSurface(const char *label) {
261 json_object *j = drawing_name_json_argument(label);
262 return this->api_call("activate_surface", j, [](bool ok, json_object *j) {
264 fprintf(stderr, "API Call activate_surface() failed: %s\n",
265 j != nullptr ? json_object_to_json_string_ext(
266 j, JSON_C_TO_STRING_PRETTY)
272 int AFBClient::Impl::deactivateSurface(const char *label) {
274 json_object *j = drawing_name_json_argument(label);
275 return this->api_call("deactivate_surface", j, [](bool ok, json_object *j) {
277 fprintf(stderr, "API Call deactivate_surface() failed: %s\n",
278 j != nullptr ? json_object_to_json_string_ext(
279 j, JSON_C_TO_STRING_PRETTY)
285 int AFBClient::Impl::endDraw(const char *label) {
287 json_object *j = drawing_name_json_argument(label);
288 return this->api_call("enddraw", j, [](bool ok, json_object *j) {
290 fprintf(stderr, "API Call endDraw() failed: %s\n",
291 j != nullptr ? json_object_to_json_string_ext(
292 j, JSON_C_TO_STRING_PRETTY)
298 void AFBClient::Impl::set_event_handler(
299 enum EventType et, std::function<void(char const *)> func) {
302 if (et >= 1 && et <= 6) { // Yeah ... just go with it!
303 this->handlers[et] = std::move(func);
308 std::pair<bool, AFBClient::EventType> make_event_type(char const *et) {
309 // Event have the form "$API/$EVENT", just try to find the first / and
311 char const *et2 = strchr(et, '/');
312 if (et2 != nullptr) {
318 if (strcasecmp(et, N) == 0) \
319 return std::pair<bool, AFBClient::EventType>( \
320 true, CONCAT(AFBClient::Event_, A)); \
323 ET("activated", Active);
324 ET("deactivated", Inactive);
325 ET("visible", Visible);
326 ET("invisible", Invisible);
327 ET("syncdraw", SyncDraw);
328 ET("flushdraw", FlushDraw);
331 return std::pair<bool, AFBClient::EventType>(false,
332 AFBClient::Event_Active);
336 /// object will be json_object_put
337 int AFBClient::Impl::api_call(
338 const char *verb, json_object *object,
339 const std::function<void(bool, json_object *)> &onReply) {
342 // We need to wrap the actual onReply call once in order to
343 // *look* like a normal functions pointer (std::functions<>
344 // with captures cannot convert to function pointers).
345 // Alternatively we could setup a local struct and use it as
346 // closure, but I think it is cleaner this way.
348 std::atomic<bool> returned{};
349 returned.store(false, std::memory_order_relaxed);
350 std::function<void(bool, json_object *)> wrappedOnReply =
351 [&returned, &call_rc, &onReply](bool ok, json_object *j) {
352 TRACEN(wrappedOnReply);
353 call_rc = ok ? 0 : -EINVAL;
354 // We know it failed, but there may be an explanation in the
360 returned.store(true, std::memory_order_release);
363 // make the actual call, use wrappedOnReply as closure
364 int rc = afb_wsj1_call_j(
365 this->wsj1, wmAPI, verb, object,
366 [](void *closure, afb_wsj1_msg *msg) {
369 reinterpret_cast<std::function<void(bool, json_object *)> *>(
371 (*onReply)(!(afb_wsj1_msg_is_reply_ok(msg) == 0),
372 afb_wsj1_msg_object_j(msg));
378 stderr, "calling %s/%s(%s) failed: %m\n", wmAPI, verb,
379 json_object_to_json_string_ext(object, JSON_C_TO_STRING_PRETTY));
380 // Call the reply handler regardless with a NULL json_object*
381 onReply(false, nullptr);
383 // We need to dispatch until "returned" got set, this is necessary
384 // if events get triggered by the call (and would be dispatched before
385 // the actual call-reply).
386 while (!returned.load(std::memory_order_consume)) {
387 std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
388 if (!returned.load(std::memory_order_consume)) {
389 this->dispatch_internal();
393 // return the actual API call result
400 void AFBClient::Impl::dispatch_internal() {
401 std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
403 sd_event_run(this->loop, -1);
406 void AFBClient::Impl::event(char const *et, char const *label) {
408 auto oet = make_event_type(et);
410 fprintf(stderr, "Unknown event type string '%s'\n", et);
414 auto i = this->handlers.find(oet.second);
415 if (i != this->handlers.end()) {
416 if (this->labels.find(label) != this->labels.end()) {
422 // _ _ _____ ____ ____ _ _ _
423 // ___| | __ _ ___ ___ / \ | ___| __ ) / ___| (_) ___ _ __ | |_
424 // / __| |/ _` / __/ __| / _ \ | |_ | _ \| | | | |/ _ \ '_ \| __|
425 // | (__| | (_| \__ \__ \ / ___ \| _| | |_) | |___| | | __/ | | | |_
426 // \___|_|\__,_|___/___/ /_/ \_\_| |____/ \____|_|_|\___|_| |_|\__|
428 int AFBClient::init(int port, char const *token) {
429 return this->d->init(port, token);
432 int AFBClient::dispatch() { return this->d->dispatch(); }
434 int AFBClient::requestSurface(const char *label) {
435 return this->d->requestSurface(label);
438 int AFBClient::activateSurface(const char *label) {
439 return this->d->activateSurface(label);
442 int AFBClient::deactivateSurface(const char *label) {
443 return this->d->deactivateSurface(label);
446 int AFBClient::endDraw(const char *label) { return this->d->endDraw(label); }
448 void AFBClient::set_event_handler(enum EventType et,
449 std::function<void(char const *label)> f) {
450 return this->d->set_event_handler(et, std::move(f));
453 AFBClient &AFBClient::instance() {
455 static AFBClient obj;
459 AFBClient::AFBClient() : d(new Impl) {}
461 AFBClient::~AFBClient() { delete d; }