forked from Nivekk/KOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binding.cs
131 lines (114 loc) · 3.55 KB
/
Binding.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace kOS
{
public class kOSBinding : Attribute
{
public string[] Contexts;
public kOSBinding(params string[] contexts) { Contexts = contexts; }
}
public class BindingManager
{
public CPU cpu;
public Dictionary<String, BindingSetDlg> Setters = new Dictionary<String, BindingSetDlg>();
public Dictionary<String, BindingGetDlg> Getters = new Dictionary<String, BindingGetDlg>();
public List<Binding> Bindings = new List<Binding>();
public delegate void BindingSetDlg (CPU cpu, object val);
public delegate object BindingGetDlg (CPU cpu);
public BindingManager(CPU cpu, String context)
{
this.cpu = cpu;
var contexts = new string[1];
contexts[0] = context;
foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())
{
kOSBinding attr = (kOSBinding)t.GetCustomAttributes(typeof(kOSBinding), true).FirstOrDefault();
if (attr != null)
{
if (attr.Contexts.Count() == 0 || attr.Contexts.Intersect(contexts).Any())
{
Binding b = (Binding)Activator.CreateInstance(t);
b.AddTo(this);
Bindings.Add(b);
}
}
}
}
public void AddGetter(String name, BindingGetDlg dlg)
{
Variable v = cpu.FindVariable(name);
if (v == null) v = cpu.FindVariable(name.Split(":".ToCharArray())[0]);
if (v != null)
{
if (v is BoundVariable)
{
((BoundVariable)v).Get = dlg;
}
}
else
{
var bv = cpu.CreateBoundVariable(name);
bv.Get = dlg;
bv.cpu = cpu;
}
}
public void AddSetter(String name, BindingSetDlg dlg)
{
Variable v = cpu.FindVariable(name.ToLower());
if (v != null)
{
if (v is BoundVariable)
{
((BoundVariable)v).Set = dlg;
}
}
else
{
var bv = cpu.CreateBoundVariable(name.ToLower());
bv.Set = dlg;
bv.cpu = cpu;
}
}
public void Update(float time)
{
foreach (Binding b in Bindings)
{
b.Update(time);
}
}
}
public class Binding
{
public virtual void AddTo(BindingManager manager) { }
public virtual void Update(float time) { }
}
public class BoundVariable : Variable
{
public BindingManager.BindingSetDlg Set;
public BindingManager.BindingGetDlg Get;
public CPU cpu;
public override object Value
{
get
{
return Get(cpu);
}
set
{
Set(cpu, value);
}
}
}
[kOSBinding]
public class TestBindings : Binding
{
public override void AddTo(BindingManager manager)
{
//manager.AddGetter("TEST1", delegate(CPU cpu) { return 4; });
//manager.AddSetter("TEST1", delegate(CPU cpu, object val) { cpu.PrintLine(val.ToString()); });
}
}
}