-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
2494 lines (2040 loc) · 78.2 KB
/
model.py
File metadata and controls
2494 lines (2040 loc) · 78.2 KB
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
import re
import scipy
import numpy as np
import time
import uuid
import math
import threading
import mido
import json
import logging
import tempfile
import os
import traceback
import importlib
import sys
from collections import defaultdict
from pythonosc.dispatcher import Dispatcher
from pythonosc import osc_server
from pathlib import Path
from threading import RLock
import util
import dmxio
# For Custom Fuction Nodes
import colorsys
import random
from math import *
from functions import *
logger = logging.getLogger(__name__)
def clamp(x, min_value, max_value):
return min(max(min_value, x), max_value)
MAX_VALUES = {
"bool": 1,
"int": 255,
"float": 100.0,
}
NEAR_THRESHOLD = 0.01
TYPES = ["bool", "int", "float", "any"]
UUID_DATABASE = {}
ID_COUNT = 0
def update_name(name, other_names):
def toks(obj_name):
match = re.fullmatch(r"(\D*)(\d*)$", obj_name)
if match:
prefix, number = match.groups()
if not number:
number = 0
else:
number = int(number)
return prefix, number
else:
return None, None
my_prefix, my_number = toks(name)
if my_prefix is None:
return f"{name}-1"
for other_name in other_names:
other_prefix, other_number = toks(other_name)
if other_prefix is None:
continue
if my_prefix == other_prefix:
my_number = max(my_number, other_number)
return f"{my_prefix}{my_number+1}"
# Outputs cannot be copied.
NOT_COPYABLE = [
"DmxOutput",
"DmxOutputGroup",
]
def new_ids(data):
uuid_pattern = (
r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}"
)
string_data = json.dumps(data)
obj_ids = re.findall(rf"(\w+\[{uuid_pattern}\])", string_data)
if not obj_ids:
return json.loads(string_data)
obj_ids = set(obj_ids)
for old_id in obj_ids:
match2 = re.match(rf"(\w+)\[{uuid_pattern}\]", old_id)
if not match2:
raise Exception("Failed to replace ids")
class_name = match2.groups()[0]
if class_name in NOT_COPYABLE:
continue
new_id = f"{class_name}[{uuid.uuid4()}]"
string_data = string_data.replace(old_id, new_id)
return json.loads(string_data)
def clear_database():
global UUID_DATABASE
global ID_COUNT
ID_COUNT = 0
UUID_DATABASE = {}
class Identifier:
def __init__(self):
global UUID_DATABASE
global ID_COUNT
self.id = f"{self.__class__.__name__}[{uuid.uuid4()}]"
ID_COUNT += 1
UUID_DATABASE[self.id] = self
self.deleted = False
def delete(self):
self.deleted = True
def serialize(self):
return {"id": self.id}
def deserialize(self, data):
global UUID_DATABASE
self.id = data["id"]
UUID_DATABASE[self.id] = self
cast = {"bool": int, "int": int, "float": float, "any": lambda x: x}
class Channel(Identifier):
def __init__(self, **kwargs):
super().__init__()
self._value = kwargs.get("value")
self.size = kwargs.get("size", 1)
if self._value is None:
self._value = 0 if self.size == 1 else [0] * self.size
self.dtype = kwargs.get("dtype", "float")
# TODO: Replace with regex.sub and include special chars
self.name = kwargs.get("name", "Channel").replace(" ", "")
def get(self):
return cast[self.dtype](self._value)
def set(self, value):
self._value = value
def serialize(self):
data = super().serialize()
data.update(
{
"value": self._value,
"size": self.size,
"dtype": self.dtype,
"name": self.name,
}
)
return data
def deserialize(self, data):
super().deserialize(data)
self.value = data["value"]
self.dtype = data["dtype"]
self.name = data["name"]
self.size = data["size"]
@property
def value(self):
return self.get()
@value.setter
def value(self, value):
self.set(value)
class CodeEditorChannel:
"""Decorator around the Channel for use in the code editor.
This is a restricted version of the Channel that prevents
a user from doing manipulating the internal models.
"""
def __init__(self, channel):
self._channel = channel
self.valid_attributes = ["set", "get", "value", "__class__"]
if isinstance(channel, DmxOutputGroup):
super().__getattribute__("valid_attributes").extend(
super().__getattribute__("_channel").map.keys()
)
@property
def channel(self, value):
pass
@channel.setter
def channel(self, value):
attrs = super().__getattribute__("valid_attributes")
raise CodeEditorException(
f"'channel' is not a valid attribute. Only use: {', '.join(attrs)}"
)
def __getattribute__(self, key):
attrs = super().__getattribute__("valid_attributes")
if key not in attrs:
STATE.log.append(
CodeEditorException(
f"'{key}' is not a valid attribute. Only use: {', '.join(attrs)}"
)
)
return
else:
return getattr(super().__getattribute__("_channel"), key)
def __getitem__(self, key):
return super().__getattribute__("_channel")[key]
class CodeEditorException(Exception):
"""Exceptions that pertain to the Code Editor."""
class Parameter(Identifier):
def __init__(self, name="", value=None, dtype="any"):
super().__init__()
self.name = name
self.value = value
self.dtype = dtype
def serialize(self):
data = super().serialize()
data.update(
{
"name": self.name,
"value": self.value,
}
)
return data
def deserialize(self, data):
super().deserialize(data)
self.name = data["name"]
self.value = data["value"]
class Parameterized(Identifier):
def __init__(self):
super().__init__()
self.parameters = []
def update_parameter(self, index, value):
if 0 <= index < len(self.parameters):
return True
else:
return False
def add_parameter(self, parameter):
assert self.get_parameter(parameter.name) is None
n = len(self.parameters)
self.parameters.append(parameter)
return n
def get_parameter(self, parameter_name):
for parameter in self.parameters:
if parameter_name == parameter.name:
return parameter
return None
def get_parameter_id(self, parameter_name):
parameter = self.get_parameter(parameter_name)
if parameter is not None:
return parameter.id
def serialize(self):
data = super().serialize()
data.update({"parameters": []})
for parameter in self.parameters:
data["parameters"].append(parameter.serialize())
return data
def deserialize(self, data):
super().deserialize(data)
parameters_data = data["parameters"]
for i, parameter_data in enumerate(parameters_data):
self.parameters[i].deserialize(parameter_data)
self.update_parameter(i, str(self.parameters[i].value))
class SourceNode(Parameterized):
def __init__(self, **kwargs):
super().__init__()
self.name = kwargs.get("name", "")
self.channel = Channel(**kwargs)
self.input_type = None
self.is_constant = True
def update(self, clip_beat):
pass
@property
def dtype(self):
return self.channel.dtype
@property
def value(self):
if isinstance(self.channel.value, list):
return tuple(self.channel.value)
else:
return self.channel.value
@property
def size(self):
return self.channel.size
def set(self, value):
self.channel.set(value)
def get(self):
if isinstance(self.value, list):
return tuple(self.channel.get())
else:
return self.channel.get()
def serialize(self):
data = super().serialize()
data.update(
{
"name": self.name,
"channel": self.channel.serialize(),
"input_type": self.input_type,
}
)
return data
def deserialize(self, data):
super().deserialize(data)
self.name = data["name"]
self.channel.deserialize(data["channel"])
self.input_type = data["input_type"]
class AutomatableSourceNode(SourceNode):
nice_title = "Input"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.input_type = kwargs.get("dtype", "float")
self.ext_channel = Channel(**kwargs)
self.mode = "automation"
self.min_parameter = Parameter("min", 0)
self.max_parameter = Parameter("max", MAX_VALUES[self.channel.dtype])
self.key_parameter = Parameter("key", "")
self.add_parameter(self.min_parameter)
self.add_parameter(self.max_parameter)
self.add_parameter(self.key_parameter)
self.automations = []
self.active_automation = None
self.speed = 0
self.last_beat = 0
self.is_constant = False
self.history = [self.get()]*100
def update(self, clip_beat):
self.history.pop(0)
self.history.append(self.get())
if self.active_automation is None:
return
beat = clip_beat * (2**self.speed)
current_beat = beat % self.active_automation.length
restarted = current_beat < self.last_beat
if self.mode == "armed":
if self.active_automation is not None:
value = self.active_automation.value(current_beat)
self.channel.set(value)
if restarted:
self.mode = "recording"
self.active_automation.clear()
elif self.mode == "recording":
if restarted:
self.mode = "automation"
point = Point(current_beat, self.ext_channel.get())
self.active_automation.add_point(point, replace_near=True)
self.channel.set(self.ext_channel.get())
elif self.mode == "automation":
if self.active_automation is not None:
value = self.active_automation.value(current_beat)
self.channel.set(value)
else: # manual
self.channel.set(self.ext_channel.get())
self.last_beat = current_beat
def ext_get(self):
return self.ext_channel.get()
def ext_set(self, value):
# TODO: Use clamp
value = max(self.min_parameter.value, value)
value = min(self.max_parameter.value, value)
self.ext_channel.set(value)
def set(self, value):
value = max(self.min_parameter.value, value)
value = min(self.max_parameter.value, value)
super().set(value)
def set_active_automation(self, automation):
assert automation in self.automations
self.active_automation = automation
return True
def add_automation(self, automation=None):
n = len(self.automations)
new_automation = automation or ChannelAutomation(
self.channel.dtype,
f"Preset #{n}",
min_value=self.get_parameter("min").value,
max_value=self.get_parameter("max").value,
)
self.automations.append(new_automation)
self.set_active_automation(new_automation)
return new_automation
def update_parameter(self, index, value):
if self.parameters[index] in [self.min_parameter, self.max_parameter]:
self.parameters[index].value = cast[self.channel.dtype](float(value))
min_value = self.min_parameter.value
max_value = self.max_parameter.value
for automation in self.automations:
if automation.deleted:
continue
for point in automation.points:
if point.deleted:
continue
point.y = clamp(point.y, min_value, max_value)
return True
elif self.parameters[index] == self.key_parameter:
if not isinstance(value, str):
return False
if not value.isascii():
return False
if not len(value) == 1:
return False
self.key_parameter.value = value
logger.debug("Mapping %s to %s", value, self)
for key, channel in tuple(STATE.key_channel_map.items()):
if channel == self:
del STATE.key_channel_map[key]
STATE.key_channel_map[value.upper()] = self
return True
else:
return super().update_parameter(index, value)
def serialize(self):
data = super().serialize()
data.update(
{
"ext_channel": self.ext_channel.serialize(),
"mode": self.mode,
"active_automation": self.active_automation.id
if self.active_automation
else None,
"automations": [
automation.serialize()
for automation in self.automations
if not automation.deleted
],
"speed": self.speed,
}
)
return data
def deserialize(self, data):
super().deserialize(data)
self.ext_channel.deserialize(data["ext_channel"])
self.mode = data["mode"]
self.speed = data["speed"]
for automation_data in data["automations"]:
automation = ChannelAutomation()
automation.deserialize(automation_data)
self.automations.append(automation)
self.set_active_automation(UUID_DATABASE[data["active_automation"]])
class DmxOutput(Channel):
def __init__(self, dmx_address=1, name=""):
super().__init__(dtype="int", name=name or f"Dmx{dmx_address}")
self.dmx_address = dmx_address
self.history = [0] * 500
def record(self):
self.history.pop(0)
self.history.append(self.value)
def serialize(self):
data = super().serialize()
data.update(
{
"dmx_address": self.dmx_address,
}
)
return data
def deserialize(self, data):
super().deserialize(data)
self.dmx_address = data["dmx_address"]
class DmxOutputGroup(Identifier):
def __init__(self, channel_names=[], dmx_address=1, name="Group"):
super().__init__()
self.name = name
self.dmx_address = dmx_address
self.outputs: DmxOutput = []
self.channel_names = channel_names
for i, channel_name in enumerate(channel_names):
output_channel = DmxOutput()
self.outputs.append(output_channel)
self.update_starting_address(dmx_address)
self.update_name(name)
self.map = {
self.channel_names[i]: self.outputs[i] for i in range(len(self.outputs))
}
def record(self):
for output in self.outputs:
output.record()
def update_starting_address(self, address):
self.dmx_address = address
for i, output_channel in enumerate(self.outputs):
output_channel.dmx_address = i + address
def update_name(self, name):
self.name = name
for i, output_channel in enumerate(self.outputs):
output_channel.name = f"{name}.{self.channel_names[i]}"
def serialize(self):
data = super().serialize()
data.update(
{
"name": self.name,
"dmx_address": self.dmx_address,
"channel_names": self.channel_names,
"outputs": [],
}
)
for output_channel in self.outputs:
data["outputs"].append(output_channel.serialize())
return data
def deserialize(self, data):
super().deserialize(data)
self.name = data["name"]
self.dmx_address = data["dmx_address"]
self.channel_names = data["channel_names"]
for i, output_data in enumerate(data["outputs"]):
self.outputs[i].deserialize(output_data)
def __getattr__(self, name):
return self.map[name]
def __getitem__(self, name):
return self.map[name]
class ColorNode(SourceNode):
nice_title = "Color"
def __init__(self, **kwargs):
kwargs.setdefault("dtype", "any")
kwargs.setdefault("size", 3)
super().__init__(**kwargs)
self.input_type = "color"
def set(self, value):
self.channel.set(value)
class ButtonNode(SourceNode):
nice_title = "Button"
def __init__(self, **kwargs):
kwargs.setdefault("dtype", "bool")
kwargs.setdefault("size", 1)
super().__init__(**kwargs)
self.input_type = "button"
def set(self, value):
self.channel.set(value)
class OscInput(AutomatableSourceNode):
def __init__(self, **kwargs):
kwargs.setdefault("name", f"OSC")
kwargs.setdefault("dtype", "int")
super().__init__(**kwargs)
self.endpoint_parameter = Parameter("endpoint", value="/")
self.add_parameter(self.endpoint_parameter)
self.input_type = "osc_input_" + self.dtype
def update_parameter(self, index, value):
if self.parameters[index] == self.endpoint_parameter:
if value.startswith("/"):
self.parameters[index].value = value
global_osc_server().map_channel(value, self)
return True
else:
return super().update_parameter(index, value)
class MidiInput(AutomatableSourceNode):
def __init__(self, **kwargs):
kwargs.setdefault("name", "MIDI")
kwargs.setdefault("dtype", "int")
super().__init__(**kwargs)
self.device_parameter = Parameter("device", value="")
self.id_parameter = Parameter("id", value="/")
self.add_parameter(self.device_parameter)
self.add_parameter(self.id_parameter)
self.input_type = "midi"
def update_parameter(self, index, value):
if self.parameters[index] == self.device_parameter:
if not value:
return False
self.parameters[index].value = value
return True
elif self.parameters[index] == self.id_parameter:
if self.device_parameter.value is None:
return False
result = value.split("/")
if not len(result) == 2 and result[0] and result[1]:
return False
self.parameters[index].value = value
return True
else:
return super().update_parameter(index, value)
class GlobalCodeStorage:
def __init__(self):
self._vars = dict()
def get(self, name, default=None):
if name not in self._vars:
self._vars[name] = default
return self._vars[name]
def set(self, name, value):
self._vars[name] = value
def items(self):
return self._vars.items()
class Point(Identifier):
def __init__(self, x=None, y=None):
super().__init__()
self.x = x
self.y = y
def serialize(self):
data = super().serialize()
data.update(
{
"x": self.x,
"y": self.y,
}
)
return data
def deserialize(self, data):
super().deserialize(data)
self.x = data["x"]
self.y = data["y"]
class ChannelAutomation(Identifier):
default_interpolation_type = {
"bool": "previous",
"int": "linear",
"float": "linear",
}
TIME_RESOLUTION = 1 / 60.0
def __init__(self, dtype="int", name="", min_value=0, max_value=1):
super().__init__()
self.dtype = dtype
self.name = name
self.length = 4 # beats
self.points = [Point(0, min_value), Point(self.length, max_value)]
self.interpolation = self.default_interpolation_type[self.dtype]
self.reinterpolate()
@property
def values_x(self):
return [p.x for p in self.points if not p.deleted]
@property
def values_y(self):
return [p.y for p in self.points if not p.deleted]
def value(self, beat_time):
if self.f is None:
v = 0
else:
try:
v = self.f(beat_time % self.length)
except Exception as e:
logger.warning(e)
v = 0
if np.isnan(v):
v = 0
if self.dtype == "bool":
return int(v > 0.5)
elif self.dtype == "int":
return int(v)
else:
return float(v)
def n_points(self):
return len(self.points)
def add_point(self, point, replace_near=False):
# Hack to make sure the first/lest point is never a deleted point
for p in self.points:
if p.deleted:
p.x = 1e-6
self.points.append(point)
self.points.sort(key=lambda p: p.x)
self.reinterpolate()
def shift_points(self, amount):
# TODO: Not working
x1 = 0 - amount
x2 = self.length - amount
new_first_point = Point(x1, self.value(x1))
new_last_point = Point(x2, self.value(x2))
self.add_point(new_first_point)
self.add_point(new_last_point)
for point in self.points:
point.x += amount
p = self.points[0]
while p.x < 0:
self.points.pop(0)
self.points.append(p)
p.x = p.x % self.length
p = self.points[0]
p = self.points[-1]
while p.x > self.length:
self.points.pop(-1)
self.points.insert(0, p)
p.x = p.x % self.length
p = self.points[-1]
self.reinterpolate()
def set_interpolation(self, kind):
self.interpolation = kind
self.reinterpolate()
def reinterpolate(self):
self.f = scipy.interpolate.interp1d(
self.values_x,
self.values_y,
kind=self.interpolation,
assume_sorted=False,
bounds_error=False,
)
def set_length(self, new_length):
if new_length > self.length:
self.add_point(Point(new_length, self.points[-1].y))
else:
for point in self.points:
if point.deleted:
continue
if point.x > new_length:
point.deleted = True
self.add_point(Point(new_length, self.value(new_length)))
self.length = new_length
self.reinterpolate()
def clear(self):
# TODO: This is dangerous since some of the code assume there are always at least two points
self.points.clear()
def serialize(self):
data = super().serialize()
data.update(
{
"length": self.length,
"points": [
point.serialize() for point in self.points if not point.deleted
],
"dtype": self.dtype,
"name": self.name,
"interpolation": self.interpolation,
}
)
return data
def deserialize(self, data):
super().deserialize(data)
self.name = data["name"]
self.dtype = data["dtype"]
self.points = []
for point_data in data["points"]:
point = Point()
point.deserialize(point_data)
self.points.append(point)
self.length = data["length"]
self.name = data["name"]
self.set_interpolation(data["interpolation"])
class ClipPreset(Identifier):
def __init__(self, name=None, presets=None):
super().__init__()
self.name = name
self.presets = presets or []
def execute(self):
for i, preset in enumerate(self.presets):
channel, automation, speed = preset
if channel.is_constant:
channel.set(automation)
else:
channel.set_active_automation(automation)
channel.speed = speed
def update(self, preset_name, presets):
self.name = preset_name
self.presets = presets
def serialize(self):
data = super().serialize()
data.update(
{
"name": self.name,
"presets": [
(
channel.id,
automation if channel.is_constant else automation.id,
speed,
)
for channel, automation, speed in self.presets
],
}
)
return data
def deserialize(self, data):
super().deserialize(data)
self.name = data["name"]
for preset_data in data["presets"]:
channel_id, automation_id, speed = preset_data
channel = UUID_DATABASE[channel_id]
self.presets.append(
(
channel,
automation_id
if channel.is_constant
else UUID_DATABASE[automation_id],
speed,
)
)
class MultiClipPreset(Identifier):
def __init__(self, name=None, clip_presets=None):
super().__init__()
self.name = name
self.presets = clip_presets or []
def execute(self):
start = time.time()
for clip_preset in self.presets:
track, clip, preset = clip_preset
STATE.execute(f"set_clip {track.id} {clip.id}")
preset.execute()
STATE.start()
def serialize(self):
data = super().serialize()
data.update(
{
"name": self.name,
"presets": [
f"{track.id}:{clip.id}:{preset.id}"
for track, clip, preset in self.presets
],
}
)
return data
def deserialize(self, data):
super().deserialize(data)
self.name = data["name"]
for preset_ids in data["presets"]:
track_id, clip_id, preset_id = preset_ids.split(":")
self.presets.append(
(
UUID_DATABASE[track_id],
UUID_DATABASE[clip_id],
UUID_DATABASE[preset_id],
)
)
class Trigger(Identifier):
"""Triggers can be used to map aribitrary inputs to program commands."""
def __init__(self, name, type_, event, command):
"""Constructor.
Args:
name (str): The name of the Trigger.
type (str): The type of the event to fire the Trigger ("midi", "osc", or "key").
event (tuple): Tuple of the event (e.g, midi node and value, osc, etc.).
command (str): The command to execute when the event is met.
"""
self.name = name
self.type = type_
self.event = event
self.command = command
def test(self, event):
return self.event == event
def run(self):
STATE.log.append(f"Trigger Fired! {self.name}: {self.event} {self.command}")
STATE.execute(self.command)
class TriggerManager:
def __init__(self):
self.triggers = []
def add_trigger(self, trigger):
self.triggers.append(trigger)
def fire_triggers(self, type_, event):
for trigger in self.triggers:
if type_ == trigger.type and trigger.test(event):
trigger.run()
class Code:
def __init__(self, code_id):
self.id = code_id
self._update_path()
self.compiled = None
def exists(self):
return (
os.path.exists(self.file_path_name)
if self.file_path_name is not None
else False
)
def reload(self):
try:
if self.file_path_name is not None: