app/afbclient: use the correct names for active/inactive events
[staging/windowmanager.git] / client-lib / AFBClient.cpp
1 /*
2  * Copyright (C) 2017 Mentor Graphics Development (Deutschland) GmbH
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include "AFBClient.h"
18
19 #include <cassert>
20 #include <cctype>
21 #include <cerrno>
22 #include <cstdio>
23 #include <cstdlib>
24 #include <cstring>
25
26 #include <atomic>
27 #include <map>
28 #include <mutex>
29 #include <set>
30
31 #include <unistd.h>
32
33 #include <systemd/sd-event.h>
34
35 #include <json-c/json.h>
36
37 extern "C" {
38 #include <afb/afb-ws-client.h>
39 #include <afb/afb-wsj1.h>
40 }
41
42 #define UNUSED(x) (void)(x)
43
44 //       _                 ___                 _
45 //   ___| | __ _ ___ ___  |_ _|_ __ ___  _ __ | |
46 //  / __| |/ _` / __/ __|  | || '_ ` _ \| '_ \| |
47 // | (__| | (_| \__ \__ \  | || | | | | | |_) | |
48 //  \___|_|\__,_|___/___/ |___|_| |_| |_| .__/|_|
49 //                                      |_|
50 class AFBClient::Impl {
51     friend class AFBClient;
52
53     // This is the AFBClient interface impl
54     int init(int port, char const *token);
55     int dispatch();
56
57     // WM API
58     int requestSurface(const char *label);
59     int activateSurface(const char *label);
60     int deactivateSurface(const char *label);
61     int endDraw(const char *label);
62
63     void set_event_handler(enum EventType et, handler_fun func);
64
65     Impl();
66     ~Impl();
67
68     struct afb_wsj1 *wsj1;
69     struct sd_event *loop;
70
71     std::set<std::string> labels;
72     std::map<EventType, handler_fun> handlers;
73
74     int api_call(const char *verb, json_object *object,
75                  const std::function<void(bool, json_object *)> &onReply);
76     void dispatch_internal();
77
78 public:
79     void event(char const *et, char const *label);
80 };
81
82 namespace {
83
84 constexpr const int token_maxlen = 20;
85 constexpr const char *const wmAPI = "winman";
86
87 #ifdef NDEBUG
88 #define TRACE()
89 #define TRACEN(N)
90 #else
91 #define CONCAT_(X, Y) X##Y
92 #define CONCAT(X, Y) CONCAT_(X, Y)
93
94 #define TRACE() \
95     ScopeTrace __attribute__((unused)) CONCAT(trace_scope_, __LINE__)(__func__)
96 #define TRACEN(N) \
97     ScopeTrace __attribute__((unused)) CONCAT(named_trace_scope_, __LINE__)(#N)
98
99 struct ScopeTrace {
100     thread_local static int indent;
101     char const *f{};
102     explicit ScopeTrace(char const *func) : f(func) {
103         fprintf(stderr, "%*s%s -->\n", 2 * indent++, "", this->f);
104     }
105     ~ScopeTrace() { fprintf(stderr, "%*s%s <--\n", 2 * --indent, "", this->f); }
106 };
107 thread_local int ScopeTrace::indent = 0;
108 #endif
109
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) {
113     TRACE();
114     UNUSED(closure);
115     UNUSED(verb);
116     UNUSED(api);
117     UNUSED(msg);
118 }
119
120 /* called when wsj1 receives an event */
121 void onEvent(void *closure, const char *event, afb_wsj1_msg *msg) {
122     TRACE();
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")));
126 }
127
128 /* called when wsj1 hangsup */
129 void onHangup(void *closure, afb_wsj1 *wsj1) {
130     TRACE();
131     UNUSED(closure);
132     UNUSED(wsj1);
133     fputs("Hangup, the WindowManager vanished\n", stderr);
134     exit(1);  // XXX: there should be something ... *better* here.
135 }
136
137 constexpr struct afb_wsj1_itf itf = {
138     onHangup, onCall, onEvent,
139 };
140
141 // XXX: I am not sure this is the right thing to do though...
142 std::recursive_mutex dispatch_mutex;
143
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));
147     return j;
148 }
149
150 }  // namespace
151
152 //       _                 ___                 _   _                 _
153 //   ___| | __ _ ___ ___  |_ _|_ __ ___  _ __ | | (_)_ __ ___  _ __ | |
154 //  / __| |/ _` / __/ __|  | || '_ ` _ \| '_ \| | | | '_ ` _ \| '_ \| |
155 // | (__| | (_| \__ \__ \  | || | | | | | |_) | | | | | | | | | |_) | |
156 //  \___|_|\__,_|___/___/ |___|_| |_| |_| .__/|_| |_|_| |_| |_| .__/|_|
157 //                                      |_|                   |_|
158 AFBClient::Impl::Impl() : wsj1{}, loop{}, labels(), handlers() { TRACE(); }
159
160 AFBClient::Impl::~Impl() {
161     TRACE();
162     afb_wsj1_unref(wsj1);
163     sd_event_unref(loop);
164 }
165
166 int AFBClient::Impl::init(int port, char const *token) {
167     TRACE();
168     char *uribuf = nullptr;
169     int rc = -1;
170
171     if (this->loop != nullptr && this->wsj1 != nullptr) {
172         fputs("AFBClient instance is already initialized!\n", stderr);
173         rc = -EALREADY;
174         goto fail;
175     }
176
177     if ((token == nullptr) || strlen(token) > token_maxlen) {
178         fputs("Token is invalid\n", stderr);
179         rc = -EINVAL;
180         goto fail;
181     }
182
183     for (char const *p = token; *p != 0; p++) {
184         if (isalnum(*p) == 0) {
185             fputs("Token is invalid\n", stderr);
186             rc = -EINVAL;
187             goto fail;
188         }
189     }
190
191     if (port < 1 || port > 0xffff) {
192         fputs("Port is invalid\n", stderr);
193         rc = -EINVAL;
194         goto fail;
195     }
196
197     /* get the default event loop */
198     rc = sd_event_default(&this->loop);
199     if (rc < 0) {
200         fprintf(stderr, "Connection to default event loop failed: %s\n",
201                 strerror(-rc));
202         goto fail;
203     }
204
205     asprintf(&uribuf, "ws://localhost:%d/api?token=%s", port, token);
206
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);
214         rc = -errno;
215         goto fail;
216     }
217
218     return 0;
219
220 fail:
221     return rc;
222 }
223
224 int AFBClient::Impl::dispatch() {
225     std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
226     return sd_event_run(this->loop, 1);
227 }
228
229 int AFBClient::Impl::requestSurface(const char *label) {
230     TRACE();
231
232     if (this->labels.find(label) != this->labels.end()) {
233         fputs("Surface label already known!\n", stderr);
234         return -EINVAL;
235     }
236
237     json_object *j = drawing_name_json_argument(label);
238
239     int rc = -1;
240     /* send the request */
241     int rc2 =
242         this->api_call("request_surface", j, [&rc](bool ok, json_object *j) {
243             if (ok) {
244                 int id =
245                     json_object_get_int(json_object_object_get(j, "response"));
246                 char *buf;
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");
251                     rc = -errno;
252                 } else {
253                     rc = 0;  // Single point of success
254                 }
255             } else {
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)
259                                      : "no-info");
260                 rc = -EINVAL;
261             }
262         });
263
264     if (rc2 < 0) {
265         rc = rc2;
266     }
267
268     if (rc >= 0) {
269         this->labels.insert(this->labels.end(), label);
270     }
271
272     return rc;
273 }
274
275 int AFBClient::Impl::activateSurface(const char *label) {
276     TRACE();
277     json_object *j = drawing_name_json_argument(label);
278     return this->api_call("activate_surface", j, [](bool ok, json_object *j) {
279         if (!ok) {
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)
283                                  : "no-info");
284         }
285     });
286 }
287
288 int AFBClient::Impl::deactivateSurface(const char *label) {
289     TRACE();
290     json_object *j = drawing_name_json_argument(label);
291     return this->api_call("deactivate_surface", j, [](bool ok, json_object *j) {
292         if (!ok) {
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)
296                                  : "no-info");
297         }
298     });
299 }
300
301 int AFBClient::Impl::endDraw(const char *label) {
302     TRACE();
303     json_object *j = drawing_name_json_argument(label);
304     return this->api_call("enddraw", j, [](bool ok, json_object *j) {
305         if (!ok) {
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)
309                                  : "no-info");
310         }
311     });
312 }
313
314 void AFBClient::Impl::set_event_handler(
315     enum EventType et, std::function<void(char const *)> func) {
316     TRACE();
317
318     if (et >= 1 && et <= 6) {  // Yeah ... just go with it!
319         this->handlers[et] = std::move(func);
320     }
321 }
322
323 namespace {
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
326     // get on with it.
327     char const *et2 = strchr(et, '/');
328     if (et2 != nullptr) {
329         et = et2 + 1;
330     }
331
332 #define ET(N, A)                                          \
333     do {                                                  \
334         if (strcasecmp(et, N) == 0)                       \
335             return std::pair<bool, AFBClient::EventType>( \
336                 true, CONCAT(AFBClient::Event_, A));      \
337     } while (false)
338
339     ET("active", Active);
340     ET("inactive", Inactive);
341     ET("visible", Visible);
342     ET("invisible", Invisible);
343     ET("syncdraw", SyncDraw);
344     ET("flushdraw", FlushDraw);
345 #undef ET
346
347     return std::pair<bool, AFBClient::EventType>(false,
348                                                  AFBClient::Event_Active);
349 }
350 }  // namespace
351
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) {
356     TRACE();
357
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.
363     int call_rc = 0;
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
371             // json object.
372             {
373                 TRACEN(onReply);
374                 onReply(ok, j);
375             }
376             returned.store(true, std::memory_order_release);
377         };
378
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) {
383             TRACEN(callClosure);
384             auto *onReply =
385                 reinterpret_cast<std::function<void(bool, json_object *)> *>(
386                     closure);
387             (*onReply)(!(afb_wsj1_msg_is_reply_ok(msg) == 0),
388                        afb_wsj1_msg_object_j(msg));
389         },
390         &wrappedOnReply);
391
392     if (rc < 0) {
393         fprintf(
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);
398     } else {
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();
406             }
407         }
408
409         // return the actual API call result
410         rc = call_rc;
411     }
412
413     return rc;
414 }
415
416 void AFBClient::Impl::dispatch_internal() {
417     std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
418     TRACE();
419     sd_event_run(this->loop, -1);
420 }
421
422 void AFBClient::Impl::event(char const *et, char const *label) {
423     TRACE();
424     auto oet = make_event_type(et);
425     if (!oet.first) {
426         fprintf(stderr, "Unknown event type string '%s'\n", et);
427         return;
428     }
429
430     auto i = this->handlers.find(oet.second);
431     if (i != this->handlers.end()) {
432         if (this->labels.find(label) != this->labels.end()) {
433             i->second(label);
434         }
435     }
436 }
437
438 //       _                    _    _____ ____   ____ _ _            _
439 //   ___| | __ _ ___ ___     / \  |  ___| __ ) / ___| (_) ___ _ __ | |_
440 //  / __| |/ _` / __/ __|   / _ \ | |_  |  _ \| |   | | |/ _ \ '_ \| __|
441 // | (__| | (_| \__ \__ \  / ___ \|  _| | |_) | |___| | |  __/ | | | |_
442 //  \___|_|\__,_|___/___/ /_/   \_\_|   |____/ \____|_|_|\___|_| |_|\__|
443 //
444 int AFBClient::init(int port, char const *token) {
445     return this->d->init(port, token);
446 }
447
448 int AFBClient::dispatch() { return this->d->dispatch(); }
449
450 int AFBClient::requestSurface(const char *label) {
451     return this->d->requestSurface(label);
452 }
453
454 int AFBClient::activateSurface(const char *label) {
455     return this->d->activateSurface(label);
456 }
457
458 int AFBClient::deactivateSurface(const char *label) {
459     return this->d->deactivateSurface(label);
460 }
461
462 int AFBClient::endDraw(const char *label) { return this->d->endDraw(label); }
463
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));
467 }
468
469 AFBClient &AFBClient::instance() {
470     TRACE();
471     static AFBClient obj;
472     return obj;
473 }
474
475 AFBClient::AFBClient() : d(new Impl) {}
476
477 AFBClient::~AFBClient() { delete d; }