1 module sbylib.event.charevent;
2 
3 import std;
4 import sbylib.wrapper.glfw;
5 import sbylib.event;
6 
7 private alias CharCallback = void delegate(Window, uint);
8 
9 private struct CharNotification {}
10 private struct Char_t {}
11 
12 Char_t Char() {
13     return Char_t();
14 }
15 
16 CharNotification typed(Char_t) {
17     return CharNotification();
18 }
19 
20 Event!(uint) when(CharNotification condition) {
21     import sbylib.event : when;
22 
23     auto event = new Event!(uint);
24     auto cb = CharEventWatcher.add((Window, uint codepoint) {
25         event.fire(codepoint);
26     });
27     when(event.finish).then({
28         CharEventWatcher.remove(cb);
29     });
30     return event;
31 }
32 
33 private class CharEventWatcher {
34 static:
35     private Array!CharCallback callbackList;
36     private bool initialized = false;
37 
38     private void use() {
39         if (initialized) return;
40         initialized = true;
41         Window.getCurrentWindow().setCharCallback!(charCallback, (Exception e) { assert(false, e.toString()); });
42     }
43 
44     private CharCallback add(CharCallback callback) {
45         use();
46         callbackList ~= callback;
47         return callback;
48     }
49 
50     private void remove(CharCallback callback) {
51         callbackList.linearRemove(callbackList[].find(callback).take(1));
52     }
53 
54     void charCallback(Window window, uint codepoint) {
55         foreach (cb; callbackList) {
56             cb(window, codepoint);
57         }
58     }
59 }