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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
|
//
// Instantiator.cs
//
// Author:
// Jean-Philippe Bruyère <jp.bruyere@hotmail.com>
//
// Copyright (c) 2013-2017 Jean-Philippe Bruyère
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Threading;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Xml;
using System.Reflection.Emit;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using Crow.IML;
namespace Crow
{
public delegate object InstanciatorInvoker(Interface iface);
/// <summary>
/// Reflexion being very slow, the settings of the starting values for widgets are set by a dynamic method.
/// This method is created on the first instacing and is recalled for further widget instancing.
///
/// It includes:
/// - XML values setting
/// - Default values (appearing as attribute in C#) loading
/// - Styling
///
/// Instantiators are shared amongs interfaces. Their are stored with their path as key, and inlined template
/// and itemtemplate are stored with a generated uuid
/// </summary>
public class Instantiator
{
#region Dynamic Method ID generation
static long curId = 0;
internal static long NewId {
get { return curId++; }
}
#endregion
public Type RootType;
InstanciatorInvoker loader;
internal string sourcePath;
#region CTOR
/// <summary>
/// Initializes a new instance of the Instantiator class.
/// </summary>
public Instantiator (string path) : this (Interface.GetStreamFromPath(path)) {
sourcePath = path;
}
/// <summary>
/// Initializes a new instance of the Instantiator class.
/// </summary>
public Instantiator (Stream stream)
{
#if DEBUG_LOAD
Stopwatch loadingTime = new Stopwatch ();
loadingTime.Start ();
#endif
using (XmlTextReader itr = new XmlTextReader (stream)) {
parseIML (itr);
}
#if DEBUG_LOAD
loadingTime.Stop ();
Debug.WriteLine ("IML Instantiator creation '{2}' : {0} ticks, {1} ms",
loadingTime.ElapsedTicks, loadingTime.ElapsedMilliseconds, imlPath);
#endif
}
//TODO:check if still used
public Instantiator (Type _root, InstanciatorInvoker _loader)
{
RootType = _root;
loader = _loader;
}
/// <summary>
/// Create a new instantiator from IML fragment provided directely as a string
/// </summary>
/// <returns>A new instantiator</returns>
/// <param name="fragment">IML string</param>
public static Instantiator CreateFromImlFragment (string fragment)
{
try {
using (Stream s = new MemoryStream (Encoding.UTF8.GetBytes (fragment))) {
return new Instantiator (s);
}
} catch (Exception ex) {
throw new Exception ("Error loading IML fragment:\n" + fragment + "\n", ex);
}
}
#endregion
/// <summary>
/// Creates a new instance of the GraphicObject compiled in the instantiator
/// and bind it the an interface
/// </summary>
/// <returns>The new graphic object instance</returns>
/// <param name="iface">The interface to bind to</param>
public GraphicObject CreateInstance(Interface iface){
return loader (iface) as GraphicObject;
}
List<DynamicMethod> dsValueChangedDynMeths = new List<DynamicMethod>();
List<Delegate> cachedDelegates = new List<Delegate>();
/// <summary>
/// store indices of template delegate to be handled by root parentChanged event
/// </summary>
List<int> templateCachedDelegateIndices = new List<int>();
Delegate templateBinding;
#region IML parsing
/// <summary>
/// Parses IML and build a dynamic method that will be used to instanciate one or multiple occurence of the IML file or fragment
/// </summary>
void parseIML (XmlTextReader reader) {
Context ctx = new Context (findRootType (reader));
ctx.nodesStack.Push (new Node (ctx.RootType));
emitLoader (reader, ctx);
ctx.nodesStack.Pop ();
foreach (int idx in templateCachedDelegateIndices)
ctx.emitCachedDelegateHandlerAddition(idx, CompilerServices.eiLogicalParentChanged);
ctx.ResolveNamedTargets ();
emitBindingDelegates (ctx);
ctx.il.Emit (OpCodes.Ldloc_0);//load root obj to return
ctx.il.Emit(OpCodes.Ret);
reader.Read ();//close tag
RootType = ctx.RootType;
loader = (InstanciatorInvoker)ctx.dm.CreateDelegate (typeof (InstanciatorInvoker), this);
}
/// <summary>
/// read first node to set GraphicObject class for loading
/// and let reader position on that node
/// </summary>
Type findRootType (XmlTextReader reader)
{
string root = "Object";
while (reader.Read ()) {
if (reader.NodeType == XmlNodeType.Element) {
root = reader.Name;
break;
}
}
Type t = tryGetGOType (root);
if (t == null)
throw new Exception ("IML parsing error: undefined root type (" + root + ")");
return t;
}
void emitLoader (XmlTextReader reader, Context ctx)
{
string tmpXml = reader.ReadOuterXml ();
if (ctx.nodesStack.Peek().HasTemplate)
emitTemplateLoad (ctx, tmpXml);
emitGOLoad (ctx, tmpXml);
//emitCheckAndBindValueChanged (ctx);
}
/// <summary>
/// process template and item template definition prior to
/// other attributes or childs processing
/// </summary>
/// <param name="ctx">Loading Context</param>
/// <param name="tmpXml">xml fragment</param>
void emitTemplateLoad (Context ctx, string tmpXml) {
//if its a template, first read template elements
using (XmlTextReader reader = new XmlTextReader (tmpXml, XmlNodeType.Element, null)) {
List<string[]> itemTemplateIds = new List<string[]> ();
bool inlineTemplate = false;
reader.Read ();
string templatePath = reader.GetAttribute ("Template");
int depth = reader.Depth + 1;
while (reader.Read ()) {
if (!reader.IsStartElement () || reader.Depth > depth)
continue;
if (reader.Name == "Template") {
inlineTemplate = true;
reader.Read ();
readChildren (reader, ctx, -1);
} else if (reader.Name == "ItemTemplate") {
string dataType = "default", datas = "", path = "";
while (reader.MoveToNextAttribute ()) {
if (reader.Name == "DataType")
dataType = reader.Value;
else if (reader.Name == "Data")
datas = reader.Value;
else if (reader.Name == "Path")
path = reader.Value;
}
reader.MoveToElement ();
string itemTmpID;
if (string.IsNullOrEmpty (path)) {
itemTmpID = Guid.NewGuid ().ToString ();
Interface.Instantiators [itemTmpID] =
new ItemTemplate (new MemoryStream (Encoding.UTF8.GetBytes (reader.ReadInnerXml ())), dataType, datas);
} else {
if (!reader.IsEmptyElement)
throw new Exception ("ItemTemplate with Path attribute may not include sub nodes");
itemTmpID = path+dataType+datas;
if (!Interface.Instantiators.ContainsKey (itemTmpID))
Interface.Instantiators [itemTmpID] =
new ItemTemplate (Interface.GetStreamFromPath (itemTmpID), dataType, datas);
}
itemTemplateIds.Add (new string [] { dataType, itemTmpID, datas });
}
}
if (!inlineTemplate) {//load from path or default template
ctx.il.Emit (OpCodes.Ldloc_0);//Load current templatedControl ref
if (string.IsNullOrEmpty (templatePath)) {
ctx.il.Emit (OpCodes.Ldnull);//default template loading
} else {
ctx.il.Emit (OpCodes.Ldarg_1);//load currentInterface
ctx.il.Emit (OpCodes.Ldstr, templatePath); //Load template path string
ctx.il.Emit (OpCodes.Callvirt,//call Interface.Load(path)
CompilerServices.miIFaceLoad);
}
ctx.il.Emit (OpCodes.Callvirt, CompilerServices.miLoadTmp);//load template
}
//copy item templates (review this)
foreach (string [] iTempId in itemTemplateIds) {
ctx.il.Emit (OpCodes.Ldloc_0);//load TempControl ref
ctx.il.Emit (OpCodes.Ldfld, CompilerServices.fldItemTemplates);//load ItemTemplates dic field
ctx.il.Emit (OpCodes.Ldstr, iTempId [0]);//load key
ctx.il.Emit (OpCodes.Ldstr, iTempId [1]);//load value
ctx.il.Emit (OpCodes.Callvirt, CompilerServices.miGetITemp);
ctx.il.Emit (OpCodes.Callvirt, CompilerServices.miAddITemp);
if (!string.IsNullOrEmpty (iTempId [2])) {
//expand delegate creation
ctx.il.Emit (OpCodes.Ldloc_0);//load TempControl ref
ctx.il.Emit (OpCodes.Ldfld, CompilerServices.fldItemTemplates);
ctx.il.Emit (OpCodes.Ldstr, iTempId [0]);//load key
ctx.il.Emit (OpCodes.Callvirt, CompilerServices.miGetITempFromDic);
ctx.il.Emit (OpCodes.Ldloc_0);//load root of treeView
ctx.il.Emit (OpCodes.Callvirt, CompilerServices.miCreateExpDel);
}
}
}
}
/// <summary>
/// process styling, attributes and children loading.
/// </summary>
/// <param name="ctx">parsing context</param>
/// <param name="tmpXml">xml fragment</param>
void emitGOLoad (Context ctx, string tmpXml) {
using (XmlTextReader reader = new XmlTextReader (tmpXml, XmlNodeType.Element, null)) {
reader.Read ();
#region Styling and default values loading
//first check for Style attribute then trigger default value loading
if (reader.HasAttributes) {
string style = reader.GetAttribute ("Style");
if (!string.IsNullOrEmpty (style))
CompilerServices.EmitSetValue (ctx.il, CompilerServices.piStyle, style);
}
ctx.il.Emit (OpCodes.Ldloc_0);
ctx.il.Emit (OpCodes.Callvirt, CompilerServices.miLoadDefaultVals);
#endregion
#region Attributes reading
if (reader.HasAttributes) {
while (reader.MoveToNextAttribute ()) {
if (reader.Name == "Style")
continue;
MemberInfo mi = ctx.CurrentNodeType.GetMember (reader.Name).FirstOrDefault ();
if (mi == null)
throw new Exception ("Member '" + reader.Name + "' not found in " + ctx.CurrentNodeType.Name);
if (mi.MemberType == MemberTypes.Event) {
foreach (string exp in CompilerServices.splitOnSemiColumnOutsideAccolades(reader.Value)) {
string trimed = exp.Trim();
if (trimed.StartsWith ("{", StringComparison.OrdinalIgnoreCase))
compileAndStoreDynHandler (ctx, mi as EventInfo, trimed.Substring (1, trimed.Length - 2));
else
emitHandlerBinding (ctx, mi as EventInfo, trimed);
}
continue;
}
PropertyInfo pi = mi as PropertyInfo;
if (pi == null)
throw new Exception ("Member '" + reader.Name + "' is not a property in " + ctx.CurrentNodeType.Name);
if (pi.Name == "Name")
ctx.StoreCurrentName (reader.Value);
if (reader.Value.StartsWith ("{", StringComparison.OrdinalIgnoreCase))
readPropertyBinding (ctx, reader.Name, reader.Value.Substring (1, reader.Value.Length - 2));
else
CompilerServices.EmitSetValue (ctx.il, pi, reader.Value);
}
reader.MoveToElement ();
}
#endregion
readChildren (reader, ctx);
ctx.nodesStack.ResetCurrentNodeIndex ();
}
}
/// <summary>
/// Parse child node an generate corresponding msil
/// </summary>
void readChildren (XmlTextReader reader, Context ctx, int startingIdx = 0)
{
bool endTagReached = false;
int nodeIdx = startingIdx;
while (reader.Read ()) {
switch (reader.NodeType) {
case XmlNodeType.EndElement:
endTagReached = true;
break;
case XmlNodeType.Element:
//skip Templates
if (reader.Name == "Template" ||
reader.Name == "ItemTemplate") {
reader.Skip ();
continue;
}
//push 2x current instance on stack for parenting and reseting loc0 to parent
//loc_0 will be used for child
ctx.il.Emit (OpCodes.Ldloc_0);
ctx.il.Emit (OpCodes.Ldloc_0);
Type t = tryGetGOType (reader.Name);
if (t == null)
throw new Exception (reader.Name + " type not found");
ConstructorInfo ci = t.GetConstructor (
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
null, Type.EmptyTypes, null);
if (ci == null)
throw new Exception ("No default parameterless constructor found in " + t.Name);
ctx.il.Emit (OpCodes.Newobj, ci);
ctx.il.Emit (OpCodes.Stloc_0);//child is now loc_0
CompilerServices.emitSetCurInterface (ctx.il);
ctx.nodesStack.Push (new Node (t, nodeIdx));
emitLoader (reader, ctx);
ctx.nodesStack.Pop ();
ctx.il.Emit (OpCodes.Ldloc_0);//load child on stack for parenting
ctx.il.Emit (OpCodes.Callvirt, ctx.nodesStack.Peek().GetAddMethod(nodeIdx));
ctx.il.Emit (OpCodes.Stloc_0); //reset local to current go
nodeIdx++;
break;
}
if (endTagReached)
break;
}
}
#endregion
void readPropertyBinding (Context ctx, string sourceMember, string expression)
{
NodeAddress sourceNA = ctx.CurrentNodeAddress;
BindingDefinition bindingDef = sourceNA.GetBindingDef (sourceMember, expression);
#if DEBUG_BINDING
Debug.WriteLine("Property Binding: " + bindingDef.ToString());
#endif
if (bindingDef.IsDataSourceBinding)//bind on data source
emitDataSourceBindings (ctx, bindingDef);
else
ctx.StorePropertyBinding (bindingDef);
}
#region Emit Helper
void dataSourceChangedEmitHelper(object dscSource, object dataSource, int dynMethIdx){
if (dataSource is IValueChange)
(dataSource as IValueChange).ValueChanged +=
(EventHandler<ValueChangeEventArgs>)dsValueChangedDynMeths [dynMethIdx].CreateDelegate (typeof(EventHandler<ValueChangeEventArgs>), dscSource);
}
/// <summary> Emits remove old data source event handler./summary>
void emitRemoveOldDataSourceHandler(ILGenerator il, string eventName, string delegateName, bool DSSide = true){
System.Reflection.Emit.Label cancel = il.DefineLabel ();
il.Emit (OpCodes.Ldarg_2);//load old parent
il.Emit (OpCodes.Ldfld, CompilerServices.fiDSCOldDS);
il.Emit (OpCodes.Brfalse, cancel);//old parent is null
//remove handler
if (DSSide){//event is defined in the dataSource instance
il.Emit (OpCodes.Ldarg_2);//1st arg load old datasource
il.Emit (OpCodes.Ldfld, CompilerServices.fiDSCOldDS);
}else//the event is in the source
il.Emit (OpCodes.Ldarg_1);//1st arg load old datasource
il.Emit (OpCodes.Ldstr, eventName);//2nd arg event name
il.Emit (OpCodes.Ldstr, delegateName);//3d arg: delegate name
il.Emit (OpCodes.Call, CompilerServices.miRemEvtHdlByName);
il.MarkLabel(cancel);
}
#endregion
#region Event Bindings
/// <summary>
/// Compile events expression in IML attributes, and store the result in the instanciator
/// Those handlers will be bound when instatiing
/// </summary>
void compileAndStoreDynHandler (Context ctx, EventInfo sourceEvent, string expression)
{
//store event handler dynamic method in instanciator
int dmIdx = cachedDelegates.Count;
cachedDelegates.Add (CompilerServices.compileDynEventHandler (sourceEvent, expression, ctx.CurrentNodeAddress));
ctx.emitCachedDelegateHandlerAddition(dmIdx, sourceEvent);
}
/// <summary> Emits handler method bindings </summary>
void emitHandlerBinding (Context ctx, EventInfo sourceEvent, string expression){
NodeAddress currentNode = ctx.CurrentNodeAddress;
BindingDefinition bindingDef = currentNode.GetBindingDef (sourceEvent.Name, expression);
#if DEBUG_BINDING
Debug.WriteLine("Event Binding: " + bindingDef.ToString());
#endif
if (bindingDef.IsTemplateBinding | bindingDef.IsDataSourceBinding) {
//we need to bind datasource method to source event
DynamicMethod dm = new DynamicMethod ("dyn_dsORtmpChangedForHandler" + NewId,
typeof(void),
CompilerServices.argsBoundDSChange, true);
ILGenerator il = dm.GetILGenerator (256);
System.Reflection.Emit.Label cancel = il.DefineLabel ();
il.DeclareLocal (typeof(MethodInfo));//used to cancel binding if method doesn't exist
il.Emit (OpCodes.Nop);
emitRemoveOldDataSourceHandler (il, sourceEvent.Name, bindingDef.TargetMember, false);
//fetch method in datasource and test if it exist
il.Emit (OpCodes.Ldarg_2);//load new datasource
il.Emit (OpCodes.Ldfld, CompilerServices.fiDSCNewDS);
il.Emit (OpCodes.Brfalse, cancel);//cancel if new datasource is null
il.Emit (OpCodes.Ldarg_2);//load new datasource
il.Emit (OpCodes.Ldfld, CompilerServices.fiDSCNewDS);
il.Emit (OpCodes.Ldstr, bindingDef.TargetMember);//load handler method name
il.Emit (OpCodes.Call, CompilerServices.miGetMethInfoWithRefx);
il.Emit (OpCodes.Stloc_0);//save MethodInfo
il.Emit (OpCodes.Ldloc_0);//push mi for test if null
il.Emit (OpCodes.Brfalse, cancel);
il.Emit (OpCodes.Ldarg_1);//load datasource change source where the event is as 1st arg of handler.add
if (bindingDef.IsTemplateBinding)//fetch source instance with address
CompilerServices.emitGetInstance (il, bindingDef.SourceNA);
//load handlerType of sourceEvent to create delegate (1st arg)
il.Emit (OpCodes.Ldtoken, sourceEvent.EventHandlerType);
il.Emit (OpCodes.Call, CompilerServices.miGetTypeFromHandle);
il.Emit (OpCodes.Ldarg_2);//load new datasource where the method is defined
il.Emit (OpCodes.Ldfld, CompilerServices.fiDSCNewDS);
il.Emit (OpCodes.Ldloc_0);//load methodInfo (3rd arg)
il.Emit (OpCodes.Callvirt, CompilerServices.miCreateBoundDel);
il.Emit (OpCodes.Callvirt, sourceEvent.AddMethod);//call add event
System.Reflection.Emit.Label finish = il.DefineLabel ();
il.Emit (OpCodes.Br, finish);
il.MarkLabel (cancel);
il.EmitWriteLine (string.Format ("Handler method '{0}' for '{1}' not found in new dataSource ", bindingDef.TargetMember, sourceEvent.Name));
il.MarkLabel (finish);
il.Emit (OpCodes.Ret);
//store dschange delegate in instatiator instance for access while instancing graphic object
int delDSIndex = cachedDelegates.Count;
cachedDelegates.Add (dm.CreateDelegate (CompilerServices.ehTypeDSChange, this));
if (bindingDef.IsDataSourceBinding)
ctx.emitCachedDelegateHandlerAddition (delDSIndex, CompilerServices.eiDSChange);
else //template handler binding, will be added to root parentChanged
templateCachedDelegateIndices.Add (delDSIndex);
} else {//normal in tree handler binding, store until tree is complete (end of parse)
ctx.UnresolvedTargets.Add (new EventBinding (
bindingDef.SourceNA, sourceEvent,
bindingDef.TargetNA, bindingDef.TargetMember, bindingDef.TargetName));
}
}
#endregion
#region Property Bindings
/// <summary>
/// Create and store in the instanciator the ValueChanged delegates
/// those delegates uses grtree functions to set destination value so they don't
/// need to be bound to destination instance as in the ancient system.
/// </summary>
void emitBindingDelegates(Context ctx){
foreach (KeyValuePair<NodeAddress,Dictionary<string, List<MemberAddress>>> bindings in ctx.Bindings ) {
if (bindings.Key.Count == 0)//template binding
emitTemplateBindings (ctx, bindings.Value);
else
emitPropertyBindings (ctx, bindings.Key, bindings.Value);
}
}
void emitPropertyBindings(Context ctx, NodeAddress origine, Dictionary<string, List<MemberAddress>> bindings){
Type origineNodeType = origine.NodeType;
//value changed dyn method
DynamicMethod dm = new DynamicMethod ("dyn_valueChanged" + NewId,
typeof (void), CompilerServices.argsValueChange, true);
ILGenerator il = dm.GetILGenerator (256);
System.Reflection.Emit.Label endMethod = il.DefineLabel ();
il.DeclareLocal (CompilerServices.TObject);
il.Emit (OpCodes.Nop);
int i = 0;
foreach (KeyValuePair<string, List<MemberAddress>> bindingCase in bindings ) {
System.Reflection.Emit.Label nextTest = il.DefineLabel ();
#region member name test
//load source member name
il.Emit (OpCodes.Ldarg_1);
il.Emit (OpCodes.Ldfld, CompilerServices.fiVCMbName);
il.Emit (OpCodes.Ldstr, bindingCase.Key);//load name to test
il.Emit (OpCodes.Ldc_I4_4);//StringComparison.Ordinal
il.Emit (OpCodes.Callvirt, CompilerServices.stringEquals);
il.Emit (OpCodes.Brfalse, nextTest);//if not equal, jump to next case
#endregion
#region destination member affectations
PropertyInfo piOrig = origineNodeType.GetProperty (bindingCase.Key);
Type origineType = null;
if (piOrig != null)
origineType = piOrig.PropertyType;
foreach (MemberAddress ma in bindingCase.Value) {
//first we have to load destination instance onto the stack, it is access
//with graphic tree functions deducted from nodes topology
il.Emit (OpCodes.Ldarg_0);//load source instance of ValueChanged event
NodeAddress destination = ma.Address;
if (destination.Count == 0){//template reverse binding
//fetch destination instance (which is the template root)
for (int j = 0; j < origine.Count ; j++)
il.Emit(OpCodes.Callvirt, CompilerServices.miGetLogicalParent);
}else
CompilerServices.emitGetInstance (il, origine, destination);
if (origineType != null && destination.Count > 0){//else, prop less binding or reverse template bind, no init requiered
//for initialisation dynmeth, push destination instance loc_0 is root node in ctx
ctx.il.Emit(OpCodes.Ldloc_0);
CompilerServices.emitGetInstance (ctx.il, destination);
//init dynmeth: load actual value from origine
ctx.il.Emit (OpCodes.Ldloc_0);
CompilerServices.emitGetInstance (ctx.il, origine);
ctx.il.Emit (OpCodes.Callvirt, origineNodeType.GetProperty (bindingCase.Key).GetGetMethod());
}
//load new value
il.Emit (OpCodes.Ldarg_1);
il.Emit (OpCodes.Ldfld, CompilerServices.fiVCNewValue);
if (origineType == null)//property less binding, no init
CompilerServices.emitConvert (il, ma.Property.PropertyType);
else if (destination.Count > 0) {
if (origineType.IsValueType)
ctx.il.Emit(OpCodes.Box, origineType);
CompilerServices.emitConvert (ctx.il, origineType, ma.Property.PropertyType);
CompilerServices.emitConvert (il, origineType, ma.Property.PropertyType);
ctx.il.Emit (OpCodes.Callvirt, ma.Property.GetSetMethod());//set init value
} else {// reverse templateBinding
il.Emit (OpCodes.Ldstr, ma.memberName);//arg 3 of setValueWithReflexion
il.Emit (OpCodes.Call, CompilerServices.miSetValWithRefx);
continue;
}
il.Emit (OpCodes.Callvirt, ma.Property.GetSetMethod());//set value on value changes
}
#endregion
il.Emit (OpCodes.Br, endMethod);
il.MarkLabel (nextTest);
i++;
}
il.MarkLabel (endMethod);
il.Emit (OpCodes.Ret);
//store and emit Add in ctx
int dmIdx = cachedDelegates.Count;
cachedDelegates.Add (dm.CreateDelegate (typeof(EventHandler<ValueChangeEventArgs>)));
ctx.emitCachedDelegateHandlerAddition (dmIdx, CompilerServices.eiValueChange, origine);
#if DEBUG_BINDING
Debug.WriteLine("\tCrow property binding: " + dm.Name);
#endif
}
void emitTemplateBindings(Context ctx, Dictionary<string, List<MemberAddress>> bindings){
//value changed dyn method
DynamicMethod dm = new DynamicMethod ("dyn_tmpValueChanged",
typeof (void), CompilerServices.argsValueChange, true);
ILGenerator il = dm.GetILGenerator (256);
//create parentchanged dyn meth in parallel to have only one loop over bindings
DynamicMethod dmPC = new DynamicMethod ("dyn_InitAndLogicalParentChanged",
typeof (void),
CompilerServices.argsBoundDSChange, true);
ILGenerator ilPC = dmPC.GetILGenerator (256);
il.Emit (OpCodes.Nop);
ilPC.Emit (OpCodes.Nop);
System.Reflection.Emit.Label endMethod = il.DefineLabel ();
il.DeclareLocal (CompilerServices.TObject);
ilPC.DeclareLocal (CompilerServices.TObject);//used for checking propery less bindings
ilPC.DeclareLocal (typeof(MemberInfo));//used for checking propery less bindings
System.Reflection.Emit.Label cancel = ilPC.DefineLabel ();
#region Unregister previous parent event handler
//unregister previous parent handler if not null
ilPC.Emit (OpCodes.Ldarg_2);//load old parent
ilPC.Emit (OpCodes.Ldfld, CompilerServices.fiDSCOldDS);
ilPC.Emit (OpCodes.Brfalse, cancel);//old parent is null
ilPC.Emit (OpCodes.Ldarg_2);//load old parent
ilPC.Emit (OpCodes.Ldfld, CompilerServices.fiDSCOldDS);
//Load cached delegate
ilPC.Emit(OpCodes.Ldarg_0);//load ref to this instanciator onto the stack
ilPC.Emit(OpCodes.Ldfld, CompilerServices.fiTemplateBinding);
//add template bindings dynValueChanged delegate to new parent event
ilPC.Emit(OpCodes.Callvirt, CompilerServices.eiValueChange.RemoveMethod);//call remove event
#endregion
ilPC.MarkLabel(cancel);
#region check if new parent is null
cancel = ilPC.DefineLabel ();
ilPC.Emit (OpCodes.Ldarg_2);//load datasource change arg
ilPC.Emit (OpCodes.Ldfld, CompilerServices.fiDSCNewDS);
ilPC.Emit (OpCodes.Brfalse, cancel);//new ds is null
#endregion
int i = 0;
foreach (KeyValuePair<string, List<MemberAddress>> bindingCase in bindings ) {
System.Reflection.Emit.Label nextTest = il.DefineLabel ();
#region member name test
//load source member name
il.Emit (OpCodes.Ldarg_1);
il.Emit (OpCodes.Ldfld, CompilerServices.fiVCMbName);
il.Emit (OpCodes.Ldstr, bindingCase.Key);//load name to test
il.Emit (OpCodes.Ldc_I4_4);//StringComparison.Ordinal
il.Emit (OpCodes.Callvirt, CompilerServices.stringEquals);
il.Emit (OpCodes.Brfalse, nextTest);//if not equal, jump to next case
#endregion
#region destination member affectations
foreach (MemberAddress ma in bindingCase.Value) {
if (ma.Address.Count == 0){
Debug.WriteLine("\t\tBUG: reverse template binding in normal template binding");
continue;//template binding
}
//first we try to get memberInfo of new parent, if it doesn't exist, it's a propery less binding
ilPC.Emit (OpCodes.Ldarg_2);//load new parent onto the stack for handler addition
ilPC.Emit (OpCodes.Ldfld, CompilerServices.fiDSCNewDS);
ilPC.Emit (OpCodes.Stloc_0);//save new parent
//get parent type
ilPC.Emit (OpCodes.Ldloc_0);//push parent instance
ilPC.Emit (OpCodes.Ldstr, bindingCase.Key);//load member name
ilPC.Emit (OpCodes.Call, CompilerServices.miGetMembIinfoWithRefx);
ilPC.Emit (OpCodes.Stloc_1);//save memberInfo
ilPC.Emit (OpCodes.Ldloc_1);//push mi for test if null
System.Reflection.Emit.Label propLessReturn = ilPC.DefineLabel ();
ilPC.Emit (OpCodes.Brfalse, propLessReturn);
//first we have to load destination instance onto the stack, it is access
//with graphic tree functions deducted from nodes topology
il.Emit (OpCodes.Ldarg_0);//load source instance of ValueChanged event
CompilerServices.emitGetChild (il, typeof(TemplatedControl), -1);
CompilerServices.emitGetInstance (il, ma.Address);
ilPC.Emit (OpCodes.Ldarg_2);//load destination instance to set actual value of member
ilPC.Emit (OpCodes.Ldfld, CompilerServices.fiDSCNewDS);
CompilerServices.emitGetChild (ilPC, typeof(TemplatedControl), -1);
CompilerServices.emitGetInstance (ilPC, ma.Address);
//load new value
il.Emit (OpCodes.Ldarg_1);
il.Emit (OpCodes.Ldfld, CompilerServices.fiVCNewValue);
//for the parent changed dyn meth we need to fetch actual value for initialisation thrue reflexion
ilPC.Emit (OpCodes.Ldloc_0);//push root instance of instanciator as parentChanged source
ilPC.Emit (OpCodes.Ldloc_1);//push mi for value fetching
ilPC.Emit (OpCodes.Call, CompilerServices.miGetValWithRefx);
CompilerServices.emitConvert (il, ma.Property.PropertyType);
CompilerServices.emitConvert (ilPC, ma.Property.PropertyType);
il.Emit (OpCodes.Callvirt, ma.Property.GetSetMethod());
ilPC.Emit (OpCodes.Callvirt, ma.Property.GetSetMethod());
ilPC.MarkLabel(propLessReturn);
}
#endregion
il.Emit (OpCodes.Br, endMethod);
il.MarkLabel (nextTest);
i++;
}
//il.Emit (OpCodes.Pop);
il.MarkLabel (endMethod);
il.Emit (OpCodes.Ret);
//store template bindings in instanciator
templateBinding = dm.CreateDelegate (typeof(EventHandler<ValueChangeEventArgs>));
#region emit LogicalParentChanged method
//load new parent onto the stack for handler addition
ilPC.Emit (OpCodes.Ldarg_2);
ilPC.Emit (OpCodes.Ldfld, CompilerServices.fiDSCNewDS);
//Load cached delegate
ilPC.Emit(OpCodes.Ldarg_0);//load ref to this instanciator onto the stack
ilPC.Emit(OpCodes.Ldfld, CompilerServices.fiTemplateBinding);
//add template bindings dynValueChanged delegate to new parent event
ilPC.Emit(OpCodes.Callvirt, CompilerServices.eiValueChange.AddMethod);//call add event
ilPC.MarkLabel (cancel);
ilPC.Emit (OpCodes.Ret);
//store dschange delegate in instatiator instance for access while instancing graphic object
int delDSIndex = cachedDelegates.Count;
cachedDelegates.Add(dmPC.CreateDelegate (CompilerServices.ehTypeDSChange, this));
#endregion
ctx.emitCachedDelegateHandlerAddition(delDSIndex, CompilerServices.eiLogicalParentChanged);
}
/// <summary>
/// create the valuechanged handler, the datasourcechanged handler and emit event handling
/// </summary>
void emitDataSourceBindings(Context ctx, BindingDefinition bindingDef){
DynamicMethod dm = null;
ILGenerator il = null;
int dmVC = 0;
PropertyInfo piSource = ctx.CurrentNodeType.GetProperty(bindingDef.SourceMember);
//if no dataSource member name is provided, valuechange is not handle and datasource change
//will be used as origine value
string delName = "dyn_DSvalueChanged" + NewId;
if (!string.IsNullOrEmpty(bindingDef.TargetMember)){
#region create valuechanged method
dm = new DynamicMethod (delName,
typeof (void),
CompilerServices.argsBoundValueChange, true);
il = dm.GetILGenerator (256);
System.Reflection.Emit.Label endMethod = il.DefineLabel ();
il.DeclareLocal (CompilerServices.TObject);
il.Emit (OpCodes.Nop);
//load value changed member name onto the stack
il.Emit (OpCodes.Ldarg_2);
il.Emit (OpCodes.Ldfld, CompilerServices.fiVCMbName);
//test if it's the expected one
il.Emit (OpCodes.Ldstr, bindingDef.TargetMember);
il.Emit (OpCodes.Ldc_I4_4);//StringComparison.Ordinal
il.Emit (OpCodes.Callvirt, CompilerServices.stringEquals);
il.Emit (OpCodes.Brfalse, endMethod);
//set destination member with valueChanged new value
//load destination ref
il.Emit (OpCodes.Ldarg_0);
//load new value onto the stack
il.Emit (OpCodes.Ldarg_2);
il.Emit (OpCodes.Ldfld, CompilerServices.fiVCNewValue);
//by default, source value type is deducted from target member type to allow
//memberless binding, if targetMember exists, it will be used to determine target
//value type for conversion
CompilerServices.emitConvert (il, piSource.PropertyType);
il.Emit (OpCodes.Callvirt, piSource.GetSetMethod ());
il.MarkLabel (endMethod);
il.Emit (OpCodes.Ret);
//vc dyn meth is stored in a cached list, it will be bound to datasource only
//when datasource of source graphic object changed
dmVC = dsValueChangedDynMeths.Count;
dsValueChangedDynMeths.Add (dm);
#endregion
}
#region emit dataSourceChanged event handler
//now we create the datasource changed method that will init the destination member with
//the actual value of the origin member of the datasource and then will bind the value changed
//dyn methode.
//dm is bound to the instanciator instance to have access to cached dyn meth and delegates
dm = new DynamicMethod ("dyn_dschanged" + NewId,
typeof (void),
CompilerServices.argsBoundDSChange, true);
il = dm.GetILGenerator (256);
il.DeclareLocal (CompilerServices.TObject);//used for checking propery less bindings
il.DeclareLocal (typeof(MemberInfo));//used for checking propery less bindings
System.Reflection.Emit.Label cancel = il.DefineLabel ();
System.Reflection.Emit.Label newDSIsNull = il.DefineLabel ();
System.Reflection.Emit.Label cancelInit = il.DefineLabel ();
il.Emit (OpCodes.Nop);
emitRemoveOldDataSourceHandler(il, "ValueChanged", delName, true);
if (!string.IsNullOrEmpty(bindingDef.TargetMember)){
if (bindingDef.TwoWay){
// System.Reflection.Emit.Label cancelRemove = il.DefineLabel ();
// //remove handler if not null
// il.Emit (OpCodes.Ldarg_2);//load old parent
// il.Emit (OpCodes.Ldfld, CompilerServices.fiDSCOldDS);
// il.Emit (OpCodes.Brfalse, cancelRemove);//old parent is null
//remove handler
emitRemoveOldDataSourceHandler(il, "ValueChanged", delName, false);
// il.Emit (OpCodes.Ldarg_1);//3d arg: instance bound to delegate (the source)
// il.Emit (OpCodes.Ldstr, "ValueChanged");//2nd arg event name
// il.Emit (OpCodes.Ldarg_2);//1st arg load old datasource
// il.Emit (OpCodes.Ldfld, CompilerServices.fiDSCOldDS);
// il.Emit (OpCodes.Call, CompilerServices.miRemEvtHdlByTarget);
// il.MarkLabel(cancelRemove);
}
il.Emit (OpCodes.Ldarg_2);//load datasource change arg
il.Emit (OpCodes.Ldfld, CompilerServices.fiDSCNewDS);
il.Emit (OpCodes.Brfalse, newDSIsNull);//new ds is null
}
#region fetch initial Value
if (!string.IsNullOrEmpty(bindingDef.TargetMember)){
il.Emit (OpCodes.Ldarg_2);//load new datasource
il.Emit (OpCodes.Ldfld, CompilerServices.fiDSCNewDS);
il.Emit (OpCodes.Ldstr, bindingDef.TargetMember);//load member name
il.Emit (OpCodes.Call, CompilerServices.miGetMembIinfoWithRefx);
il.Emit (OpCodes.Stloc_1);//save memberInfo
il.Emit (OpCodes.Ldloc_1);//push mi for test if null
il.Emit (OpCodes.Brfalse, cancelInit);//propertyLessBinding
}
il.Emit (OpCodes.Ldarg_1);//load source of dataSourceChanged which is the dest instance
il.Emit (OpCodes.Ldarg_2);//load new datasource
il.Emit (OpCodes.Ldfld, CompilerServices.fiDSCNewDS);
if (!string.IsNullOrEmpty(bindingDef.TargetMember)){
il.Emit (OpCodes.Ldloc_1);//push mi for value fetching
il.Emit (OpCodes.Call, CompilerServices.miGetValWithRefx);
}
CompilerServices.emitConvert (il, piSource.PropertyType);
il.Emit (OpCodes.Callvirt, piSource.GetSetMethod ());
#endregion
if (!string.IsNullOrEmpty(bindingDef.TargetMember)){
il.MarkLabel(cancelInit);
//check if new dataSource implement IValueChange
il.Emit (OpCodes.Ldarg_2);//load new datasource
il.Emit (OpCodes.Ldfld, CompilerServices.fiDSCNewDS);
il.Emit (OpCodes.Isinst, typeof(IValueChange));
il.Emit (OpCodes.Brfalse, cancel);
il.Emit(OpCodes.Ldarg_0);//load ref to this instanciator onto the stack
il.Emit (OpCodes.Ldarg_1);//load datasource change source
il.Emit (OpCodes.Ldarg_2);//load new datasource
il.Emit (OpCodes.Ldfld, CompilerServices.fiDSCNewDS);
il.Emit(OpCodes.Ldc_I4, dmVC);//load index of dynmathod
il.Emit (OpCodes.Call, CompilerServices.miDSChangeEmitHelper);
il.MarkLabel (cancel);
if (bindingDef.TwoWay){
il.Emit (OpCodes.Ldarg_1);//arg1: dataSourceChange source, the origine of the binding
il.Emit (OpCodes.Ldstr, bindingDef.SourceMember);//arg2: orig member
il.Emit (OpCodes.Ldarg_2);//arg3: new datasource
il.Emit (OpCodes.Ldfld, CompilerServices.fiDSCNewDS);
il.Emit (OpCodes.Ldstr, bindingDef.TargetMember);//arg4: dest member
il.Emit (OpCodes.Call, CompilerServices.miDSReverseBinding);
}
}
il.MarkLabel (newDSIsNull);
il.Emit (OpCodes.Ret);
//store dschange delegate in instatiator instance for access while instancing graphic object
int delDSIndex = cachedDelegates.Count;
cachedDelegates.Add(dm.CreateDelegate (CompilerServices.ehTypeDSChange, this));
#endregion
ctx.emitCachedDelegateHandlerAddition(delDSIndex, CompilerServices.eiDSChange);
#if DEBUG_BINDING
Debug.WriteLine("\tDataSource ValueChanged: " + delName);
Debug.WriteLine("\tDataSource Changed: " + dm.Name);
#endif
}
/// <summary>
/// Two way binding for datasource, graphicObj=>dataSource link, datasource value has priority
/// and will be set as init for source property (in emitDataSourceBindings func)
/// </summary>
/// <param name="orig">Graphic object instance, source of binding</param>
/// <param name="origMember">Origin member name</param>
/// <param name="dest">datasource instance, target of the binding</param>
/// <param name="destMember">Destination member name</param>
static void dataSourceReverseBinding(IValueChange orig, string origMember, object dest, string destMember){
Type tOrig = orig.GetType ();
Type tDest = dest.GetType ();
PropertyInfo piOrig = tOrig.GetProperty (origMember);
PropertyInfo piDest = tDest.GetProperty (destMember);
if (piDest == null) {
Debug.WriteLine ("Member '{0}' not found in new DataSource '{1}' of '{2}'", destMember, dest, orig);
return;
}
#if DEBUG_BINDING
Debug.WriteLine ("DS Reverse binding: Member '{0}' found in new DS '{1}' of '{2}'", destMember, dest, orig);
#endif
#region ValueChanged emit
DynamicMethod dm = new DynamicMethod ("dyn_valueChanged" + NewId,
typeof (void), CompilerServices.argsBoundValueChange, true);
ILGenerator il = dm.GetILGenerator (256);
System.Reflection.Emit.Label endMethod = il.DefineLabel ();
il.DeclareLocal (CompilerServices.TObject);
il.Emit (OpCodes.Nop);
//load value changed member name onto the stack
il.Emit (OpCodes.Ldarg_2);
il.Emit (OpCodes.Ldfld, CompilerServices.fiVCMbName);
//test if it's the expected one
il.Emit (OpCodes.Ldstr, origMember);
il.Emit (OpCodes.Ldc_I4_4);//StringComparison.Ordinal
il.Emit (OpCodes.Callvirt, CompilerServices.stringEquals);
il.Emit (OpCodes.Brfalse, endMethod);
//set destination member with valueChanged new value
//load destination ref
il.Emit (OpCodes.Ldarg_0);
//load new value onto the stack
il.Emit (OpCodes.Ldarg_2);
il.Emit (OpCodes.Ldfld, CompilerServices.fiVCNewValue);
CompilerServices.emitConvert (il, piOrig.PropertyType, piDest.PropertyType);
il.Emit (OpCodes.Callvirt, piDest.GetSetMethod ());
il.MarkLabel (endMethod);
il.Emit (OpCodes.Ret);
#endregion
orig.ValueChanged += (EventHandler<ValueChangeEventArgs>)dm.CreateDelegate (typeof(EventHandler<ValueChangeEventArgs>), dest);
}
#endregion
/// <summary>
/// search for graphic object type in crow assembly, if not found,
/// search for type independently of namespace in entry assembly
/// </summary>
/// <returns>the corresponding type object</returns>
/// <param name="typeName">graphic object type name without its namespace</param>
Type tryGetGOType (string typeName){
Type t = Type.GetType ("Crow." + typeName);
if (t != null)
return t;
Assembly a = Assembly.GetEntryAssembly ();
foreach (Type expT in a.GetExportedTypes ()) {
if (expT.Name == typeName)
return expT;
}
return null;
}
}
}
|