MayaFlux 1.0.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
Instantiate.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "ActionTable.hpp"
4#include "CallTable.hpp"
5#include "StaticGeometry.hpp"
6
8
9/** @brief Attribute that names an element, which shares the namespace of ids. */
10inline constexpr std::string_view element_name_attribute { "name" };
11
12/** @brief Attribute of a form element that gives vertices to draw instead of a call. */
13inline constexpr std::string_view vertex_topology_attribute { "topology" };
14
15/** @brief Surfaces by the document name a host binds them to. */
16using SurfaceMap = std::map<std::string, Surface, std::less<>>;
17
18/**
19 * @struct PlacedInstance
20 * @brief Where an instance of a document ended up.
21 */
23 /// @brief The document's surface id, a key of the SurfaceMap that was given.
24 std::string surface;
25
26 /// @brief The id of the element the instance is anchored on, in that surface's Layer.
27 uint32_t element {};
28};
29
30/** @brief The placed instances of a document by the id the document gave them. */
31using PlacedInstances = std::map<std::string, PlacedInstance, std::less<>>;
32
33namespace Detail {
34
35 /**
36 * The document's own attributes on an instance, all beginning with the
37 * reserved prefix. They are applied to the placed element through its Layer.
38 */
40 bool hidden {};
41 std::optional<bool> interactive;
42 std::optional<std::string> relate;
43 bool front {};
44 bool back {};
45 std::optional<Kinesis::AABB2D> clip;
46 };
47
48 /**
49 * An action prepared for one event of one instance: the filter to
50 * subscribe with, and the action a host registered, already decoded.
51 */
56
57 template <typename Source, typename Access>
59 public:
63 using Placer = typename Table::Placer;
64
66 std::string surface_id;
68 std::string id;
69 uint64_t row {};
72 std::vector<ActionBinding> actions;
73 };
74
75 using Prepared = std::vector<PreparedInstance>;
76
77 DocumentWalk(const Table& table, const Source& root, std::string& error,
78 const Actions* actions = nullptr, const Calls* calls = nullptr)
79 : m_table(table)
80 , m_root(root)
81 , m_error(error)
82 , m_actions(actions)
83 , m_calls(calls)
84 {
85 }
86
88 {
89 if (Access::name(m_root) != "forma")
90 return fail(m_root, "root element must be <forma>");
91 if (!only_attributes(m_root, { "version", "xmlns" }, "xmlns:") || !check_version())
92 return false;
93
94 bool templates_seen = false;
95 const bool traversed = Access::for_each_child(m_root, [&](const Source& section) {
96 const auto name = Access::name(section);
97 if (name == "templates") {
98 if (templates_seen)
99 return fail(section, "<templates> may appear only once");
100 templates_seen = true;
101 return read_templates(section);
102 }
103 if (name == "surface")
104 return read_surface(section);
105 return fail(section, "<" + std::string(name) + "> is not allowed in <forma>");
106 });
107 return traversed && check_instances();
108 }
109
110 std::optional<Prepared> prepare(SurfaceMap& surfaces)
111 {
112 Prepared prepared;
113 for (const SurfaceInstances& entry : m_surfaces) {
114 const auto bound = surfaces.find(entry.id);
115 if (bound == surfaces.end()) {
116 fail(entry.element, "surface " + entry.id + " is not bound by the host");
117 return std::nullopt;
118 }
119 for (size_t i = 0; i < entry.instances.size(); ++i) {
120 const Source& instance = entry.instances[i];
121 const InstanceInfo& info = entry.info[i];
122 std::optional<Placer> placer;
123 if (info.form) {
124 if (const auto call = Access::attribute(*info.form, reserved_call_attribute)) {
125 const typename Calls::Maker* make = m_calls->find(*call);
126 placer = std::invoke(*make, *info.form, instance, info.hit, m_error);
127 } else {
128 placer = vertex_placer(*info.form, instance, info.hit);
129 }
130 } else {
131 const Source& factory_element = m_templates.at(info.template_id);
132 const typename Table::Instantiator* decode = m_table.find(Access::name(factory_element));
133 placer = std::invoke(*decode, factory_element, instance, m_error);
134 }
135 if (!placer) {
136 if (m_error.empty())
137 fail(instance, "could not prepare the instance");
138 return std::nullopt;
139 }
140 std::vector<ActionBinding> actions;
141 for (const ActionSpec& spec : info.actions) {
142 const typename Actions::Maker* make = m_actions->find(spec.action);
143 auto action = std::invoke(*make, spec.element, m_error);
144 if (!action) {
145 if (m_error.empty())
146 fail(spec.element, "could not prepare the action " + spec.action);
147 return std::nullopt;
148 }
149 actions.push_back(ActionBinding {
150 .filter = spec.filter, .action = std::move(*action) });
151 }
152 prepared.push_back(PreparedInstance {
153 .surface_id = entry.id,
154 .surface = &bound->second,
155 .id = info.id,
156 .row = Access::location(instance),
157 .placer = std::move(*placer),
158 .layer = info.layer,
159 .actions = std::move(actions),
160 });
161 }
162 }
163 return prepared;
164 }
165
166 std::optional<std::vector<Placer>> prepare_bulk(std::string_view template_id,
167 const Kakshya::CompositeArray& rows)
168 {
169 const auto found = m_templates.find(std::string(template_id));
170 if (found == m_templates.end()) {
171 m_error = "document has no template " + std::string(template_id);
172 return std::nullopt;
173 }
174 const auto* bulk = m_table.find_bulk(Access::name(found->second));
175 if (!bulk) {
176 fail(found->second, "factory " + std::string(Access::name(found->second))
177 + " has no bulk placement; register it with expose_typed");
178 return std::nullopt;
179 }
180 auto placers = std::invoke(*bulk, found->second, rows, m_error);
181 if (!placers && m_error.empty())
182 fail(found->second, "could not prepare instances");
183 return placers;
184 }
185
186 /**
187 * Names every placed element after its instance, then applies the
188 * document's Layer attributes: relations first, so a later front or back
189 * moves the whole group, then visibility, interaction and clip.
190 */
191 static bool apply(const Prepared& prepared, const std::vector<uint32_t>& elements,
192 std::string& error)
193 {
194 for (size_t i = 0; i < prepared.size(); ++i) {
195 Element* element = prepared[i].surface->layer().get(elements[i]);
196 if (!element) {
197 error = Table::located(prepared[i].row, "instance " + prepared[i].id
198 + " placed an element the surface does not hold");
199 return false;
200 }
201 element->name = prepared[i].id;
202 }
203
204 for (size_t i = 0; i < prepared.size(); ++i) {
205 const auto& relate = prepared[i].layer.relate;
206 if (!relate)
207 continue;
208 const auto target = std::ranges::find_if(prepared, [&](const PreparedInstance& other) {
209 return other.surface_id == prepared[i].surface_id && other.id == *relate;
210 });
211 const size_t j = static_cast<size_t>(target - prepared.begin());
212 if (target == prepared.end()
213 || !prepared[i].surface->layer().relate(elements[j], elements[i])) {
214 error = Table::located(prepared[i].row, "could not relate " + prepared[i].id
215 + " to " + *relate);
216 return false;
217 }
218 }
219
220 for (size_t i = 0; i < prepared.size(); ++i) {
221 Layer& layer = prepared[i].surface->layer();
222 const LayerAttributes& attributes = prepared[i].layer;
223 if (attributes.hidden)
224 layer.set_visible(elements[i], false);
225 if (attributes.interactive)
226 layer.set_interactive(elements[i], *attributes.interactive);
227 if (attributes.clip)
228 layer.set_clip(elements[i], attributes.clip);
229 if (attributes.front)
230 layer.bring_to_front(elements[i]);
231 if (attributes.back)
232 layer.send_to_back(elements[i]);
233 }
234
235 for (size_t i = 0; i < prepared.size(); ++i) {
236 for (const ActionBinding& binding : prepared[i].actions)
237 wire(*prepared[i].surface, elements[i], prepared[i].id, binding);
238 }
239 return true;
240 }
241
242 private:
248
250 std::string id;
251 std::string template_id;
253 std::vector<ActionSpec> actions;
254 std::optional<Source> form;
256 };
257
259 std::string id;
260 Source element;
261 std::vector<Source> instances;
262 std::vector<bool> direct;
263 std::vector<InstanceInfo> info;
264 };
265
267 const Source& m_root;
268 std::string& m_error;
273 std::unordered_map<std::string, Source> m_templates;
274 std::vector<SurfaceInstances> m_surfaces;
275
276 bool fail(const Source& at, std::string message)
277 {
278 m_error = Table::located(Access::location(at), message);
279 return false;
280 }
281
282 bool only_attributes(const Source& source, std::initializer_list<std::string_view> allowed,
283 std::string_view allowed_prefix = {})
284 {
285 return Access::for_each_attribute(source, [&](std::string_view name, std::string_view) {
286 if (std::ranges::find(allowed, name) != allowed.end()
287 || (!allowed_prefix.empty() && name.starts_with(allowed_prefix))) {
288 return true;
289 }
290 return fail(source, "<" + std::string(Access::name(source))
291 + "> has an unsupported attribute " + std::string(name));
292 });
293 }
294
296 {
297 const auto text = Access::attribute(m_root, "version");
298 if (!text)
299 return fail(m_root, "<forma> needs a version attribute");
300 uint32_t version {};
302 if (!Reflect::TextCodec<uint32_t>::decode(*text, version, reason) || version != 1)
303 return fail(m_root, "unsupported Forma document version " + std::string(*text));
304 return true;
305 }
306
307 std::optional<std::string> claim_id(const Source& source)
308 {
309 if (!m_ids.claim(source, m_error))
310 return std::nullopt;
311 const std::string id(*Access::attribute(source, reserved_id_attribute));
312 if (const auto held = m_names.location_of(id)) {
313 fail(source, "id " + id + " is already used by an element at row " + std::to_string(*held));
314 return std::nullopt;
315 }
316 return id;
317 }
318
319 std::optional<std::string> claim_name(const Source& source)
320 {
321 if (!m_names.claim(source, m_error))
322 return std::nullopt;
323 const std::string name(*Access::attribute(source, element_name_attribute));
324 if (const auto held = m_ids.location_of(name)) {
325 fail(source, "name " + name + " is already used as an id at row " + std::to_string(*held));
326 return std::nullopt;
327 }
328 return name;
329 }
330
331 bool read_templates(const Source& section)
332 {
333 if (!only_attributes(section, {}))
334 return false;
335 return Access::for_each_child(section, [&](const Source& definition) {
336 if (Access::name(definition) != "template") {
337 return fail(definition, "<" + std::string(Access::name(definition))
338 + "> is not allowed in <templates>");
339 }
340 return read_template(definition);
341 });
342 }
343
344 bool read_template(const Source& definition)
345 {
346 if (!only_attributes(definition, { reserved_id_attribute }))
347 return false;
348 const auto id = claim_id(definition);
349 if (!id)
350 return false;
351
352 std::optional<Source> factory_element;
353 size_t count = 0;
354 Access::for_each_child(definition, [&](const Source& child) {
355 if (!factory_element)
356 factory_element.emplace(child);
357 ++count;
358 return true;
359 });
360 if (count != 1)
361 return fail(definition, "<template> needs exactly one factory element");
362
363 const auto name = Access::name(*factory_element);
364 if (!m_table.contains(name))
365 return fail(*factory_element, "no registered factory " + std::string(name));
366 m_templates.emplace(*id, *factory_element);
367 return true;
368 }
369
370 bool read_surface(const Source& surface)
371 {
372 if (!only_attributes(surface, { reserved_id_attribute }))
373 return false;
374 const auto id = claim_id(surface);
375 if (!id)
376 return false;
377
378 SurfaceInstances entry { .id = *id, .element = surface, .instances = {}, .direct = {}, .info = {} };
379 const bool traversed = Access::for_each_child(surface, [&](const Source& instance) {
380 const auto kind = Access::name(instance);
381 if (kind != "instance" && kind != "element") {
382 return fail(instance, "<" + std::string(kind) + "> is not allowed in <surface>");
383 }
384 entry.instances.push_back(instance);
385 entry.direct.push_back(kind == "element");
386 return true;
387 });
388 if (traversed)
389 m_surfaces.push_back(std::move(entry));
390 return traversed;
391 }
392
393 bool read_flag(const Source& instance, std::string_view name, std::string_view value, bool& out)
394 {
396 if (!Reflect::TextCodec<bool>::decode(value, out, reason))
397 return fail(instance, "<" + std::string(Access::name(instance)) + "> has an invalid "
398 + std::string(name) + " attribute");
399 return true;
400 }
401
402 bool read_layer_attributes(const Source& instance, LayerAttributes& out)
403 {
404 const bool read = Access::for_each_attribute(instance,
405 [&](std::string_view name, std::string_view value) {
406 if (!name.starts_with(reserved_prefix))
407 return true;
408 const std::string_view key = name.substr(reserved_prefix.size());
409 if (key == "hidden")
410 return read_flag(instance, name, value, out.hidden);
411 if (key == "front")
412 return read_flag(instance, name, value, out.front);
413 if (key == "back")
414 return read_flag(instance, name, value, out.back);
415 if (key == "interactive") {
416 bool flag {};
417 if (!read_flag(instance, name, value, flag))
418 return false;
419 out.interactive = flag;
420 return true;
421 }
422 if (key == "relate") {
423 if (value.empty())
424 return fail(instance, "<instance> needs an instance id in " + std::string(name));
425 out.relate = std::string(value);
426 return true;
427 }
428 if (key == "clip") {
429 glm::vec4 rect {};
431 if (!Reflect::TextCodec<glm::vec4>::decode(value, rect, reason))
432 return fail(instance, "<instance> needs four numbers in " + std::string(name));
433 if (!(rect.z > 0.F) || !(rect.w > 0.F))
434 return fail(instance, std::string(name) + " needs a positive width and height");
435 out.clip = Kinesis::AABB2D::from_origin_size({ rect.x, rect.y }, { rect.z, rect.w });
436 return true;
437 }
438 return fail(instance, "<instance> has an unsupported attribute " + std::string(name));
439 });
440 if (!read)
441 return false;
442 if (out.front && out.back) {
443 return fail(instance, std::string(reserved_prefix) + "front and "
444 + std::string(reserved_prefix) + "back cannot both be set");
445 }
446 return true;
447 }
448
449 bool read_actions(const Source& instance, InstanceInfo& info)
450 {
451 return Access::for_each_child(instance, [&](const Source& child) {
452 if (Access::name(child) != reserved_action_element) {
453 return fail(child, "<" + std::string(Access::name(child))
454 + "> is not allowed in <instance>");
455 }
456 return read_action(child, info);
457 });
458 }
459
460 bool read_action(const Source& on, InstanceInfo& info)
461 {
462 using Type = Core::WindowEventType;
463
464 if (!m_actions)
465 return fail(on, "<on> needs an action table, and none was given");
466
467 const auto event_text = Access::attribute(on, action_event_attribute);
468 if (!event_text)
469 return fail(on, "<on> needs an event attribute");
471 Type event {};
473 if (!Reflect::TextCodec<Type>::decode(*event_text, event, reason))
474 return fail(on, "<on> has an unsupported event " + std::string(*event_text));
475 filter.event_type = event;
476
477 if (const auto button_text = Access::attribute(on, action_button_attribute)) {
478 if (event != Type::MOUSE_BUTTON_PRESSED && event != Type::MOUSE_BUTTON_RELEASED
479 && event != Type::MOUSE_MOTION) {
480 return fail(on, "<on> takes a button only for MOUSE_BUTTON_PRESSED, MOUSE_BUTTON_RELEASED and MOUSE_MOTION");
481 }
482 IO::MouseButtons button {};
483 if (!Reflect::TextCodec<IO::MouseButtons>::decode(*button_text, button, reason)
484 || button == IO::MouseButtons::Unknown) {
485 return fail(on, "<on> has an unsupported button " + std::string(*button_text));
486 }
487 filter.button = button;
488 }
489
490 if (const auto key_text = Access::attribute(on, action_key_attribute)) {
491 if (event != Type::KEY_PRESSED && event != Type::KEY_RELEASED && event != Type::KEY_REPEAT)
492 return fail(on, "<on> takes a key only for KEY_PRESSED, KEY_RELEASED and KEY_REPEAT");
493 const auto key = IO::from_string(*key_text);
494 if (!key)
495 return fail(on, "<on> has an unsupported key " + std::string(*key_text));
496 filter.key_code = *key;
497 }
498
499 if (!Context::receives(filter)) {
500 return fail(on, "<on> event " + std::string(*event_text)
501 + " is not delivered to an element, or needs a key attribute");
502 }
503
504 const auto name = Access::attribute(on, action_name_attribute);
505 if (!name)
506 return fail(on, "<on> needs an action attribute");
507 if (!m_actions->contains(*name))
508 return fail(on, "no registered action " + std::string(*name));
509
510 info.actions.push_back(ActionSpec {
511 .element = on, .filter = filter, .action = std::string(*name) });
512 return true;
513 }
514
515 static void wire(Surface& surface, uint32_t element, const std::string& instance,
516 const ActionBinding& binding)
517 {
518 Layer* layer = &surface.layer();
519 Context* context = &surface.ctx();
520 context->subscribe(element, binding.filter,
521 [layer, context, instance, action = binding.action](
522 uint32_t id, const Core::WindowEvent& event, glm::vec2 ndc) {
523 action(ActionEvent { *layer, *context, id, instance, event, ndc });
524 });
525 }
526
528 {
529 for (SurfaceInstances& entry : m_surfaces) {
530 for (size_t k = 0; k < entry.instances.size(); ++k) {
531 const Source& instance = entry.instances[k];
532 InstanceInfo info;
533 if (entry.direct[k]) {
534 if (!read_element(instance, info))
535 return false;
536 } else {
537 const auto id = claim_id(instance);
538 if (!id)
539 return false;
540 const auto reference = Reflect::check_reference<Source, Access>(instance,
542 [this](std::string_view value) { return m_templates.contains(std::string(value)); },
543 m_error);
544 if (!reference)
545 return false;
546
547 info = InstanceInfo { .id = *id, .template_id = std::string(*reference), .layer = {}, .actions = {}, .form = std::nullopt };
548 if (!read_layer_attributes(instance, info.layer) || !read_actions(instance, info))
549 return false;
550 }
551 entry.info.push_back(std::move(info));
552 }
553 if (!check_relations(entry))
554 return false;
555 }
556 return true;
557 }
558
559 /**
560 * An element declares what C++ declares for one placed form: its name, the initial
561 * state, the Layer calls that follow placement (visible, interactive, relate, front, back,
562 * clip, spelled as the Layer and Element members are), one form that calls a registered
563 * function, and the actions on its events.
564 */
565 bool read_element(const Source& element, InstanceInfo& info)
566 {
567 const auto name = claim_name(element);
568 if (!name)
569 return false;
570 info.id = *name;
571
572 bool visible = true;
573 const bool read = Access::for_each_attribute(element,
574 [&](std::string_view attribute, std::string_view value) {
575 if (attribute == element_name_attribute || attribute == reserved_state_attribute)
576 return true;
577 if (attribute == "visible")
578 return read_flag(element, attribute, value, visible);
579 if (attribute == "front")
580 return read_flag(element, attribute, value, info.layer.front);
581 if (attribute == "back")
582 return read_flag(element, attribute, value, info.layer.back);
583 if (attribute == "interactive") {
584 bool flag {};
585 if (!read_flag(element, attribute, value, flag))
586 return false;
587 info.layer.interactive = flag;
588 return true;
589 }
590 if (attribute == "relate") {
591 if (value.empty())
592 return fail(element, "<element> needs an element name in relate");
593 info.layer.relate = std::string(value);
594 return true;
595 }
596 if (attribute == "clip") {
597 Kinesis::AABB2D region {};
599 if (!Reflect::TextCodec<Kinesis::AABB2D>::decode(value, region, reason))
600 return fail(element, "<element> needs four numbers in clip");
601 if (!(region.max.x > region.min.x) || !(region.max.y > region.min.y))
602 return fail(element, "clip needs a positive width and height");
603 info.layer.clip = region;
604 return true;
605 }
606 return fail(element, "<element> has an unsupported attribute " + std::string(attribute));
607 });
608 if (!read)
609 return false;
610 info.layer.hidden = !visible;
611 if (info.layer.front && info.layer.back)
612 return fail(element, "front and back cannot both be set");
613
614 const bool traversed = Access::for_each_child(element, [&](const Source& child) {
615 const auto kind = Access::name(child);
616 if (kind == "form") {
617 if (info.form)
618 return fail(child, "<element> may hold only one <form>");
619 info.form = child;
620 return check_form(child);
621 }
622 if (kind == reserved_action_element)
623 return read_action(child, info);
624 if (is_hit_child(kind))
625 return read_hit_child<Source, Access>(child, info.hit, m_error);
626 return fail(child, "<" + std::string(kind) + "> is not allowed in <element>");
627 });
628 if (!traversed)
629 return false;
630 if (!info.form)
631 return fail(element, "<element> needs a <form>");
632 return true;
633 }
634
635 /**
636 * A form either calls a registered function or gives vertices to draw, as C++ either
637 * passes a function's Form to Tend or submits vertices to a slice.
638 */
639 bool check_form(const Source& form)
640 {
641 const auto call = Access::attribute(form, reserved_call_attribute);
642 const auto topology = Access::attribute(form, vertex_topology_attribute);
643 if (call && topology)
644 return fail(form, "<form> may call a function or give a topology, not both");
645 if (!call) {
646 if (!topology)
647 return fail(form, "<form> needs a call or a topology attribute");
648 return true;
649 }
650 if (!m_calls)
651 return fail(form, "<form> needs a call table, and none was given");
652 if (!m_calls->contains(*call))
653 return fail(form, "no registered call " + std::string(*call));
654 bool has_child = false;
655 Access::for_each_child(form, [&](const Source&) {
656 has_child = true;
657 return false;
658 });
659 if (has_child)
660 return fail(form, "<form> that calls a function takes no children");
661 return true;
662 }
663
664 /** The placement of vertices written in a form element, which have no state. */
665 std::optional<Placer> vertex_placer(const Source& form, const Source& element, const ElementHit& hit)
666 {
667 if (Access::attribute(element, reserved_state_attribute)) {
668 fail(element, "a form of vertices has no state, so <element> may not give one");
669 return std::nullopt;
670 }
671 uint64_t where {};
672 const auto input = vertex_binding<Source, Access>().read(form, m_error, &where);
673 if (!input) {
675 return std::nullopt;
676 }
677 auto vertices = vertex_form(*input);
678 apply_hit(vertices, hit);
679 return Detail::form_placer<Placer, std::monostate>(std::move(vertices), std::monostate {});
680 }
681
683 {
684 for (size_t i = 0; i < entry.info.size(); ++i) {
685 const auto& relate = entry.info[i].layer.relate;
686 if (!relate)
687 continue;
688 const std::string attribute = entry.direct[i] ? "relate" : std::string(reserved_prefix) + "relate";
689 if (*relate == entry.info[i].id) {
690 return fail(entry.instances[i], attribute + " may not name the "
691 + (entry.direct[i] ? "element" : "instance") + " itself");
692 }
693 const bool known = std::ranges::any_of(entry.info, [&](const InstanceInfo& other) {
694 return other.id == *relate;
695 });
696 if (!known) {
697 return fail(entry.instances[i], attribute + " refers to "
698 + *relate + ", which is not an " + (entry.direct[i] ? "element or instance" : "instance")
699 + " of surface " + entry.id);
700 }
701 }
702 return true;
703 }
704 };
705
706}
707
708namespace Detail {
709
710 template <typename Source, typename Access>
711 std::optional<PlacedInstances> instantiate(const FactoryTable<Source, Access>& table,
712 const ActionTable<Source, Access>* actions, const CallTable<Source, Access>* calls,
713 const Source& root, SurfaceMap& surfaces, std::string& error)
714 {
715 error.clear();
716 DocumentWalk<Source, Access> walk(table, root, error, actions, calls);
717 if (!walk.read_structure())
718 return std::nullopt;
719 const auto prepared = walk.prepare(surfaces);
720 if (!prepared)
721 return std::nullopt;
722
723 PlacedInstances placed;
724 std::vector<uint32_t> elements;
725 elements.reserve(prepared->size());
726 for (const auto& item : *prepared) {
727 const auto element = item.placer(*item.surface, error);
728 if (!element)
729 return std::nullopt;
730 elements.push_back(*element);
731 placed.emplace(item.id, PlacedInstance { .surface = item.surface_id, .element = *element });
732 }
733 if (!DocumentWalk<Source, Access>::apply(*prepared, elements, error))
734 return std::nullopt;
735 return placed;
736 }
737
738}
739
740/**
741 * @brief Place every instance of a document through a table.
742 *
743 * The document is a tree of a root element named forma carrying a version of 1.
744 * The root may also carry xmlns declarations, which are ignored, so the mf:
745 * prefix below can be declared for tools that validate namespaces.
746 * Its templates element holds template elements, each with an id and exactly one
747 * child, the factory, whose name is looked up in the table. Its surface
748 * elements hold instance elements with an id, a template naming a template, and
749 * the placement attributes the factory describes. Ids are unique across the
750 * document. A surface id is a name the host binds in @p surfaces.
751 *
752 * An instance may also carry attributes of the document's own, all beginning
753 * with mf: and applied to the placed element through its Layer:
754 * - mf:hidden and mf:interactive take true or false.
755 * - mf:relate names another instance of the same surface that this one belongs
756 * with, so hiding, moving or removing that one reaches this one.
757 * - mf:front and mf:back move the element, and its relations, to the top or
758 * the bottom of the paint and hit order. They exclude each other.
759 * - mf:clip takes x y width height and confines hit testing to that region.
760 * Every placed element is also named after its instance, so Layer::find
761 * reaches it by the id the document gave it.
762 *
763 * Placement is two phases. The structure is checked and every instance is
764 * decoded first, so a bad document fails before any Surface is touched. Then
765 * each prepared instance is placed in document order and the Layer attributes
766 * are applied.
767 *
768 * @tparam Source Element type of the document tree, with a Reflect::RecordAccess.
769 * @param table Factories by name.
770 * @param root Root element of the document.
771 * @param surfaces Surfaces by the name the document's surface elements use.
772 * @param error Receives the reason, with a row, when nullopt is returned.
773 * @return Each placed instance by id, with its surface and element.
774 * @note A failure while placing may leave earlier instances on their Surface.
775 */
776template <typename Source, typename Access = Reflect::RecordAccess<Source>>
777[[nodiscard]] std::optional<PlacedInstances> instantiate_document(
778 const FactoryTable<Source, Access>& table, const Source& root,
779 SurfaceMap& surfaces, std::string& error)
780{
781 return Detail::instantiate<Source, Access>(table, nullptr, nullptr, root, surfaces, error);
782}
783
784/**
785 * @brief Place a document whose instances attach host actions to events.
786 *
787 * As the overload without actions, and an instance may also hold on children.
788 * Each names an event (press, release, drag, move, enter, leave or scroll), a
789 * button for press, release and drag (left by default), and an action
790 * registered in @p actions, with that action's own parameters as further
791 * attributes. The names and parameters are resolved with the rest of the
792 * document, so an unknown action fails before anything is placed. The actions
793 * are subscribed beside the element's own wiring, so they never replace it.
794 *
795 * @param actions Actions by name.
796 */
797template <typename Source, typename Access = Reflect::RecordAccess<Source>>
798[[nodiscard]] std::optional<PlacedInstances> instantiate_document(
800 const Source& root, SurfaceMap& surfaces, std::string& error)
801{
802 return Detail::instantiate<Source, Access>(table, &actions, nullptr, root, surfaces, error);
803}
804
805/**
806 * @struct ManifestTables
807 * @brief The three tables a document is placed through, as one plain value.
808 *
809 * factories serve instances of templates, calls serve elements whose form calls a described
810 * function, and actions serve the on children of either. Each holds only what its builder
811 * registers.
812 */
813template <typename Source, typename Access = Reflect::RecordAccess<Source>>
819
820/**
821 * @brief Place a document through all three tables.
822 *
823 * As instantiate_document, and a surface may also hold element children. An element has a
824 * name that shares the namespace of ids, a state, the Layer attributes visible, interactive,
825 * relate, front, back and clip, one form that names a registered call and gives its arguments
826 * by parameter name, and on children. The checks run before anything is placed, as for an
827 * instance.
828 */
829template <typename Source, typename Access = Reflect::RecordAccess<Source>>
830[[nodiscard]] std::optional<PlacedInstances> instantiate_document(
831 const ManifestTables<Source, Access>& tables, const Source& root,
832 SurfaceMap& surfaces, std::string& error)
833{
835 tables.factories, &tables.actions, &tables.calls, root, surfaces, error);
836}
837
838/**
839 * @brief Make one element per row of typed placements from a single template.
840 *
841 * The template's factory must have been registered with expose_typed. Its
842 * inputs are decoded once and each row, laid out as the described composite
843 * layout of the factory's placement type, becomes one element on @p surface.
844 * Everything is prepared before anything is placed. Rows carry no ids, so the
845 * elements are not named.
846 *
847 * @param template_id Id of a template in the document.
848 * @param rows One row of placement values per element.
849 * @return The element id of each row in row order, or nullopt with the reason in error.
850 */
851template <typename Source, typename Access = Reflect::RecordAccess<Source>>
852[[nodiscard]] std::optional<std::vector<uint32_t>> instantiate_rows(
853 const FactoryTable<Source, Access>& table, const Source& root,
854 std::string_view template_id, const Kakshya::CompositeArray& rows,
855 Surface& surface, std::string& error)
856{
857 error.clear();
858 Detail::DocumentWalk<Source, Access> walk(table, root, error);
859 if (!walk.read_structure())
860 return std::nullopt;
861 const auto placers = walk.prepare_bulk(template_id, rows);
862 if (!placers)
863 return std::nullopt;
864
865 std::vector<uint32_t> elements;
866 elements.reserve(placers->size());
867 for (const auto& placer : *placers) {
868 const auto element = placer(surface, error);
869 if (!element)
870 return std::nullopt;
871 elements.push_back(*element);
872 }
873 return elements;
874}
875
876/**
877 * @brief instantiate_rows for a document that uses all three tables.
878 *
879 * The whole document is checked again before the rows are placed, so a document with elements
880 * or on children needs the calls and actions that check reads, and this overload gives them.
881 */
882template <typename Source, typename Access = Reflect::RecordAccess<Source>>
883[[nodiscard]] std::optional<std::vector<uint32_t>> instantiate_rows(
884 const ManifestTables<Source, Access>& tables, const Source& root,
885 std::string_view template_id, const Kakshya::CompositeArray& rows,
886 Surface& surface, std::string& error)
887{
888 error.clear();
889 Detail::DocumentWalk<Source, Access> walk(tables.factories, root, error, &tables.actions, &tables.calls);
890 if (!walk.read_structure())
891 return std::nullopt;
892 const auto placers = walk.prepare_bulk(template_id, rows);
893 if (!placers)
894 return std::nullopt;
895
896 std::vector<uint32_t> elements;
897 elements.reserve(placers->size());
898 for (const auto& placer : *placers) {
899 const auto element = placer(surface, error);
900 if (!element)
901 return std::nullopt;
902 elements.push_back(*element);
903 }
904 return elements;
905}
906
907}
Owns a sequence of values that share a CompositeLayout.
std::function< std::optional< Action >(const Source &, std::string &)> Maker
Actions by name, which a document attaches to events and never defines.
std::function< std::optional< Placer >(const Source &, const Source &, const ElementHit &, std::string &)> Maker
Functions a document calls by name, with the function's own parameter names as attributes.
bool subscribe(uint32_t id, Vruta::WindowEventFilter filter, SubscriberFn fn)
Subscribe to the window events that reach an element, without replacing any of its own callbacks.
Definition Context.cpp:163
static bool receives(const Vruta::WindowEventFilter &filter) noexcept
Whether an element can receive what a filter asks for.
Definition Context.cpp:136
Event wiring between a Layer and a window surface.
Definition Context.hpp:42
std::optional< Prepared > prepare(SurfaceMap &surfaces)
ActionTable< Source, Access > Actions
Reflect::AttributeIndex< Source, Access > m_names
std::vector< PreparedInstance > Prepared
bool read_actions(const Source &instance, InstanceInfo &info)
bool check_relations(const SurfaceInstances &entry)
std::optional< std::vector< Placer > > prepare_bulk(std::string_view template_id, const Kakshya::CompositeArray &rows)
static void wire(Surface &surface, uint32_t element, const std::string &instance, const ActionBinding &binding)
bool read_flag(const Source &instance, std::string_view name, std::string_view value, bool &out)
std::optional< Placer > vertex_placer(const Source &form, const Source &element, const ElementHit &hit)
The placement of vertices written in a form element, which have no state.
std::vector< SurfaceInstances > m_surfaces
DocumentWalk(const Table &table, const Source &root, std::string &error, const Actions *actions=nullptr, const Calls *calls=nullptr)
std::optional< std::string > claim_id(const Source &source)
bool only_attributes(const Source &source, std::initializer_list< std::string_view > allowed, std::string_view allowed_prefix={})
bool fail(const Source &at, std::string message)
std::optional< std::string > claim_name(const Source &source)
bool read_element(const Source &element, InstanceInfo &info)
An element declares what C++ declares for one placed form: its name, the initial state,...
bool read_action(const Source &on, InstanceInfo &info)
static bool apply(const Prepared &prepared, const std::vector< uint32_t > &elements, std::string &error)
Names every placed element after its instance, then applies the document's Layer attributes: relation...
std::unordered_map< std::string, Source > m_templates
bool read_layer_attributes(const Source &instance, LayerAttributes &out)
bool check_form(const Source &form)
A form either calls a registered function or gives vertices to draw, as C++ either passes a function'...
FactoryTable< Source, Access > Table
bool read_template(const Source &definition)
Reflect::AttributeIndex< Source, Access > m_ids
static std::string located(uint64_t row, std::string_view message)
std::function< std::optional< Placer >(const Source &, const Source &, std::string &)> Instantiator
std::function< std::optional< uint32_t >(Surface &, std::string &)> Placer
Named factories that turn a template's factory element and an instance into placed Forma elements,...
bool set_interactive(uint32_t id, bool interactive)
Definition Layer.cpp:87
bool set_visible(uint32_t id, bool visible)
Definition Layer.cpp:96
bool bring_to_front(uint32_t id)
Move element to the top of the hit-test and paint order (drawn last), cascading to every related elem...
Definition Layer.cpp:119
bool send_to_back(uint32_t id)
Move element to the bottom of the hit-test and paint order (drawn first), cascading to every related ...
Definition Layer.cpp:145
bool set_clip(uint32_t id, std::optional< Kinesis::AABB2D > clip)
Confine hit testing of an element to a region, or lift the confinement with std::nullopt.
Definition Layer.cpp:78
Flat registry of Elements on a surface.
Definition Layer.hpp:28
Context & ctx() noexcept
Access the event router.
Definition Surface.hpp:170
Layer & layer() noexcept
Access the spatial registry.
Definition Surface.hpp:159
Named owner of a (Window, Layer, Context) triple: the Forma canvas.
Definition Surface.hpp:121
The values of one attribute across a tree, each claimed by one element.
WindowEventType
Types of window and input events.
MouseButtons
Enumeration for mouse buttons.
Definition Keys.hpp:203
std::optional< Keys > from_string(std::string_view str) noexcept
Converts a string to the corresponding Keys enum value.
Definition Keys.cpp:42
Placer form_placer(Geometry::Form< State > form, State initial)
A Placer that places a form with an initial state on a Surface and returns its element id.
Definition CallTable.hpp:44
std::optional< PlacedInstances > instantiate(const FactoryTable< Source, Access > &table, const ActionTable< Source, Access > *actions, const CallTable< Source, Access > *calls, const Source &root, SurfaceMap &surfaces, std::string &error)
std::map< std::string, PlacedInstance, std::less<> > PlacedInstances
The placed instances of a document by the id the document gave them.
constexpr std::string_view action_button_attribute
constexpr std::string_view element_name_attribute
Attribute that names an element, which shares the namespace of ids.
constexpr std::string_view reserved_state_attribute
Attribute of an element that holds the initial value of its state.
Definition CallTable.hpp:17
std::optional< std::vector< uint32_t > > instantiate_rows(const FactoryTable< Source, Access > &table, const Source &root, std::string_view template_id, const Kakshya::CompositeArray &rows, Surface &surface, std::string &error)
Make one element per row of typed placements from a single template.
constexpr std::string_view reserved_call_attribute
Attribute of a form element that names the function it calls.
Definition CallTable.hpp:14
constexpr std::string_view reserved_action_element
The child element of an instance that attaches an action to an event.
void apply_hit(Geometry::Form< T > &form, const ElementHit &hit)
Write a document's spatial fields after a form's own.
constexpr std::string_view action_event_attribute
Attribute names of an on element that the document owns.
constexpr std::string_view action_name_attribute
std::function< void(const ActionEvent &)> Action
Code a host registers by name to run when an instance's event happens.
bool read_hit_child(const Source &child, ElementHit &hit, std::string &error)
Read one spatial child of an element into hit.
constexpr std::string_view vertex_topology_attribute
Attribute of a form element that gives vertices to draw instead of a call.
Geometry::Form< std::monostate > vertex_form(const VertexGeometryInputs &input)
A Form with no state that draws ordered vertices exactly as written.
constexpr std::string_view action_key_attribute
constexpr std::string_view reserved_id_attribute
Attribute names a document owns on an instance.
std::map< std::string, Surface, std::less<> > SurfaceMap
Surfaces by the document name a host binds them to.
constexpr std::string_view reserved_prefix
constexpr std::string_view reserved_template_attribute
std::optional< PlacedInstances > instantiate_document(const FactoryTable< Source, Access > &table, const Source &root, SurfaceMap &surfaces, std::string &error)
Place every instance of a document through a table.
Reflect::RecordBinding< VertexGeometryInputs, Source, Access > vertex_binding()
The binding of a vertex form: a topology and one or more vertex children, with an optional defaults c...
bool is_hit_child(std::string_view name)
Whether an element of this name sets spatial fields: bounds, or a region.
std::optional< std::string_view > check_reference(const Source &source, std::string_view attribute, Exists &&exists, std::string &error)
Check that an element's attribute names a value that exists.
Event data for window and input events.
static AABB2D from_origin_size(glm::vec2 origin, glm::vec2 size) noexcept
Construct from a minimum corner and a size.
Definition Bounds.hpp:104
Axis-aligned bounding rectangle in a 2D coordinate space.
Definition Bounds.hpp:63
An action prepared for one event of one instance: the filter to subscribe with, and the action a host...
std::optional< Kinesis::AABB2D > clip
The document's own attributes on an instance, all beginning with the reserved prefix.
The spatial fields a document gives an element, as Element carries them.
std::string name
Optional human-readable label for Lila introspection and debug logging.
Definition Element.hpp:100
A bounded, renderable region on a window surface.
Definition Element.hpp:62
ActionTable< IO::XmlElementView, Reflect::RecordAccess< IO::XmlElementView > > actions
FactoryTable< IO::XmlElementView, Reflect::RecordAccess< IO::XmlElementView > > factories
CallTable< IO::XmlElementView, Reflect::RecordAccess< IO::XmlElementView > > calls
The three tables a document is placed through, as one plain value.
uint32_t element
The id of the element the instance is anchored on, in that surface's Layer.
std::string surface
The document's surface id, a key of the SurfaceMap that was given.
Where an instance of a document ended up.
Conversion of authored text to one value type.
Definition TextCodec.hpp:81
std::optional< Core::WindowEventType > event_type
std::optional< IO::MouseButtons > button
Filter criteria for window input events.