app: use id_shift of 22, just like in Qt
[staging/windowmanager.git] / src / app.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 "app.hpp"
18 #include "json_helper.hpp"
19 #include "layers.hpp"
20 #include "layout.hpp"
21 #include "util.hpp"
22 #include "wayland.hpp"
23
24 #include <cstdio>
25 #include <memory>
26
27 #include <cassert>
28
29 #include <json-c/json.h>
30
31 #include <algorithm>
32 #include <bits/signum.h>
33 #include <csignal>
34 #include <fstream>
35 #include <json.hpp>
36
37 namespace wm {
38
39 namespace {
40 App *g_app;
41
42 using json = nlohmann::json;
43
44 struct wm::area area_from_json(json const &j) {
45    return wm::area{
46       j["name"],
47       {
48          j["width"], j["height"], j["x"], j["y"],
49       },
50       j["zorder"],
51    };
52 }
53
54 result<struct layout> layout_from_json(json const &j) {
55    auto &ja = j["areas"];
56
57    auto l = layout{j["name"], uint32_t(ja.size()), {}};
58
59    if (ja.size() > layout::MAX_N_AREAS) {
60       return Err<struct layout>("Invalid number of areas in layout");
61    }
62
63    logdebug("Loading layout '%s' with %u areas", l.name.c_str(),
64             unsigned(ja.size()));
65
66    std::transform(std::cbegin(ja), std::cend(ja), std::begin(l.areas),
67                   area_from_json);
68
69    return Ok(l);
70 }
71
72 result<json> file_to_json(char const *filename) {
73    std::ifstream i(filename);
74    if (i.fail()) {
75       return Err<json>("Could not open config file");
76    }
77    json j;
78    i >> j;
79    return Ok(j);
80 }
81
82 // Will throw if parsing fails
83 struct result<layouts_type> load_layout(char const *filename) {
84    logdebug("loading layout from %s", filename);
85
86    auto j = file_to_json(filename);
87    if (j.is_err()) {
88       return Err<layouts_type>(j.unwrap_err());
89    }
90    json jlayouts = j.unwrap();
91
92    auto layouts = layouts_type();
93    layouts.reserve(jlayouts.size());
94    std::transform(std::cbegin(jlayouts), std::cend(jlayouts),
95                   std::back_inserter(layouts), layout_from_json);
96
97    return Ok(layouts);
98 }
99
100 struct result<layer_map>
101    load_layer_map(char const *filename) {
102    logdebug("loading IDs from %s", filename);
103
104    auto j = file_to_json(filename);
105    if (j.is_err()) {
106       return Err<layer_map>(j.unwrap_err());
107    }
108    json jids = j.unwrap();
109
110    return to_layer_map(jids);
111 }
112
113 }  // namespace
114
115 //       _                    _                  _                 _
116 //   ___| | __ _ ___ ___     / \   _ __  _ __   (_)_ __ ___  _ __ | |
117 //  / __| |/ _` / __/ __|   / _ \ | '_ \| '_ \  | | '_ ` _ \| '_ \| |
118 // | (__| | (_| \__ \__ \  / ___ \| |_) | |_) | | | | | | | | |_) | |
119 //  \___|_|\__,_|___/___/ /_/   \_\ .__/| .__/  |_|_| |_| |_| .__/|_|
120 //                                |_|   |_|                 |_|
121 App::App(wl::display *d)
122    : api{this},
123      chooks{this},
124      display{d},
125      controller{},
126      outputs(),
127      config(),
128      layouts(),
129      layers(),
130      pending(),
131      name_mapping(),
132      id_alloc{},
133      last_active() {
134    assert(g_app == nullptr);
135    g_app = this;
136
137    try {
138       {
139          auto l = load_layer_map(
140             this->config.get_string("layers.json").value().c_str());
141          if (l.is_ok()) {
142             this->layers = l.unwrap();
143          } else {
144             logerror("%s", l.err().value());
145          }
146       }
147
148       {
149          auto l =
150             load_layout(this->config.get_string("layout.json").value().c_str());
151          if (l.is_ok()) {
152             this->layouts = l.unwrap();
153          } else {
154             logerror("%s", l.err().value());
155          }
156       }
157    } catch (std::exception &e) {
158       logerror("Loading of configuration failed: %s", e.what());
159    }
160 }
161
162 App::~App() { g_app = nullptr; }
163
164 int App::init() {
165    if (!this->display->ok()) {
166       return -1;
167    }
168
169    if (this->layers.mapping.empty()) {
170       logerror("No surface -> layer mapping loaded");
171       return -1;
172    }
173
174    this->display->add_global_handler(
175       "wl_output", [this](wl_registry *r, uint32_t name, uint32_t v) {
176          this->outputs.emplace_back(std::make_unique<wl::output>(r, name, v));
177       });
178
179    this->display->add_global_handler(
180       "ivi_controller", [this](wl_registry *r, uint32_t name, uint32_t v) {
181          this->controller = std::make_unique<struct genivi::controller>(r, name, v);
182
183          // Init controller hooks
184          this->controller->chooks = &this->chooks;
185
186          // XXX: This protocol needs the output, so lets just add our mapping
187          // here...
188          this->controller->add_proxy_to_id_mapping(
189             this->outputs.back()->proxy.get(),
190             wl_proxy_get_id(reinterpret_cast<struct wl_proxy *>(
191                this->outputs.back()->proxy.get())));
192       });
193
194    // First level objects
195    this->display->roundtrip();
196    // Second level objects
197    this->display->roundtrip();
198    // Third level objects
199    this->display->roundtrip();
200
201    return init_layout();
202 }
203
204 int App::dispatch_events() {
205    int ret = this->display->dispatch();
206    if (ret == -1) {
207       logerror("wl_display_dipatch() returned error %d",
208                this->display->get_error());
209       return -1;
210    }
211    this->display->flush();
212
213    // execute pending tasks, that is layout changes etc.
214    this->execute_pending();
215
216    return 0;
217 }
218
219 //  _       _ _       _                         _    ____
220 // (_)_ __ (_) |_    | | __ _ _   _  ___  _   _| |_ / /\ \
221 // | | '_ \| | __|   | |/ _` | | | |/ _ \| | | | __| |  | |
222 // | | | | | | |_    | | (_| | |_| | (_) | |_| | |_| |  | |
223 // |_|_| |_|_|\__|___|_|\__,_|\__, |\___/ \__,_|\__| |  | |
224 //              |_____|       |___/                 \_\/_/
225 int App::init_layout() {
226    if (!this->controller) {
227       logerror("ivi_controller global not available");
228       return -1;
229    }
230
231    if (this->outputs.empty()) {
232       logerror("no output was set up!");
233       return -1;
234    }
235
236    auto &c = this->controller;
237
238    auto &o = this->outputs.front();
239    auto &s = c->screens.begin()->second;
240    auto &layers = c->layers;
241
242    // XXX: Write output dimensions to ivi controller...
243    c->output_size = genivi::size{uint32_t(o->width), uint32_t(o->height)};
244
245    // Clear scene
246    layers.clear();
247
248    // Clear screen
249    s->clear();
250
251    // Quick and dirty setup of layers
252    // XXX: This likely needs to be sorted by order (note, we don't (yet?)
253    // do any zorder arrangement).
254    for (auto const &i : this->layers.mapping) {
255       c->layer_create(i.layer_id, o->width, o->height);
256       auto &l = layers[i.layer_id];
257       l->set_destination_rectangle(0, 0, o->width, o->height);
258       l->set_visibility(1);
259       logdebug("Setting up layer %s (%d) for surfaces %d-%d", i.name.c_str(),
260                i.layer_id, i.id_min, i.id_max);
261    }
262
263    // Add layers to screen (XXX: are they sorted correctly?)
264    s->set_render_order(this->layers.layers);
265
266    c->commit_changes();
267
268    this->display->flush();
269
270    return 0;
271 }
272
273 void App::surface_set_layout(uint32_t surface_id) {
274    if (!this->controller->surface_exists(surface_id)) {
275       logerror("Surface %d does not exist", int(surface_id));
276       return;
277    }
278
279    auto o_layer_id = this->layers.get_layer_id(surface_id);
280
281    if (!o_layer_id) {
282       logerror("Surface %d is not associated with any layer!", int(surface_id));
283       return;
284    }
285
286    uint32_t layer_id = o_layer_id.value();
287    logdebug("surface_set_layout for surface %u on layer %u", surface_id,
288             layer_id);
289
290    auto const &layer = this->layers.get_layer(layer_id);
291    auto rect = layer.value().rect;
292    auto &s = this->controller->surfaces[surface_id];
293
294    int x = rect.x;
295    int y = rect.y;
296    int w = rect.w;
297    int h = rect.h;
298
299    // less-than-0 values refer to MAX + 1 - $VALUE
300    // e.g. MAX is either screen width or height
301    if (w < 0) {
302       w = this->controller->output_size.w + 1 + w;
303    }
304    if (h < 0) {
305       h = this->controller->output_size.h + 1 + h;
306    }
307
308    // configure surface to wxh dimensions
309    s->set_configuration(w, h);
310    // set source reactangle, even if we should not need to set it.
311    s->set_source_rectangle(0, 0, w, h);
312    // set destination to the display rectangle
313    s->set_destination_rectangle(x, y, w, h);
314
315    // XXX: The main_surface will be visible regardless
316    s->set_visibility(
317       surface_id == static_cast<unsigned>(this->layers.main_surface) ? 1 : 0);
318    this->controller->layers[layer_id]->add_surface(s.get());
319
320    logdebug("Surface %u now on layer %u with rect { %d, %d, %d, %d }",
321             surface_id, layer_id, x, y, w, h);
322 }
323
324 char const *App::activate_surface(uint32_t surface_id) {
325    if (!this->controller->surface_exists(surface_id)) {
326       return "Surface does not exist";
327    }
328
329    // This should involve a policy check, but as we do not (yet) have
330    // such a thing, we will just switch to this surface.
331    // XXX: input focus missing!!1
332
333    // Make it visible, no (or little effect) if already visible
334    auto &s = this->controller->surfaces[surface_id];
335
336    // Set all others invisible
337    for (auto &i : this->controller->surfaces) {
338       auto &si = this->controller->sprops[i.second->id];
339       if (si.visibility == 1 && si.id != s->id &&
340           int(si.id) != this->layers.main_surface) {
341          i.second->set_visibility(0);
342       }
343    }
344    s->set_visibility(1);
345
346    // commit changes
347    this->controller->commit_changes();
348    this->display->flush();
349
350    // Current active surface is the first in last_active
351    this->last_active.push_front(s->id);
352    /// // XXX: I am not sure I even need 5 elements...
353    /// this->last_active.resize(std::min(int(this->last_active.size()), 5));
354
355    // no error
356    return nullptr;
357 }
358
359 char const *App::deactivate_surface(uint32_t surface_id) {
360    if (surface_id == this->layers.main_surface) {
361       return "Cannot deactivate main_surface";
362    }
363
364    if (this->last_active.empty()) {
365       return "Cannot deactivate surface (not active)";
366    }
367
368    // XXX: should an active surface not alsways be front() or
369    // front+1() of last_active?!
370
371    // XXX: Should I really be able to deactivate a surface that is not
372    // front() of last_active?
373    auto is = std::find(this->last_active.begin(),
374                        this->last_active.end(),
375                        surface_id);
376
377    if (is == this->last_active.end()) {
378       return "Cannot deactivate surface (not active)";
379    }
380
381    this->last_active.erase(is);
382
383    if (! this->last_active.empty()) {
384       // Should be active already, shouldn't it?
385       this->activate_surface(this->last_active.front());
386    } else {
387       this->activate_surface(this->layers.main_surface);
388    }
389
390    return nullptr;
391 }
392
393 void App::add_task(char const *name, std::function<void()> &&f) {
394    this->pending.emplace_back(std::make_pair(name, f));
395 }
396
397 void App::execute_pending() {
398    if (!this->pending.empty()) {
399       for (auto &t : this->pending) {
400          logdebug("executing task '%s'", t.first);
401          t.second();
402       }
403       this->pending.clear();
404       this->controller->commit_changes();
405       this->display->flush();
406    }
407 }
408
409 //                      _          _   _____                 _
410 //  _ __  _ __ _____  _(_) ___  __| | | ____|_   _____ _ __ | |_ ___
411 // | '_ \| '__/ _ \ \/ / |/ _ \/ _` | |  _| \ \ / / _ \ '_ \| __/ __|
412 // | |_) | | | (_) >  <| |  __/ (_| | | |___ \ V /  __/ | | | |_\__ \
413 // | .__/|_|  \___/_/\_\_|\___|\__,_| |_____| \_/ \___|_| |_|\__|___/
414 // |_|
415 void App::surface_created(uint32_t surface_id) {
416    surface_id >>= id_allocator::id_shift;
417
418    logdebug("surface_id is %u", surface_id);
419
420    // We need to execute the surface setup after its creation.
421    this->add_task("surface_set_layout",
422                   [surface_id, this] { this->surface_set_layout(surface_id); });
423 }
424
425 void App::surface_removed(uint32_t surface_id) {
426    surface_id >>= id_allocator::id_shift;
427
428    logdebug("surface_id is %u", surface_id);
429
430    this->add_task("remove surface ID",
431                   [surface_id, this] {
432                      this->id_alloc.remove_id(surface_id);
433
434                      // Also remove from last_active, if found
435                      auto i = std::find(this->last_active.begin(),
436                                         this->last_active.end(), surface_id);
437                      if (i != this->last_active.end()) {
438                         this->last_active.erase(i);
439                      }
440                   });
441 }
442
443 void App::emit_activated(char const *label) {
444    this->api.send_event("activated", json_object_new_string(label));
445 }
446
447 void App::emit_deactivated(char const *label) {
448    this->api.send_event("deactivated", json_object_new_string(label));
449 }
450
451 void App::emit_syncdraw(char const *label) {
452    this->api.send_event("syncdraw", json_object_new_string(label));
453 }
454
455 void App::emit_visible(char const *label, bool is_visible) {
456    this->api.send_event(is_visible ? "visible" : "invisible", json_object_new_string(label));
457 }
458
459 result<int> App::request_surface(char const *drawing_name) {
460    auto lid = this->layers.get_layer_id(std::string(drawing_name));
461    if (!lid) {
462       // XXX: to we need to put these applications on the App layer?
463       return Err<int>("Drawing name does not match any role");
464    }
465
466    auto rname = this->id_alloc.lookup(drawing_name);
467    if (!rname) {
468       // name does not exist yet, allocate surface id...
469       auto id = int(this->id_alloc.generate_id(drawing_name));
470       this->layers.add_surface(id, lid.value());
471
472       // XXX: you should fix this!
473       if (!this->layers.main_surface_name.empty() &&
474           this->layers.main_surface_name == drawing_name) {
475          this->layers.main_surface = id;
476          this->activate_surface(id);
477          logdebug("Set main_surface id to %u", id);
478       }
479
480       return Ok<int>(id);
481    }
482
483    // Check currently registered drawing names if it is already there.
484    return Err<int>("Surface already present");
485 }
486
487 char const *App::activate_surface(char const *drawing_name) {
488    auto osid = this->id_alloc.lookup(drawing_name);
489
490    if (osid) {
491       logdebug("ativate surface with name %s and id %u", drawing_name,
492                osid.value());
493       auto ret = this->activate_surface(osid.value());
494       if (!ret) {
495          this->emit_activated(drawing_name);
496       }
497       return ret;
498    }
499
500    logerror("surface %s unknown", drawing_name);
501    return "Surface unknown";
502 }
503
504 char const *App::deactivate_surface(char const *drawing_name) {
505    auto osid = this->id_alloc.lookup(drawing_name);
506
507    if (osid) {
508       logdebug("deativate surface with name %s and id %u", drawing_name,
509                osid.value());
510       return this->deactivate_surface(osid.value());
511    }
512
513    logerror("surface %s unknown", drawing_name);
514    return "Surface unknown";
515 }
516
517 //  _     _           _ _                            _   _                 _
518 // | |__ (_)_ __   __| (_)_ __   __ _     __ _ _ __ (_) (_)_ __ ___  _ __ | |
519 // | '_ \| | '_ \ / _` | | '_ \ / _` |   / _` | '_ \| | | | '_ ` _ \| '_ \| |
520 // | |_) | | | | | (_| | | | | | (_| |  | (_| | |_) | | | | | | | | | |_) | |
521 // |_.__/|_|_| |_|\__,_|_|_| |_|\__, |___\__,_| .__/|_| |_|_| |_| |_| .__/|_|
522 //                              |___/_____|   |_|                   |_|
523 binding_api::result_type binding_api::request_surface(
524    char const *drawing_name) {
525    auto r = this->app->request_surface(drawing_name);
526    if (r.is_err()) {
527       return Err<json_object *>(r.unwrap_err());
528    }
529    return Ok(json_object_new_int(r.unwrap()));
530 }
531
532 binding_api::result_type binding_api::activate_surface(
533    char const *drawing_name) {
534    logdebug("%s drawing_name %s", __func__, drawing_name);
535    auto r = this->app->activate_surface(drawing_name);
536    if (r != nullptr) {
537       return Err<json_object *>(r);
538    }
539    return Ok(json_object_new_object());
540 }
541
542 binding_api::result_type binding_api::deactivate_surface(char const* drawing_name) {
543    logdebug("%s drawing_name %s", __func__, drawing_name);
544    auto r = this->app->deactivate_surface(drawing_name);
545    if (r != nullptr) {
546       return Err<json_object *>(r);
547    }
548    return Ok(json_object_new_object());
549 }
550
551 binding_api::result_type binding_api::enddraw(char const* drawing_name) {
552    logdebug("%s drawing_name %s", __func__, drawing_name);
553    return Err<json_object*>("not implemented");
554 }
555
556 binding_api::result_type binding_api::list_drawing_names() {
557    logdebug("%s", __func__);
558    json j = this->app->id_alloc.names;
559    return Ok(json_tokener_parse(j.dump().c_str()));
560 }
561
562 binding_api::result_type binding_api::debug_layers() {
563    logdebug("%s", __func__);
564    return Ok(json_tokener_parse(this->app->layers.to_json().dump().c_str()));
565 }
566
567 binding_api::result_type binding_api::debug_surfaces() {
568    logdebug("%s", __func__);
569    return Ok(to_json(this->app->controller->sprops));
570 }
571
572 binding_api::result_type binding_api::debug_status() {
573    logdebug("%s", __func__);
574    json_object *jr = json_object_new_object();
575    json_object_object_add(jr, "surfaces",
576                           to_json(this->app->controller->sprops));
577    json_object_object_add(jr, "layers", to_json(this->app->controller->lprops));
578    return Ok(jr);
579 }
580
581 binding_api::result_type binding_api::debug_terminate() {
582    logdebug("%s", __func__);
583    raise(SIGKILL);  // XXX afb-daemon kills it's pgroup using TERM, which
584                     // doesn't play well with perf
585    return Ok(json_object_new_object());
586 }
587
588 binding_api::result_type binding_api::demo_activate_surface(
589    uint32_t surfaceid) {
590    char const *e = this->app->activate_surface(surfaceid);
591    if (e != nullptr) {
592       return Err<json_object *>(e);
593    }
594    return Ok(json_object_new_object());
595 }
596
597 binding_api::result_type binding_api::demo_activate_all() {
598    for (auto &s : this->app->controller->surfaces) {
599       s.second->set_visibility(1);
600    }
601    this->app->controller->commit_changes();
602    this->app->display->flush();
603    return Ok(json_object_new_object());
604 }
605
606 //                  _             _ _            _                 _
607 //   ___ ___  _ __ | |_ _ __ ___ | | | ___ _ __ | |__   ___   ___ | | _____
608 //  / __/ _ \| '_ \| __| '__/ _ \| | |/ _ \ '__|| '_ \ / _ \ / _ \| |/ / __|
609 // | (_| (_) | | | | |_| | | (_) | | |  __/ |   | | | | (_) | (_) |   <\__ \
610 //  \___\___/|_| |_|\__|_|  \___/|_|_|\___|_|___|_| |_|\___/ \___/|_|\_\___/
611 //                                         |_____|
612 void controller_hooks::surface_created(uint32_t surface_id) {
613    this->app->surface_created(surface_id);
614 }
615
616 void controller_hooks::surface_removed(uint32_t surface_id) {
617    this->app->surface_removed(surface_id);
618 }
619
620 void controller_hooks::add_task(char const *name, std::function<void()> &&f) {
621    this->app->add_task(name, std::move(f));
622 }
623
624 }  // namespace wm