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