-
Notifications
You must be signed in to change notification settings - Fork 0
/
JITModPatch.sc
1411 lines (1315 loc) · 38.3 KB
/
JITModPatch.sc
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
JITModPatch {
classvar <current;
var <name;
var <>proxyspace, <>server, <>buffers, <>midi, <customInit, <cleanup;
var <>doc, gui;
var <path;
var <dirty = false; // I'm not sure I can really support this?
// sometimes I need to check the old value before it was set
// but it's changed before we get any notifications here
// I can't think of any way except to mirror every NodeMap
var nodeMapMirrors;
var controllers; // track changes in proxyspace
*initClass {
Class.initClassTree(Event);
Class.initClassTree(AbstractPlayControl);
(this.filenameSymbol.asString.dirname +/+ "psSet-event-type.scd").load;
}
*new { |server, name, loading = false|
^super.new.init(server, name, loading: loading)
}
*newFrom { |archive|
^super.new.initFromArchive(archive)
}
init { |argServer, argName, array, loading = false|
name = argName;
server = argServer;
if(server.isNil) { server = Server.default };
// .load boots the server automatically; .new doesn't
NotificationCenter.registerOneShot(this, \ready, \init, {
server.waitForBoot { // just to be sure
proxyspace = StereoProxySpace(server, name);
proxyspace.put(\out, #{ |amp = 0.2| amp * JMInput.ar });
proxyspace.at(\out).play;
buffers = JMBufferSet(this);
this.initDoc;
this.initController;
JITModPatchGui(this); // uses dependencies
this.dirty = false;
};
});
server.waitForBoot {
if(loading.not) {
NotificationCenter.notify(this, \ready);
};
};
}
initFromArchive { |archive|
name = archive[\name];
proxyspace = archive[\proxyspace];
buffers = archive[\buffers] ?? { JMBufferSet(this) };
midi = archive[\midi];
customInit = archive[\customInit];
cleanup = archive[\cleanup];
this.initDoc(archive[\string]);
this.initController;
if(midi.notNil) { this.initMidiCtl };
proxyspace.use { customInit.value(this) };
JITModPatchGui(this); // uses dependencies
this.dirty = false; // loader will override this
}
initDoc { |string("~out = #{ |amp = 0.2| amp * JMInput.ar }; ~out.play;\n\n")|
doc = Document.new(this.docTitle, string, envir: proxyspace)
.toFrontAction_({ current = this })
// .endFrontAction_({
// // NOTE: This doesn't really work for pattern NodeProxies yet
// if(this.class.loadingPatch !== this) {
// current = nil
// };
// })
;
// seems we need a little time for string/envir to sync up
AppClock.sched(0.5, { doc.front });
}
initController {
var makeCtl = { |proxy|
// we might not be in the environment at this point
var key = proxyspace.use { proxy.key },
setFunc = { |obj, what, args|
// NEW: respond to fixed values too
// to update same-name parameters in other proxies
this.proxyDidSet(obj, args);
};
controllers[key].remove; // if anything was there before, drop it now
controllers[key] = SimpleController(proxy)
.put(\source, { this.dirty = true })
.put(\set, setFunc)
.put(\map, setFunc)
// workaround for a bug in Halo:
// Halo clobbers my SimpleController upon .clear
// so I have to put it back
.put(\clear, {
// actually this is probably wrong:
// NodeProxy:clear doesn't wipe out the NodeMap
// nodeMapMirrors[key].clear; // maybe?
{
if(proxy.dependants.includes(controllers[key]).not) {
proxy.addDependant(controllers[key]);
}
}.defer(0.1);
});
// per NodeProxy:xfadePerform, it appears that the \map or \set notification
// may come from either the nodeproxy or the nodemap...???
controllers[(key ++ "_nodeMap").asSymbol].remove;
controllers[(key ++ "_nodeMap").asSymbol] = SimpleController(proxy.nodeMap)
.put(\set, setFunc)
.put(\map, setFunc);
};
nodeMapMirrors = IdentityDictionary.new;
// when init-ing from archive, the 'set' statements
// have already run and nodeMaps are already populated,
// so, copy them
proxyspace.keysValuesDo { |key, proxy|
nodeMapMirrors[key] = IdentityDictionary.new
.putAll(proxy.nodeMap);
};
if(controllers.isNil) {
controllers = IdentityDictionary.new
} {
controllers.do(_.remove);
};
controllers[\proxyspace] = SimpleController(proxyspace)
.put(\newProxy, { |obj, what, proxy, loading|
var key = proxyspace.findKeyForValue(proxy);
if(nodeMapMirrors[key].isNil) { // shouldn't that always be true?
nodeMapMirrors[key] = IdentityDictionary.new;
};
makeCtl.(proxy);
// if we are in the process of loading a patch, don't set 'dirty'
if(loading.isNil) {
this.dirty = true;
};
});
proxyspace.keysValuesDo { |key, proxy|
makeCtl.(proxy);
};
controllers[\buffers] = SimpleController(buffers)
.put(\addBuffer, { |obj, what, name|
// these should automatically 'dirty' the patch
proxyspace.put(name, buffers.asRef(name));
})
.put(\removeBuffer, { |obj, what, name|
proxyspace.at(name).clear;
})
// .put(\didFree, {})
;
}
clear {
// if(dirty) {}; // ???
{
try { cleanup.value(this) } { |error|
if(error.notNil) { error.reportError; "^^^ error thrown during custom cleanup".warn };
};
controllers.do { |ctl| ctl.remove };
controllers.clear;
proxyspace.do { |proxy| proxy.stop }; // disconnect from speakers before clearing
0.1.wait;
proxyspace.clear;
proxyspace.remove; // take it out of the global collection, for 'load'
buffers.clear;
midi.free;
doc.tryPerform(\close); // may not have been initialized, if loading
if(current === this) { current = nil };
// gui.close; gui = nil;
this.changed(\didFree);
}.fork(AppClock);
}
*loadingPatch { ^Library.at(\JITModPatch, \nowLoading) }
*loadingPatch_ { |patch|
if(patch.notNil) {
Library.put(\JITModPatch, \nowLoading, patch)
} {
Library.global.removeEmptyAt(\JITModPatch, \nowLoading);
};
}
*load { |path|
var new = this.new(loading: true);
if(path.notNil) {
^new.load(path)
};
// else (btw, later implement default path)
FileDialog(
{ |path| new.load(path) },
{ NotificationCenter.notify(new, \ready) }, // finish initing empty patch
fileMode: 1, acceptMode: 0, stripResult: true,
path: Archive.at(\JITModPatch, \lastPath).tryPerform(\dirname));
^new // you can have it now but it will be ready later
}
load { |p|
var file = File(p, "r"), code, archive, saveExecutingPath;
if(file.isOpen) {
server.waitForBoot {
var cond = Condition.new,
// 'clear' is asynchronous now
ctl = SimpleController(this).put(\didFree, {
ctl.remove;
cond.unhang;
});
this.class.loadingPatch = this;
protect {
this.clear;
cond.hang;
code = file.readAllString;
saveExecutingPath = thisProcess.nowExecutingPath;
current = this;
thisProcess.nowExecutingPath = p;
archive = code.interpret;
this.initFromArchive(archive);
} { |error|
this.class.loadingPatch = nil;
thisProcess.nowExecutingPath = saveExecutingPath;
file.close;
defer { // defer to allow error to clear before handling
if(error.notNil) {
this.changed(\load, \error, error);
} {
this.path = p;
this.changed(\load, \success);
}
};
}
};
} {
"JITModPatch:% could not open '%' for loading".format(name, path).warn;
this.changed(\load, \openFailed);
}
}
save { |path|
if(path.notNil) {
this.prSave(path)
} {
FileDialog({ |path| this.prSave(path) }, fileMode: 0, acceptMode: 1, stripResult: true,
path: Archive.at(\JITModPatch, \lastPath).tryPerform(\dirname));
};
}
prSave { |p|
var file = File(p, "w");
var text,
getDoc = { |cond|
// hacking into Document internals a bit
// the backend still exists for this, just "hidden"
// in the official Document interface
// Windows sometimes loses Document text mirroring
// so this is the only safe way to be sure we get *all* the contents
var funcID = ScIDE.getQUuid;
Document.asyncActions[funcID] = { |str|
text = str;
cond.unhang;
};
ScIDE.getTextByQUuid(doc.quuid, funcID, 0, -1);
};
if(file.isOpen) {
this.path = p;
{
var cond = Condition.new;
protect {
// file's end result should be the patch
file << "var proxyspace = %.new(name: %), buffers, midi;\n\n"
.format(proxyspace.class.name, name.asCompileString);
getDoc.value(cond);
cond.hang;
text = text.clump(8000);
file << "var doc = [";
text.do { |str, i|
if(i > 0) { file << "," };
file << "\n\t" <<< str;
};
file << "\n].join;\n\n";
file << "var customInit = " <<< customInit << ";\n";
file << "var cleanup = " <<< cleanup << ";\n";
if(buffers.notEmpty) {
buffers.save(path);
buffers.storeOn(file);
};
if(midi.notNil) {
file << "midi = ";
midi.storeOn(file);
file << "(proxyspace);\n";
};
file << "\nproxyspace.use {\n\n";
// guarantee that buffer proxies get populated first
// otherwise patterns may look for ~xyz.source and find nothing
buffers.buffers.keysValuesDo { |name, buf|
file << "~" << name << " = buffers.asRef(" <<< name << ");\n";
};
file << "\n";
proxyspace.use { proxyspace.storeOn2(file) };
file << "\};\n";
// result for loading, should embed real objects
file << "(name: " <<< name << ", proxyspace: proxyspace, string: doc, midi: midi, buffers: buffers, customInit: customInit, cleanup: cleanup)\n";
} { |error|
file.close;
defer { // defer to allow error to clear before handling
if(error.notNil) {
this.changed(\save, \error, error);
} {
this.dirty = false;
this.changed(\save, \success);
}
};
};
}.fork(AppClock);
} {
"JITModPatch:% could not open '%' for saving".format(name, path).warn;
this.changed(\save, \openFailed);
}
}
docTitle { ^"JITModPatch: " ++ (name ?? "Untitled") }
name_ { |n|
name = n;
doc.title = this.docTitle;
this.changed(\name, name);
}
path_ { |p|
path = p;
if(path.notNil) {
Archive.put(\JITModPatch, \lastPath, path);
if(name.isNil) { this.name = path.basename.splitext[0] };
};
}
customInit_ { |func|
// proper usage: cleanup removes whatever you created
if(func.notNil) {
cleanup.value(this);
};
customInit = func;
customInit.value(this);
}
cleanup_ { |func|
cleanup = func;
}
dirty_ { |bool|
dirty = bool;
this.changed(\dirty, bool);
}
// updates
proxyDidSet { |obj, args|
var mapChanged = false, src;
var event = this.setEvent
.put(\gt, nil).put(\t_trig, nil)
.put(\sustain, inf); // otherwise, set/reset/set/reset gate
var setKeys = IdentitySet.new;
var proxyKey = proxyspace.findKeyForValue(obj);
var oldNodeMap = nodeMapMirrors[proxyKey];
if(proxyKey.notNil) {
args.pairsDo { |key, value|
// if we're 'set'ting to a BusPlug,
// then the connections have changed
if(value.isKindOf(BusPlug)) {
mapChanged = true;
} {
// if we're 'set'ting to a non-busplug,
// but it was previously mapped to a busplug,
// then the connections have changed
src = oldNodeMap[key];
if(src.isKindOf(BusPlug)) {
mapChanged = true;
// also make sure to remove *all* channels
if(src.numChannels > 1) {
value = value.asArray.wrapExtend(src.numChannels);
};
};
setKeys.add(key);
event.put(key, value);
};
oldNodeMap.put(key, value);
};
if(setKeys.notEmpty) { event.put(\setArgs, setKeys).play };
};
if(mapChanged or: { proxyKey.isNil }) { this.changed(\setMapping, args) };
if(dirty.not) {
this.dirty = true; // but changing anything dirties the state
};
}
// proxyspace access
at { |key| ^proxyspace.at(key) }
put { |key, obj| proxyspace.put(key, obj) }
// midi
initMidi { |device, name, channel|
if(device.notNil) {
midi = JMMIDI.newByName(proxyspace, device, name, channel);
} {
midi = JMMIDI(proxyspace, channel);
};
this.changed(\initedMidi, midi);
this.dirty = true;
}
initMidiCtl {
if(midi.isNil) { this.initMidi };
controllers[\midi] = SimpleController(midi)
.put(\didFree, { controllers[\midi].remove; midi = nil; });
#[channel, addCtl, removeCtl].do { |key|
controllers[\midi].put(key, { this.dirty = true });
};
}
clearMidi {
midi.free;
midi = nil;
}
learnCtl { |name, spec|
if(midi.isNil) { this.initMidi };
midi.learnCtl(name, spec);
}
addCtl { |num, name, spec|
if(midi.isNil) { this.initMidi };
midi.addCtl(num, name, spec);
}
removeCtl { |num, name|
if(midi.isNil) { this.initMidi };
midi.removeCtl(num, name);
}
// OSC-MIDI bridge
midiOSCBridge { |profile = \openstage|
^JMMIDI_OSCBridge(this, profile)
}
// buffers
readBuf { |name, path, startFrame = 0, numFrames = -1, action|
var buf = JMBuf(server),
finish = this.prFinishBufAction(name, buf);
buf.doOnInfo = {
finish.value(true);
try { action.value } { |err|
err.reportError;
"^^^ Error during readBuf action".warn;
};
};
buf.allocRead(path, startFrame, numFrames, { |buf| ["/b_query", buf.bufnum] });
^buf
}
readBufChannel { |name, path, startFrame = 0, numFrames = -1, channels, action|
var buf, finish;
if(channels.isNil) {
Error("JITModPatch:readBufChannel: Please supply a 'channels' array").throw;
};
buf = JMBuf(server);
finish = this.prFinishBufAction(name, buf);
buf.doOnInfo = {
finish.value(true);
try { action.value } { |err|
err.reportError;
"^^^ Error during readBuf action".warn;
};
};
buf.allocReadChannel(path, startFrame, numFrames, channels, { |buf| ["/b_query", buf.bufnum] });
^buf
}
prFinishBufAction { |name, buf|
var status,
failResp = OSCFunc({ |msg|
if(msg[3] == buf.bufnum) {
finish.(false);
};
}, '/fail', buf.server.addr),
finish = { |success|
failResp.free;
if(success) {
buffers.put(name, buf); // 'buffers' sends \addBuffer
} {
buf.free; // reuse bufnum
buffers.changed(\bufReadFailed, name, buf);
};
status = success;
};
// schedule timeout
AppClock.sched(3, {
if(status.isNil) { finish.(false) };
// if status is notNil, then we already did finish (true or false)
});
^finish
}
addBuf { |name, buffer, replace = true|
buffers.put(name, buffer, replace);
}
freeBuf { |name|
buffers.removeAt(name);
}
// event support
setEvent { |event| ^proxyspace.setEvent(event) }
getConnections {
// This is not modularized at all because I'm lazy
var chains = Array.new,
findChain = { |conn|
chains.detect { |chain|
conn.canConnect(chain.first)
or: {
chain.last.canConnect(conn)
}
};
},
// problem: cleaning 'c' array (we are iterating over it)
scanLinks = {
(1 .. chains.size - 1).do { |i| // 1, 2, 3...
if(chains[i].notNil) {
block { |break|
i.do { |j| // 0, 1 .. i-1
if(chains[j].notNil) {
if(chains[j].last.canConnect(chains[i].first)) {
// c[i] goes to end of c[j]
chains[i].do { |conn| chains[j].add(conn) };
chains[i] = nil;
break.();
} {
if(chains[i].last.canConnect(chains[j].first)) {
// c[i] goes to head of c[j]
chains[i].reverseDo { |conn| chains[j].addFirst(conn) };
chains[i] = nil;
break.();
}
};
};
};
};
};
};
chains = chains.reject(_.isNil);
};
proxyspace.keysValuesDo { |key, proxy|
var conn, chain;
proxy.nodeMap.keysValuesDo { |key, src|
if(src.isKindOf(BusPlug)) {
conn = JITModConnection(src, proxy, key);
chain = findChain.(conn);
if(chain.notNil) {
if(chain.last.canConnect(conn)) {
chain.add(conn);
} {
chain.addFirst(conn);
};
scanLinks.();
} {
chains = chains.add(LinkedList.new.addFirst(conn));
};
};
};
};
^chains
}
}
JITModPatchGui {
var <model,
<view, window,
psGuiView, psGui,
saveButton, saveAsButton, loadButton, synthdefButton, clearButton,
midiButton, bufButton,
stack,
bufferView, // not yet
midiView,
connView,
controllers;
*new { |model, parent, bounds|
var view, iMadeWindow = false;
if(parent.isNil) {
// ProxyMixer may be up to 1086 wide
parent = Window(model.docTitle, Rect(100, 200, 1120, 600))
.userCanClose_(false)
.front;
iMadeWindow = true;
if(bounds.isNil) { bounds = parent.view.bounds.insetBy(5, 5) };
};
view = View(parent, bounds);
^super.newCopyArgs(model).init(view, if(iMadeWindow) { parent } { nil })
}
*newForLayout { |model|
var view = View();
^super.newCopyArgs(model).init(view)
}
init { |argView, argWindow|
var saveWin;
view = argView;
window = argWindow;
view.layout = VLayout(
HLayout(
[VLayout(
HLayout(
nil,
bufButton = Button().fixedWidth_(120)
.states_([["Buffers 缓冲区"]])
.action_({ stack.index = 0 }),
midiButton = Button().fixedWidth_(150)
.states_([["MIDI controllers 控制"]])
.action_({ stack.index = 1 }),
nil
),
stack = StackLayout(
bufferView = JMBufferView(model),
midiView = JMMidiView(model),
).mode_(\stackOne),
), stretch: 1],
[VLayout(
HLayout(
nil,
saveButton = Button().fixedWidth_(90),
saveAsButton = Button().fixedWidth_(105),
loadButton = Button().fixedWidth_(90),
synthdefButton = Button().fixedWidth_(90),
clearButton = Button().fixedWidth_(90),
nil,
),
connView = TextView().editable_(false)
), stretch: 1]
),
psGuiView = View().fixedHeight_(295)
);
model.proxyspace.use {
// must be in the right environment
psGui = ProxyMixer(model.proxyspace, 12, psGuiView, Rect(0, 0, 1090, 275));
};
saveButton.states_([["save 保存"]])
.action_({ { model.save(model.path) }.defer(0.1) }); // model.path may be nil; gives file dialog
saveAsButton.states_([["save as 另存为"]])
.action_({ { model.save(nil) }.defer(0.1) });
loadButton.states_([["load 打开"]])
.action_({
{
FileDialog({ |path| model.load(path) }, fileMode: 1, acceptMode: 0, stripResult: true,
path: Archive.at(\JITModPatch, \lastPath).tryPerform(\dirname));
}.defer(0.1)
});
synthdefButton.states_([["SynthDef"]])
.action_({
var str = CollStream.new;
var doc, name;
JMDecompiler(model).streamCode(str);
// either success, or threw an error, so we press forward
{
doc = Document.new;
0.5.wait;
name = model.name ?? { "JITModPatch as synthdef" };
str = "(\nSynthDef('" ++ name.escapeChar($') ++ "', { |out|\n"
++ str.collection // has trailing \n
++ "\tOut.ar(out, env[\\outOut]);\n}).add;\n)\n";
doc.title_(name).string_(str);
}.fork(AppClock);
});
clearButton.states_([["quit 关闭"]])
.action_({
if(model.dirty) {
saveWin = Window("save?", Rect.aboutPoint(Window.screenBounds.center, 100, 60));
saveWin.layout = VLayout(
StaticText().align_(\center).string_("You have unsaved changes."),
HLayout(
nil,
Button().states_([["save 保存"]])
.action_({
saveWin.close;
{ this.prSave(model.path, { model.clear }); }.defer(0.1)
}),
Button().states_([["save as 另存为"]])
.action_({
saveWin.close;
{ this.prSave(nil, { model.clear }); }.defer(0.1)
}),
Button().states_([["discard 抛弃"]])
.action_({ saveWin.close; model.clear }),
Button().states_([["cancel 取消"]])
.action_({ saveWin.close })
)
);
saveWin.front;
} {
model.clear;
}
});
controllers = IdentityDictionary.new;
controllers[\patch] = SimpleController(model)
.put(\dirty, { |obj, what, bool|
defer { saveButton.enabled = bool };
})
.put(\setMapping, { |obj, what, args| this.updateConn })
.put(\name, { |obj, what, name|
if(window.notNil) {
defer {
window.name = model.docTitle;
};
};
})
.put(\didFree, {
this.close;
controllers.do(_.remove);
});
this.updateConn;
}
// calls up to the model to save, and finishes with an action at the end
prSave { |path, action|
controllers[\patch].put(\save, { |obj, what, code, error|
controllers[\patch].removeAt(\save);
switch(code)
{ \success } {
action.value;
}
{ \openFailed } {
this.errorWindow("File open failed", "Could not open the file");
}
{ \error } {
this.errorWindow("Error during save", error.errorString)
}
{ this.errorWindow("Oops", "Unexpected save status") }
});
model.save(path);
}
errorWindow { |title, msg|
var errWin;
errWin = Window(title, Rect.aboutPoint(Window.screenBounds.center, 100, 60));
errWin.layout = VLayout(
StaticText().align_(\center).string_(msg),
HLayout(
nil,
Button().states_([["OK"]]).action_({ errWin.close })
)
);
errWin.front;
}
close {
if(window.notNil) { window.close };
}
// updateParams { |args|
// }
updateConn {
var chains = model.getConnections;
var out = CollStream.new;
// 'use' is required for asCompileString
model.proxyspace.use {
chains.do { |chain|
out << chain.first.src.asCompileString;
chain.do { |conn, i|
out << " <>>";
if(conn.name != \in) {
out << "." << conn.name;
};
out << " " << conn.target.asCompileString;
};
out << "\n";
};
};
defer { connView.string = out.collection };
}
}
JITModConnection {
// (src: src, target: target, name: name, srcRate: src.rate)
var <>src, <>target, <>name, <>srcRate;
*new { |src, target, name|
^super.newCopyArgs(src, target, name, src.rate)
}
canConnect { |that|
^(srcRate == that.srcRate and: { target === that.src })
}
}
JMBufferSet {
var <>model, <server, <buffers, <path, controllers;
// path should be the full path of the .jitmod file -- set in 'save'
// for loading, we won't have the JITModPatch right now
// so, hack: 'model' may be a server. You fill in the 'model' later
*new { |model|
^super.newCopyArgs(model).init;
}
init {
if(model.isKindOf(Server)) {
server = model;
model = nil;
} {
server = model.server;
};
buffers = IdentityDictionary.new;
controllers = IdentityDictionary.new;
}
clear {
buffers.do(_.free);
buffers.clear;
this.changed(\didFree);
}
isEmpty { ^buffers.isEmpty }
notEmpty { ^buffers.notEmpty }
at { |name| ^buffers[name.asSymbol] }
put { |name, buffer, replace(true)|
var old, arrayID;
// array of buffers? allocConsecutive
if(buffer.size > 0) {
name = name.asString;
arrayID = UniqueID.next;
buffer.do { |buf, i|
buf.arrayID = arrayID;
this.put((name ++ i.asString.padLeft(3, "0")).asSymbol, buf);
};
^this
};
if(buffer.isMemberOf(Buffer)) {
"Buffers may display incorrectly; use JMBuf instead (name = %)"
.format(name.asCompileString).warn;
};
name = name.asSymbol;
if(buffer.isNil) { ^this.removeAt(name) };
old = buffers[name];
if(replace.not and: { old.notNil }) {
"Buffer '%' already exists; use a different name".format(name).warn;
} {
// wait a bit, to allow new bufnum to propagate out to synths
{ old.free }.defer(1);
buffers[name] = buffer;
this.changed(\addBuffer, name, buffer);
};
controllers[buffer.bufnum] = SimpleController(buffer)
.put(\done, { |obj, what, cmd, reallyDone|
if(reallyDone == true) {
this.changed(\bufferContentsChanged, obj, cmd, reallyDone);
};
});
}
removeAt { |name|
name = name.asSymbol;
if(buffers[name].notNil) {
controllers[buffers[name].bufnum].remove;
controllers[buffers[name].bufnum] = nil;
buffers[name].free;
buffers[name] = nil;
this.changed(\removeBuffer, name);
}
}
dir { |p|
^(p.dirname +/+ p.basename.splitext[0] ++ "_buffers")
}
save { |p| // p = path to .jitmod file, not directory!
var dir = this.dir(p);
if(File.exists(dir) and: { File.type(dir) != \directory }) {
"% already exists and is not a directory; can't save here".format(dir).warn;
^false
};
if(File.exists(dir)) {
(dir +/+ "*").pathMatch.do { |path| File.delete(path) };
} {
File.mkdir(dir);
};
buffers.keysValuesDo { |name, buffer|
var format, match;
if(buffer.tryPerform(\isWavetable) == true) {
name = name ++ "_wt";
format = "float";
} {
name = name.asString;
format = "int16";
};
if(buffer.tryPerform(\arrayID).notNil) {
// mark buffer arrays with filenames like "a[000]_wt.wav"
match = name.findRegexp("[0-9][0-9][0-9]");
if(match.size > 0) {
name = name.replace(match[0][1], "[" ++ match[0][1] ++ "]");
};
};
buffer.write(dir +/+ name ++ ".wav", "wav", format);
};
path = p;
}
load { |path|
var dir = this.dir(path), paths, arrayPaths, name, key, wt,
loadOne = { |path, buf|
var match;
name = path.basename.splitext[0];
match = name.findRegexp("\\[([0-9][0-9][0-9])\\]");
if(match.size > 0) {
name = name.replace(match[0][1], match[1][1]); // strip brackets from name, for key
};
wt = name.endsWith("_wt");
if(wt) {
key = name.drop(-3).asSymbol;
} {
key = name.asSymbol;
};
if(buf.isNil) {
buf = JMBuf(server);
};
buffers[key] = buf.allocRead(path, completionMessage: { |buf| ["/b_query", buf.bufnum] });
if(wt) {
buffers[key].isWavetable = true;
};
};
if(File.exists(dir) and: { File.type(dir) == \directory }) {
this.clear;
paths = (dir +/+ "*.wav").pathMatch;
// need to search for indices; keep arrays together (consecutive bufnums)
arrayPaths = paths.collect { |path| [path, path.findRegexp("\\[[0-9][0-9][0-9]\\]")] }
.select { |pair| pair[1].size > 0 }
.separate { |a, b|
a[0][ .. a[1][0][0]] != b[0][ .. b[1][0][0]]
}
.do { |pathArray|
var bufBase = server.bufferAllocator.alloc(pathArray.size),
arrayID = UniqueID.next; // arrayed buffers must be tagged, for saving later
pathArray.do { |pair, i|
var new = JMBuf(server, bufnum: bufBase + i).arrayID_(arrayID);
loadOne.(pair[0], new)
};
};
arrayPaths = arrayPaths.collect { |array| array.collect(_[0]) }.flatten(1);
paths.do { |path|
if(arrayPaths.every { |a| a != path }) {
loadOne.(path)
}
};
^true
} {
"'%' directory doesn't exist; can't load buffers".format(dir).warn;
^false
}
}
storeOn { |stream|
// user should have called 'save' already
// we'll check
var dir;
if(path.notNil) { dir = this.dir(path) };
if(dir.notNil and: { File.exists(dir) and: { File.type(dir) == \directory } }) {
// for loading, always relative path
stream << "\nbuffers = JMBufferSet(Server.default);\n";
stream << "if(buffers.load(thisProcess.nowExecutingPath).not) { Error(\"Buffer loading failed\").throw };\n";
stream << "Server.default.sync;\n\n";
} {
Error("JMBufferSet directory doesn't exist; storeOn can't proceed").throw;
};
}
asKeyValuePairs {
var pairs = Array(buffers.size * 2);
buffers.keysDo { |name|
pairs.add(name).add(this.asRef(name));
};
^pairs
}
asRef { |name|
^JMBufferRef(name, buffers[name])
}
}
JMBufferRef {
var <name, <buffer;
*new { |name, buffer|
^super.newCopyArgs(name, buffer)
}
asControlInput { ^buffer.bufnum }
storeOn { |stream|
stream << "buffers.asRef(" <<< name << ")"
}
printOn { |stream|
stream << "JMBufferRef(" <<< name << ", " << buffer << ")"