-
Notifications
You must be signed in to change notification settings - Fork 25
/
output.js
1318 lines (1223 loc) · 61.7 KB
/
output.js
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
/**
* Created by Fry on 4/17/16.
*/
const ipcRenderer = require('electron').ipcRenderer
const request = require('request')
ipcRenderer.on('record_dde_window_size', function(event){
//onsole.log("top of on record_window_size")
persistent_set("dde_window_x", window.screenX)
persistent_set("dde_window_y", window.screenY)
persistent_set("dde_window_width", window.outerWidth)
persistent_set("dde_window_height", window.outerHeight)
});
window.set_dde_window_size_to_persistent_values = function(){
console.log("top of set_dde_window_size_to_persistent_values " +
persistent_get("dde_window_width") + " " +
persistent_get("dde_window_height"))
ipcRenderer.send('set_dde_window_size',
persistent_get("dde_window_x"),
persistent_get("dde_window_y"),
persistent_get("dde_window_width"),
persistent_get("dde_window_height"))
}
//_________show_window and helper fns__________
window.set_in_ui = function(path_string, value){
let path_elts = path_string.split(".")
let the_loc = window
for (var i = 0; i < path_elts.length; i++){
var path_elt = path_elts[i]
if (i == (path_elts.length - 1)){ //on last elt so set it
if( // the_loc.hasOwnProperty("attributes") /doesn't work
the_loc.hasAttributes() &&
the_loc.attributes.hasOwnProperty(path_elt)) {
the_loc.setAttribute(path_elt, value)
} //necewssary for "active" attributes like cx in svg ellipse, in order to actually change the visible appearance of the ellipse
else { the_loc[path_elt] = value }
}
else {
the_loc = the_loc[path_elt]
}
}
}
window.remove_in_ui = function(path_string){
let elt = value_of_path(path_string)
elt.remove()
}
window.replace_in_ui = function(path_string, new_html){
let elt = value_of_path(path_string)
$(elt).replaceWith(new_html)
}
function html_to_tag_name(html){
if (html.length < 2) { return null }
var start_pos = 0
if (html[0] == "<") start_pos = 1
var end_pos = html.indexOf(" ")
if (end_pos == -1) end_pos = html.length
let result = html.substring(start_pos, end_pos)
if (result.endsWith("/>")) result = result.substring(0, result.length - 2)
else if (result.endsWith(">")) result = result.substring(0, result.length - 1)
return result.trim()
}
window.html_to_tag_name = html_to_tag_name
function html_attributes_and_values(html){
html = html.trim()
if (html.length < 3) { return null }
let start_pos = 0
if (html[0] == "<") {
start_pos = html.indexOf(" ")
if (start_pos == -1) return []
}
let end_pos = html.length
if (last(html) == ">") end_pos = end_pos - 1
if (html[end_pos - 1] == "/") end_pos = end_pos - 1
let attr_string = html.substring(start_pos, end_pos)
attr_string.trim()
let result = []
/*//let pairs = attr_string.split(" ")
for(let pair of pairs){
pair = pair.trim()
if (pair.length > 2){
let name_val = pair.trim().split("=")
let name = name_val[0].trim()
let val = name_val[1].trim()
//cut off quotes from val if any
let val_start = 0
if (["'", '"', "`"].includes(val[0])) val_start = 1
let val_end = val.length
if (["'", '"', "`"].includes(last(val))) val_end = val_end - 1
val = val.substring(val_start, val_end)
result.push([name, val])
}
}*/
var state = "before_name"
var name = ""
var start_token = 0
var string_delim = null
for(let i = 0; i < attr_string.length; i++){
let char = attr_string[i]
if (state == "before_name"){
if (char == " ") {}
else if (char == "/") break;
else if (char == ">") break;
else { start_token = i; state = "in_name"}
}
else if (state == "in_name") {
if (char == "=") {
name = attr_string.substring(start_token, i)
state = "in_val"
start_token = i + 1
}
}
else if (state == "in_val"){
if ((start_token == i) && ["'", '"', "`"].includes(char)){
state = "in_string"
start_token += 1
string_delim = char
}
else if (char == " ") {
val = attr_string.substring(start_token, i)
result.push([name, val])
state = "before_name"
}
}
else if (state == "in_string"){ //pretend no backslashed string delimiters.
if (char == string_delim) {
val = attr_string.substring(start_token, i)
if (val.length > 0) {
result.push([name, val])
}
//else we only had "" for the val so just ignore it.
state = "before_name"
}
}
else { shouldnt("in html_attributes_and_values with illegal state of: " + state) }
}
return result
}
window.html_attributes_and_values = html_attributes_and_values
//inserts the new_html as the new last child of the element indicated by path_string
window.append_in_ui = function(path_string, new_html){
let elt = value_of_path(path_string)
//$(elt).append(new_html) //doesn't refresh svg
//elt.addChild(jquery.parseHTML(new_html)) //doesn't refresh svg
let ancestor_svg = $(elt).closest("svg")
if (ancestor_svg.length > 0) {
ancestor_svg = ancestor_svg[0]
//"refreshes" the rendered html. If I don't do this, you don't see the new svg elt added
//$(ancestor_svg).html($(ancestor_svg).html()); //from http://stackoverflow.com/questions/3642035/jquerys-append-not-working-with-svg-element
//not the most popular answer, but one that works better for my purposes
//however doing this html refresh gets rid of all the onclick methods on the svg tags so clicking
//only works once, then no more onclick metnods so clicking fails
//ancestor_svg.forceRedraw() //preserves the onclick methods but doesn't do what its name sez.
//ancestor_svg.style.webkitTransform = ancestor_svg.style.webkitTransform //fails
//ancestor_svg.style.display='none';
//ancestor_svg.offsetHeight; // no need to store this anywhere, the reference is enough
//ancestor_svg.style.display='';
// $(ancestor_svg).css('display', 'none').height();
// $(ancestor_svg).css('display', 'block');
let new_tag = html_to_tag_name(new_html)
let attr_vals = html_attributes_and_values(new_html)
let new_svg_elt = document.createElementNS("http://www.w3.org/2000/svg", new_tag);
for (let pair of attr_vals){
new_svg_elt.setAttribute(pair[0], pair[1])
}
ancestor_svg.appendChild(new_svg_elt);
}
else{
$(elt).append(new_html)
}
}
//get the value of the path in the UI.
window.get_in_ui = function(path_string){
return value_of_path(path_string)
}
var window_index = 0
function set_window_index(jqxw_jq){
let the_window_index = window_index
jqxw_jq.attr('data-window_index', the_window_index)
//console.log ("setting window to index: " + the_window_index)
window_index += 1
return the_window_index
}
window.set_window_index = set_window_index
function is_window_shown(index){
let win = $('[data-window_index=' + index + ']')
return win.length != 0
}
window.is_window_shown = is_window_shown
//index can be an int or a string
function get_window_of_index(index){
if (index == undefined){ //risky to just get the latest created, but a good trick when I need to call some init for a window as in combo box for app builder from ab.fill_in_action_names
index = window_index - 1
}
//onsole.log ("getting window of index: " + index + " with next window_index: " + window_index)
let win = $('[data-window_index=' + index + ']')
//onsole.log("get_window_of_index got win: " + win)
return win
}
window.get_window_of_index = get_window_of_index
function get_index_of_window(jqxw_jq){
return jqxw_jq.attr('data-window_index')
}
window.get_index_of_window = get_index_of_window
function get_jqxw_jq_of_window_containing_elt(elt){ //elt is usually a button that's inside the window
if (elt.tagName == "LI"){
var window_index = $(elt).attr("data-window_index")
return get_window_of_index(window_index)
}
else {
var window_elt = elt.closest(".show_window")
return $(window_elt)
}
}
window.get_jqxw_jq_of_window_containing_elt = get_jqxw_jq_of_window_containing_elt
function get_window_content_of_elt(elt){
if (elt.tagName == "LI"){
var window_index = $(elt).attr("data-window_index")
var jqxw_jq = get_window_of_index(window_index)
return jqxw_jq.find(".show_window_content")
}
else {
return $(elt).closest(".show_window_content")
}
}
window.get_jqxw_jq_of_window_containing_elt
function get_window_index_containing_elt(elt){
var jqxw_jq = get_jqxw_jq_of_window_containing_elt(elt)
return get_index_of_window(jqxw_jq)
}
window.get_window_index_containing_elt
//esp good for a zillion human_notify show windows
function close_all_show_windows(){
var wins = $('[data-window_index]')
if (wins.length > 0){ //note: if we try to close when there are no wins, we get an error.
wins.closest(".show_window").jqxWindow("close")
}
}
window.close_all_show_windows = close_all_show_windows
function show_window_values(vals){out(vals)}
window.show_window_values = show_window_values
window.show_window = function({content = "", title = "DDE Information", width = 400, height = 400, x = 200, y = 200,
background_color = "rgb(238, 238, 238)",
is_modal = false, show_close_button = true, show_collapse_button = true,
trim_strings = true, callback = show_window_values} = {}){
//callback should be a string of the fn name or anonymous source.
if ((arguments.length > 0) && (typeof(arguments[0]) == "string")){
var content = arguments[0] //all the rest of the args will be bound to their defaults by the js calling method.
}
if (typeof(content) !== "string"){
content = stringify_value(content)
}
if (typeof(callback) == "function"){
let fn_name = callback.name
if (fn_name && (fn_name != "")) {
if(fn_name == "callback") { //careful, might be just JS being clever and not the ctual name in the fn def
fn_name = function_name(callback.toString()) //extracts real name if any
if (fn_name == "") { //nope, no actual name in fn
callback = callback.toString() //get the src of the anonymous fn
}
else { callback = fn_name }
}
else { callback = fn_name }
}
else { callback = callback.toString() } //using the src of an annonymous fn.
}
//var the_instruction_id = null
//if(arguments[0]) {the_instruction_id = arguments[0].the_instruction_id}
content = "<div class='show_window_content' contentEditable='false' style='font-size:15px;'>\n" +
"<input name='window_callback_string' type='hidden' value='" + callback + "'/>\n" +
"<input name='trim_strings' type='hidden' value='" + trim_strings + "'/>\n" +
//the next 2 are only for Human.show_window
((arguments[0].the_job_name) ?
"<input name='the_job_name' type='hidden' value='" + arguments[0].the_job_name + "'/>\n": "") +
//((the_instruction_id || (the_instruction_id == 0)) ?
//"<input name='the_instruction_id' type='hidden' value='" + the_instruction_id + "'/>\n": "") +
content + "</div>" //to allow selection and copying of window content
//kludge but that's dom reality
var holder_div = document.createElement("div"); // a throw away elt
holder_div.innerHTML ='<div class="show_window" style="display:none;">' +
'<div class="window_frame" style="font-size:20px;">' + title + '</div>' + //coral #ff8c96
'<div style="overflow:auto; background-color:' + background_color + ';">' + content + '</div>' +
'</div>'
var window_elt = holder_div.firstElementChild
//body_id.appendChild(window_elt) //this is automatically done when I call jqxw_jq.jqxWindow({width:width below
var jqxw_jq = $(window_elt).jqxWindow({width: width, height: height,
position: {x: x, y: y},
//autoOpen: true, //open window upon creation, always
isModal: is_modal, //default false
showCloseButton: show_close_button, //default true but may want to turn off
// IFF you want to always close the window with your own submit button and do some action whenever window closes.
//otherwise, user could click the close button and it wouldn't run user code assocaited with their own submit button.
showCollapseButton: show_collapse_button, //default true
showAnimationDuration: 500,
closeAnimationDuration: 500, //doesn't work. its always 0
collapseAnimationDuration:500,
maxHeight: 2000, maxWidth: 2000}) //default maxWidth = 800, default maxHeight=600
//if (content_or_obj.window_class){jqxw_jq.addClass(content_or_obj.window_class)} //class isn't used by DDE (apr 2016) and I don't document it so cut it out, at least for now.
let the_window_index = set_window_index(jqxw_jq)
jqxw_jq.on('close', function (event) { jqxw_jq.remove() }); //handles both the removal from a submit button AND the removal from usre hitting the upper right close box.
//jqxw_jq.find(".jqx-window-content").css("background-color", "#eeeeee")
jqxw_jq.css("border", "5px solid #666666") //dark gray border so that shows up against black of simulation pane
//jqxw_jq.children().css("background-color", "#dddddd")
//jqxw_jq.jqxWindow({width:width, height:height, position:{x: x, y: y}, showCloseButton: true})
//jqxw_jq.jqxWindow('setTitle', title);
//jqxw_jq.jqxWindow('setContent', content);
jqxw_jq.jqxWindow('show'); //this is performed with creation option: autoOpen:true
setTimeout(install_onclick_via_data_fns, 10) //todo probably shouldn't have both of these!
setTimeout(function(){install_submit_window_fns(jqxw_jq)}, 10)
return the_window_index //used by dex.train
}
function install_onclick_via_data_fns(){
var elts = document.getElementsByClassName("onclick_via_data")
for (var index = 0; index < elts.length; index++){ //bug in js chrome: for (var elt in elts) doesn't work here.
var elt = elts[index]
elt.onclick = onclick_via_data_fn
}
}
window.install_onclick_via_data_fns = install_onclick_via_data_fns
function install_submit_window_fns(jqxw_jq){
var info_win_div = jqxw_jq.find(".show_window_content")
var ins = info_win_div.find(".clickable")
for (var index = 0; index < ins.length; index++){ //bug in js chrome: for (var elt in elts) doesn't work here.
var inp = ins[index]
inp.onclick = submit_window
}
var ins = info_win_div.find("input")
for (var index = 0; index < ins.length; index++){ //bug in js chrome: for (var elt in elts) doesn't work here.
var inp = ins[index]
if ((inp.type == "submit") || (inp.type == "button")){
inp.onclick = submit_window
}
else{
if (inp.dataset.onchange == "true") { inp.onchange = submit_window }
if (inp.dataset.oninput == "true") { inp.oninput = submit_window }
}
}
var ins = info_win_div.find("select")
for (var index = 0; index < ins.length; index++){ //bug in js chrome: for (var elt in elts) doesn't work here.
var inp = ins[index]
if (inp.dataset.onchange == "true") { inp.onchange = submit_window }
if (inp.dataset.oninput == "true") { inp.oninput = submit_window }
}
var ins = info_win_div.find("a")
for (var index = 0; index < ins.length; index++){ //bug in js chrome: for (var elt in elts) doesn't work here.
var inp = ins[index]
inp.onclick = submit_window
}
var combo_boxes = jqxw_jq.find(".combo_box") //should be a div tag a la <div class="combo_box><option>one</option><option>two</option></div>
for (var i = 0; i < combo_boxes.length; i++){
var cb = $(combo_boxes[i])
var kids = cb.children()
var choices = []
var sel_index = 0
for (var j=0; j < kids.length; j++){
var kid = kids[j] //could be nearly any html elt but option is a good choice.
choices.push(kid.innerHTML)
if (kid.selected) {sel_index = j}
}
if (cb[0].style && cb[0].style.width) {
var cb_width = cb[0].style.width
cb.jqxComboBox({height: '16px', source: choices, selectedIndex: sel_index, width: cb_width})
}
else{
cb.jqxComboBox({height: '16px', source: choices, selectedIndex: sel_index})
}
}
var window_index = get_index_of_window(jqxw_jq)
var menus = jqxw_jq.find(".menu")
for (var i = 0; i < menus.length; i++){
var menu = $(menus[i])
var outer_lis = menu[0].children[0].children
if (outer_lis && outer_lis[0] && outer_lis[0].children && outer_lis[0].children[0]){
var inner_lis = outer_lis[0].children[0].children
install_menus_and_recurse(inner_lis, window_index)
}
// else we've got a menu with zero items, but for dev purposes its nice to
//be able to show the menu's name, and its down arrow, even if nothing under it.
$(menu).jqxMenu({ width: '100px', height: '25px' })
}
}
window.install_submit_window_fns = install_submit_window_fns
function install_menus_and_recurse(inner_lis, window_index){ //the arg is li elts that *might* not be leaves
for(var j = 0; j < inner_lis.length; j++){
var inner_li = inner_lis[j]
inner_li.onclick = submit_window
$(inner_li).attr('data-window_index', window_index)//because jqx sticks these LIs outside the dom so it screws uo the normal way of looking up the dom to find it.
if (inner_li.children.length > 0){
install_menus_and_recurse(inner_li.children[0].children, window_index)
}
}
}
window.install_menus_and_recurse = install_menus_and_recurse
window.submit_window = function(event){
// descriptions of x & y's: http://stackoverflow.com/questions/6073505/what-is-the-difference-between-screenx-y-clientx-y-and-pagex-y
event.stopPropagation();
let result = {offsetX:event.offsetX, offsetY:event.offsetY, //relative to the elt clocked on
x:event.x, y:event.y, //relative to the parent of the elt clicked on
clientX:event.clientX, clientY:event.clientY, //Relative to the upper left edge of the content area (the viewport) of the browser window. This point does not move even if the user moves a scrollbar from within the browser.
pageX:event.pageX, pageY:event.pageY, //Relative to the top left of the fully rendered content area in the browser.
screenX:event.screenX, screenY:event.screenY, //Relative to the top left of the physical screen/monitor
altKey:event.altKey, //on mac, the option key.
ctrlKey:event.ctrlKey,
metaKey:event.metaKey, //on WindowsOS, the windows key, on Mac, the Command key.
shiftKey:event.shiftKey,
tagName:this.tagName}
result.window_index = get_window_index_containing_elt(this)//get_index_of_window(jsxw_jq)
//var jsxw_jq = get_jqxw_jq_of_window_containing_elt(this)
if (this.tagName == "LI"){ //user clicked on a menu item
if ($(this).attr("data-name")) {result.clicked_button_value = $(this).attr("data-name")}
else {result.clicked_button_value = this.innerHTML}
}
else if (this.tagName == "A"){
if (this.href.endsWith("#")){
result.clicked_button_value = this.innerHTML
}
else { //we've got a real url. The only thing to do with it is open a window, so
//don't even go through the handler fn, just do it.
var url = this.href
var double_slash_pos = url.indexOf("//")
url = url.substring(double_slash_pos + 2, url.length)
var single_slash_pos = url.indexOf("/")
url = url.substring(single_slash_pos + 1, url.length)
if (!url.startsWith("http")){
url = "http://" + url
}
window.open(url)
return
}
}
/*else if (this.tagName == "INPUT") {
if ((this.type == "button") || (this.type == "submit")) { //used by the callback to chose the appropriate action
if(this.name) { result.clicked_button_value = this.name }
else if (this.id) { result.clicked_button_value = this.id }
else { result.clicked_button_value = this.value } //this is the disolayed text in the button.
//but note that we *might* have 2 buttons with the same label but want them to have different actions
//so check name and id first because we can give them different values even if
//the label (value) is the same for 2 different buttons.
//but if we WANT the action to be the same for 2 same-valued buttons, fine
//give the buttons values but no name or id.
}
else { //for sliders, etc. if they have data-onchange='true' or data-onclick='true'
// if (this.oninput) { this.focus() } //because at least for input type="text", when
//the oninput fires, it unfocues the input elt.
result.clicked_button_value = this.name
}
}*/
else if (this.tagName == "INPUT") {
if(this.name) { result.clicked_button_value = this.name }
else if (this.id) { result.clicked_button_value = this.id }
else { result.clicked_button_value = this.value } //this is the disolayed text in the button.
//but note that we *might* have 2 buttons with the same label but want them to have different actions
//so check name and id first because we can give them different values even if
//the label (value) is the same for 2 different buttons.
//but if we WANT the action to be the same for 2 same-valued buttons, fine
//give the buttons values but no name or id.
}
else if (this.name) { result.clicked_button_value = this.name }
else if (this.id) { result.clicked_button_value = this.id }
var window_content_elt = get_window_content_of_elt(this)
var trim_strings_elt = window_content_elt.find("input[name|='trim_strings']")
var trim_strings = trim_strings_elt[0].value
if (trim_strings == "false") { trim_strings = false}
else {trim_strings = true}
var inputs = $(window_content_elt).find("input") //finds all the descentents of the outer div that are "input" tags
var window_callback_string = null
for (var i = 0; i < inputs.length; i++){
var inp = inputs[i]
var in_name = inp.name
if (!in_name) { in_name = inp.id }
else if (!in_name) { in_name = inp.value }
var in_type = inp.type //text (one-liner), submit, button, radio, checkbox, etc.
if (in_type == "radio"){
if (inp.checked){
result[in_name] = inp.value
}
else if (result[in_name] === undefined){ //first time we've seen a radio button from this grou.
//make sure is val is null instead of not setting
//it at call because if no button was set on init,
//and user didn't click on one, we STILL
//want a field for it in the result (unlike most
//stupid web programming that would pretend it didn't exist.
//we want to see this field when debugging, etc.
result[in_name] = null
}
}
else if (in_type == "checkbox"){
if (in_name){
var val = inp.checked
result[in_name] = val
}
}
else if (in_type == "file") { result[in_name] = ((inp.files.length > 0) ?
inp.files[0].path :
null) }
else if (in_type == "submit"){}
else if (in_type == "button"){} //button click still causes the callback to be called, but leaves window open
else if (in_type == "hidden") { //trim_strings, window_callback_string, and for Human.show_instruction: the_job_name
var val = inp.value
if (val == "false") {val = false}
else if (val == "true") {val = true}
else if (val == "null") {val = null}
else if (is_string_a_number(val)) { val = parseFloat(val) } //for "123", this will return an int
result[in_name] = val
}
else if (in_type == "text"){
if (in_name){
var val = inp.value
if (trim_strings) { val = val.trim() }
result[in_name] = val
}
}
else if (in_type == "number"){
if (in_name){
var val = parseFloat(inp.value.trim()) //comes in as a string. Gee why would an input of type number return a number? It would be too logical
if (isNaN(val)) { val = null }
result[in_name] = val
}
}
else { //all the other inputs.
if (in_name){
var val = inp.value
result[in_name] = val
}
}
}
var textareas = $(window_content_elt).find("textarea") //finds all the descentents of teh outer div that are "input" tags
for (var i = 0; i < textareas.length; i++){
var inp = textareas[i]
var in_name = inp.name
if (in_name){
var val = inp.value
if (trim_strings) { val = val.trim() }
result[in_name] = val
result[in_name + "_width"] = inp.style.width //usesd by app builder to get size of input and text areas being made by the user
result[in_name + "_height"] = inp.style.height
}
}
var selects = $(window_content_elt).find("select") //finds all the descentents of teh outer div that are "input" tags
for (var i = 0; i < selects.length; i++){
var inp = selects[i]
var in_name = (inp.name ? inp.name : inp.id)
if (in_name){
var val = inp.value
result[in_name] = val
}
}
var combo_boxes = $(window_content_elt).find(".combo_box") //should be a div tag a la <div class="combo_box><option>one</option><option selected="selected">two</option></div>
for (var i = 0; i < combo_boxes.length; i++){
let outer_cb = combo_boxes[i]
let inner_cb = outer_cb.children[1]
let val = $(outer_cb).val() //inner_cb.value
result[inner_cb.name] = val
}
if (this.type == "submit"){
//$('#jqxwindow').jqxWindow('close');
close_window(this)
}
//widget_values: result,
let callback_fn_string = result["window_callback_string"]
let cb = value_of_path(callback_fn_string)
if (!cb) { try { cb = window.eval(callback_fn_string) }
catch(err){} //just ignore
}
//cb is probably "function () ..." ie a string of a fn src code
if (!cb) { //cb could have been a named fn such that wehn evaled didn't return the fn due to bad js design
if(callback_fn_string.startsWith("function ")){
let fn_name = function_name(callback_fn_string)
if ((typeof(fn_name) == "string") && (fn_name.length > 0)) { cb = window.fn_name }
else { //we've got an anonyous function source cde def
cb = eval("(" + callback_fn_string + ")") //need extra parens are veal will error becuase JS is wrong
if(typeof(cb) != "function"){
dde_error("show_window got a callback that doesn't look like a function.")
}
}
}
else {
dde_error("In submit_window with bad format for the callback function of: " + callback_fn_string)
}
}
cb.call(null, result) //todo likely not right after electron conversion. IS result the right format for the callback
event.preventDefault()
event.stopPropagation()
if (this.oninput) { //work around bug in Chrome 51 June 8 2016 wherein when you have
//input of type text, and using my oninput techique, the
// upon a keystroke entering a char, the focus changes from the
//input elt (and out of the show_window window itself back to the codemirror editor)
//just setting the focus in this method doesn't do the trick, I have to
//do the setTimeout below to get the focus back to the orig input elt.
let the_this = this;
setTimeout(function(){
if ((the_this) && the_this.ownerDocument.body.contains(the_this)){ //its possible that the win that the_this is in will be closed by the time this code is run.
//happens in the case of Human.enter_instruction with immediate_do
the_this.focus()
}
}, 10)
}
}
//rde.hide_window = function() { $('#jqxwindow').jqxWindow('hide') }
//called from the ui, window_index_or_elt can be either a window_index_or_elt.
//called from sandbox, it must be a window_index
window.close_window = function(window_index_or_elt){ //elt can be a window_index int
//var window_elt = elt.closest(".show_window")
//$(window_elt).jqxWindow("close")
// $(window_elt).remove() //done about near jqx window constructor see .on
if ((typeof(window_index_or_elt) == "string") || (typeof(window_index_or_elt) == "number")){ //ie a window_index
let win = get_window_of_index(window_index_or_elt)
win.jqxWindow("close")
}
else {
get_jqxw_jq_of_window_containing_elt(window_index_or_elt).jqxWindow("close")
}
}
//__________out and helper fns_______
window.out_item_index = 0
function out(val, color="black", temp=false){
var text = val
if (typeof(text) != "string"){ //if its not a string, its some daeta structure so make it fixed width to demostrate code. Plus the json =retty printing doesn't work unless if its not fixed width.
text = stringify_value(text)
}
if ((color != "black") && (color != "#000000")){
text = "<span style='color:" + color + "';>" + text + "</span>"
}
var temp_str_id = ((typeof(temp) == "string") ? temp : "temp")
var existing_temp_elts = $("#" + temp_str_id)
if (temp){
if (existing_temp_elts.length == 0){
text = '<div id="' + temp_str_id + '" style="border-style:solid;border-width:1px;border-color:#0000FF;margin:5px 5px 5px 15px;padding:4px;">' + text + '</div>'
append_to_output(text)
}
else {
existing_temp_elts.html(text)
}
return "dont_print"
}
else {
if ((existing_temp_elts.length > 0) && (temp_str_id == "temp")){ //don't remove if temp is another string. This is used in Job.show_progress
existing_temp_elts.remove()
}
var out_item_id = "out_" + out_item_index
out_item_index += 1
text = '<div id="' + out_item_id + '" style="border-style:solid;border-width:1px;border-color:#AA00AA;margin:5px 5px 5px 15px;padding:4px;">' + text + '</div>'
append_to_output(text)
}
myCodeMirror.focus()
/* This fails because the "position" of the call to show_output is the position in THIS source code,
not the code being evaled.
StackTrace.get(function(sf){
return true //sf.functionName == show_output
}).then(function(sf){
var lineno = sf.lineNumber
var colno = sf.columnNumber
window[out_item_id].onclick = function(){
var src = Editor.get_javascript(true) //true means grab sel text if any, else grab the whole thing, just like EVAL button does
var start_pos_of_out_call = char_position(src, lineno, colno)
Editor.select_javascript(start_pos_of_out_call, start_pos_of_out_call + 3) //select "out"
}
}).catch(function(err){ console.log("Error in show_output stacktrace error. " + err.message)})
*/
if (temp){
return "dont_print"
}
else {
return val //so value can be used by the caller of show_output
}
}
window.out = out
/*
StackTrace.get(function(sf){
return sf.functionName == show_output
})then(function(sf){
var lineno = sf.lineNumber
var colno = sf.columnNumber
}catch("errorcb")
out_aux = function(text, color){
*/
//text is a string that represents a result from eval.
// It has been trimmed, and stringified, with <code> </code> wrapped around it probably.
//never passed 'dont_print, always prints <hr/> at end whereas regular output never does
//ui only
window.out_eval_result = function(text, color="#000000"){
if (text != '"dont_print"'){
var existing_temp = $("#temp")
if (existing_temp.length > 0){
existing_temp.remove()
}
if (starts_with_one_of(text, ['"<svg ', '"<circle ', '"<ellipse ', '"<foreignObject ', '"<line ', '"<polygon ', '"<polyline ', '"<rect ', '"<text '])) {
text = text.replace(/\</g, "<") //so I can debug calls to svg_svg, svg_cirle ettc
}
if (color && (color != "#000000")){
text = "<span style='color:" + color + "';>" + text + "</span>"
}
text = "<fieldset><legend><i>Eval Result</i></legend>" + text + "</fieldset>"
append_to_output(text)
}
//$('#js_textarea').focus() fails silently
myCodeMirror.focus()
}
window.get_output = function(){ //rather uncommon op, used only in append_to_output
return $("#output_div_id").html()
}
window.clear_output = function(){
output_div_id.innerText = ""
init_inspect();
return "dont_print"
}
//now literally never useful as if its called from js pane, then the return val from this fn will replace the output
window.append_to_output = function(text){
var out_height = output_div_id.scrollHeight
//var orig = get_output()
text += "\n"
$("#output_div_id").append(text)
output_div_id.scrollTop = out_height
install_onclick_via_data_fns()
}
//___________SOUND__________
//note Series is not defined in sandbox
window.month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September','October', 'November', 'December']
//value can either be some single random js type, or a literal object
//with a field of speak_data, in which case we use that.
function stringify_for_speak(value, recursing=false){
var result
if ((typeof(value) == "object") && (value !== null) && value.hasOwnProperty("speak_data")){
if (recursing) {
dde_error('speak passed an invalid argument that is a literal object<br/>' +
'that has a property of "speak_data" (normally valid)<br/>' +
'but whose value itself is a literal object with a "speak_data" property<br/>' +
'which can cause infinite recursion.')
}
else { return stringify_for_speak(value.speak_data, true) }
}
else if (typeof(value) == "string") { result = value }
else if (value === undefined) { result = "undefined"}
else if (value instanceof Date){
var mon = value.getMonth()
var day = value.getDate()
var year = value.getFullYear()
var hours = value.getHours()
var mins = value.getMinutes()
if (mins == 0) { mins = "oclock, exactly" }
else if(mins < 10) { mins = "oh " + mins }
result = month_names[mon] + ", " + day + ", " + year + ", " + hours + ", " + mins
//don't say seconds because this is speech after all.
}
else if (Array.isArray(value)){
result = ""
for (var elt of value){
result += stringify_for_speak(elt) + ", "
}
}
else {
result = JSON.stringify(value, null, 2)
if (result == undefined){ //as happens at least for functions
result = value.toString()
}
}
return result
}
window.stringify_for_speak = stringify_for_speak
function speak({speak_data = "hello", volume = 1.0, rate = 1.0, pitch = 1.0, lang = "en_US", voice = 0, callback = null} = {}){
if (arguments.length > 0){
var speak_data = arguments[0] //, volume = 1.0, rate = 1.0, pitch = 1.0, lang = "en_US", voice = 0, callback = null
}
var text = stringify_for_speak(speak_data)
var msg = new SpeechSynthesisUtterance();
//var voices = window.speechSynthesis.getVoices();
//msg.voice = voices[10]; // Note: some voices don't support altering params
//msg.voiceURI = 'native';
msg.text = text
msg.volume = volume; // 0 to 1
msg.rate = rate; // 0.1 to 10
msg.pitch = pitch; // 0 to 2
msg.lang = lang;
var voices = window.speechSynthesis.getVoices();
msg.voice = voices[voice]; // voice is just an index into the voices array, 0 thru 3
msg.onend = callback
speechSynthesis.speak(msg);
return speak_data
}
window.speak = speak
//________recognize_speech_____________
//all these vars meaningful in ui only.
/*
window.recognition = null
window.recognize_speech_window_index = null
window.recognize_speech_phrase_callback = null
window.recognize_speech_finish_callback = null
window.recognize_speech_only_once = null
window.recognize_speech_click_to_talk = null
window.recognize_speech_last_text = null
window.recognize_speech_last_confidence = null
window.recognize_speech_finish_array = []
window.recognize_speech_finish_phrase = "finish" //set by recognize_speech ui
function init_recognize_speech(){
recognition = new webkitSpeechRecognition();
recognition.continuous = false;
recognition.interimResults = false;
recognition.lang = "en-US";
recognition.onstart = function(event) {
recognize_speech_img_id.src = 'mic-animate.gif';
let instructions
if ( recognize_speech_only_once ) { instructions = "Speak now.<br/>Be quiet to finish.<br/>" }
else {
instructions = "Speak now.<br/>" +
"Pause to let DDE process your phrase.<br/>" +
'Say <b>' + recognize_speech_finish_phrase + '</b> to end recognition.'
}
recognize_speech_instructions_id.innerHTML = instructions
}
recognition.onresult = function(event) {
//out('recognize_speech top of onresult');
recognize_speech_img_id.src = 'mic.gif';
recognize_speech_instructions_id.innerHTML = "Stop talking"
recognize_speech_last_text = event.results[0][0].transcript //event_to_text(event)
recognize_speech_last_confidence = event.results[0][0].confidence
recognize_speech_finish_array.push([recognize_speech_last_text, recognize_speech_last_confidence])
//out("recognized speech: " + recognize_speech_last_text)
if (!recognize_speech_only_once && (recognize_speech_last_text == recognize_speech_finish_phrase)){
}
else if(recognize_speech_phrase_callback) {
recognize_speech_phrase_callback(
recognize_speech_last_text,
recognize_speech_last_confidence)
}
//typed_input_id.value = text
}
recognition.onend = function(event) {
//out('recognize_speech top of onend');
if (recognize_speech_only_once) { close_window(recognize_speech_window_index) }
else if (recognize_speech_last_text == recognize_speech_finish_phrase){
close_window(recognize_speech_window_index)
if (recognize_speech_finish_callback){
recognize_speech_finish_callback(recognize_speech_finish_array)
}
}
else if (recognize_speech_click_to_talk){
recognize_speech_img_id.src = 'mic.gif';
recognize_speech_instructions_id.innerHTML = ""
}
//Note that its hard to turn off the calling of onstart when the user just closes the
//window via the window close box. This will do it.
//but bware, it does NOT call the finish_callback, rather closing the window
//is like a cancel, ie do nothing.
else if (is_window_shown(recognize_speech_window_index)){ //more than once AND don't have to click to talk
start_recognition() //this will set the gif and the instructions
}
}
recognition.onerror = function(event) {
if (window["recognize_speech_img_id"]){
recognize_speech_img_id.src = 'mic.gif';
recognize_speech_instructions_id.innerHTML = "Stop talking"
}
if (is_window_shown(recognize_speech_window_index)){ //don't show this error message if the user closed the window
out("onerror called with: " + event.error, "red")
}
}
} //end init_recognize_speech
//window.init_recognize_speech = init_recognize_speech
//public
function recognize_speech_default_phrase_callback(text, confidence){
out("text: " + text + "<br/>confidence: " + confidence.toFixed(2))
}
window.recognize_speech_default_phrase_callback = recognize_speech_default_phrase_callback
function recognize_speech({title="Recognize Speech", prompt="",
only_once=true, click_to_talk=true,
width=400, height=180, x=400, y=200,
background_color="rgb(238, 238, 238)",
phrase_callback=recognize_speech_default_phrase_callback,
finish_callback=null, //unused if only_once=true
finish_phrase="finish", //unused if only_once=true
show_window_callback="system_use_only"}={}){
init_recognize_speech()
recognize_speech_phrase_callback = phrase_callback
recognize_speech_finish_callback = finish_callback
let click_to_talk_html = ""
if (click_to_talk) {
click_to_talk_html = "<input type='button' value='Click to talk'/><br/>"
}
//note: this show_window is evaled FIRST (and only) in the ui, so the phrase_callback should be a callback_number
recognize_speech_finish_array = []
recognize_speech_finish_phrase = finish_phrase
recognize_speech_only_once = only_once
recognize_speech_window_index =
show_window({content: "<div>" + prompt + "</div>" +
click_to_talk_html +
"<img id='recognize_speech_img_id' src='mic.gif'/>" +
"<span id='recognize_speech_instructions_id'/>",
title: title,
width: width, height: height, x: x, y: y,
background_color: background_color,
//callback only would ever get called if there's a click-to-talk button
callback: show_window_callback //start_recognition //called from sandbox initially
})
recognize_speech_click_to_talk = click_to_talk
if (!click_to_talk) { start_recognition() }
}
window.recognize_speech = recognize_speech
function start_recognition(){
recognition.start()
}
window.start_recognition = start_recognition
*/
//_______end Chrome Apps recognize_speech_______
//Google cloud rocognize speech
// started from https://github.com/GoogleCloudPlatform/nodejs-docs-samples/blob/master/speech/recognize.js
/*function streamingMicRecognize() {
const record = require('node-record-lpcm16'); // [START speech_streaming_mic_recognize]
const Speech = require('@google-cloud/speech'); // Imports the Google Cloud client library
//const speech = Speech() // Instantiates a client
const my_path = adjust_path_to_os(__dirname + '/dexter-dev-env-code.json')
console.log("my_path is" +
":" + my_path)
const speech = Speech({
projectId: 'dexter-dev-env',
keyFilename: my_path
})
//from https://github.com/GoogleCloudPlatform/google-cloud-node#cloud-speech-alpha
//const speechClient = speech({
// projectId: 'dexter-dev-env',
// keyFilename: adjust_path_to_os(__dirname + '/dexter-dev-env-code.json')
//})
const request = { config: { encoding: 'LINEAR16', sampleRate: 16000 },
singleUtterance: false,
interimResults: false,
verbose: true};
// Create a recognize stream
const recognizeStream = speech.createRecognizeStream(request)
.on('error', console.error)
.on('data', function(data){console.log(data)})
//process.stdout.write(data.results)
// Start recording and send the microphone input to the Speech API
record.start({
sampleRate: 16000,
threshold: 0
}).pipe(recognizeStream);
console.log('Listening, press Ctrl+C to stop.');
}
window.streamingMicRecognize = streamingMicRecognize
*/
function beeps(times=1, callback){
if (times == 0){