binding: ping() dispatches only pending events
[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    // execute pending tasks, that is layout changes etc.
163    // this->execute_pending();
164
165    return 0;
166 }
167
168 int App::dispatch_pending_events() {
169    if (this->pending_events.load(std::memory_order_consume)) {
170       this->pending_events.store(false, std::memory_order_release);
171       this->display->dispatch_pending();
172       return 0;
173    }
174    return -1;
175 }
176
177 //  _       _ _       _                         _    ____
178 // (_)_ __ (_) |_    | | __ _ _   _  ___  _   _| |_ / /\ \
179 // | | '_ \| | __|   | |/ _` | | | |/ _ \| | | | __| |  | |
180 // | | | | | | |_    | | (_| | |_| | (_) | |_| | |_| |  | |
181 // |_|_| |_|_|\__|___|_|\__,_|\__, |\___/ \__,_|\__| |  | |
182 //              |_____|       |___/                 \_\/_/
183 int App::init_layers() {
184    if (!this->controller) {
185       logerror("ivi_controller global not available");
186       return -1;
187    }
188
189    if (this->outputs.empty()) {
190       logerror("no output was set up!");
191       return -1;
192    }
193
194    auto &c = this->controller;
195
196    auto &o = this->outputs.front();
197    auto &s = c->screens.begin()->second;
198    auto &layers = c->layers;
199
200    // XXX: Write output dimensions to ivi controller...
201    c->output_size = genivi::size{uint32_t(o->width), uint32_t(o->height)};
202
203    // Clear scene
204    layers.clear();
205
206    // Clear screen
207    s->clear();
208
209    // Quick and dirty setup of layers
210    // XXX: This likely needs to be sorted by order (note, we don't (yet?)
211    // do any zorder arrangement).
212    for (auto const &i : this->layers.mapping) {
213       c->layer_create(i.layer_id, o->width, o->height);
214       auto &l = layers[i.layer_id];
215       l->set_destination_rectangle(0, 0, o->width, o->height);
216       l->set_visibility(1);
217       logdebug("Setting up layer %s (%d) for surfaces %d-%d and role match \"%s\"", i.name.c_str(),
218                i.layer_id, i.id_min, i.id_max, i.role.c_str());
219       this->layouts[l->id] = LayoutState{};
220    }
221
222    // Add layers to screen (XXX: are they sorted correctly?)
223    s->set_render_order(this->layers.layers);
224
225    c->commit_changes();
226
227    this->display->flush();
228
229    return 0;
230 }
231
232 namespace {
233
234 // This can fix the HomeScreen...
235 void redraw_fix(App *app, std::unique_ptr<genivi::surface> &s, int x, int y,
236                 int w, int h) {
237    {  // XXX: Work around weston redraw issues
238       // trigger an update by changing the source dimensions!
239       s->set_configuration(w + 1, h);
240       s->set_source_rectangle(0, 0, w + 1, h);
241       s->set_destination_rectangle(x, y, w + 1, h);
242       app->controller->commit_changes();
243       app->display->roundtrip();
244
245       // wait some time, for the process to do its thing...
246       using namespace std::chrono_literals;
247       std::this_thread::sleep_for(100ms);
248
249       // Set a different size then what we actually want.
250       s->set_configuration(w, h);
251       s->set_source_rectangle(0, 0, w, h);
252       s->set_destination_rectangle(x, y, w, h);
253       app->controller->commit_changes();
254       app->display->roundtrip();
255    }
256 }
257
258 }  // namespace
259
260 void App::surface_set_layout_full(uint32_t surface_id) {
261    if (!this->controller->surface_exists(surface_id)) {
262       logerror("Surface %d does not exist", int(surface_id));
263       return;
264    }
265
266    auto o_layer_id = this->layers.get_layer_id(surface_id);
267
268    if (!o_layer_id) {
269       logerror("Surface %d is not associated with any layer!", int(surface_id));
270       return;
271    }
272
273    uint32_t layer_id = o_layer_id.value();
274    logdebug("surface_set_layout for surface %u on layer %u", surface_id,
275             layer_id);
276
277    auto const &layer = this->layers.get_layer(layer_id);
278    auto rect = layer.value().rect;
279    auto &s = this->controller->surfaces[surface_id];
280
281    int x = rect.x;
282    int y = rect.y;
283    int w = rect.w;
284    int h = rect.h;
285
286    // less-than-0 values refer to MAX + 1 - $VALUE
287    // e.g. MAX is either screen width or height
288    if (w < 0) {
289       w = this->controller->output_size.w + 1 + w;
290    }
291    if (h < 0) {
292       h = this->controller->output_size.h + 1 + h;
293    }
294
295    // configure surface to wxh dimensions
296    s->set_configuration(w, h);
297
298    // set source reactangle, even if we should not need to set it.
299    s->set_source_rectangle(0, 0, w, h);
300
301    // set destination to the display rectangle
302    s->set_destination_rectangle(x, y, w, h);
303
304    s->set_visibility(0);
305    s->set_opacity(256);
306
307    this->controller->commit_changes();
308    this->display->roundtrip();
309
310    //redraw_fix(this, s, x, y, w, h);
311
312    logdebug("Surface %u now with rect { %d, %d, %d, %d }",
313             surface_id, x, y, w, h);
314 }
315
316 void App::surface_set_layout_split(uint32_t surface_id, uint32_t sub_surface_id) {
317    if (!this->controller->surface_exists(surface_id)) {
318       logerror("Surface %d does not exist", int(surface_id));
319       return;
320    }
321
322    auto o_layer_id = this->layers.get_layer_id(surface_id);
323
324    if (!o_layer_id) {
325       logerror("Surface %d is not associated with any layer!", int(surface_id));
326       return;
327    }
328
329    uint32_t layer_id = o_layer_id.value();
330    logdebug("surface_set_layout for surface %u on layer %u", surface_id,
331             layer_id);
332
333    auto const &layer = this->layers.get_layer(layer_id);
334    auto rect = layer.value().rect;
335    auto &s = this->controller->surfaces[surface_id];
336    auto &ss = this->controller->surfaces[sub_surface_id];
337
338    int x = rect.x;
339    int y = rect.y;
340    int w = rect.w;
341    int h = rect.h;
342
343    this->state.main = surface_id;
344    this->state.sub = sub_surface_id;
345    this->state.state = LayoutState::LayoutSplit;
346
347    // less-than-0 values refer to MAX + 1 - $VALUE
348    // e.g. MAX is either screen width or height
349    if (w < 0) {
350       w = this->controller->output_size.w + 1 + w;
351    }
352    if (h < 0) {
353       h = this->controller->output_size.h + 1 + h;
354    }
355
356    int x_off = 0;
357    int y_off = 0;
358
359    // split along major axis
360    if (w > h) {
361       w /= 2;
362       x_off = w;
363    } else {
364       h /= 2;
365       y_off = h;
366    }
367
368    // configure surface to wxh dimensions
369    s->set_configuration(w, h);
370    // set source reactangle, even if we should not need to set it.
371    s->set_source_rectangle(0, 0, w, h);
372    // set destination to the display rectangle
373    s->set_destination_rectangle(x, y, w, h);
374
375    s->set_visibility(1);
376    s->set_opacity(256);
377
378    // configure surface to wxh dimensions
379    ss->set_configuration(w, h);
380    // set source reactangle, even if we should not need to set it.
381    ss->set_source_rectangle(0, 0, w, h);
382    // set destination to the display rectangle
383    ss->set_destination_rectangle(x+x_off, y+y_off, w, h);
384
385    ss->set_visibility(1);
386    ss->set_opacity(256);
387
388    this->controller->commit_changes();
389    this->display->roundtrip();
390
391    //redraw_fix(this, s, x, y, w, h);
392    //redraw_fix(this, ss, x+x_off, y+y_off, w, h);
393
394    logdebug("Surface %u now on layer %u with rect { %d, %d, %d, %d }",
395             surface_id, layer_id, x, y, w, h);
396 }
397
398 char const *App::activate_surface(char const *drawing_name) {
399    int surface_id = -1;
400
401    {
402       auto oid = this->lookup_id(drawing_name);
403       if (oid) {
404          surface_id = oid.value();
405       } else {
406          return "Surface does not exist";
407       }
408    }
409
410    if (!this->controller->surface_exists(surface_id)) {
411       return "Surface does not exist";
412    }
413
414    if (this->state.main == surface_id || this->state.sub == surface_id) {
415       return "Surface already active";
416    }
417
418    // This should involve a policy check, but as we do not (yet) have
419    // such a thing, we will just switch to this surface.
420    // XXX: input focus missing!!1
421
422    if (this->state != LayoutState{}) {
423       switch (this->state.state) {
424          case LayoutState::LayoutSingle:
425             if (this->can_split(surface_id)) {
426                this->surface_set_layout_split(this->state.main, surface_id);
427                return nullptr;
428             }
429             break;
430
431          case LayoutState::LayoutSplit:
432             if (this->can_split(surface_id)) {
433                this->deactivate(this->state.sub);
434                this->surface_set_layout_split(this->state.main, surface_id);
435             }
436
437          case LayoutState::LayoutNone:
438             break;
439       }
440    }
441
442    // Make it visible, no (or little effect) if already visible
443    auto &s = this->controller->surfaces[surface_id];
444
445    // Set all others invisible
446    for (auto &i : this->controller->surfaces) {
447       auto &si = this->controller->sprops[i.second->id];
448       if (si.id != s->id && si.visibility != 0 &&
449           int(si.id) != this->layers.main_surface) {
450          this->deactivate(si.id);
451       }
452    }
453    this->activate(s->id);
454
455    // commit changes
456    this->controller->commit_changes();
457    this->display->flush();
458
459    this->state.main = surface_id;
460    this->state.state = LayoutState::LayoutSingle;
461
462    // no error
463    return nullptr;
464 }
465
466 char const *App::deactivate_surface(char const *drawing_name) {
467    int surface_id = -1;
468
469    {
470       auto oid = this->lookup_id(drawing_name);
471       if (oid) {
472          surface_id = oid.value();
473       } else {
474          return "Surface does not exist";
475       }
476    }
477
478    if (surface_id == this->layers.main_surface) {
479       return "Cannot deactivate main_surface";
480    }
481
482    switch (this->state.state) {
483       case LayoutState::LayoutSplit:
484          if (surface_id == this->state.main) {
485             this->deactivate(surface_id);
486             this->surface_set_layout_full(this->state.main);
487
488             this->deactivate(this->state.sub);
489             this->surface_set_layout_full(this->state.sub);
490
491             this->state.main = -1;
492             this->state.sub = -1;
493             this->state.state = LayoutState::LayoutSingle;
494          } else if (surface_id == this->state.sub) {
495             this->deactivate(surface_id);
496             this->surface_set_layout_full(this->state.sub);
497             this->surface_set_layout_full(this->state.main);
498
499             // XXX send syndraw events....
500
501             this->state.sub = -1;
502             this->state.state = LayoutState::LayoutSingle;
503          }
504          break;
505
506       case LayoutState::LayoutSingle:
507          this->deactivate(surface_id);
508          this->state.main = -1;
509          this->state.sub = -1;
510          break;
511
512       case LayoutState::LayoutNone:
513          break;
514    }
515
516
517    this->controller->commit_changes();
518    this->display->flush();
519
520    return nullptr;
521 }
522
523 //                      _          _   _____                 _
524 //  _ __  _ __ _____  _(_) ___  __| | | ____|_   _____ _ __ | |_ ___
525 // | '_ \| '__/ _ \ \/ / |/ _ \/ _` | |  _| \ \ / / _ \ '_ \| __/ __|
526 // | |_) | | | (_) >  <| |  __/ (_| | | |___ \ V /  __/ | | | |_\__ \
527 // | .__/|_|  \___/_/\_\_|\___|\__,_| |_____| \_/ \___|_| |_|\__|___/
528 // |_|
529 void App::surface_created(uint32_t surface_id) {
530    logdebug("surface_id is %u", surface_id);
531
532    this->surface_set_layout_full(surface_id);
533
534    this->controller->layers[this->layers.get_layer_id(surface_id).value()]
535            ->add_surface(this->controller->surfaces[surface_id].get());
536
537    // activate the main_surface right away
538    if (surface_id == static_cast<unsigned>(this->layers.main_surface)) {
539       logdebug("Activating main_surface (%d)", surface_id);
540
541       this->activate_surface(
542               this->lookup_name(surface_id).value_or("unknown-name").c_str());
543    }
544 }
545
546 void App::surface_removed(uint32_t surface_id) {
547    logdebug("surface_id is %u", surface_id);
548
549    this->id_alloc.remove_id(surface_id);
550 }
551
552 void App::emit_activated(char const *label) {
553    this->api.send_event("activated", label);
554 }
555
556 void App::emit_deactivated(char const *label) {
557    this->api.send_event("deactivated", label);
558 }
559
560 void App::emit_syncdraw(char const *label) {
561    this->api.send_event("syncdraw", label);
562 }
563
564 void App::emit_flushdraw(char const *label) {
565    this->api.send_event("syncdraw", label);
566 }
567
568 void App::emit_visible(char const *label, bool is_visible) {
569    this->api.send_event(is_visible ? "visible" : "invisible", label);
570 }
571
572 void App::emit_invisible(char const *label) { return emit_visible(label, 0); }
573
574 void App::emit_visible(char const *label) { return emit_visible(label, 1); }
575
576 result<int> App::request_surface(char const *drawing_name) {
577    auto lid = this->layers.get_layer_id(std::string(drawing_name));
578    if (!lid) {
579       // XXX: to we need to put these applications on the App layer?
580       return Err<int>("Drawing name does not match any role");
581    }
582
583    auto rname = this->lookup_id(drawing_name);
584    if (!rname) {
585       // name does not exist yet, allocate surface id...
586       auto id = int(this->id_alloc.generate_id(drawing_name));
587       this->layers.add_surface(id, lid.value());
588
589       // XXX: we set the main_surface[_name] here and now,
590       // not sure if we want this, but it worked so far.
591       if (!this->layers.main_surface_name.empty() &&
592           this->layers.main_surface_name == drawing_name) {
593          this->layers.main_surface = id;
594          logdebug("Set main_surface id to %u", id);
595       }
596
597       return Ok<int>(id);
598    }
599
600    // Check currently registered drawing names if it is already there.
601    return Err<int>("Surface already present");
602 }
603
604 void App::activate(unsigned id) {
605    if (this->controller->sprops[id].visibility == 0) {
606       this->controller->surfaces[id]->set_visibility(1);
607       char const *label =
608          this->lookup_name(id).value_or("unknown-name").c_str();
609       this->emit_activated(label);
610       this->emit_visible(label);
611    }
612 }
613
614 void App::deactivate(unsigned id) {
615    if (this->controller->sprops[id].visibility != 0) {
616       this->controller->surfaces[id]->set_visibility(0);
617       char const *label =
618          this->lookup_name(id).value_or("unknown-name").c_str();
619       this->emit_deactivated(label);
620       this->emit_invisible(label);
621    }
622 }
623
624 bool App::can_split(unsigned new_id) {
625    if (this->state.state == LayoutState::LayoutSingle) {
626       auto new_id_layer = this->layers.get_layer_id(new_id).value();
627       auto current_id_layer =
628          this->layers.get_layer_id(this->state.main).value();
629
630       // surfaces are on separate layers, don't bother.
631       if (new_id_layer != current_id_layer) {
632          return false;
633       }
634
635       std::string const &new_id_str = this->lookup_name(new_id).value();
636       std::string const &cur_id_str =
637          this->lookup_name(this->state.main).value();
638
639       auto const &layer = this->layers.get_layer(new_id_layer);
640
641       logdebug("layer info name: %s", layer->name.c_str());
642
643       if (layer->layouts.empty()) {
644          return false;
645       }
646
647       for (auto i = layer->layouts.cbegin(); i != layer->layouts.cend(); i++) {
648          logdebug("%d main_match '%s'", new_id_layer, i->main_match.c_str());
649          auto rem = std::regex(i->main_match);
650          if (std::regex_match(cur_id_str, rem)) {
651             // build the second one only if the first already matched
652             logdebug("%d sub_match '%s'", new_id_layer, i->sub_match.c_str());
653             auto res = std::regex(i->sub_match);
654             if (std::regex_match(new_id_str, res)) {
655                return true;
656             }
657          }
658       }
659    }
660
661    return false;
662 }
663
664 //                  _             _ _            _                 _
665 //   ___ ___  _ __ | |_ _ __ ___ | | | ___ _ __ | |__   ___   ___ | | _____
666 //  / __/ _ \| '_ \| __| '__/ _ \| | |/ _ \ '__|| '_ \ / _ \ / _ \| |/ / __|
667 // | (_| (_) | | | | |_| | | (_) | | |  __/ |   | | | | (_) | (_) |   <\__ \
668 //  \___\___/|_| |_|\__|_|  \___/|_|_|\___|_|___|_| |_|\___/ \___/|_|\_\___/
669 //                                         |_____|
670 void controller_hooks::surface_created(uint32_t surface_id) {
671    this->app->surface_created(surface_id);
672 }
673
674 void controller_hooks::surface_removed(uint32_t surface_id) {
675    this->app->surface_removed(surface_id);
676 }
677
678 }  // namespace wm