-
Notifications
You must be signed in to change notification settings - Fork 53
/
MetaOperator.cs
1496 lines (1305 loc) · 68.7 KB
/
MetaOperator.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
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
// Copyright (c) 2016 Framefield. All rights reserved.
// Released under the MIT license. (see LICENSE.txt)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Media;
namespace Framefield.Core
{
public class MetaOperator : INotifyPropertyChanged, IDisposable
{
public event PropertyChangedEventHandler PropertyChanged;
internal class InstanceProperties
{
// first item is instance guid of opPart
public Dictionary<Guid, OperatorPart.Function> InputValues { get; set; }
public string Name { get; set; }
public Point Position { get; set; }
public double Width { get; set; }
public bool Visible { get; set; }
public bool Disabled { get; set; }
public Dictionary<Guid, IOperatorPartState> OperatorPartStates { get; set; }
public InstanceProperties()
{
InputValues = new Dictionary<Guid, OperatorPart.Function>();
Name = String.Empty;
Position = new Point(100, 100);
Width = 100;
Visible = true;
OperatorPartStates = new Dictionary<Guid, IOperatorPartState>();
}
public InstanceProperties(IEnumerable<MetaInput> inputs) : this()
{
foreach (var input in inputs)
{
InputValues[input.ID] = input.DefaultFunc;
}
}
public InstanceProperties Clone()
{
var newOpProps = new InstanceProperties()
{
Name = string.Copy(Name),
Position = Position,
Width = Width,
Visible = Visible,
Disabled = Disabled
};
// clone input values
foreach (var inputValue in InputValues)
{
newOpProps.InputValues[inputValue.Key] = inputValue.Value.Clone();
}
// clone states
foreach (var state in OperatorPartStates)
{
newOpProps.OperatorPartStates[state.Key] = state.Value.Clone();
}
return newOpProps;
}
public void ExchangeGuids(Dictionary<Guid, Guid> oldToNewGuid)
{
var updatedInputValues = new Dictionary<Guid, OperatorPart.Function>();
foreach (var inputValue in InputValues)
{
Guid newId = Guid.Empty;
if (!oldToNewGuid.TryGetValue(inputValue.Key, out newId))
newId = inputValue.Key;
updatedInputValues[newId] = inputValue.Value;
}
InputValues = updatedInputValues;
var updatedStates = new Dictionary<Guid, IOperatorPartState>();
foreach (var state in OperatorPartStates)
{
Guid newInstanceId = Guid.Empty;
if (!oldToNewGuid.TryGetValue(state.Key, out newInstanceId))
newInstanceId = state.Key;
updatedStates[newInstanceId] = state.Value;
}
OperatorPartStates = updatedStates;
}
}
#region Properties
public Guid ID { get; set; }
public String Revision { get; set; }
private string _name = string.Empty;
public string Name
{
get { return _name; }
set
{
_name = value;
if (IsBasic)
OperatorParts[0].Item2.Name = _name + "Func";
RaisePropertyChangedEvent("Name");
Changed = true;
}
}
private List<MetaInput> _metaInputs;
public List<MetaInput> Inputs
{
get => _metaInputs;
internal set
{
_metaInputs = value;
ReorderInputsOfOpInstance();
}
}
public void ReorderInputsOfOpInstance()
{
foreach (var instance in _instances)
{
var newList = new List<OperatorPart>();
for (int index = 0; index < _metaInputs.Count; index++)
{
foreach (var input in instance.Inputs)
{
if (input.ID == _metaInputs[index].ID)
{
newList.Add(input);
break; // there should be no 2 inputs with same id
}
}
}
instance.Inputs = newList;
}
Changed = true;
}
public List<MetaOutput> Outputs { get; internal set; }
internal Dictionary<Guid, Tuple<MetaOperator, InstanceProperties>> Operators { get; set; }
public List<Tuple<Guid, MetaOperatorPart>> OperatorParts
{
get { return _operatorParts; }
set
{
foreach (var opPart in value)
opPart.Item2.Parent = this;
_operatorParts = value;
}
}
public List<MetaConnection> Connections { get; set; }
public string Description
{
get { return _description; }
set
{
_description = value;
RaisePropertyChangedEvent("Description");
Changed = true;
}
}
private string _description = string.Empty;
private string _namespace = string.Empty;
public string Namespace
{
get { return _namespace; }
set
{
if (value != _namespace)
{
_namespace = value;
RaisePropertyChangedEvent("Namespace");
Changed = true;
}
}
}
public bool IsBasic { get { return OperatorParts.Count > 0; } }
public int InstanceCount { get { return _instances.Count; } }
private bool _changed = false;
public bool Changed
{
get
{
var stateChanged = (from op in Operators
from stateEntry in op.Value.Item2.OperatorPartStates
where stateEntry.Value.Changed
select stateEntry).Any();
var opPartChanged = (from opPart in OperatorParts
where opPart.Item2.ScriptChanged
select opPart).Any();
return _changed || stateChanged || opPartChanged;
}
internal set
{
_changed = value;
if (value == false)
{
foreach (var op in Operators)
{
foreach (var stateEntry in op.Value.Item2.OperatorPartStates)
{
stateEntry.Value.Changed = false;
}
}
foreach (var opPart in OperatorParts)
{
opPart.Item2.ScriptChanged = false;
}
}
}
}
public IEnumerable<string> SupplierAssemblyNames
{
get
{
return from opEntry in Operators
where IsBasic // additional check
let dependencyOpDefinition = opEntry.Value.Item1
where dependencyOpDefinition.IsBasic
let supplierAssemblyName = dependencyOpDefinition.OperatorParts.First().Item2.SourceName
select supplierAssemblyName;
}
}
public IEnumerable<MetaOperator> SupplierDefinitions
{
get
{
return from opEntry in Operators
where IsBasic // additional check
let dependencyOpDefinition = opEntry.Value.Item1
where dependencyOpDefinition.IsBasic
select dependencyOpDefinition;
}
}
// todo: move to cmd
public void SetSupplierAssemblies(IEnumerable<Assembly> supplierAssemblies)
{
foreach (var opEntry in Operators.Reverse())
{
var supplierOpPartDefinition = opEntry.Value.Item1.OperatorParts.First().Item2;
supplierOpPartDefinition.ScriptChangedEvent -= OperatorParts.First().Item2.HandleDependencyOperator_ScriptChange;
RemoveOperator(opEntry.Key);
}
foreach (var supplierAssembly in supplierAssemblies)
{
var idSearchPattern = new Regex(@".+Func_ID([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})_Version[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}");
var match = idSearchPattern.Match(supplierAssembly.FullName);
if (match.Success && match.Groups.Count > 2)
{
var idToLookFor = Guid.Parse(match.Groups[1].Value);
//Logger.Debug("{0} at path: {1}", supplierAssembly.GetName(), supplierAssembly.Location);
var correspondingOpDefinition = (from opDefintion in MetaManager.Instance.MetaOperators
where opDefintion.Value.IsBasic
let opPartDefintion = opDefintion.Value.OperatorParts[0].Item2
where opPartDefintion.ID == idToLookFor
select opDefintion.Value).FirstOrDefault();
AddOperator(correspondingOpDefinition);
var supplierOpPartDefinition = correspondingOpDefinition.OperatorParts.First().Item2;
supplierOpPartDefinition.ScriptChangedEvent += OperatorParts.First().Item2.HandleDependencyOperator_ScriptChange;
}
}
}
#endregion
#region Constructor
public MetaOperator(Guid id)
{
ID = id;
Revision = string.Empty;
Inputs = new List<MetaInput>();
Outputs = new List<MetaOutput>();
Operators = new Dictionary<Guid, Tuple<MetaOperator, InstanceProperties>>();
OperatorParts = new List<Tuple<Guid, MetaOperatorPart>>();
Connections = new List<MetaConnection>();
Description = String.Empty;
Namespace = String.Empty;
Changed = false;
}
#endregion
public void Dispose()
{
var instances = new List<Operator>(_instances);
instances.ForEach(instance => instance.Dispose());
_instances.Clear();
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("InstanceCount"));
}
public MetaOperator Clone(string newName)
{
var oldToNewGuidDict = new Dictionary<Guid, Guid>();
oldToNewGuidDict[Guid.Empty] = Guid.Empty;
var inputs = new List<MetaInput>();
Inputs.ForEach(i =>
{
var newInput = i.Clone();
inputs.Add(newInput);
oldToNewGuidDict[i.ID] = newInput.ID;
});
var outputs = new List<MetaOutput>();
Outputs.ForEach(o =>
{
var newOutput = o.Clone();
outputs.Add(newOutput);
oldToNewGuidDict[o.ID] = newOutput.ID;
});
var opParts = new List<Tuple<Guid, MetaOperatorPart>>();
OperatorParts.ForEach(e =>
{
var newElement = Tuple.Create(Guid.NewGuid(), e.Item2.Clone(newName + "Func"));
opParts.Add(newElement);
oldToNewGuidDict[e.Item1] = newElement.Item1;
oldToNewGuidDict[e.Item2.ID] = newElement.Item2.ID;
});
var ops = new Dictionary<Guid, Tuple<MetaOperator, InstanceProperties>>();
foreach (var o in Operators)
{
var newElement = Tuple.Create(o.Value.Item1, o.Value.Item2.Clone());
var id = Guid.NewGuid();
ops[id] = newElement;
oldToNewGuidDict[o.Key] = id;
oldToNewGuidDict[o.Value.Item1.ID] = newElement.Item1.ID;
}
foreach (var o in ops)
o.Value.Item2.ExchangeGuids(oldToNewGuidDict);
var connections = new List<MetaConnection>();
Connections.ForEach(c =>
{
Guid newSourceOpID = Guid.Empty;
if (!oldToNewGuidDict.TryGetValue(c.SourceOpID, out newSourceOpID))
newSourceOpID = c.SourceOpID;
Guid newSourceOpPartID = Guid.Empty;
if (!oldToNewGuidDict.TryGetValue(c.SourceOpPartID, out newSourceOpPartID))
newSourceOpPartID = c.SourceOpPartID;
Guid newTargetOpID = Guid.Empty;
if (!oldToNewGuidDict.TryGetValue(c.TargetOpID, out newTargetOpID))
newTargetOpID = c.TargetOpID;
Guid newTargetOpPartID = Guid.Empty;
if (!oldToNewGuidDict.TryGetValue(c.TargetOpPartID, out newTargetOpPartID))
newTargetOpPartID = c.TargetOpPartID;
connections.Add(new MetaConnection(newSourceOpID, newSourceOpPartID, newTargetOpID, newTargetOpPartID));
});
return new MetaOperator(Guid.NewGuid())
{
Name = newName,
Inputs = inputs,
Outputs = outputs,
OperatorParts = opParts,
Operators = ops,
Connections = connections,
Description = Description,
Namespace = Namespace,
Changed = true,
};
}
#region Consistency Checks
// checks for inconsistancies and fixes them if found
// Note: this method modifies directly the meta op, therefore it must be called only at startup at a point where no instances are created
public void CheckForInconsistencyAndFixThem()
{
// check for missing ops
var opEntriesToRemove = (from opEntry in Operators where opEntry.Value == null select opEntry).ToArray();
foreach (var opEntry in opEntriesToRemove)
{
RemoveOperator(opEntry.Key);
Logger.Error("Removed reference to missing operator instance {0} in {1}. Be careful now, only save and publish this change, if you know what you're doing.", opEntry.Key, Name);
}
// if meta op is basic type (== has a code op part) then the code op part must be a multi input
if (IsBasic && OperatorParts[0].Item2.IsMultiInput == false)
{
Logger.Warn("Fixing OpPart definition of code operator to multi-input: '{0} {1}'. Please report this issue.", Namespace, Name);
OperatorParts[0].Item2.IsMultiInput = true;
}
// check if there are duplicate connections stored, if that's the case check if these duplicates are pointing to a multiinput
// and are not stored within a basic op
var uniqueList = Connections.Distinct(new MetaConnectionComparer());
if (uniqueList.Count() != Connections.Count)
{
var duplicates = Connections.Except(uniqueList).ToList();
// check if output of duplicate connections are pointing to an multiinput
foreach (var connection in duplicates)
{
bool isMultiInput = true;
if (connection.TargetOpID == Guid.Empty)
{
// find connection target in among outputs and op parts of this meta op
var targetOpPart = (from opPart in OperatorParts
where opPart.Item1 == connection.TargetOpPartID
select opPart).SingleOrDefault();
if (targetOpPart != null)
{
isMultiInput = targetOpPart.Item2.IsMultiInput;
}
else
{
var targetOutput = (from output in Outputs
where output.ID == connection.TargetOpPartID
select output).Single();
isMultiInput = targetOutput.OpPart.IsMultiInput;
}
}
else
{
// find target among inputs of nested operators
var targetInput = (from op in Operators
where op.Key == connection.TargetOpID
from input in op.Value.Item1.Inputs
where input.ID == connection.TargetOpPartID
select input).Single();
isMultiInput = targetInput.IsMultiInput;
}
if (!isMultiInput || IsBasic)
{
Logger.Error("Fixing double connection in basic operator definition or connectins pointing to a single input'{0} {1}'.", Namespace, Name);
Connections.Remove(connection);
}
}
}
// check if there are connections that point to/from non existing elements anymore
var connectionsToRemove = new List<MetaConnection>();
foreach (var connection in Connections)
{
bool sourceFound;
if (connection.SourceOpID == Guid.Empty)
{
var opPartIDs = from opPart in OperatorParts select opPart.Item1;
var inputIDs = from input in Inputs select input.ID;
var allIDs = (opPartIDs).Union(inputIDs);
sourceFound = allIDs.Count(partID => partID == connection.SourceOpPartID) == 1;
}
else
{
sourceFound = (from op in Operators
where op.Key == connection.SourceOpID
from output in op.Value.Item1.Outputs
where output.ID == connection.SourceOpPartID
select output).Count() == 1;
}
bool targetFound = false;
if (sourceFound)
{
if (connection.TargetOpID == Guid.Empty)
{
var opPartIDs = from opPart in OperatorParts select opPart.Item1;
var outputIDs = from output in Outputs select output.ID;
var allIDs = (opPartIDs).Union(outputIDs);
targetFound = allIDs.Count(partID => partID == connection.TargetOpPartID) == 1;
}
else
{
targetFound = (from op in Operators
where op.Key == connection.TargetOpID
from output in op.Value.Item1.Inputs
where output.ID == connection.TargetOpPartID
select output).Count() == 1;
}
}
if (!targetFound)
connectionsToRemove.Add(connection);
}
foreach (var connection in connectionsToRemove)
{
Logger.Warn("Found connection in '{0}' pointing to non exisiting elements -> removed it.", Name);
RemoveConnection(connection, 0);
}
}
// specific meta connection comparer that ignores the ID property to find duplicated connections
private class MetaConnectionComparer : IEqualityComparer<MetaConnection>
{
// In this case a meta connections equals if all source/target properties are equal
public bool Equals(MetaConnection x, MetaConnection y)
{
return x.SourceOpID == y.SourceOpID &&
x.SourceOpPartID == y.SourceOpPartID &&
x.TargetOpID == y.TargetOpID &&
x.TargetOpPartID == y.TargetOpPartID;
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public int GetHashCode(MetaConnection connection)
{
// Check whether the object is null
if (connection == null)
return 0;
//Calculate the hash code
return connection.SourceOpID.GetHashCode() ^
connection.SourceOpPartID.GetHashCode() ^
connection.TargetOpID.GetHashCode() ^
connection.TargetOpPartID.GetHashCode();
}
}
#endregion
#region OperatorHandling
private void MoveOperatorTo(Guid opIdToMove, MetaOperator newParent, Guid newParentId)
{
var metaOpEntry = (from o in Operators where o.Key == opIdToMove select o).Single();
Operators.Remove(opIdToMove);
newParent.Operators.Add(metaOpEntry.Key, metaOpEntry.Value);
foreach (var instance in _instances)
{
instance.MoveOperatorTo(opIdToMove, newParentId);
}
}
public Guid AddOperator(MetaOperator metaOp, double posX = 100, double posY = 100, double width = 100, bool visible = true)
{
return AddOperator(metaOp, Guid.NewGuid(), posX, posY, width, visible);
}
public Guid AddOperator(MetaOperator metaOp, Guid id, double posX = 100, double posY = 100, double width = 100, bool visible = true)
{
var opProperties = new InstanceProperties() { Position = new Point(posX, posY), Width = width, Visible = visible };
foreach (var metaInput in metaOp.Inputs)
{
opProperties.InputValues.Add(metaInput.ID, metaInput.DefaultFunc);
}
foreach (var metaOpPartEntry in metaOp.OperatorParts)
{
var stateType = metaOpPartEntry.Item2.StateType;
if (stateType != null)
{
// check if part contains a state and if so create it
var state = Activator.CreateInstance(stateType) as IOperatorPartState;
opProperties.OperatorPartStates[metaOpPartEntry.Item1] = state;
}
}
return AddOperator(metaOp, opProperties, id);
}
public Operator GetOperatorInstance(Guid opID)
{
return _instances.FirstOrDefault(op => op.ID == opID);
}
internal IEnumerable<Operator> GetOperatorInstances(Guid opID)
{
return _instances.FindAll(op => op.ID == opID);
}
internal Guid AddOperator(MetaOperator metaOp, InstanceProperties opProperties, Guid id)
{
Operators.Add(id, Tuple.Create(metaOp, opProperties));
Changed = true;
foreach (var opInstance in _instances)
{
var addedOp = metaOp.CreateOperator(id);
var opProps = opProperties; // make local copy for closures in lambda functions below!
addedOp.InputAddedEvent += (o, e) => { AddInputToOperatorProperties(opProps, e.OperatorPart); };
addedOp.InputRemovedEvent += (o, e) => { RemoveInputFromOperatorProperties(opProps, e.OperatorPart); };
// bind all inputs to ourself to get informed when these change
foreach (var input in addedOp.Inputs)
{
if (!opProperties.InputValues.ContainsKey(input.ID))
{
//Logger.Warn("ignoring missing opProperty:" + input.Name);
opProperties.InputValues.Add(input.ID, input.Func);
}
input.Func = opProperties.InputValues[input.ID].Clone();
input.ChangedEvent += (o, e) => { UpdateInputValues(o as OperatorPart, opProperties); };
}
opInstance.AddOperator(addedOp); // do this as last step as this triggers update events
}
return id;
}
private void AddInputToOperatorProperties(InstanceProperties opProperties, OperatorPart input)
{
opProperties.InputValues[input.ID] = input.Func.Clone();
input.ChangedEvent += (o, e) => { UpdateInputValues(o as OperatorPart, opProperties); };
}
private static void RemoveInputFromOperatorProperties(InstanceProperties opProperties, OperatorPart input)
{
opProperties.InputValues.Remove(input.ID);
}
internal MetaOperator CombineToNewOp(Guid newMetaID, Guid newOpInstanceId, IEnumerable<Guid> opsToCombine, String name = "CombinedOp", String @namespace = "", String description = "",
double poxX = 100, double posY = 100)
{
var newOp = new MetaOperator(newMetaID);
newOp.Name = name;
newOp.Namespace = @namespace;
newOp.Description = description;
AddOperator(newOp, newOpInstanceId, poxX, posY);
// find the connections within the grouped op
var internalConnections = (from con in Connections
from sourceOp in opsToCombine
from targetOp in opsToCombine
where con.SourceOpID == sourceOp
where con.TargetOpID == targetOp
select con).ToList();
var inputConnections = (from con in Connections
from targetOp in opsToCombine
let opIDs = from o in Operators select o.Key
from op in opIDs.Except(opsToCombine).Union(new List<Guid>() { Guid.Empty })
where con.TargetOpID == targetOp
where con.SourceOpID == op
select con).ToList();
var outputConnections = (from con in Connections
from sourceOp in opsToCombine
let opIDs = from o in Operators select o.Key
from op in opIDs.Except(opsToCombine).Union(new List<Guid>() { Guid.Empty })
where con.SourceOpID == sourceOp
where con.TargetOpID == op
select con).ToList();
var allConnectionsUnsorted = inputConnections.Union(internalConnections).Union(outputConnections);
var allConnectionsSorted = new List<Tuple<MetaConnection, int>>(); // these are later on needed to restore multi input order (item2 == multiIdx)!
foreach (var con in Connections)
{
if (allConnectionsUnsorted.Contains(con))
{
var idxOfCon = Connections.FindIndex(c => c == con); // index of connection
var fstIdxOfConTarget = Connections.FindIndex(c => c.TargetOpID == con.TargetOpID && c.TargetOpPartID == con.TargetOpPartID);
var multiInputIdx = idxOfCon - fstIdxOfConTarget;
allConnectionsSorted.Add(Tuple.Create(con, multiInputIdx));
}
}
// remove all connections to combined ops from parent op
var consToRemove = new List<Tuple<MetaConnection, int>>(allConnectionsSorted);
consToRemove.Reverse();
foreach (var con in consToRemove)
{
RemoveConnection(con.Item1, con.Item2);
}
foreach (var opId in opsToCombine)
{
MoveOperatorTo(opId, newOp, newOpInstanceId);
}
// build new inputs and connection to them
// first group them so that for several connections which have the same source only one input is generated
var groupedInputs = (from con in inputConnections
group con by (con.SourceOpID.ToString() + con.SourceOpPartID.ToString())
into g
select g).ToList();
foreach (var inputGroup in groupedInputs)
{
MetaConnection prevCon = null;
MetaInput targetInput = null;
var targetName = new StringBuilder();
foreach (var con in inputGroup)
{
prevCon = con;
targetInput = (from op in newOp.Operators
where op.Key == con.TargetOpID
from prevTarget in op.Value.Item1.Inputs
where con.TargetOpPartID == prevTarget.ID
select prevTarget).Single();
if (targetName.Length > 0)
targetName.Append(" | ");
targetName.Append(targetInput.Name);
}
var sourceName = (prevCon.SourceOpID == Guid.Empty) ? Name : GetName(prevCon.SourceOpID);
var newInputName = String.IsNullOrEmpty(sourceName) ? targetName.ToString() : sourceName;
var newInput = new MetaInput(Guid.NewGuid(), newInputName, targetInput.OpPart, targetInput.DefaultValue.Clone(), targetInput.IsMultiInput);
newInput.Relevance = MetaInput.RelevanceType.Required;
newOp.AddInput(newInput);
// create new connection in parent op from prev source to new input of combined op
var conToNewInput = new MetaConnection(prevCon.SourceOpID, prevCon.SourceOpPartID, newOpInstanceId, newInput.ID);
InsertConnectionAt(conToNewInput);
foreach (var con in inputGroup)
{
// set stored connection to new input
con.SourceOpID = Guid.Empty;
con.SourceOpPartID = newInput.ID;
}
}
// build new outputs and connections to them
foreach (var con in outputConnections)
{
var sourceOutput = (from op in newOp.Operators
where op.Key == con.SourceOpID
from prevSource in op.Value.Item1.Outputs
where con.SourceOpPartID == prevSource.ID
select prevSource).Single();
var newOutput = new MetaOutput(Guid.NewGuid(), sourceOutput.Name, sourceOutput.OpPart);
newOp.AddOutput(newOutput);
var conFromNewOutput = new MetaConnection(newOpInstanceId, newOutput.ID, con.TargetOpID, con.TargetOpPartID);
var prevConWithMultiIdx = allConnectionsSorted.Find(c => c.Item1.SourceOpID == con.SourceOpID &&
c.Item1.SourceOpPartID == con.SourceOpPartID &&
c.Item1.TargetOpID == con.TargetOpID &&
c.Item1.TargetOpPartID == con.TargetOpPartID);
InsertConnectionAt(conFromNewOutput, prevConWithMultiIdx.Item2);
// set stored connection to new output
con.TargetOpID = Guid.Empty;
con.TargetOpPartID = newOutput.ID;
}
// setup all connections within new op
// first group all connections to same input in order to get multi input indices
var groupedConnections = (from con in allConnectionsSorted
group con by (con.Item1.TargetOpID.ToString() + con.Item1.TargetOpPartID.ToString()) into g
select g).ToList();
// insert the connections to new op
foreach (var conGroup in groupedConnections)
{
var index = 0;
foreach (var con in conGroup)
{
newOp.InsertConnectionAt(con.Item1, index);
index++;
}
}
Changed = true;
return newOp;
}
// returns a dict with mapping of old instance ids to new instance ids
internal Dictionary<Guid, Guid> UngroupOperator(Guid id, MetaOperator valueMetaOp)
{
var opEntryToUngroup = (from op in Operators where op.Key == id select op).First();
var metaOpToUngroup = opEntryToUngroup.Value.Item1;
// get position of ungrouped op
var ungroupOpPosition = GetPosition(id);
var opIDsToUngroup = (from op in metaOpToUngroup.Operators select op.Key);
var topLeftPoint = new Point(double.MaxValue, double.MaxValue);
foreach (var opIdToUngroup in opIDsToUngroup)
{
if (metaOpToUngroup.GetVisible(opIdToUngroup))
{
var pos = metaOpToUngroup.GetPosition(opIdToUngroup);
if (pos.X < topLeftPoint.X)
topLeftPoint.X = pos.X;
if (pos.Y < topLeftPoint.Y)
topLeftPoint.Y = pos.Y;
}
}
var offsetToUngroupOpPos = ungroupOpPosition - topLeftPoint;
// for each internal op create instantiation here
var opsToUngroup = new Dictionary<Guid, Tuple<MetaOperator, InstanceProperties>>(metaOpToUngroup.Operators); // make copy as we're modifying original list during move
var originalToCopyMap = new Dictionary<Guid, Guid>();
foreach (var opEntry in opsToUngroup)
{
var opID = opEntry.Key;
var op = opEntry.Value.Item1;
var newOpId = Guid.NewGuid();
AddOperator(op, opEntry.Value.Item2.Clone(), newOpId);
var pos = GetPosition(newOpId);
SetPosition(newOpId, pos + offsetToUngroupOpPos);
originalToCopyMap[opID] = newOpId;
}
// find the connections within the op
var internalConnections = (from con in metaOpToUngroup.Connections
from sourceOp in opIDsToUngroup
from targetOp in opIDsToUngroup
where con.SourceOpID == sourceOp
where con.TargetOpID == targetOp
select new MetaConnection(originalToCopyMap[con.SourceOpID], con.SourceOpPartID, originalToCopyMap[con.TargetOpID], con.TargetOpPartID)).ToList();
var newConnectionsToInputsTmp = (from conToOp in Connections
where conToOp.TargetOpID == opEntryToUngroup.Key
from conFromInput in metaOpToUngroup.Connections
from targetOp in opIDsToUngroup
where conFromInput.SourceOpID == Guid.Empty
where conFromInput.TargetOpID == targetOp
where conToOp.TargetOpPartID == conFromInput.SourceOpPartID
let newCon = new MetaConnection(conToOp.SourceOpID, conToOp.SourceOpPartID,
originalToCopyMap[conFromInput.TargetOpID], conFromInput.TargetOpPartID)
select new { NewCon = newCon, PrevInputID = conFromInput.SourceOpPartID }).ToList();
var newConnectionsToInputs = (from con in newConnectionsToInputsTmp select con.NewCon).ToList();
// connections that have as input a hidden op (e.g. when a 'ungrouped' input was animated) get
// an additional value op inserted to visualize this connection
var connectionsWhichNeedAdditionalValueOp = (from conToInput in newConnectionsToInputsTmp
from opEntry in Operators
where opEntry.Key == conToInput.NewCon.SourceOpID
where opEntry.Value.Item2.Visible == false
select conToInput).ToList();
foreach (var con in connectionsWhichNeedAdditionalValueOp)
{
var newValueOpID = Guid.NewGuid();
AddOperator(valueMetaOp, new InstanceProperties(valueMetaOp.Inputs), newValueOpID);
var inputThatIsReplaced = (from input in metaOpToUngroup.Inputs where input.ID == con.PrevInputID select input).Single();
foreach (var instance in _instances)
{
var valueInstance = (from op in instance.InternalOps where op.ID == newValueOpID select op).Single();
valueInstance.Name = inputThatIsReplaced.Name;
}
var newCon = new MetaConnection(con.NewCon.SourceOpID, con.NewCon.SourceOpPartID, newValueOpID, valueMetaOp.Inputs[0].ID);
newConnectionsToInputs.Add(newCon);
con.NewCon.SourceOpID = newValueOpID;
con.NewCon.SourceOpPartID = valueMetaOp.Outputs[0].ID;
}
var newConnectionsFromOutputs = (from conFromOp in Connections
where conFromOp.SourceOpID == opEntryToUngroup.Key
from conToOutput in metaOpToUngroup.Connections
from sourceOp in opIDsToUngroup
where conToOutput.SourceOpID == sourceOp
where conToOutput.TargetOpID == Guid.Empty
where conToOutput.TargetOpPartID == conFromOp.SourceOpPartID
let newCon = new MetaConnection(originalToCopyMap[conToOutput.SourceOpID], conToOutput.SourceOpPartID,
conFromOp.TargetOpID, conFromOp.TargetOpPartID)
let index = GetConnectionIndexAtTargetInput(conFromOp)
select new { Connection = newCon, Index = index }).ToList();
var allInputConnectionsUnsorted = newConnectionsToInputs.Union(internalConnections).ToList();
RemoveOperator(id);
// setup all connections within new op
// first group all connections to same input in order to get multi input indices
var groupedInputConnections = (from con in allInputConnectionsUnsorted
group con by (con.TargetOpID.ToString() + con.TargetOpPartID.ToString())
into @group
select @group).ToList();
// insert the connections to new op
foreach (var conGroup in groupedInputConnections)
{
var index = 0;
foreach (var con in conGroup)
{
InsertConnectionAt(con, index);
index++;
}
}
// add connections from outputs
foreach (var c in newConnectionsFromOutputs)
{
InsertConnectionAt(c.Connection, c.Index);
}
Changed = true;
return originalToCopyMap;
}
internal void RemoveOperator(Guid opId)
{
// first remove connections to and from op
RemoveAllConnectionsToOp(opId);
RemoveAllConnectionsFromOp(opId);
// then remove op itself
Operators.Remove(opId);
foreach (var opInstance in _instances)
{
RemoveOperatorFromInstance(opId, opInstance);
}
Changed = true;
}
internal void RemoveInstance(Operator op)
{
_instances.Remove(op);
RaisePropertyChangedEvent("InstanceCount");
//Changed = true;
}
private void RaisePropertyChangedEvent(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private InstanceProperties GetOperatorProperties(Guid opId)
{
return Operators[opId].Item2;
}
internal string GetName(Guid opId)
{
return GetOperatorProperties(opId).Name;
}
internal void SetName(Guid opId, string name)
{
GetOperatorProperties(opId).Name = name;
Changed = true;
}
internal Point GetPosition(Guid opId)
{
return GetOperatorProperties(opId).Position;
}
internal void SetPosition(Guid opId, Point position)
{
GetOperatorProperties(opId).Position = position;
foreach (var opParentInstance in _instances)
{
var op = opParentInstance.InternalOps.Find(o => o.ID == opId);
op.TriggerPositionChanged(new PositionChangedEventArgs(position));
}
Changed = true;
}
internal double GetWidth(Guid opId)
{
return GetOperatorProperties(opId).Width;
}
internal void SetWidth(Guid opId, double width)
{
GetOperatorProperties(opId).Width = width;
foreach (var opParentInstance in _instances)
{
var op = opParentInstance.InternalOps.Find(o => o.ID == opId);
op.TriggerWidthChanged(new WidthChangedEventArgs(width));
}
Changed = true;
}
internal bool GetVisible(Guid opId)
{
return GetOperatorProperties(opId).Visible;
}
internal void SetVisible(Guid opId, bool visible)
{
GetOperatorProperties(opId).Visible = visible;
foreach (var opParentInstance in _instances)
{
var op = opParentInstance.InternalOps.Find(o => o.ID == opId);
op.TriggerVisibleChanged(new VisibleChangedEventArgs(visible));
}
Changed = true;
}
internal bool GetDisabled(Guid opId)
{
return GetOperatorProperties(opId).Disabled;
}
internal void SetDisabled(Guid opId, bool disabled)
{
GetOperatorProperties(opId).Disabled = disabled;
foreach (var opParentInstance in _instances)
{