Skip to content
Flecs v4.2
script/events

  • C

    View on GitHub

    1#include <events.h>
    2#include <stdio.h>
    3
    4// This example shows how to use mouse, keyboard and focus events in scripts.
    5// The script describes a panel with a text field, a slider and a button. Each
    6// widget uses async blocks to wait for the events it is interested in.
    7//
    8// The application is responsible for figuring out which entity is under the
    9// mouse, and sends events with ecs_script_mouse_event() and
    10// ecs_script_keyboard_event(). Events are first delivered to their target, and
    11// then propagate to the parents of the target. Keyboard events are delivered to
    12// the entity that has the focus.
    13
    14// Tag for entities that can get the focus
    15ECS_TAG_DECLARE(Focusable);
    16
    17// Position of an entity relative to its parent
    18typedef struct {
    19 float x, y;
    20} Position;
    21
    22ECS_COMPONENT_DECLARE(Position);
    23
    24const char *code =
    25 "using flecs.script\n"
    26 "\n"
    27
    28 // A button counts how often it is activated. The activate event is sent
    29 // when the button is clicked, and when Enter or Space is pressed while the
    30 // button has the focus. A click on a child of the button (like its label)
    31 // propagates to the button.
    32 "template Button {\n"
    33 " Focusable\n"
    34 " mut count = 0\n"
    35 " async {\n"
    36 " while true {\n"
    37 " const e = await on.activate(this)\n"
    38 " count = count + 1\n"
    39 " if e.keyboard {\n"
    40 " await print(\"{this.name()}: activated by key ({count})\")\n"
    41 " } else {\n"
    42 " await print(\"{this.name()}: activated by click ({count})\")\n"
    43 " }\n"
    44 " }\n"
    45 " }\n"
    46 "}\n"
    47 "\n"
    48
    49 // A slider changes its value when it is dragged. A drag event is delivered
    50 // for each mouse movement while a button is held down, with the distance
    51 // moved since the previous event in delta_x and delta_y.
    52 "template Slider {\n"
    53 " Focusable\n"
    54 " mut value = 50\n"
    55 " async {\n"
    56 " while true {\n"
    57 " const e = await on.drag(this)\n"
    58 " if e.delta_x != 0 {\n"
    59 " value = value + e.delta_x\n"
    60 " await print(\"{this.name()}: dragged to {value}\")\n"
    61 " }\n"
    62 " }\n"
    63 " }\n"
    64 " async {\n"
    65 " while true {\n"
    66 " const e = await on.key_down(this)\n"
    67 " if e.key == \"ArrowRight\" {\n"
    68 " value = value + 1\n"
    69 " await print(\"{this.name()}: stepped to {value}\")\n"
    70 " }\n"
    71 " }\n"
    72 " }\n"
    73 "}\n"
    74 "\n"
    75
    76 // A text field reacts to getting and losing the focus, and adds the keys
    77 // that are typed to its text. Typed keys stop propagating, so that they are
    78 // not handled by the panel as well. Escape does propagate.
    79 "template TextField {\n"
    80 " Focusable\n"
    81 " mut text = \"\"\n"
    82 " async {\n"
    83 " while true {\n"
    84 " await on.focus(this)\n"
    85 " await print(\"{this.name()}: focused\")\n"
    86 " }\n"
    87 " }\n"
    88 " async {\n"
    89 " while true {\n"
    90 " await on.blur(this)\n"
    91 " await print(\"{this.name()}: lost focus\")\n"
    92 " }\n"
    93 " }\n"
    94 " async {\n"
    95 " while true {\n"
    96 " const e = await on.key_down(this)\n"
    97 " if e.key != \"Escape\" {\n"
    98 " text = \"{text}{e.key}\"\n"
    99 " await print(\"{this.name()}: text is '{text}'\")\n"
    100 " await e.stop_propagation()\n"
    101 " }\n"
    102 " }\n"
    103 " }\n"
    104 "}\n"
    105 "\n"
    106
    107 // The panel receives the events of its children. It gets a focus event
    108 // whenever one of its children gets the focus, and handles keys that its
    109 // children let through. Escape clears the focus with the focus() function.
    110 // When a press propagates to the panel, local_x and local_y are relative to
    111 // the panel instead of to the entity that was pressed.
    112 "template Panel {\n"
    113 " async {\n"
    114 " while true {\n"
    115 " const e = await on.press(this)\n"
    116 " const x: i32 = e.local_x\n"
    117 " const y: i32 = e.local_y\n"
    118 " await print(\"{this.name()}: press at {x}, {y}\")\n"
    119 " }\n"
    120 " }\n"
    121 " async {\n"
    122 " while true {\n"
    123 " const e = await on.focus(this)\n"
    124 " await print(\"{this.name()}: focus moved to {e.target.name()}\")\n"
    125 " }\n"
    126 " }\n"
    127 " async {\n"
    128 " while true {\n"
    129 " const e = await on.key_down(this)\n"
    130 " if e.key == \"Escape\" {\n"
    131 " await focus(0)\n"
    132 " await print(\"{this.name()}: Escape cleared the focus\")\n"
    133 " } else {\n"
    134 " await print(\"{this.name()}: received key {e.key}\")\n"
    135 " }\n"
    136 " }\n"
    137 " }\n"
    138 "}\n"
    139 "\n"
    140 "Panel panel {\n"
    141 " Position: {100, 100}\n"
    142 " TextField name { Position: {10, 10} }\n"
    143 " Slider volume { Position: {10, 40} }\n"
    144 " Button ok {\n"
    145 " Position: {10, 70}\n"
    146 " label { Position: {5, 5} }\n"
    147 " }\n"
    148 "}\n";
    149
    150// Print function that can be called from async blocks. Async functions return
    151// a future, which this function resolves immediately.
    152static void print(
    153 const ecs_function_ctx_t *ctx,
    154 int32_t argc,
    155 const ecs_value_t *argv,
    156 ecs_script_future_t *future)
    157{
    158 (void)ctx;
    159 (void)argc;
    160 bool ok = true;
    161 printf(" %s\n", *(char**)argv[0].ptr);
    162 ecs_script_future_resolve(future,
    163 &(ecs_value_t){ .type = ecs_id(ecs_bool_t), .ptr = &ok });
    164 ecs_script_future_release(future);
    165}
    166
    167// Hook that decides which entity gets the focus. When a mouse button is
    168// pressed, the focus goes to the first entity with the Focusable tag, starting
    169// from the entity under the mouse. A press on an entity without a Focusable
    170// parent (like the panel background) keeps the focus where it is.
    171static ecs_entity_t to_focus(
    172 ecs_world_t *world,
    173 ecs_entity_t entity,
    174 ecs_entity_t current,
    175 ecs_script_focus_source_t source,
    176 void *ctx)
    177{
    178 (void)ctx;
    179
    180 // Accept focus changes from the application and from scripts as they are
    181 if (source != EcsScriptFocusPress) {
    182 return entity;
    183 }
    184
    185 for (; entity; entity = ecs_get_parent(world, entity)) {
    186 if (ecs_has(world, entity, Focusable)) {
    187 return entity;
    188 }
    189 }
    190
    191 return current;
    192}
    193
    194// Hook that converts a screen position to a position relative to an entity.
    195// When a mouse event propagates to a parent, the event module calls this hook
    196// to compute local_x and local_y for the parent.
    197static void to_local(
    198 ecs_world_t *world,
    199 ecs_entity_t entity,
    200 float screen_x,
    201 float screen_y,
    202 float *local_x,
    203 float *local_y,
    204 void *ctx)
    205{
    206 (void)ctx;
    207
    208 *local_x = screen_x;
    209 *local_y = screen_y;
    210
    211 // Subtract the positions of the entity and its parents
    212 for (; entity; entity = ecs_get_parent(world, entity)) {
    213 const Position *p = ecs_get(world, entity, Position);
    214 if (p) {
    215 *local_x -= p->x;
    216 *local_y -= p->y;
    217 }
    218 }
    219}
    220
    221// Send a mouse event. The target is the entity under the mouse, and buttons is
    222// a bitmask of the buttons that are held down. The event module derives press,
    223// drag, release and click events from changes in the buttons. The application
    224// provides the position relative to the target, which here uses the same
    225// function as the to_local hook.
    226static void mouse(
    227 ecs_world_t *world,
    228 ecs_entity_t target,
    229 float x,
    230 float y,
    231 uint32_t buttons)
    232{
    233 EcsScriptMouseEvent evt = {
    234 .target = target,
    235 .screen_x = x, .screen_y = y,
    236 .buttons = buttons
    237 };
    238
    239 to_local(world, target, x, y, &evt.local_x, &evt.local_y, NULL);
    240 ecs_script_mouse_event(world, &evt);
    241}
    242
    243// Send a key down and key up event to the entity with the focus
    244static void key(
    245 ecs_world_t *world,
    246 const char *name)
    247{
    248 char *k = ECS_CONST_CAST(char*, name);
    249 ecs_script_keyboard_event(world, &(EcsScriptKeyboardEvent){
    250 .key = k, .down = true });
    251 ecs_script_keyboard_event(world, &(EcsScriptKeyboardEvent){
    252 .key = k, .down = false });
    253}
    254
    255static void print_focus(
    256 ecs_world_t *world)
    257{
    258 ecs_entity_t focus = ecs_script_get_focus(world);
    259 printf(" [app] focus is %s\n", focus ? ecs_get_name(world, focus) : "none");
    260}
    261
    262int main(int argc, char *argv[]) {
    263 ecs_world_t *world = ecs_init_w_args(argc, argv);
    264
    265 // Import the module that adds the on.* functions to scripts
    266 ECS_IMPORT(world, FlecsScriptInput);
    267
    268 ECS_TAG_DEFINE(world, Focusable);
    269 ECS_COMPONENT_DEFINE(world, Position);
    270
    271 // Add reflection data to Position so it can be assigned in the script
    272 ecs_struct(world, {
    273 .entity = ecs_id(Position),
    274 .members = {
    275 { .name = "x", .type = ecs_id(ecs_f32_t) },
    276 { .name = "y", .type = ecs_id(ecs_f32_t) }
    277 }
    278 });
    279
    280 ecs_async_function(world, {
    281 .name = "print",
    282 .return_type = ecs_id(ecs_bool_t),
    283 .params = {{ .name = "msg", .type = ecs_id(ecs_string_t) }},
    284 .callback = print
    285 });
    286
    287 ecs_script_set_event_hooks(world, &(ecs_script_event_hooks_t){
    288 .to_local = to_local,
    289 .to_focus = to_focus
    290 });
    291
    292 if (!ecs_script(world, { .code = code })) {
    293 printf("script failed to run\n");
    294 return -1;
    295 }
    296
    297 // Run the async blocks until they wait for their first event
    298 ecs_script_tasks_progress(world);
    299
    300 ecs_entity_t panel = ecs_lookup(world, "panel");
    301 ecs_entity_t name = ecs_lookup(world, "panel.name");
    302 ecs_entity_t volume = ecs_lookup(world, "panel.volume");
    303 ecs_entity_t ok = ecs_lookup(world, "panel.ok");
    304 ecs_entity_t label = ecs_lookup(world, "panel.ok.label");
    305
    306 // The click on the label propagates to the button. The to_focus hook moves
    307 // the focus from the label to the button.
    308 printf("Click the label of the ok button:\n");
    309 mouse(world, label, 117, 177, 1);
    310 mouse(world, label, 117, 177, 0);
    311 print_focus(world);
    312
    313 // Keys typed into the text field don't reach the panel
    314 printf("\nClick the name field and type:\n");
    315 mouse(world, name, 120, 115, 1);
    316 mouse(world, name, 120, 115, 0);
    317 key(world, "h");
    318 key(world, "i");
    319
    320 // The panel is not Focusable, so the focus stays on the text field
    321 printf("\nClick the panel background:\n");
    322 mouse(world, panel, 180, 190, 1);
    323 mouse(world, panel, 180, 190, 0);
    324 print_focus(world);
    325
    326 // Move the mouse to the slider, press, move while pressed and release
    327 printf("\nDrag the volume slider:\n");
    328 mouse(world, volume, 120, 145, 0);
    329 mouse(world, volume, 120, 145, 1);
    330 mouse(world, volume, 140, 145, 1);
    331 mouse(world, volume, 155, 145, 1);
    332 mouse(world, volume, 155, 145, 0);
    333
    334 // The slider doesn't stop the key event, so it propagates to the panel
    335 printf("\nPress a key on the slider:\n");
    336 key(world, "ArrowRight");
    337
    338 // Applications can set the focus directly, for example to implement Tab
    339 printf("\nMove the focus from the application:\n");
    340 ecs_script_set_focus(world, ok);
    341 key(world, "Enter");
    342
    343 printf("\nPress Escape:\n");
    344 key(world, "Escape");
    345 print_focus(world);
    346
    347 return ecs_fini(world);
    348
    349 // Output
    350 // Click the label of the ok button:
    351 // panel: focus moved to ok
    352 // panel: press at 17, 77
    353 // ok: activated by click (1)
    354 // [app] focus is ok
    355 //
    356 // Click the name field and type:
    357 // name: focused
    358 // panel: focus moved to name
    359 // panel: press at 20, 15
    360 // name: text is 'h'
    361 // name: text is 'hi'
    362 //
    363 // Click the panel background:
    364 // panel: press at 80, 90
    365 // [app] focus is name
    366 //
    367 // Drag the volume slider:
    368 // name: lost focus
    369 // panel: focus moved to volume
    370 // panel: press at 20, 45
    371 // volume: dragged to 70
    372 // volume: dragged to 85
    373 //
    374 // Press a key on the slider:
    375 // volume: stepped to 86
    376 // panel: received key ArrowRight
    377 //
    378 // Move the focus from the application:
    379 // panel: focus moved to ok
    380 // ok: activated by key (2)
    381 // panel: received key Enter
    382 //
    383 // Press Escape:
    384 // panel: Escape cleared the focus
    385 // [app] focus is none
    386}
    FLECS_API const ecs_entity_t ecs_id(EcsDocDescription)
    Component ID for EcsDocDescription.
    bool ecs_bool_t
    Primitive type definitions.
    Definition meta.h:95
    char * ecs_string_t
    Built-in string type.
    Definition meta.h:110
    float ecs_f32_t
    Built-in f32 type.
    Definition meta.h:108
    #define ecs_struct(world,...)
    Create a struct type.
    Definition meta.h:1838
    #define ECS_IMPORT(world, id)
    Wrapper around ecs_import().
    Definition module.h:125
    ecs_id_t ecs_entity_t
    An entity identifier.
    Definition flecs.h:396
    struct ecs_world_t ecs_world_t
    A world is the container for all ECS data and supporting features.
    Definition flecs.h:440
    ecs_entity_t ecs_get_parent(const ecs_world_t *world, ecs_entity_t entity)
    Get the parent (target of the ChildOf relationship) for an entity.
    #define ECS_TAG_DECLARE
    Forward declare a tag.
    Definition flecs_c.h:29
    #define ECS_COMPONENT_DEFINE(world, id_)
    Define a forward-declared component.
    Definition flecs_c.h:75
    #define ECS_TAG_DEFINE(world, id_)
    Define a forward-declared tag.
    Definition flecs_c.h:39
    #define ECS_COMPONENT_DECLARE(id)
    Forward declare a component.
    Definition flecs_c.h:65
    #define ecs_get(world, entity, T)
    Get a component.
    Definition flecs_c.h:342
    #define ecs_has(world, entity, T)
    Test if an entity has a component.
    Definition flecs_c.h:498
    ecs_entity_t ecs_lookup(const ecs_world_t *world, const char *path)
    Look up an entity by its path.
    const char * ecs_get_name(const ecs_world_t *world, ecs_entity_t entity)
    Get the name of an entity.
    int ecs_fini(ecs_world_t *world)
    Delete a world.
    ecs_world_t * ecs_init_w_args(int argc, char *argv[])
    Create a new world with arguments.
    Script function context.
    Definition script.h:150
    Value of a dynamic type.
    Definition flecs.h:1069
    flecs::entity entity(Args &&... args) const
    Create an entity.