-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathui.html
More file actions
970 lines (834 loc) · 30.6 KB
/
ui.html
File metadata and controls
970 lines (834 loc) · 30.6 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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>NF VisSynth MCP</title>
<script src="./ui/jquery-2.1.4.js"></script>
<script src="./ui/jquery-ui.js"></script>
<script src="./ui/jquery.ui.touch-punch.js"></script>
<link rel="stylesheet" type="text/css" href="./ui/ui.css">
</head>
<body>
<div class="header container">
<h1>VIS SYNTH MCP</h1>
<button id=restart onclick="restart()">RESTART</button>
<button id=screenshot onclick="screenshot()">SCREENSHOT</button>
<button id=recorder_button onclick="toggle_recorder()">START RECORDING</button>
<button id=stream_button onclick="toggle_stream()">START STREAM</button>
<button id=undo onclick="undo()">UNDO</button>
<span id=stats>offline</span>
</div>
<div class="effects container">
<h2>Effects</h2>
<button id=show_files onclick="show_panel('files')">FILES</button>
<button id=show_devices onclick="show_panel('devices')">DEVICES</button>
<button id=show_effects onclick="show_panel('effects')">EFFECTS</button>
<div id=effects>
</div>
<div id=files>
</div>
<div id=devices>
</div>
</div>
<div class="chains container">
<h2>Chains</h2> <button id=new_chain onclick="new_chain()">ADD EMPTY</button><button id=clone_chain onclick="clone_chain()">CLONE</button>
<div id="chains">
<div class="chain_token">
<input placeholder="enter name" value="">
</div>
</div>
</div>
<div class="chain container">
<h2></h2>
<div id="chain"></div>
<button id=chain_code_button onclick="toggle_code()">CODE</button>
</div>
<div class="pre_chain container">
<h2>Setup Before</h2>
<div id="pre_chain"></div>
</div>
<div class="post_chain container">
<h2>Setup After</h2>
<div id="post_chain"></div>
</div>
<div class="preview container" onclick="toggle_preview()">
<button id=preview_button>PREVIEW</button>
<video id=preview></video>
</div>
<div id=help></div>
<script type="module">
import {WebRTC} from './vissynth/webrtc.js';
// get session url, if any
var session_url='/';
if(document.location.hash)
session_url+=document.location.hash.substring(1)+'_';
// establish WebSocket connection
var websocket;
var put=function(url,data)
{
websocket.send(JSON.stringify({'method':'put','path':url,'data':data}));
}
var get=function(url,callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.responseType='text';
xmlHttp.open('GET',url.replace(/^\//,''),true);
if(callback) xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState!=4) return;
callback(xmlHttp.responseText);
}
xmlHttp.send(null);
}
// send command to remote server
function send(command)
{
put('/feeds'+session_url+'command',command+';\n');
}
window.restart=function()
{
send('document.location.reload()');
setTimeout(updateChain,500); // TODO get rid of wait (race condition prone)
}
window.screenshot=function()
{
send('canvas.screenshot()');
}
var recording=false;
window.toggle_recorder=function()
{
recording=!recording;
send('canvas.recording('+(recording ? 'true' : 'false')+')');
// put(recording ? '/recorder/start' : '/recorder/stop' , '');
$('#recorder_button').html(recording ? 'STOP RECORDING' : 'START RECORDING');
if(recording) $('#recorder_button').addClass ('active');
else $('#recorder_button').removeClass('active');
}
var streaming=false;
window.toggle_stream=function()
{
streaming=!streaming;
send('canvas.webrtc('+(streaming ? 'true' : 'false')+')');
$('#stream_button').html(streaming ? 'STOP STREAMING' : 'START STREAMING');
if(recording) $('#stream_button').addClass ('active');
else $('#stream_button').removeClass('active');
}
/* the undo history. updated by frequent save() calls */
var undo_history=[];
/* save all chains to server and undo_history */
var save=function()
{
var chains=[];
chains.push($('#pre_chain').data('chain'));
chains.push($('#post_chain').data('chain'));
$('#chains .chain_token').each(function(){
chains.push($(this).data('chain'));
});
var json=JSON.stringify(chains,null,' ');
put('/saves'+session_url+'chains.json',json);
// notify other UI clients
put('/feeds'+session_url+'update',json);
undo_history.push(json);
console.log('Saved.');
savetimeout=false;
}
/* recursively create UI for an effect, callback provides the UI for a signle value */
var get_ui=function(key,node,callback)
{
var ui=$('<div>');
var key_element=$('<span class=key>');
key_element.html(key);
ui.append(key_element);
var type=typeof(node);
ui.addClass('ui_'+type);
var value_element=$('<span class=value>');
ui.append(value_element);
if(type=='object')
{
if(node.type) ui.attr("ui_type",node.type);
for(var key2 in node)
{
value_element.append(get_ui(key2,node[key2],callback));
}
}
else
{
callback(value_element,node);
}
return ui;
}
/* create JS object from UI DOM */
var get_data=function(ui)
{
var divs=ui.find('>div');
var data={};
divs.each(function(){
var key=$(this).find('>.key').text();
var value_element=$(this).find('>.value');
var value;
if(value_element.children().length)
value=get_data(value_element);
else
{
value=value_element.text();
if($.isNumeric(value)) value=parseFloat(value);
}
data[key]=value;
});
return data;
}
/* create an effect DOM, value_renderer provides the UI for a single value */
var create_effect_element=function(effect,value_renderer)
{
var li=get_ui('',effect,value_renderer).find('>span.value');
li.addClass('effect');
var effect_template=effects[effect.effect];
li.attr('ui_effect',effect.effect);
for(let key in effect_template)
if(key!='args')
li.attr('ui_'+key, effect_template[key]);
return li;
}
/* create UI DOM for an array of effects into container */
var listEffects=function(effects,container,mode)
{
$(container).empty();
effects.forEach(function(effect){
if(typeof effect == "string") // display name
{
$(container).parent().find('h2').text(effect);
return;
}
var li=create_effect_element(effect,function(element,value){
element.html(document.createTextNode(''+value));
});
$(container).append(li);
});
// the effects may be dragged to the chain list
if(mode=='draggable')
$(container+'>*').draggable({
connectToSortable: "#chain,#pre_chain,#post_chain",
appendTo:'body',
helper: "clone",
revert: "invalid",
scroll: false,
distance: 10,
delay: 300,
stop: function(){
updateChain();
}
});
}
// callback for creating a slider manipulating a single value
var add_slider=function(container,value_element)
{
var slider=$('<input class=value_ui type=range min="-0.999" max="0.999" step="0.0002">');
var slider_value_element=$('<input type=number class=slider_value>');
// initalize slider knob with current value
var value=value_element.text();
// also initalize numerical display element
slider_value_element.val(value);
value=logify(value);
slider.attr('value',value);
// adjust the value_element if slider is moved
var handler=function(){
var value=expify(parseFloat(this.value));
console.log(this.value+" "+value);
value_element.text(value);
slider_value_element.val(value);
updateChain();
};
slider.on('input',handler);
// adjust the slider if value_element is changed
slider_value_element.on('input',function(){
var value=parseFloat(this.value);
value_element.text(value);
slider.val(logify(value));
updateChain();
});
slider_value_element.on('click',function(){$(this).select()});
// reset to 0 on double click
slider.on('dblclick',function(){
slider[0].value="0";
handler.call(slider[0]);
});
$(container).append(slider_value_element);
$(container).append(slider);
}
var add_input=function(container,value_element)
{
var input=$('<input class=value_ui type=text>');
// initalize input with current value
input.attr('value',value_element.text());
// adjust the value_element if text is changed
input.on('change',function(){
value_element.text(this.value);
updateChain();
});
$(container).append(input);
}
// create value adjust UI for a single effect
var get_adjust_ui=function(effect_element){
// visibly mark effect as the currently adjusted
effect_element.addClass('ui_target');
// link value elements to theirself to know the original one to adjust after cloning
effect_element.find('.value').each(function(){
// store this element to itself
$(this).data('original_value_element',this);
});
// copy the UI with data but without event handlers
var slider_ui=effect_element.clone(true).off();
// add slider to each numerical value
slider_ui.find('.ui_number>.value').each(function(){
var element=$(this);
var key=element.parent().find('.key').text();
// get value field of original value_element to manipulate by this UI
var value_element=$(element.data('original_value_element'));
// if we may adjust a number, add a slider
element.empty();
add_slider(element,value_element);
});
// add input to each string value except first (the effect name)
slider_ui.find('.ui_string>.value').slice(1).each(function(){
var element=$(this);
var key=element.parent().find('.key').text();
// get value field of original value_element to manipulate by this UI
var value_element=$(element.data('original_value_element'));
// if we may adjust a number, add a slider
element.empty();
add_input(element,value_element);
});
var popup;
// OSC toggle button handler
var toggle_osc=function(){
var value_element=$($(this).parent().data('original_value_element'));
var key=value_element.parent().find('>.key').text();
var new_value;
if(value_element.parent().attr('ui_type')=='osc')
{
// replace OSC by it's pure offset or amplitude value, whats larger.
var osc=get_data(value_element);
new_value=Math.abs(osc.a)>Math.abs(osc.o) ? osc.a : osc.o;
}
else
{
var offset=parseFloat(value_element.text());
new_value={type:'osc',f:5.0,a:offset/2,p:0.0,o:offset,waveform:'sine',duty:0.5};
}
var new_ui=get_ui(key,new_value,function(element,value){
element.html(document.createTextNode(''+value));
});
value_element.parent().replaceWith(new_ui);
// update and store effect chain
updateChain();
// refresh UI
popup.remove();
effect_element.click();
}
// BEAT toggle button handler
var toggle_beat=function(){
var value_element=$($(this).parent().data('original_value_element'));
var key=value_element.parent().find('>.key').text();
var new_value;
if(value_element.parent().attr('ui_type')=='beat')
{
// replace BEAT by it's pure offset or amplitude value, whats larger.
var beat=get_data(value_element);
new_value=Math.abs(beat.a)>Math.abs(beat.o) ? beat.a : beat.o;
}
else
{
var offset=parseFloat(value_element.text());
new_value={type:'beat',pulse:0.0,f:2.0,a:offset/2,p:0.0,o:offset/2};
}
var new_ui=get_ui(key,new_value,function(element,value){
element.html(document.createTextNode(''+value));
});
value_element.parent().replaceWith(new_ui);
// update and store effect chain
updateChain();
// refresh UI
popup.remove();
effect_element.click();
}
// add OSC and BEAT button to each value
slider_ui.find('>.ui_number>.value').each(function(){
var element=$(this);
// get value field of original value_element to manipulate by this UI
var value_element=$(element.data('original_value_element'));
element.append($('<button>OSC</button>').click(toggle_osc));
element.append($('<button>BEAT</button>').click(toggle_beat));
});
// add REMOVE OSC button to each value OSC UI
slider_ui.find('.ui_object[ui_type="osc"]>.value').each(function(){
var element=$(this);
element.prepend($('<button>REMOVE OSC</button>').click(toggle_osc));
});
// add REMOVE BEAT button to each value BEAT UI
slider_ui.find('.ui_object[ui_type="beat"]>.value').each(function(){
var element=$(this);
element.prepend($('<button>REMOVE BEAT</button>').click(toggle_beat));
});
// the first element in a nested UI block shows it's type, so disable it.
slider_ui.find('.ui_object input').first().attr('disabled',true);
// add popup container to body
popup=create_popup('adjust_ui',effect_element,slider_ui);
};
var create_popup=function(classname,anchor,content_element)
{
var container=$('<div>');
container.addClass(classname);
container.addClass('popup');
container.append(content_element);
$(document.body).append(container);
container.position({my:'top',at:'bottom',of:$(anchor),collision:'fit'});
var close=function(){
if(document.activeElement)
document.activeElement.blur(); // trigger change events if pending
container.remove();
anchor.removeClass('ui_target');
};
container.on('mouseleave',close);
// hide popup on outside click too
$(document).one('mouseclick',function(ev){
if(!$.contains($(classname)[0],ev.target))
$(classname).trigger('mouseleave');
});
container.draggable();
return container;
}
var savetimeout=false;
var updateChain=function(event,ui)
{
if(savetimeout) clearTimeout(savetimeout);
savetimeout=setTimeout(save,1000);
var full_chain=[];
// for all three chains pre, current and post collect the effect data
['#pre_chain','#chain','#post_chain'].forEach(function(selector){
var chain=[];
// add name to pre- or post chain. For other chains, it is done by chain token.
if(selector=='#pre_chain' || selector=='#post_chain')
chain.push($(selector).parent().find('h2').html());
$(selector).find('.effect').each(function(){
var effect=get_data($(this));
chain.push(effect);
full_chain.push(effect);
});
// store data to chain
$(selector).data('chain',chain);
});
// update active token data (will be used on switching and saving)
var chain=$('#chain').data('chain');
chain.unshift($('#chains .active input').val()); // prepend name
$('#chains .active').data('chain',chain);
// send out to control server
send('canvas.setChain('+JSON.stringify(full_chain)+')');
}
$('#chain,#pre_chain,#post_chain').sortable({
distance:10,
delay:300,
tolerance: 'pointer',
stop: updateChain,
receive: function(event,ui){
var new_element=$(this).data()['ui-sortable'].currentItem;
new_element.removeAttr('style'); // remove obsolete jQuery d&d styles
updateChain(event,ui);
},
// allow removal of items by dragging them out
over: function(){this.is_outside=false},
out: function(){this.is_outside=true},
beforeStop: function(ev,ui){
$(this).data('prevent_click',true); // store to prevent mouseup click handlers (FF fix)
if(this.is_outside)
{
$(ui.item).remove();
updateChain();
}
}
});
var token=$('#chains .chain_token').clone();
$('#chains .chain_token').addClass('active');
var load=function(json)
{
if(!json) return;
var chains=JSON.parse(json);
var pre_chain=chains.shift();
var post_chain=chains.shift();
listEffects(pre_chain,'#pre_chain');
listEffects(post_chain,'#post_chain');
// delete old lists before loading new ones
$('#chains').empty();
chains.forEach(function(chain)
{
if(!chain) chain=[""];
var chain_token=token.clone();
$('#chains').append(chain_token);
if(!chain[0] || typeof(chain[0])!='string')
chain.unshift("");
chain_token.find('input').val(chain[0]);
chain_token.data('chain',chain);
});
// TODO refresh active chain view
//$('#chains .chain_token').removeClass('active');
//$(this).addClass('active');
// load chain to editor
var list=$('#chain');
var chain=$('#chains .chain_token').first().addClass('active').data('chain');
listEffects(chain,list);
}
/* pop last undo state */
window.undo=function(){
undo_history.pop(); // pop last "same" state
// pop last state
var last_state=undo_history.pop();
if(last_state)
{
load(last_state);
updateChain();
}
}
/* compress and expand values for sliders to enable large adjustments */
var logify=function(x){
return (-2+Math.sqrt(x*x+4))/x;
}
var expify=function(x){
return Math.round((-2/(x+1)-2/(x-1))*1000)/1000;
}
get('./ui/effects.json',function(data){
effects=JSON.parse(data);
var new_effects=[];
for(let key in effects)
{
// create flat object with the effect name in 'effect'
// like the ones send to the server
var new_effect={effect:key};
if(effects[key].args)
for(let i in effects[key].args)
new_effect[i]=effects[key].args[i];
new_effects.push(new_effect);
}
listEffects(new_effects,'#effects','draggable');
// list the files now, we have to postpone it until now
// otherwise the "image" and "video" effects won't show up properly
// as metadata like the number of inputs is fetched from the effects definition
listFiles();
});
let effects=[];
var listFiles=function()
{
get('/files',function(data){
var files=JSON.parse(data);
var new_effects=[];
for(let key in files)
{
// create flat object with the effect name in 'effect'
// like the ones send to the server
var file=files[key];
var suffix=file.split('.').pop().toLowerCase();
var types={'mov':'video','mp4':'video','webm':'video','jpg':'image','jpeg':'image','png':'image','svg':'image','gif':'image'};
var type=types[suffix];
if(!type) continue;
// create flat object with the effect name in 'effect'
// like the ones send to the server
var new_effect={effect:type};
if(effects[type].args)
for(let i in effects[type].args)
new_effect[i]=effects[type].args[i];
new_effect.url="files/"+file;
new_effects.push(new_effect);
}
listEffects(new_effects,'#files','draggable');
});
}
// provide list of device names for convenient selection
var listDevices=function(device_list){
var new_effects=[];
var add_effect=function(type,device_id,name){
// create flat object with the effect name in 'effect'
// like the ones send to the server
var new_effect={effect:type};
if(effects[type].args)
for(let i in effects[type].args)
new_effect[i]=effects[type].args[i];
new_effect.name =name;
new_effect.device=device_id;
new_effects.push(new_effect);
}
device_list.video.forEach(function(device,index){
add_effect('capture',index,device.label);
});
device_list.audio.forEach(function(device,index){
add_effect('select_audio',index,device.label);
});
listEffects(new_effects,'#devices','draggable');
}
// tell server to rescan devices and report to us
var fetchDevices=function(){
send('devices.update()');
}
window.show_panel=function(panel)
{
if(panel=='files') listFiles();
if(panel=='devices') fetchDevices();
$('.effects>div').hide();
$('.effects>div#'+panel).show();
$('.effects>h2').html(panel);
};
show_panel('effects');
// the effects in the current chain may be clicked to display adjust UI
$('#chain,#pre_chain,#post_chain').on('click','.effect',function(){
if($(this).parent().data('prevent_click'))
{
$(this).parent().data('prevent_click',false);
return;
}
get_adjust_ui($(this));
});
// the chains are sortable...
$("#chains").sortable({
distance:10,
delay: 300,
appendTo: 'body',
// allow removal of items by dragging them out
over: function(){this.is_outside=false},
out: function(){this.is_outside=true},
beforeStop: function(ev,ui){
if(this.is_outside)
{
$(ui.item).remove();
updateChain();
}
},
remove: function(e,ui) {
ui.item.clone('true').insertAfter(ui.item);
$(this).sortable('cancel');
updateTimeline();
return ui;
},
connectWith:'#timeline'
});
// a chain is displayed and activated on click on its token
$('#chains').on('click','.chain_token',function()
{
// mark only current token active
$('#chains .chain_token').removeClass('active');
$(this).addClass('active');
// load chain to editor
var list=$('#chain');
var chain=$(this).data('chain');
listEffects(chain,list);
// send chain to output
updateChain();
});
// pressing a number key is like clicking the 0-9 th chain
$(document).keypress(function(e){
if ($(e.target).closest("input")[0]) return; // ignore keys if in input field
if ($(e.target).closest("textarea")[0]) return; // ignore keys if in textarea field
var number=parseInt(String.fromCharCode(e.which));
if(number)
$('#chains .chain_token:nth-child('+number+')').click();
});
// chains can be renamed
$('#chains').on('change','.chain_token>input',updateChain);
// clone current chain
window.clone_chain=function()
{
var chain=$('#chains .active');
var new_chain=chain.clone(true); // clone with data appended
chain.siblings().first().after(new_chain); // insert new chain after the empty list following the current chain position
new_chain.click(); // mark new chain active
}
// create new chain buttom
window.new_chain=function(){
var chain_token=token.clone();
$('#chains').prepend(chain_token);
chain_token.data('chain',[""]);
chain_token.click();
}
var code_to_chain=function(code){
var chain_token=$('#chains .active');
var data=JSON.parse(code);
chain_token.data('chain',data);
chain_token.find('input').val(data[0]); // set name input
chain_token.click(); // trigger UI refresh
}
window.toggle_code=function (e){
var textarea=$('<textarea class="chain_code container" spellcheck=false></textarea>');
var data=$('#chain').data('chain');
var json=JSON.stringify(data,' ',2);
textarea.val(json);
textarea.on('change',function(){
code_to_chain(this.value);
});
var anchor=$('#chain_code_button');
create_popup('.code_ui',anchor,textarea);
textarea.focus();
textarea.select();
}
// load chains
get('/saves'+session_url+'chains.json',function(data){
if(!data) // no saved chains in this session
get('/saves/chains.json',load); // load default chain instead
else
load(data);
});
// add help...
// a tooltip is shown for any item matching certain selector
// the help content is taken from the list in help.html, using
// the selector set in their help_for attributes to assign it.
get('/help.html',function(html){
var help=$(html);
var helper_timeout=false;
// each help block is shown for all elements matching it's selector
help.filter('div').each(function(){
// read selector from this help block
var selector=$(this).attr('help_for');
var text=this;
// defered event handlers (on body) to assign all future elements as well.
$(document).on('mouseenter',selector,function(){
clearTimeout(helper_timeout);
// add a little delay before showing the tooltip to avoid clutter and permanent CPU stress on mouse motion
helper_timeout=setTimeout(function(){
$('#help').html(text);
$('#help').show();
},400);
});
$(document).on('mouseleave',selector,function(){
clearTimeout(helper_timeout);
$('#help').hide();
});
});
});
// keep help at the mouse
$(document).on('mousemove',function(e){
$('#help').css({left: e.pageX+20, top: e.pageY+20});
});
// preview pane
var preview=false;
var offline_timeout=false;
var open_socket=function()
{
websocket=new WebSocket((document.location.protocol=='https:'?'wss:':'ws:')+'//'+document.location.hostname+':'+document.location.port+document.location.pathname.replace('ui.html',''));
websocket.onopen=function(){
// opt in for preview and screenshot feeds
websocket.send(JSON.stringify({'method':'get', path:'/feeds'+session_url+'devices',data:''}));
websocket.send(JSON.stringify({'method':'get', path:'/feeds'+session_url+'stats',data:''}));
websocket.send(JSON.stringify({'method':'get', path:'/feeds'+session_url+'screenshot',data:''}));
websocket.send(JSON.stringify({'method':'get', path:'/feeds'+session_url+'update',data:''}));
};
websocket.onmessage=function(event)
{
var packet=JSON.parse(event.data);
var path=packet.path, message=packet.data;
if(path=='/feeds'+session_url+'devices')
{
var device_list=JSON.parse(message);
// refresh visible device list
listDevices(device_list);
}
else if(path=='/feeds'+session_url+'stats')
{
var json=message;
var data=JSON.parse(json);
document.getElementById('stats').innerHTML='online, running '+(Math.round(10000./data.frame_time)/10.)+' fps';
if(offline_timeout) clearTimeout(offline_timeout);
offline_timeout=setTimeout(function(){
document.getElementById('stats').innerHTML='offline';
offline_timeout=false;
},1000);
}
else if(path=='/feeds'+session_url+'screenshot'){
var link=$('<a>');
link.attr('href',message);
link.attr('download',message.startsWith('data:image/jpeg') ? 'VisSynthWebScreenshot.jpg' : 'VisSynthWebMovie.webm' );
$(document.body).append(link);
link[0].click();
// link.remove();
}
else if(path=='/feeds'+session_url+'update'){
console.log('Update by external data');
load(message);
}
}
websocket.onclose=function()
{
setTimeout(open_socket,1000);
}
}
open_socket();
let webrtc=null;
window.toggle_preview=async function(){
preview=!preview;
send('canvas.preview('+preview+')');
if(preview) {
$('#preview_button').addClass ('active');
webrtc=await WebRTC("","/webrtc_preview"+session_url,null, document.getElementById('preview'));
setTimeout(webrtc.call, 1000);
} else {
$('#preview_button').removeClass('active');
if(webrtc) webrtc.hangup();
}
}
// screenshot button
function screenshot(){
send('canvas.screenshot()');
}
// double tap quirk for touch screens
var last_tap;
$(document.body).on('touchend','*',function(e){
var timestamp=Date.now();
if(timestamp<last_tap+300)
$(this).trigger('dblclick');
last_tap=timestamp;
});
</script>
<script>
// media manager
var post=function(data)
{
var formData = new FormData();
for(let key in data)
formData.append(key, data[key]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'save.php');
xhr.send(formData);
return xhr;
}
function addUpload(elementSelector)
{
var doc = document.querySelector(elementSelector);
doc.ondragover = function () { this.className = 'hover'; return false; };
doc.ondragend = function () { this.className = ''; return false; };
doc.ondrop = function (event) {
event.preventDefault && event.preventDefault();
this.className = '';
// now do something with:
var files = event.dataTransfer.files;
var formData = new FormData();
formData.append('action','upload');
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
}
// var progress=document.getElementById('progress');
// now post a new XHR request
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload');
xhr.onload = function() {
// progress.value = progress.innerHTML = 100;
alert('upload complete, response: '+xhr.responseText);
listFiles();
};
/* xhr.upload.onprogress = function (event) {
if (event.lengthComputable) {
var complete = (event.loaded / event.total * 100 | 0);
progress.value = progress.innerHTML = complete;
}
}*/
xhr.send(formData);
return false;
};
}
addUpload('body');
</script>
</body>
</html>