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