-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathGSMarkupDecoder.j
593 lines (511 loc) · 22.9 KB
/
GSMarkupDecoder.j
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
/* -*-objc-*-
Author: Daniel Boehringer (2012)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
*/
@import <Foundation/CPObject.j>
@import "GSMarkupConnector.j"
@implementation FSRegexBindingTransformer : CPObject
{
CPString _regex;
CPString _template;
CPString _revregex;
CPString _revtemplate;
}
- (id)initWithRegex:(CPString)aRegex template:(CPString)aTemplate reverseRegex:(CPString)revRegex reverseTemplate:(CPString)reverseTemplate
{
if (self = [super init])
{
_regex = aRegex;
_template = aTemplate;
_revregex = revRegex;
_revtemplate = reverseTemplate;
}
return self;
}
- (CPString)transformedValue:(id)theObject
{ var ret = theObject;
if (!ret)
return ret;
return ret.replace(new RegExp(_regex, "i"), _template)
}
- (id)reverseTransformedValue:(CPString)aString
{
var ret = aString;
if (!ret)
return ret;
return ret.replace(new RegExp(_revregex, "i"), _revtemplate)
}
+ (BOOL)allowsReverseTransformation
{
return YES;
}
@end
@implementation CPString (CapitalizedString)
- (CPString) stringByUppercasingFirstCharacter
{ var length = [self length];
if (length < 1) return self;
else {
var s;
/* Get the first character. */
var c = [self characterAtIndex: 0];
/* If it's not lowercase ... */
if (c < 'a' || c > 'z')
{
/* then no need to uppercase. */
return self;
}
/* Else, uppercase the first character. */
c = c.toUpperCase();
s = [CPString stringWithString:c];
if (length == 1) return s;
else return [s stringByAppendingString: [self substringFromIndex: 1]];
}
}
- (CPString) trimmedString
{ var t=self.replace(/^\s+|\s+$/g,"");
if(!t) return @"";
return [CPString stringWithString: t];
}
@end
@implementation CPData(FileLoading)
- (id)initWithContentsOfURL:(CPURL)aURL
{ var plist = [CPURLConnection sendSynchronousRequest:[CPURLRequest requestWithURL:aURL] returningResponse:nil error:nil];
if (plist == nil) return nil;
return plist;
}
- (id)initWithContentsOfFile:(CPString)aPath
{ return [self initWithContentsOfURL:[CPURL URLWithString:aPath]];
}
@end
@implementation GSMarkupDecoder: CPObject
{ var _uniqueID;
CPMutableDictionary _nameTable;
CPMutableDictionary _replicationNameTable;
CPDictionary _externalNameTable;
CPMutableDictionary _tagNameToObjectClass;
CPString _xmlStr;
CPMutableArray _objects;
CPMutableArray _connectors;
}
+ initialize
{ if(self=[super initialize])
{
}
return self;
}
+ (id) decoderWithContentsOfFile: (CPString)file
{
return [[self alloc] initWithContentsOfFile: file];
}
- (id) initWithContentsOfFile: (CPString)file
{
var d = [[CPData alloc] initWithContentsOfFile: file];
return [self initWithData: d];
}
- (id) initWithData: someXMLData
{ return [self initWithXMLString: [someXMLData rawString]];
}
- (Class) objectClassForTagName: (CPString)tagName mappedByFormatArray: arr
{ var c;
var capitalizedTagName = [tagName stringByUppercasingFirstCharacter];
var className = [_tagNameToObjectClass objectForKey: tagName];
if (className != nil) [arr insertObject:className atIndex:0];
var i, cnt=arr.length;
for(i=0; i<cnt; i++)
{ className = [CPString stringWithFormat: arr[i], capitalizedTagName];
c = CPClassFromString (className);
if (c != Nil) return c;
} return Nil;
}
- (Class) objectClassForTagName: (CPString)tagName
{ return [self objectClassForTagName: tagName
mappedByFormatArray: [CPArray arrayWithObjects: @"GSMarkup%@Tag",@"GSMarkupTag%@", @"GS%@Tag", @"GSTag%@", @"%@Tag", @"Tag%@"]];
}
- (id) connectorClassForTagName: (CPString)tagName
{ if (tagName == "control")
{ return [GSMarkupControlConnector class];
} else if (tagName == "outlet")
{ return [GSMarkupOutletConnector class];
}
return [self objectClassForTagName: tagName
mappedByFormatArray: [CPArray arrayWithObjects: @"GSMarkup%@Connector", @"GSMarkupConnector%@", @"GS%@Connector", @"GSConnector%@", @"%@Connector",@"Connector%@"]];
}
- (id) entityClassForTagName: (CPString)tagName
{ return [self objectClassForTagName: tagName mappedByFormatArray: [CPArray arrayWithObjects: @"GSMarkup%@"]];
}
- (id) attributesForDOMNode: aDOMNode
{ var attributes=aDOMNode.attributes;
if(!attributes) return nil;
var ret=[CPMutableDictionary dictionary];
var i,cnt=attributes.length;
for(i=0;i<cnt;i++)
{ [ret setValue: attributes[i].nodeValue forKey: attributes[i].nodeName];
}
return ret;
}
- (id) insertChildrenOfDOMNode: aDOMNode intoContainer: container
{ if(!aDOMNode) return nil;
var children;
if (children=aDOMNode.childNodes)
{ var tagChildren=[CPMutableArray new];
var childrenCount=children.length;
var i;
for(i=0;i<childrenCount;i++)
{ var co=[self insertMarkupObjectFromDOMNode: children[i] intoContainer: nil];
if(co) [tagChildren addObject: co ];
else
{ var cnv=children[i].nodeValue;
var ts=[cnv trimmedString];
if( ts && ts.length) return [CPArray arrayWithObject: cnv];
}
}
return tagChildren;
}
return nil;
}
- (id) insertMarkupObjectFromDOMNode: o intoContainer: container
{
var nclass;
nclass=[self objectClassForTagName: o.nodeName];
if(!nclass) nclass=[self connectorClassForTagName: o.nodeName];
if(!nclass) nclass=[self entityClassForTagName: o.nodeName];
if (nclass)
{ var attribs=[self attributesForDOMNode: o];
var oid=[attribs objectForKey:@"id"];
if(!oid) oid=[CPString stringWithFormat: @"%@%d", o.nodeName, ++_uniqueID];
var keys = [attribs allKeys];
var i, count = [keys count];
for (i = 0; i < count; i++)
{ var key, value;
key = [keys objectAtIndex: i];
if(![key length]) continue;
value = [attribs objectForKey: key];
if (container !== _connectors && ( key === 'delegate' || [value hasPrefix: @"#"]) )
{ if(container === _entites)
{ [attribs setObject: [GSMarkupConnector getObjectForIdString: [value substringFromIndex: 1] usingNameTable: _externalNameTable] forKey: key];
} else if(key !== 'itemsBinding' && key !== 'valueBinding' && key !== 'enabledBinding') // bindings will be processed elsewhere
{ var outlet; // GSMarkupOutletConnector
/* We pass the value unchanged to the outlet. If
* value contains a key value path using dots, those
* will be processed by the outlet when it is
* established. */
var outlet = [[GSMarkupOutletConnector alloc]
initWithSource: oid
target: value
label: key];
if(outlet)
{ [_connectors addObject: outlet];
/* Hide the attribute - it has been already processed. */
[attribs removeObjectForKey: key];
}
}
}
}
var newo= [[nclass alloc] initWithAttributes: attribs content: [self insertChildrenOfDOMNode: o intoContainer: container]];
if(!newo) return nil;
if(container) [container addObject:newo];
if(container!=_connectors) [_nameTable setObject:newo forKey:oid];
return newo;
} return nil;
}
- (id) parseXMLString: aXMLStr
{ function _parseXml(xmlStr)
{ if (typeof window.DOMParser != "undefined") {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
} else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.validateOnParse = false;
xmlDoc.loadXML(xmlStr);
if (xmlDoc.parseError.errorCode != 0)
{ alert("Error in line " + xmlDoc.parseError.line +
" position " + xmlDoc.parseError.linePos +
"\nError Code: " + xmlDoc.parseError.errorCode +
"\nError Reason: " + xmlDoc.parseError.reason +
"Error Line: " + xmlDoc.parseError.srcText);
}
return xmlDoc;
}
else {
throw new Error("No XML parser found");
}
}
var t= _parseXml(aXMLStr);
if(!t) return nil;
return t;
}
- (id) initWithXMLString:aXMLStr
{ _xmlStr=aXMLStr;
_nameTable=[CPMutableDictionary dictionary];
_tagNameToObjectClass=[CPMutableDictionary dictionary];
_objects=[CPMutableArray array];
_connectors=[CPMutableArray array];
_entites=[CPMutableArray array];
return self;
}
- (void) setExternalNameTable:(CPDictionary) context
{ _externalNameTable=context;
}
- (void) setObjectClass: (CPString)className
forTagName: (CPString)tagName
{ [_tagNameToObjectClass setObject: className forKey: tagName];
}
- (void) processDOMNode: aDOMNode intoContainer:(id) aContainer
{ if(!aDOMNode) return;
var children;
if (children = aDOMNode.childNodes)
{ var childrenCount=children.length;
for(i=0;i<childrenCount;i++)
{ [self insertMarkupObjectFromDOMNode: children[i] intoContainer: aContainer];
}
}
}
// replace symbolic relationships in entities with the real objects
- (void) _postprocessEntities
{ var i, l=_entites.length;
for(i=0;i<l;i++)
{ var e=_entites[i];
var eFS=[e platformObject];
var rels=[eFS relationships];
if(!rels) continue;
var j,l1=rels.length;
for(j=0;j<l1;j++)
{ [rels[j] setTarget: [[_nameTable objectForKey: [rels[j] target] ] platformObject] ];
}
}
}
-(id) _getObjectForIdString:(CPString) peek
{ var ret;
if ([peek hasPrefix: @"#"])
{ ret =[GSMarkupConnector getObjectForIdString: [peek substringFromIndex:1] usingNameTable: _externalNameTable]; // external objects are already platformObjects
} else ret= [GSMarkupConnector getPlatformObjectForIdString: peek usingNameTable: _nameTable];
return ret;
}
- (void) _postprocessForBindings:(CPArray) someArr
{ var i, l=someArr.length;
for(i = 0; i < l; i++)
{ var o=someArr[i];
if(![o respondsToSelector:@selector(platformObject)]) continue;
var oPO;
var peek;
if (peek=[[o attributes] objectForKey: "itemsBinding"]) // items such as in pull-down or combobox
{ var r = [peek rangeOfString: @"."];
if (r.location != CPNotFound)
{ r = [peek rangeOfString: @"." options: CPBackwardsSearch];
var pathComponents = [peek componentsSeparatedByString:"."];
var subPathArray = [pathComponents subarrayWithRange: CPMakeRange(0, pathComponents.length-2)];
var baseObjectPath = (subPathArray.length>1)? subPathArray.join("."):subPathArray[0];
var arrCtrl = [self _getObjectForIdString: baseObjectPath];
var itemsFace = [peek substringFromIndex: CPMaxRange(r)];
var valItemsFace;
if([arrCtrl respondsToSelector:@selector(pk)])
valItemsFace = [arrCtrl pk];
oPO=[o platformObject];
if([oPO isKindOfClass:[CPPopUpButton class]])
{ if(itemsFace && valItemsFace)
{
[oPO bind:"itemArray" toObject:arrCtrl withKeyPath: "arrangedObjects."+itemsFace options: @{"valueFace":valItemsFace}];
}
} else if([oPO isKindOfClass:[CPSegmentedControl class]])
{
// crude hack to make mask bindings work in ARGOS
if([[o attributes] objectForKey: "mask"])
{
subPathArray = [pathComponents subarrayWithRange: CPMakeRange(0, pathComponents.length-3)]; // <!> fime detect .selection/arrangedObjects instead of using a constant
baseObjectPath = (subPathArray.length>1)? subPathArray.join("."):subPathArray[0];
arrCtrl = [self _getObjectForIdString: baseObjectPath];
itemsFace = [pathComponents subarrayWithRange: CPMakeRange(2, pathComponents.length-2)].join(".");
[oPO bind:"mask" toObject:arrCtrl withKeyPath:itemsFace options:nil];
}
else if(itemsFace && valItemsFace)
{ [oPO bind:"segments" toObject:arrCtrl withKeyPath:"arrangedObjects."+itemsFace options:@{"valueFace":valItemsFace}];
}
} else if([oPO isKindOfClass:[GSComboBoxTagValue class]])
{ [oPO bind:CPContentBinding toObject:arrCtrl withKeyPath:"arrangedObjects."+itemsFace options:@{"valueFace":valItemsFace}];
} else if([oPO isKindOfClass:[CPComboBox class]])
{ [oPO bind:CPContentValuesBinding toObject:arrCtrl withKeyPath:"arrangedObjects."+itemsFace options:nil];
}
}
}
if (peek=[[o attributes] objectForKey: "valueBinding"])
{ var r = [peek rangeOfString: @"."];
oPO=[o platformObject];
if ([oPO isKindOfClass: [CPTableView class] ])
{ var target=[self _getObjectForIdString: peek];
if([o boolValueForAttribute: "viewBasedBindings"] == 1)
{ [oPO bind:"content" toObject: target withKeyPath:"arrangedObjects" options: nil];
[oPO bind:"selectionIndexes" toObject: target withKeyPath:"selectionIndexes" options:nil];
} else // "explicit" bindings for tableView columns, where you do not want to connect the columns individually but through "identifier" property
{ var _content=[o content];
var j, l1 = _content? _content.length : 0;
for(j = 0; j < l1; j++)
{ var column = _content[j];
if (column && [column isKindOfClass:[GSMarkupTagTableColumn class]])
{
var bindingOptions = nil;
var columnAttributes = [column attributes];
if ([columnAttributes objectForKey:"transformingRegex"])
{
var bindingTransformer = [[FSRegexBindingTransformer alloc] initWithRegex:[columnAttributes objectForKey:"transformingRegex"]
template:[columnAttributes objectForKey:"transformingTemplate"]
reverseRegex:[columnAttributes objectForKey:"transformingReverseRegex"]
reverseTemplate:[columnAttributes objectForKey:"transformingReverseTemplate"]];
bindingOptions = @{CPValueTransformerBindingOption:bindingTransformer};
}
[[column platformObject] bind:CPValueBinding
toObject:target
withKeyPath:@"arrangedObjects."+[[column attributes] objectForKey:"identifier"]
options:bindingOptions];
if(target)
target.__tableViewForSpinner=[[column platformObject] tableView];
}
}
}
}
else
{ var objectName = [peek substringToIndex: r.location];
var target = [self _getObjectForIdString: objectName];
var keyValuePath = [peek substringFromIndex: CPMaxRange(r)];
var binding=CPValueBinding;
if([oPO isKindOfClass:[FSArrayController class]])
{ binding="contentArray";
} else if([oPO isKindOfClass:[CPPopUpButton class]])
{ binding="selectedTag";
}
var options=nil;
if([[o attributes] objectForKey: "continuousBinding"]==="YES") options=@{CPContinuouslyUpdatesValueBindingOption:YES};
[oPO bind:binding toObject:target withKeyPath:keyValuePath options:options];
if([oPO isKindOfClass:[CPCollectionView class]])
{
if (r.location != CPNotFound)
{ var pathComponents=[peek componentsSeparatedByString:"."];
if(pathComponents.length>2)
{ var subPathArray=[pathComponents subarrayWithRange: CPMakeRange(1, pathComponents.length-2)];
keyValuePath =subPathArray.join(".")+".selectionIndexes";
} else keyValuePath="selectionIndexes";
} else keyValuePath="selectionIndexes"
[oPO bind: "selectionIndexes" toObject: target withKeyPath: keyValuePath options: nil ];
}
}
}
if (peek=[[o attributes] objectForKey: "enabledBinding"])
{ var r = [peek rangeOfString: @"."];
var objectName = [peek substringToIndex: r.location];
var target = [self _getObjectForIdString: objectName];
var keyValuePath = [peek substringFromIndex: CPMaxRange(r)];
var binding=CPEnabledBinding;
var options=nil;
oPO=[o platformObject];
[oPO bind:binding toObject:target withKeyPath:keyValuePath options: options ];
}
if (peek=[[o attributes] objectForKey: "filterPredicate"])
{
oPO=[o platformObject];
if( [oPO isKindOfClass:[FSArrayController class]])
{ [oPO setClearsFilterPredicateOnInsertion:NO];
[oPO setFilterPredicate: [self _getObjectForIdString:peek] ];
}
}
if (peek=[[o attributes] objectForKey: "formatterClass"])
{ var displayFormat=[[o attributes] objectForKey: "displayFormat"];
var editingFormat=[[o attributes] objectForKey: "editingFormat"];
var emptyIsValid=([o boolValueForAttribute: "editingFormat"]==1);
oPO=[o platformObject];
if(!displayFormat && !editingFormat)
[oPO setFormatter: [CPClassFromString(peek) new]];
else [oPO setFormatter: [CPClassFromString(peek)
formatterWithDisplayFormat: displayFormat
editingFormat: editingFormat
emptyIsValid: emptyIsValid]];
}
if ([[o content] count])
[self _postprocessForBindings:[o content]];
}
}
- (void) _postprocessForEntities:(CPArray) someArr
{ var i, l=someArr.length;
for(i=0;i<l;i++)
{ var o=someArr[i];
if(![o isKindOfClass:GSMarkupArrayController])
continue;
var oPO=[o platformObject];
var peek;
if(peek=[[o attributes] objectForKey:"sortDescriptor"])
{ [oPO setSortDescriptors:[[self _getObjectForIdString:peek]]];
}
if (peek=[[o attributes] objectForKey:"entity"])
{
var entity=[_replicationNameTable objectForKey:peek];
if(!entity)
entity=[[_nameTable objectForKey:peek] platformObject];
if(!entity)
{
var re = new RegExp("(.+)@([0-9]+)");
var m = re.exec(peek);
if(m)
{
if(!_replicationNameTable) _replicationNameTable = @{};
entity = [[[_nameTable objectForKey:m[1]] platformObject] copyOfEntity];
[_replicationNameTable setObject:entity forKey:peek]
}
}
[oPO setEntity: entity];
}
if( [o boolValueForAttribute: "autoFetch"] == 1 )
{ var entityName=[[o attributes] objectForKey: "entity"];
if (entityName)
{ var entity;
if (entity=[[_nameTable objectForKey: entityName ] platformObject])
{ var ao = [[FSMutableArray alloc] initWithArray:[] ofEntity:entity];
ao._kvoMethod=@selector(setContent:);
ao._kvoOwner=oPO
[oPO setContent:ao]
[entity._store fetchObjectsForURLRequest:[entity._store requestForAddressingAllObjectsInEntity:entity] inEntity:entity requestDelegate:ao];
}
}
} else if ([o boolValueForAttribute: "autoFetchSync"] == 1)
{ var entityName=[[o attributes] objectForKey:"entity"];
if (entityName)
{ var entity;
if (entity=[[_nameTable objectForKey:entityName] platformObject])
[oPO setContent:[entity allObjects] ];
}
}
if([[o content] count])
[self _postprocessForEntities:[o content]];
}
}
-(void) parse
{ var t= [self parseXMLString:_xmlStr];
var objs= t.getElementsByTagName("objects");
if(objs) [self processDOMNode: objs[0] intoContainer: _objects];
var entities= t.getElementsByTagName("entities");
if(entities)
{ [self processDOMNode: entities[0] intoContainer: _entites];
[self _postprocessEntities];
}
var cons= t.getElementsByTagName("connectors");
if(cons) [self processDOMNode: cons[0] intoContainer: _connectors];
[self _postprocessForEntities:_objects];
[self _postprocessForBindings:_objects];
}
-(id) nameTable
{ return _nameTable;
}
-(id) objects
{ return _objects;
}
-(id) connectors
{ return _connectors;
}
-(id) entities
{ return _entities;
}
@end