0452d16b868df5ddea046b92b601ca7990bfc7fb
[staging/windowmanager.git] / AFBClient.cpp
1 #include "AFBClient.h"
2
3 #include <cassert>
4 #include <cctype>
5 #include <cerrno>
6 #include <cstdio>
7 #include <cstdlib>
8 #include <cstring>
9
10 #include <mutex>
11
12 #include <unistd.h>
13
14 #include <systemd/sd-event.h>
15
16 #include <json-c/json.h>
17
18 extern "C" {
19 #include <afb/afb-ws-client.h>
20 #include <afb/afb-wsj1.h>
21 }
22
23 #define UNUSED(x) (void)(x)
24
25 namespace {
26
27 constexpr const int token_maxlen = 20;
28 constexpr const char *const wmAPI = "winman";
29
30 #ifdef NDEBUG
31 #define TRACE()
32 #define TRACEN(N)
33 #else
34 #define CONCAT_(X, Y) X##Y
35 #define CONCAT(X, Y) CONCAT_(X, Y)
36
37 #define TRACE() \
38     ScopeTrace __attribute__((unused)) CONCAT(trace_scope_, __LINE__)(__func__)
39 #define TRACEN(N) \
40     ScopeTrace __attribute__((unused)) CONCAT(named_trace_scope_, __LINE__)(#N)
41
42 struct ScopeTrace {
43     thread_local static int indent;
44     char const *f{};
45     ScopeTrace(char const *func) : f(func) {
46         fprintf(stderr, "%*s%s -->\n", 2 * indent++, "", this->f);
47     }
48     ~ScopeTrace() { fprintf(stderr, "%*s%s <--\n", 2 * --indent, "", this->f); }
49 };
50 thread_local int ScopeTrace::indent = 0;
51 #endif
52
53 /* called when wsj1 receives a method invocation */
54 void onCall(void *closure, const char *api, const char *verb,
55             struct afb_wsj1_msg *msg) {
56     TRACE();
57     UNUSED(closure);
58     int rc;
59     printf("ON-CALL %s/%s:\n%s\n", api, verb,
60            json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
61                                           JSON_C_TO_STRING_PRETTY));
62     fflush(stdout);
63     rc = afb_wsj1_reply_error_s(msg, "\"unimplemented\"", nullptr);
64     if (rc < 0)
65         fprintf(stderr, "replying failed: %m\n");
66 }
67
68 /* called when wsj1 receives an event */
69 void onEvent(void *closure, const char *event, afb_wsj1_msg *msg) {
70     TRACE();
71     UNUSED(closure);
72     printf("ON-EVENT %s:\n%s\n", event,
73            json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
74                                           JSON_C_TO_STRING_PRETTY));
75     fflush(stdout);
76 }
77
78 /* called when wsj1 hangsup */
79 void onHangup(void *closure, afb_wsj1 *wsj1) {
80     TRACE();
81     UNUSED(closure);
82     UNUSED(wsj1);
83     printf("ON-HANGUP\n");
84     fflush(stdout);
85     exit(0);
86 }
87
88 static struct afb_wsj1_itf itf = {
89     onHangup, onCall, onEvent,
90 };
91
92 std::recursive_mutex dispatch_mutex;
93
94 void dispatch_internal(struct sd_event *loop) {
95     std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
96     TRACE();
97     sd_event_run(loop, -1);
98 }
99
100 /// object will be json_object_put
101 int api_call(struct sd_event *loop, struct afb_wsj1 *wsj1, const char *verb,
102              json_object *object,
103              std::function<void(bool, json_object *)> onReply) {
104     TRACE();
105
106     // We need to wrap the actual onReply call once in order to
107     // *look* like a normal functions pointer (std::functions<>
108     // with captures cannot convert to function pointers).
109     // Alternatively we could setup a local struct and use it as
110     // closure, but I think it is cleaner this way.
111     int call_rc = 0;
112     bool returned = false;
113     std::function<void(bool, json_object *)> wrappedOnReply =
114         [&returned, &call_rc, &onReply](bool ok, json_object *j) {
115             TRACEN(wrappedOnReply);
116             call_rc = ok ? 0 : -EINVAL;
117             // We know it failed, but there may be an explanation in the
118             // json object.
119             {
120                 TRACEN(onReply);
121                 onReply(ok, j);
122             }
123             returned = true;
124         };
125
126     // make the actual call, use wrappedOnReply as closure
127     int rc = afb_wsj1_call_j(
128         wsj1, wmAPI, verb, object,
129         [](void *closure, afb_wsj1_msg *msg) {
130             TRACEN(callClosure);
131             auto *onReply =
132                 reinterpret_cast<std::function<void(bool, json_object *)> *>(
133                     closure);
134             (*onReply)(!!afb_wsj1_msg_is_reply_ok(msg),
135                        afb_wsj1_msg_object_j(msg));
136         },
137         &wrappedOnReply);
138
139     if (rc < 0) {
140         fprintf(
141             stderr, "calling %s/%s(%s) failed: %m\n", wmAPI, verb,
142             json_object_to_json_string_ext(object, JSON_C_TO_STRING_PRETTY));
143         // Call the reply handler regardless with a NULL json_object*
144         onReply(false, nullptr);
145     } else {
146         // We need to dispatch until "returned" got set, this is necessary
147         // if events get triggered by the call (and would be dispatched before
148         // the actual call-reply).
149         while (!returned) {
150             dispatch_internal(loop);
151         }
152
153         // return the actual API call result
154         rc = call_rc;
155     }
156
157     return rc;
158 }
159
160 }  // namespace
161
162 AFBClient &AFBClient::instance() {
163     TRACE();
164     static AFBClient obj;
165     return obj;
166 }
167
168 AFBClient::AFBClient() : wsj1{}, loop{} { TRACE(); }
169
170 AFBClient::~AFBClient() {
171     TRACE();
172     afb_wsj1_unref(wsj1);
173     sd_event_unref(loop);
174     loop = nullptr;
175 }
176
177 int AFBClient::init(int port, char const *token) {
178     TRACE();
179     char *uribuf = nullptr;
180     int rc = -1;
181
182     if (!token || strlen(token) > token_maxlen) {
183         fprintf(stderr, "Token is invalid\n");
184         rc = -EINVAL;
185         goto fail;
186     }
187
188     for (char const *p = token; *p; p++) {
189         if (!isalnum(*p)) {
190             fprintf(stderr, "Token is invalid\n");
191             rc = -EINVAL;
192             goto fail;
193         }
194     }
195
196     if (port < 1 && port > 0xffff) {
197         fprintf(stderr, "Port is invalid\n");
198         rc = -EINVAL;
199         goto fail;
200     }
201
202     /* get the default event loop */
203     rc = sd_event_default(&loop);
204     if (rc < 0) {
205         fprintf(stderr, "Connection to default event loop failed: %s\n",
206                 strerror(-rc));
207         goto fail;
208     }
209
210     asprintf(&uribuf, "ws://localhost:%d/api?token=%s", port, token);
211
212     /* connect the websocket wsj1 to the uri given by the first argument */
213     wsj1 = afb_ws_client_connect_wsj1(loop, uribuf, &itf, nullptr);
214     if (wsj1 == nullptr) {
215         sd_event_unref(loop);
216         fprintf(stderr, "Connection to %s failed: %m\n", uribuf);
217         rc = -errno;
218         goto fail;
219     }
220
221     return 0;
222
223 fail:
224     return rc;
225 }
226
227 int AFBClient::dispatch() {
228     std::lock_guard<std::recursive_mutex> guard(dispatch_mutex);
229     return sd_event_run(loop, 1);
230 }
231
232 int AFBClient::requestSurface(const char *label) {
233     TRACE();
234     json_object *jp = json_object_new_object();
235     json_object_object_add(jp, "drawing_name", json_object_new_string(label));
236     int rc = -1;
237     /* send the request */
238     int rc2 = api_call(
239         loop, wsj1, "request_surface", jp, [&rc](bool ok, json_object *j) {
240             if (ok) {
241                 int id =
242                     json_object_get_int(json_object_object_get(j, "response"));
243                 char *buf;
244                 asprintf(&buf, "%d", id);
245                 printf("setenv(\"QT_IVI_SURFACE_ID\", %s, 1)\n", buf);
246                 if (setenv("QT_IVI_SURFACE_ID", buf, 1) != 0) {
247                     fprintf(stderr, "putenv failed: %m\n");
248                     rc = -errno;
249                 } else {
250                     rc = 0;  // Single point of success
251                 }
252             } else {
253                 fprintf(stderr, "Could not get surface ID from WM: %s\n",
254                         j ? json_object_to_json_string_ext(
255                                 j, JSON_C_TO_STRING_PRETTY)
256                           : "no-info");
257                 rc = -EINVAL;
258             }
259         });
260
261     return rc2 < 0 ? rc2 : rc;
262 }
263
264 int AFBClient::activateSurface(const char *label) {
265     TRACE();
266     json_object *j = json_object_new_object();
267     json_object_object_add(j, "drawing_name", json_object_new_string(label));
268     return api_call(loop, wsj1, "activate_surface", j, [](bool ok,
269                                                           json_object *j) {
270         if (!ok) {
271             fprintf(
272                 stderr, "API Call activate_surface() failed: %s\n",
273                 j ? json_object_to_json_string_ext(j, JSON_C_TO_STRING_PRETTY)
274                   : "no-info");
275         }
276     });
277 }
278
279 int AFBClient::deactivateSurface(const char *label) {
280     TRACE();
281     json_object *j = json_object_new_object();
282     json_object_object_add(j, "drawing_name", json_object_new_string(label));
283     return api_call(loop, wsj1, "deactivate_surface", j, [](bool ok,
284                                                             json_object *j) {
285         if (!ok) {
286             fprintf(
287                 stderr, "API Call deactivate_surface() failed: %s\n",
288                 j ? json_object_to_json_string_ext(j, JSON_C_TO_STRING_PRETTY)
289                   : "no-info");
290         }
291     });
292 }
293
294 int AFBClient::endDraw(const char *label) {
295     TRACE();
296     json_object *j = json_object_new_object();
297     json_object_object_add(j, "drawing_name", json_object_new_string(label));
298     return api_call(loop, wsj1, "enddraw", j, [](bool ok, json_object *j) {
299         if (!ok) {
300             fprintf(
301                 stderr, "API Call endDraw() failed: %s\n",
302                 j ? json_object_to_json_string_ext(j, JSON_C_TO_STRING_PRETTY)
303                   : "no-info");
304         }
305     });
306 }
307
308 void AFBClient::set_event_handler(enum EventType et,
309                                   std::function<void(char const *)> func) {
310     UNUSED(et);
311     UNUSED(func);
312     TRACE();
313     // XXX todo
314 }