2 * Copyright (C) 2017 Mentor Graphics Development (Deutschland) GmbH
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "AFBClient.h"
33 #include <systemd/sd-event.h>
35 #include <json-c/json.h>
38 #include <afb/afb-ws-client.h>
39 #include <afb/afb-wsj1.h>
42 #define UNUSED(x) (void)(x)
45 // ___| | __ _ ___ ___ |_ _|_ __ ___ _ __ | |
46 // / __| |/ _` / __/ __| | || '_ ` _ \| '_ \| |
47 // | (__| | (_| \__ \__ \ | || | | | | | |_) | |
48 // \___|_|\__,_|___/___/ |___|_| |_| |_| .__/|_|
50 class AFBClient::Impl {
51 friend class AFBClient;
53 // This is the AFBClient interface impl
54 int init(int port, char const *token);
58 int requestSurface(const char *label);
59 int activateSurface(const char *label);
60 int deactivateSurface(const char *label);
61 int endDraw(const char *label);
63 void set_event_handler(enum EventType et, handler_fun func);
68 struct afb_wsj1 *wsj1;
69 struct sd_event *loop;
71 std::set<std::string> labels;
72 std::map<EventType, handler_fun> handlers;
74 int api_call(const char *verb, json_object *object,
75 const std::function<void(bool, json_object *)> &onReply);
76 void dispatch_internal();
79 void event(char const *et, char const *label);
84 constexpr const int token_maxlen = 20;
85 constexpr const char *const wmAPI = "winman";
91 #define CONCAT_(X, Y) X##Y
92 #define CONCAT(X, Y) CONCAT_(X, Y)
95 ScopeTrace __attribute__((unused)) CONCAT(trace_scope_, __LINE__)(__func__)
97 ScopeTrace __attribute__((unused)) CONCAT(named_trace_scope_, __LINE__)(#N)
100 thread_local static int indent;
102 explicit ScopeTrace(char const *func) : f(func) {
103 fprintf(stderr, "%*s%s -->\n", 2 * indent++, "", this->f);
105 ~ScopeTrace() { fprintf(stderr, "%*s%s <--\n", 2 * --indent, "", this->f); }
107 thread_local int ScopeTrace::indent = 0;
110 /* called when wsj1 receives a method invocation */
111 void onCall(void *closure, const char *api, const char *verb,
112 struct afb_wsj1_msg *msg) {
120 /* called when wsj1 receives an event */
121 void onEvent(void *closure, const char *event, afb_wsj1_msg *msg) {
123 reinterpret_cast<AFBClient::Impl *>(closure)->event(
124 event, json_object_get_string(
125 json_object_object_get(afb_wsj1_msg_object_j(msg), "data")));
128 /* called when wsj1 hangsup */
129 void onHangup(void *closure, afb_wsj1 *wsj1) {
133 fputs("Hangup, the WindowManager vanished\n", stderr);
134 exit(1); // XXX: there should be something ... *better* here.
137 constexpr struct afb_wsj1_itf itf = {
138 onHangup, onCall, onEvent,
141 // XXX: I am not sure this is the right thing to do though...
142 std::recursive_mutex dispatch_mutex;
144 json_object *drawing_name_json_argument(char const *label) {
145 json_object *j = json_object_new_object();
146 json_object_object_add(j, "drawing_name", json_object_new_string(label));
153 // ___| | __ _ ___ ___ |_ _|_ __ ___ _ __ | | (_)_ __ ___ _ __ | |
154 // / __| |/ _` / __/ __| | || '_ ` _ \| '_ \| | | | '_ ` _ \| '_ \| |
155 // | (__| | (_| \__ \__ \ | || | | | | | |_) | | | | | | | | | |_) | |
156 // \___|_|\__,_|___/___/ |___|_| |_| |_| .__/|_| |_|_| |_| |_| .__/|_|
158 AFBClient::Impl::Impl() : wsj1{}, loop{}, labels(), handlers() { TRACE(); }
160 AFBClient::Impl::~Impl() {
162 afb_wsj1_unref(wsj1);
163 sd_event_unref(loop);
166 int AFBClient::Impl::init(int port, char const *token) {
168 char *uribuf = nullptr;
171 if (this->loop != nullptr && this->wsj1 != nullptr) {
172 fputs("AFBClient instance is already initialized!\n", stderr);
177 if ((token == nullptr) || strlen(token) > token_maxlen) {
178 fputs("Token is invalid\n", stderr);
183 for (char const *p = token; *p != 0; p++) {
184 if (isalnum(*p) == 0) {
185 fputs("Token is invalid\n", stderr);
191 if (port < 1 || port > 0xffff) {
192 fputs("Port is invalid\n", stderr);
197 /* get the default event loop */
198 rc = sd_event_default(&this->loop);
200 fprintf(stderr, "Connection to default event loop failed: %s\n",
205 asprintf(&uribuf, "ws://localhost:%d/api?token=%s", port, token);
207 /* connect the websocket wsj1 to the uri given by the first argument */
208 this->wsj1 = afb_ws_client_connect_wsj1(
209 this->loop, uribuf, const_cast<struct afb_wsj1_itf *>(&itf), this);
210 if (this->wsj1 == nullptr) {
211 sd_event_unref(this->loop);
212 this->loop = nullptr;
213 fprintf(stderr, "Connection to %s failed: %m\n", uribuf);
224 int AFBClient::Impl::dispatch() {
225 std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
226 return sd_event_run(this->loop, 1);
229 int AFBClient::Impl::requestSurface(const char *label) {
232 if (this->labels.find(label) != this->labels.end()) {
233 fputs("Surface label already known!\n", stderr);
237 json_object *j = drawing_name_json_argument(label);
240 /* send the request */
242 this->api_call("request_surface", j, [&rc](bool ok, json_object *j) {
245 json_object_get_int(json_object_object_get(j, "response"));
247 asprintf(&buf, "%d", id);
248 printf("setenv(\"QT_IVI_SURFACE_ID\", %s, 1)\n", buf);
249 if (setenv("QT_IVI_SURFACE_ID", buf, 1) != 0) {
250 fprintf(stderr, "putenv failed: %m\n");
253 rc = 0; // Single point of success
256 fprintf(stderr, "Could not get surface ID from WM: %s\n",
257 j != nullptr ? json_object_to_json_string_ext(
258 j, JSON_C_TO_STRING_PRETTY)
269 this->labels.insert(this->labels.end(), label);
275 int AFBClient::Impl::activateSurface(const char *label) {
277 json_object *j = drawing_name_json_argument(label);
278 return this->api_call("activate_surface", j, [](bool ok, json_object *j) {
280 fprintf(stderr, "API Call activate_surface() failed: %s\n",
281 j != nullptr ? json_object_to_json_string_ext(
282 j, JSON_C_TO_STRING_PRETTY)
288 int AFBClient::Impl::deactivateSurface(const char *label) {
290 json_object *j = drawing_name_json_argument(label);
291 return this->api_call("deactivate_surface", j, [](bool ok, json_object *j) {
293 fprintf(stderr, "API Call deactivate_surface() failed: %s\n",
294 j != nullptr ? json_object_to_json_string_ext(
295 j, JSON_C_TO_STRING_PRETTY)
301 int AFBClient::Impl::endDraw(const char *label) {
303 json_object *j = drawing_name_json_argument(label);
304 return this->api_call("enddraw", j, [](bool ok, json_object *j) {
306 fprintf(stderr, "API Call endDraw() failed: %s\n",
307 j != nullptr ? json_object_to_json_string_ext(
308 j, JSON_C_TO_STRING_PRETTY)
314 void AFBClient::Impl::set_event_handler(
315 enum EventType et, std::function<void(char const *)> func) {
318 if (et >= 1 && et <= 6) { // Yeah ... just go with it!
319 this->handlers[et] = std::move(func);
324 std::pair<bool, AFBClient::EventType> make_event_type(char const *et) {
325 // Event have the form "$API/$EVENT", just try to find the first / and
327 char const *et2 = strchr(et, '/');
328 if (et2 != nullptr) {
334 if (strcasecmp(et, N) == 0) \
335 return std::pair<bool, AFBClient::EventType>( \
336 true, CONCAT(AFBClient::Event_, A)); \
339 ET("activated", Active);
340 ET("deactivated", Inactive);
341 ET("visible", Visible);
342 ET("invisible", Invisible);
343 ET("syncdraw", SyncDraw);
344 ET("flushdraw", FlushDraw);
347 return std::pair<bool, AFBClient::EventType>(false,
348 AFBClient::Event_Active);
352 /// object will be json_object_put
353 int AFBClient::Impl::api_call(
354 const char *verb, json_object *object,
355 const std::function<void(bool, json_object *)> &onReply) {
358 // We need to wrap the actual onReply call once in order to
359 // *look* like a normal functions pointer (std::functions<>
360 // with captures cannot convert to function pointers).
361 // Alternatively we could setup a local struct and use it as
362 // closure, but I think it is cleaner this way.
364 std::atomic<bool> returned{};
365 returned.store(false, std::memory_order_relaxed);
366 std::function<void(bool, json_object *)> wrappedOnReply =
367 [&returned, &call_rc, &onReply](bool ok, json_object *j) {
368 TRACEN(wrappedOnReply);
369 call_rc = ok ? 0 : -EINVAL;
370 // We know it failed, but there may be an explanation in the
376 returned.store(true, std::memory_order_release);
379 // make the actual call, use wrappedOnReply as closure
380 int rc = afb_wsj1_call_j(
381 this->wsj1, wmAPI, verb, object,
382 [](void *closure, afb_wsj1_msg *msg) {
385 reinterpret_cast<std::function<void(bool, json_object *)> *>(
387 (*onReply)(!(afb_wsj1_msg_is_reply_ok(msg) == 0),
388 afb_wsj1_msg_object_j(msg));
394 stderr, "calling %s/%s(%s) failed: %m\n", wmAPI, verb,
395 json_object_to_json_string_ext(object, JSON_C_TO_STRING_PRETTY));
396 // Call the reply handler regardless with a NULL json_object*
397 onReply(false, nullptr);
399 // We need to dispatch until "returned" got set, this is necessary
400 // if events get triggered by the call (and would be dispatched before
401 // the actual call-reply).
402 while (!returned.load(std::memory_order_consume)) {
403 std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
404 if (!returned.load(std::memory_order_consume)) {
405 this->dispatch_internal();
409 // return the actual API call result
416 void AFBClient::Impl::dispatch_internal() {
417 std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
419 sd_event_run(this->loop, -1);
422 void AFBClient::Impl::event(char const *et, char const *label) {
424 auto oet = make_event_type(et);
426 fprintf(stderr, "Unknown event type string '%s'\n", et);
430 auto i = this->handlers.find(oet.second);
431 if (i != this->handlers.end()) {
432 if (this->labels.find(label) != this->labels.end()) {
438 // _ _ _____ ____ ____ _ _ _
439 // ___| | __ _ ___ ___ / \ | ___| __ ) / ___| (_) ___ _ __ | |_
440 // / __| |/ _` / __/ __| / _ \ | |_ | _ \| | | | |/ _ \ '_ \| __|
441 // | (__| | (_| \__ \__ \ / ___ \| _| | |_) | |___| | | __/ | | | |_
442 // \___|_|\__,_|___/___/ /_/ \_\_| |____/ \____|_|_|\___|_| |_|\__|
444 int AFBClient::init(int port, char const *token) {
445 return this->d->init(port, token);
448 int AFBClient::dispatch() { return this->d->dispatch(); }
450 int AFBClient::requestSurface(const char *label) {
451 return this->d->requestSurface(label);
454 int AFBClient::activateSurface(const char *label) {
455 return this->d->activateSurface(label);
458 int AFBClient::deactivateSurface(const char *label) {
459 return this->d->deactivateSurface(label);
462 int AFBClient::endDraw(const char *label) { return this->d->endDraw(label); }
464 void AFBClient::set_event_handler(enum EventType et,
465 std::function<void(char const *label)> f) {
466 return this->d->set_event_handler(et, std::move(f));
469 AFBClient &AFBClient::instance() {
471 static AFBClient obj;
475 AFBClient::AFBClient() : d(new Impl) {}
477 AFBClient::~AFBClient() { delete d; }