-
Notifications
You must be signed in to change notification settings - Fork 128
/
minigui_xml.d
421 lines (368 loc) · 10.3 KB
/
minigui_xml.d
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
/++
A small extension module to [arsd.minigui] that adds
functions for creating widgets and windows from short
XML descriptions.
If you choose to use this, it will require [arsd.dom]
to be compiled into your project too.
---
import arsd.minigui_xml;
Window window = createWindowFromXml(`
<MainWindow>
<Button label="Hi!" />
</MainWindow>
`);
---
To add custom widgets to the minigui_xml factory, you need
to register them with FIXME.
You can attach some events right in the XML using attributes.
The attribute names are `onEVENTNAME` or `ondirectEVENTNAME`
and the values are one of the following three value types:
$(LIST
* If it starts with `&`, it is a delegate you need
to register using the FIXME function.
* If it starts with `(`, it is a string passed to
the [arsd.dom.querySelector] function to get an
element reference
* Otherwise, it tries to call a script function (if
scripting is available).
)
Keep in mind
For example, to make a page widget that changes based on a
drop down selection, you may:
```xml
<DropDownSelection onchange="$(+PageWidget).setCurrentTab">
<option>Foo</option>
<option>Bar</option>
</DropDownSelection>
<PageWidget name="mypage">
<!-- contents elided -->
</PageWidget>
```
That will create a select widget that when it changes, it will
look for the next PageWidget sibling (that's the meaning of `+PageWidget`,
see css selector syntax for more) and call its `setCurrentTab`
method.
Since the function knows `setCurrentTab` takes an integer, it will
automatically pull the `intValue` member out of the event and pass
it to the method.
The given XML is the same as the following D:
---
auto select = new DropDownSelection(parent);
select.addOption("Foo");
select.addOption("Bar");
auto page = new PageWidget(parent);
page.name = "mypage";
select.addEventListener("change", (Event event)
{
page.setCurrentTab(event.intValue);
});
---
+/
module arsd.minigui_xml;
public import arsd.minigui;
public import arsd.minigui : Event;
import arsd.textlayouter;
import arsd.dom;
import std.conv;
import std.exception;
import std.functional : toDelegate;
import std.string : strip;
import std.traits;
private template ident(T...)
{
static if(is(T[0]))
alias ident = T[0];
else
alias ident = void;
}
enum ParseContinue { recurse, next, abort }
alias WidgetFactory = ParseContinue delegate(Widget parent, Element element, out Widget result);
alias WidgetTextHandler = void delegate(Widget widget, string text);
WidgetFactory[string] widgetFactoryFunctions;
WidgetTextHandler[string] widgetTextHandlers;
void delegate(string eventName, Widget, Event, string content) xmlScriptEventHandler;
static this()
{
xmlScriptEventHandler = toDelegate(&nullScriptEventHandler);
}
void nullScriptEventHandler(string eventName, Widget w, Event e, string)
{
import std.stdio : stderr;
stderr.writeln("Ignoring event ", eventName, " ", e, " on widget ", w.elementName, " because xmlScriptEventHandler is not set");
}
private bool startsWith(T)(T[] doesThis, T[] startWithThis)
{
return doesThis.length >= startWithThis.length && doesThis[0 .. startWithThis.length] == startWithThis;
}
private bool isLower(char c)
{
return c >= 'a' && c <= 'z';
}
private bool isUpper(char c)
{
return c >= 'A' && c <= 'Z';
}
private char assumeLowerToUpper(char c)
{
return cast(char)(c - 'a' + 'A');
}
private char assumeUpperToLower(char c)
{
return cast(char)(c - 'A' + 'a');
}
string hyphenate(string argname)
{
int hyphen;
foreach (i, char c; argname)
if (c.isUpper && (i == 0 || !argname[i - 1].isUpper))
hyphen++;
if (hyphen == 0)
return argname;
char[] ret = new char[argname.length + hyphen];
int i;
bool prevUpper;
foreach (char c; argname)
{
bool upper = c.isUpper;
if (upper)
{
if (!prevUpper)
ret[i++] = '-';
ret[i++] = c.assumeUpperToLower;
}
else
{
ret[i++] = c;
}
prevUpper = upper;
}
assert(i == ret.length);
return cast(string) ret;
}
string unhyphen(string argname)
{
int hyphen;
foreach (i, char c; argname)
if (c == '-' && (i == 0 || argname[i - 1] != '-'))
hyphen++;
if (hyphen == 0)
return argname;
char[] ret = new char[argname.length - hyphen];
int i;
char prev;
foreach (char c; argname)
{
if (c != '-')
{
if (prev == '-' && c.isLower)
ret[i++] = c.assumeLowerToUpper;
else
ret[i++] = c;
}
prev = c;
}
assert(i == ret.length);
return cast(string) ret;
}
void initMinigui(Modules...)()
{
import std.traits;
import std.conv;
static foreach (alias Module; Modules)
{
pragma(msg, Module.stringof);
appendMiniguiModule!Module;
}
}
void appendMiniguiModule(alias Module, string prefix = null)()
{
foreach(memberName; __traits(allMembers, Module)) static if(!__traits(isDeprecated, __traits(getMember, Module, memberName)))
{
alias Member = ident!(__traits(getMember, Module, memberName));
static if(is(Member == class) && !isAbstractClass!Member && is(Member : Widget) && __traits(getProtection, Member) != "private")
{
widgetFactoryFunctions[prefix ~ memberName] = (Widget parent, Element element, out Widget widget)
{
static if(is(Member : Dialog))
{
widget = new Member();
}
else static if(is(Member : Menu))
{
widget = new Menu(null, null);
}
else static if(is(Member : Window))
{
widget = new Member("test");
}
else
{
string[string] args = element.attributes;
enum paramNames = ParameterIdentifierTuple!(__traits(getMember, Member, "__ctor"));
Parameters!(__traits(getMember, Member, "__ctor")) params;
static assert(paramNames.length, Member);
bool[cast(int)paramNames.length - 1] requiredParams;
static foreach (idx, param; params[0 .. $-1])
{{
enum hyphenated = paramNames[idx].hyphenate;
if (auto arg = hyphenated in args)
{
enforce(!requiredParams[idx], "May pass required parameter " ~ hyphenated ~ " only exactly once");
requiredParams[idx] = true;
static if(is(typeof(param) == MemoryImage))
{
}
else static if(is(typeof(param) == Color))
{
params[idx] = Color.fromString(*arg);
}
else static if(is(typeof(param) == TextLayouter))
params[idx] = null;
else
params[idx] = to!(typeof(param))(*arg);
}
else
{
enforce(false, "Missing required parameter " ~ hyphenated ~ " for Widget " ~ memberName);
assert(false);
}
}}
params[$-1] = cast(typeof(params[$-1])) parent;
auto member = new Member(params);
widget = member;
foreach (argName, argValue; args)
{
if (argName.startsWith("on-"))
{
auto eventName = argName[3 .. $].unhyphen;
widget.addEventListener(eventName, (event) { xmlScriptEventHandler(eventName, member, event, argValue); });
}
else if (argName == "name")
member.name = argValue;
else if (argName == "statusTip")
member.statusTip = argValue;
else
{
argName = argName.unhyphen;
switch (argName)
{
static foreach (idx, param; params[0 .. $-1])
{
case paramNames[idx]:
}
break;
static if (is(typeof(Member.addParameter)))
{
default:
member.addParameter(argName, argValue);
break;
}
else
{
// TODO: add generic parameter setting here (iterate by UDA maybe)
default:
enforce(false, "Unknown parameter " ~ argName ~ " for Widget " ~ memberName);
assert(false);
}
}
}
}
}
return ParseContinue.recurse;
};
enum hasText = is(typeof(Member.text) == string) || is(typeof(Member.text()) == string);
enum hasContent = is(typeof(Member.content) == string) || is(typeof(Member.content()) == string);
enum hasLabel = is(typeof(Member.label) == string) || is(typeof(Member.label()) == string);
static if (hasText || hasContent || hasLabel)
{
enum member = hasText ? "text" : hasContent ? "content" : hasLabel ? "label" : null;
widgetTextHandlers[memberName] = (Widget widget, string text)
{
auto w = cast(Member)widget;
assert(w, "Called widget text handler with widget of type "
~ typeid(widget).name ~ " but it was registered for "
~ memberName ~ " which is incompatible");
mixin("w.", member, " = w.", member, " ~ text;");
};
}
// TODO: might want to check for child methods/structs that register as child nodes
}
}
}
///
Widget makeWidgetFromString(string xml, Widget parent)
{
auto document = new Document(xml, true, true);
auto r = document.root;
return miniguiWidgetFromXml(r, parent);
}
///
Window createWindowFromXml(string xml)
{
return createWindowFromXml(new Document(xml, true, true));
}
///
Window createWindowFromXml(Document document)
{
auto r = document.root;
return cast(Window) miniguiWidgetFromXml(r, null);
}
///
Widget miniguiWidgetFromXml(Element element, Widget parent)
{
Widget w;
miniguiWidgetFromXml(element, parent, w);
return w;
}
///
ParseContinue miniguiWidgetFromXml(Element element, Widget parent, out Widget w)
{
assert(widgetFactoryFunctions !is null, "No widget factories have been registered, register them using initMinigui!(arsd.minigui); at startup");
if (auto factory = element.tagName in widgetFactoryFunctions)
{
auto c = (*factory)(parent, element, w);
if (c == ParseContinue.recurse)
{
c = ParseContinue.next;
Widget dummy;
foreach (child; element.children)
if (miniguiWidgetFromXml(child, w, dummy) == ParseContinue.abort)
{
c = ParseContinue.abort;
break;
}
}
return c;
}
else if (element.tagName == "#text")
{
string text = element.nodeValue.strip;
if (text.length)
{
assert(parent, "got xml text without parent, make sure you only pass elements!");
if (auto factory = parent.elementName in widgetTextHandlers)
(*factory)(parent, text);
else
{
import std.stdio : stderr;
stderr.writeln("WARN: no text handler for widget ", parent.elementName, " ~= ", [text]);
}
}
return ParseContinue.next;
}
else
{
enforce(false, "Unknown tag " ~ element.tagName);
assert(false);
}
}
string elementName(Widget w)
{
if (w is null)
return null;
auto name = typeid(w).name;
foreach_reverse (i, char c; name)
if (c == '.')
return name[i + 1 .. $];
return name;
}