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