App/layers: deactivate surfaces on layers above.
[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 #include <regex>
37 #include <thread>
38
39 namespace wm {
40
41 namespace {
42 App *g_app;
43
44 using nlohmann::json;
45
46 result<json> file_to_json(char const *filename) {
47    std::ifstream i(filename);
48    if (i.fail()) {
49       return Err<json>("Could not open config file");
50    }
51    json j;
52    i >> j;
53    return Ok(j);
54 }
55
56 struct result<layer_map>
57    load_layer_map(char const *filename) {
58    logdebug("loading IDs from %s", filename);
59
60    auto j = file_to_json(filename);
61    if (j.is_err()) {
62       return Err<layer_map>(j.unwrap_err());
63    }
64    json jids = j.unwrap();
65
66    return to_layer_map(jids);
67 }
68
69 }  // namespace
70
71 //       _                    _                  _                 _
72 //   ___| | __ _ ___ ___     / \   _ __  _ __   (_)_ __ ___  _ __ | |
73 //  / __| |/ _` / __/ __|   / _ \ | '_ \| '_ \  | | '_ ` _ \| '_ \| |
74 // | (__| | (_| \__ \__ \  / ___ \| |_) | |_) | | | | | | | | |_) | |
75 //  \___|_|\__,_|___/___/ /_/   \_\ .__/| .__/  |_|_| |_| |_| .__/|_|
76 //                                |_|   |_|                 |_|
77 App::App(wl::display *d)
78    : api{this},
79      chooks{this},
80      display{d},
81      controller{},
82      outputs(),
83      config(),
84      layouts(),
85      layers(),
86      id_alloc{},
87      pending_events(false) {
88    assert(g_app == nullptr);
89    g_app = this;
90
91    try {
92       {
93          auto l = load_layer_map(
94             this->config.get_string("layers.json").value().c_str());
95          if (l.is_ok()) {
96             this->layers = l.unwrap();
97          } else {
98             logerror("%s", l.err().value());
99          }
100       }
101    } catch (std::exception &e) {
102       logerror("Loading of configuration failed: %s", e.what());
103    }
104 }
105
106 App::~App() { g_app = nullptr; }
107
108 int App::init() {
109    if (!this->display->ok()) {
110       return -1;
111    }
112
113    if (this->layers.mapping.empty()) {
114       logerror("No surface -> layer mapping loaded");
115       return -1;
116    }
117
118    this->display->add_global_handler(
119       "wl_output", [this](wl_registry *r, uint32_t name, uint32_t v) {
120          this->outputs.emplace_back(std::make_unique<wl::output>(r, name, v));
121       });
122
123    this->display->add_global_handler(
124       "ivi_controller", [this](wl_registry *r, uint32_t name, uint32_t v) {
125          this->controller =
126             std::make_unique<struct genivi::controller>(r, name, v);
127
128          // Init controller hooks
129          this->controller->chooks = &this->chooks;
130
131          // XXX: This protocol needs the output, so lets just add our mapping
132          // here...
133          this->controller->add_proxy_to_id_mapping(
134             this->outputs.back()->proxy.get(),
135             wl_proxy_get_id(reinterpret_cast<struct wl_proxy *>(
136                this->outputs.back()->proxy.get())));
137       });
138
139    // First level objects
140    this->display->roundtrip();
141    // Second level objects
142    this->display->roundtrip();
143    // Third level objects
144    this->display->roundtrip();
145
146    return init_layers();
147 }
148
149 int App::dispatch_events() {
150    if (this->dispatch_events() == 0) {
151       return 0;
152    }
153
154    int ret = this->display->dispatch();
155    if (ret == -1) {
156       logerror("wl_display_dipatch() returned error %d",
157                this->display->get_error());
158       return -1;
159    }
160    this->display->flush();
161
162    return 0;
163 }
164
165 int App::dispatch_pending_events() {
166    if (this->pop_pending_events()) {
167       this->display->dispatch_pending();
168       return 0;
169    }
170    return -1;
171 }
172
173 //  _       _ _       _                         _    ____
174 // (_)_ __ (_) |_    | | __ _ _   _  ___  _   _| |_ / /\ \
175 // | | '_ \| | __|   | |/ _` | | | |/ _ \| | | | __| |  | |
176 // | | | | | | |_    | | (_| | |_| | (_) | |_| | |_| |  | |
177 // |_|_| |_|_|\__|___|_|\__,_|\__, |\___/ \__,_|\__| |  | |
178 //              |_____|       |___/                 \_\/_/
179 int App::init_layers() {
180    if (!this->controller) {
181       logerror("ivi_controller global not available");
182       return -1;
183    }
184
185    if (this->outputs.empty()) {
186       logerror("no output was set up!");
187       return -1;
188    }
189
190    auto &c = this->controller;
191
192    auto &o = this->outputs.front();
193    auto &s = c->screens.begin()->second;
194    auto &layers = c->layers;
195
196    // XXX: Write output dimensions to ivi controller...
197    c->output_size = genivi::size{uint32_t(o->width), uint32_t(o->height)};
198
199    // Clear scene
200    layers.clear();
201
202    // Clear screen
203    s->clear();
204
205    // Quick and dirty setup of layers
206    // XXX: This likely needs to be sorted by order (note, we don't (yet?)
207    // do any zorder arrangement).
208    for (auto const &i : this->layers.mapping) {
209       c->layer_create(i.layer_id, o->width, o->height);
210       auto &l = layers[i.layer_id];
211       l->set_destination_rectangle(0, 0, o->width, o->height);
212       l->set_visibility(1);
213       logdebug("Setting up layer %s (%d) for surfaces %d-%d and role match \"%s\"", i.name.c_str(),
214                i.layer_id, i.id_min, i.id_max, i.role.c_str());
215       this->layouts[l->id] = LayoutState{};
216    }
217
218    // Add layers to screen (XXX: are they sorted correctly?)
219    s->set_render_order(this->layers.layers);
220
221    c->commit_changes();
222
223    this->display->flush();
224
225    return 0;
226 }
227
228 namespace {
229
230 #ifdef WE_LIKE_NOT_TO_USE_THIS
231 // This can fix the HomeScreen...
232 void redraw_fix(App *app, std::unique_ptr<genivi::surface> &s, int x, int y,
233                 int w, int h) {
234    {  // XXX: Work around weston redraw issues
235       // trigger an update by changing the source dimensions!
236       s->set_configuration(w + 1, h);
237       s->set_source_rectangle(0, 0, w + 1, h);
238       s->set_destination_rectangle(x, y, w + 1, h);
239       app->controller->commit_changes();
240       app->display->roundtrip();
241
242       // wait some time, for the process to do its thing...
243       using namespace std::chrono_literals;
244       std::this_thread::sleep_for(100ms);
245
246       // Set a different size then what we actually want.
247       s->set_configuration(w, h);
248       s->set_source_rectangle(0, 0, w, h);
249       s->set_destination_rectangle(x, y, w, h);
250       app->controller->commit_changes();
251       app->display->roundtrip();
252    }
253 }
254 #endif
255
256 }  // namespace
257
258 void App::surface_set_layout_full(uint32_t surface_id) {
259    if (!this->controller->surface_exists(surface_id)) {
260       logerror("Surface %d does not exist", int(surface_id));
261       return;
262    }
263
264    auto o_layer_id = this->layers.get_layer_id(surface_id);
265
266    if (!o_layer_id) {
267       logerror("Surface %d is not associated with any layer!", int(surface_id));
268       return;
269    }
270
271    uint32_t layer_id = o_layer_id.value();
272    logdebug("surface_set_layout for surface %u on layer %u", surface_id,
273             layer_id);
274
275    auto const &layer = this->layers.get_layer(layer_id);
276    auto rect = layer.value().rect;
277    auto &s = this->controller->surfaces[surface_id];
278
279    int x = rect.x;
280    int y = rect.y;
281    int w = rect.w;
282    int h = rect.h;
283
284    // less-than-0 values refer to MAX + 1 - $VALUE
285    // e.g. MAX is either screen width or height
286    if (w < 0) {
287       w = this->controller->output_size.w + 1 + w;
288    }
289    if (h < 0) {
290       h = this->controller->output_size.h + 1 + h;
291    }
292
293    // configure surface to wxh dimensions
294    s->set_configuration(w, h);
295
296    // set source reactangle, even if we should not need to set it.
297    s->set_source_rectangle(0, 0, w, h);
298
299    // set destination to the display rectangle
300    s->set_destination_rectangle(x, y, w, h);
301
302    //redraw_fix(this, s, x, y, w, h);
303
304    logdebug("Surface %u now with rect { %d, %d, %d, %d }",
305             surface_id, x, y, w, h);
306 }
307
308 void App::surface_set_layout_split(uint32_t surface_id, uint32_t sub_surface_id) {
309    if (!this->controller->surface_exists(surface_id)) {
310       logerror("Surface %d does not exist", int(surface_id));
311       return;
312    }
313
314    auto o_layer_id = this->layers.get_layer_id(surface_id);
315
316    if (!o_layer_id) {
317       logerror("Surface %d is not associated with any layer!", int(surface_id));
318       return;
319    }
320
321    uint32_t layer_id = o_layer_id.value();
322    logdebug("surface_set_layout for surface %u on layer %u", surface_id,
323             layer_id);
324
325    auto const &layer = this->layers.get_layer(layer_id);
326    auto rect = layer.value().rect;
327    auto &s = this->controller->surfaces[surface_id];
328    auto &ss = this->controller->surfaces[sub_surface_id];
329
330    int x = rect.x;
331    int y = rect.y;
332    int w = rect.w;
333    int h = rect.h;
334
335    // less-than-0 values refer to MAX + 1 - $VALUE
336    // e.g. MAX is either screen width or height
337    if (w < 0) {
338       w = this->controller->output_size.w + 1 + w;
339    }
340    if (h < 0) {
341       h = this->controller->output_size.h + 1 + h;
342    }
343
344    int x_off = 0;
345    int y_off = 0;
346
347    // split along major axis
348    if (w > h) {
349       w /= 2;
350       x_off = w;
351    } else {
352       h /= 2;
353       y_off = h;
354    }
355
356    // configure surface to wxh dimensions
357    s->set_configuration(w, h);
358    // set source reactangle, even if we should not need to set it.
359    s->set_source_rectangle(0, 0, w, h);
360    // set destination to the display rectangle
361    s->set_destination_rectangle(x, y, w, h);
362
363    // configure surface to wxh dimensions
364    ss->set_configuration(w, h);
365    // set source reactangle, even if we should not need to set it.
366    ss->set_source_rectangle(0, 0, w, h);
367    // set destination to the display rectangle
368    ss->set_destination_rectangle(x+x_off, y+y_off, w, h);
369
370    //redraw_fix(this, s, x, y, w, h);
371    //redraw_fix(this, ss, x+x_off, y+y_off, w, h);
372
373    logdebug("Surface %u now on layer %u with rect { %d, %d, %d, %d }",
374             surface_id, layer_id, x, y, w, h);
375 }
376
377 char const *App::activate_surface(char const *drawing_name) {
378    ST();
379    auto const &surface_id = this->lookup_id(drawing_name);
380
381    if (!surface_id) {
382       return "Surface does not exist";
383    }
384
385    if (!this->controller->surface_exists(*surface_id)) {
386       return "Surface does not exist in controller!";
387    }
388
389    auto layer_id = *this->layers.get_layer_id(*surface_id);
390    struct LayoutState &state = **this->layers.get_layout_state(*surface_id);
391
392    logdebug("state @ %p = { %d, %d, %d }", &state, state.main, state.sub, state.s);
393
394    // disable layers that are above our current layer
395    for (auto const &l : this->layers.mapping) {
396       if (l.layer_id <= layer_id) {
397          continue;
398       }
399
400       bool flush = false;
401       if (l.state.main != -1) {
402          this->deactivate(l.state.main);
403          l.state.main = -1;
404          flush = true;
405       }
406
407       if (l.state.sub != -1) {
408          this->deactivate(l.state.sub);
409          l.state.sub = -1;
410          flush = true;
411       }
412
413       l.state.s = LayoutState::Single;
414
415       if (flush) {
416          this->controller->commit_changes();
417          this->display->flush();
418       }
419    }
420
421    if (state.main == *surface_id || state.sub == *surface_id) {
422       return "Surface already active";
423    }
424
425    // This should involve a policy check, but as we do not (yet) have
426    // such a thing, we will just switch to this surface.
427    // XXX: input focus missing!!1
428
429    if (state.main == -1) {
430       this->emit_syncdraw(drawing_name);
431
432       this->surface_set_layout_full(*surface_id);
433       this->activate(*surface_id);
434       state.main = *surface_id;
435       state.sub = -1;
436       state.s = LayoutState::Single;
437
438       this->emit_flushdraw(drawing_name);
439    } else {
440       bool can_split = this->can_split(state, *surface_id);
441
442       if (state.sub == -1) {
443          if (can_split) {
444             if (state.main != *surface_id) {
445                this->emit_syncdraw(drawing_name);
446                this->emit_syncdraw(this->lookup_name(state.main)->c_str());
447
448                this->surface_set_layout_split(state.main, *surface_id);
449                this->activate(*surface_id);
450                state.sub = *surface_id;
451
452                // Should wait for EndDraw event...
453                this->emit_flushdraw(drawing_name);
454                this->emit_flushdraw(this->lookup_name(state.main)->c_str());
455             }
456          } else {
457             this->emit_syncdraw(drawing_name);
458
459             this->surface_set_layout_full(*surface_id);
460             this->deactivate(state.main);
461             this->activate(*surface_id);
462             this->deactivate(state.sub);
463             state.main = *surface_id;
464             state.sub = -1;
465             state.s = LayoutState::Single;
466
467             this->emit_flushdraw(drawing_name);
468          }
469       }
470    }
471
472    // commit changes
473    this->controller->commit_changes();
474    this->display->flush();
475
476    // no error
477    return nullptr;
478 }
479
480 char const *App::deactivate_surface(char const *drawing_name) {
481    ST();
482    auto const &surface_id = this->lookup_id(drawing_name);
483
484    if (!surface_id) {
485       return "Surface does not exist";
486    }
487
488    if (*surface_id == this->layers.main_surface) {
489       return "Cannot deactivate main_surface";
490    }
491
492    struct LayoutState &state = **this->layers.get_layout_state(*surface_id);
493
494    if (state.main == -1) {
495       return "No surface active";
496    }
497
498    if (*surface_id == this->layers.main_surface) {
499       logdebug("Refusing to deactivate main_surface %d", *surface_id);
500       return nullptr;
501    }
502
503    logdebug("state @ %p = { %d, %d, %d }", &state, state.main, state.sub, state.s);
504
505    if (state.main == *surface_id) {
506       if (state.sub != -1) {
507          this->emit_syncdraw(this->lookup_name(state.sub)->c_str());
508
509          this->deactivate(*surface_id);
510          this->surface_set_layout_full(state.sub);
511          state.main = state.sub;
512          state.sub = -1;
513          state.s = LayoutState::Single;
514
515          this->emit_flushdraw(this->lookup_name(state.sub)->c_str());
516       } else {
517          this->deactivate(*surface_id);
518          state.main = -1;
519       }
520    }else if (state.sub == *surface_id) {
521       this->emit_syncdraw(this->lookup_name(state.main)->c_str());
522
523       this->deactivate(*surface_id);
524       this->deactivate(*surface_id);
525       this->surface_set_layout_full(state.main);
526       state.sub = -1;
527       state.s = LayoutState::Single;
528
529       this->emit_flushdraw(this->lookup_name(state.main)->c_str());
530    } else {
531       return "Surface is not active";
532    }
533
534    this->controller->commit_changes();
535    this->display->flush();
536
537    return nullptr;
538 }
539
540 //                      _          _   _____                 _
541 //  _ __  _ __ _____  _(_) ___  __| | | ____|_   _____ _ __ | |_ ___
542 // | '_ \| '__/ _ \ \/ / |/ _ \/ _` | |  _| \ \ / / _ \ '_ \| __/ __|
543 // | |_) | | | (_) >  <| |  __/ (_| | | |___ \ V /  __/ | | | |_\__ \
544 // | .__/|_|  \___/_/\_\_|\___|\__,_| |_____| \_/ \___|_| |_|\__|___/
545 // |_|
546 void App::surface_created(uint32_t surface_id) {
547    auto layer_id = this->layers.get_layer_id(surface_id);
548    logdebug("surface_id is %u, layer_id is %u", surface_id, layer_id ? *layer_id : -1u);
549
550    this->controller->layers[*layer_id]
551            ->add_surface(this->controller->surfaces[surface_id].get());
552
553    // activate the main_surface right away
554    if (surface_id == static_cast<unsigned>(this->layers.main_surface)) {
555       logdebug("Activating main_surface (%d)", surface_id);
556
557       this->activate_surface(
558               this->lookup_name(surface_id).value_or("unknown-name").c_str());
559    }
560 }
561
562 void App::surface_removed(uint32_t surface_id) {
563    logdebug("surface_id is %u", surface_id);
564
565    this->id_alloc.remove_id(surface_id);
566 }
567
568 void App::emit_activated(char const *label) {
569    this->api.send_event("activated", label);
570 }
571
572 void App::emit_deactivated(char const *label) {
573    this->api.send_event("deactivated", label);
574 }
575
576 void App::emit_syncdraw(char const *label) {
577    this->api.send_event("syncdraw", label);
578 }
579
580 void App::emit_flushdraw(char const *label) {
581    this->api.send_event("syncdraw", label);
582 }
583
584 void App::emit_visible(char const *label, bool is_visible) {
585    this->api.send_event(is_visible ? "visible" : "invisible", label);
586 }
587
588 void App::emit_invisible(char const *label) { return emit_visible(label, false); }
589
590 void App::emit_visible(char const *label) { return emit_visible(label, true); }
591
592 result<int> App::request_surface(char const *drawing_name) {
593    auto lid = this->layers.get_layer_id(std::string(drawing_name));
594    if (!lid) {
595       // XXX: to we need to put these applications on the App layer?
596       return Err<int>("Drawing name does not match any role");
597    }
598
599    auto rname = this->lookup_id(drawing_name);
600    if (!rname) {
601       // name does not exist yet, allocate surface id...
602       auto id = int(this->id_alloc.generate_id(drawing_name));
603       this->layers.add_surface(id, *lid);
604
605       // XXX: we set the main_surface[_name] here and now,
606       // not sure if we want this, but it worked so far.
607       if (!this->layers.main_surface_name.empty() &&
608           this->layers.main_surface_name == drawing_name) {
609          this->layers.main_surface = id;
610          logdebug("Set main_surface id to %u", id);
611       }
612
613       return Ok<int>(id);
614    }
615
616    // Check currently registered drawing names if it is already there.
617    return Err<int>("Surface already present");
618 }
619
620 void App::activate(int id) {
621    if (this->controller->sprops[id].visibility == 0) {
622       this->controller->surfaces[id]->set_visibility(1);
623       char const *label =
624          this->lookup_name(id).value_or("unknown-name").c_str();
625       this->emit_activated(label);
626       this->emit_visible(label);
627    }
628 }
629
630 void App::deactivate(int id) {
631    if (this->controller->sprops[id].visibility != 0) {
632       this->controller->surfaces[id]->set_visibility(0);
633       char const *label =
634          this->lookup_name(id).value_or("unknown-name").c_str();
635       this->emit_deactivated(label);
636       this->emit_invisible(label);
637    }
638 }
639
640 bool App::can_split(struct LayoutState const &state, int new_id) {
641    if (state.main != -1 && state.main != new_id) {
642       auto new_id_layer = this->layers.get_layer_id(new_id).value();
643       auto current_id_layer =
644          this->layers.get_layer_id(state.main).value();
645
646       // surfaces are on separate layers, don't bother.
647       if (new_id_layer != current_id_layer) {
648          return false;
649       }
650
651       std::string const &new_id_str = this->lookup_name(new_id).value();
652       std::string const &cur_id_str =
653          this->lookup_name(state.main).value();
654
655       auto const &layer = this->layers.get_layer(new_id_layer);
656
657       logdebug("layer info name: %s", layer->name.c_str());
658
659       if (layer->layouts.empty()) {
660          return false;
661       }
662
663       for (auto i = layer->layouts.cbegin(); i != layer->layouts.cend(); i++) {
664          logdebug("%d main_match '%s'", new_id_layer, i->main_match.c_str());
665          auto rem = std::regex(i->main_match);
666          if (std::regex_match(cur_id_str, rem)) {
667             // build the second one only if the first already matched
668             logdebug("%d sub_match '%s'", new_id_layer, i->sub_match.c_str());
669             auto res = std::regex(i->sub_match);
670             if (std::regex_match(new_id_str, res)) {
671                logdebug("layout matched!");
672                return true;
673             }
674          }
675       }
676    }
677
678    return false;
679 }
680
681 //                  _             _ _            _                 _
682 //   ___ ___  _ __ | |_ _ __ ___ | | | ___ _ __ | |__   ___   ___ | | _____
683 //  / __/ _ \| '_ \| __| '__/ _ \| | |/ _ \ '__|| '_ \ / _ \ / _ \| |/ / __|
684 // | (_| (_) | | | | |_| | | (_) | | |  __/ |   | | | | (_) | (_) |   <\__ \
685 //  \___\___/|_| |_|\__|_|  \___/|_|_|\___|_|___|_| |_|\___/ \___/|_|\_\___/
686 //                                         |_____|
687 void controller_hooks::surface_created(uint32_t surface_id) {
688    this->app->surface_created(surface_id);
689 }
690
691 void controller_hooks::surface_removed(uint32_t surface_id) {
692    this->app->surface_removed(surface_id);
693 }
694
695 }  // namespace wm