/
runtime.rb
1616 lines (1355 loc) · 54 KB
/
runtime.rb
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
#--
# This file is part of Sonic Pi: http://sonic-pi.net
# Full project source: https://github.com/samaaron/sonic-pi
# License: https://github.com/samaaron/sonic-pi/blob/main/LICENSE.md
#
# Copyright 2013, 2014, 2015, 2016 by Sam Aaron (http://sam.aaron.name).
# All rights reserved.
#
# Permission is granted for use, copying, modification, and
# distribution of modified versions of this work as long as this
# notice is included.
#++
require_relative "util"
require_relative "studio"
require_relative "incomingevents"
require_relative "counter"
require_relative "promise"
require_relative "jobs"
require_relative "synths/synthinfo"
require_relative "lang/western_theory"
require_relative "lang/sound"
require_relative "gitsave"
require_relative "lifecyclehooks"
require_relative "version"
require_relative "sthread"
require_relative "version"
require_relative "config/settings"
require_relative "preparser"
require_relative "event_history"
require_relative "thread_id"
require_relative "tau_api"
#require_relative "oscevent"
#require_relative "stream"
require 'net/http'
require 'uri'
require 'thread'
require 'fileutils'
require 'set'
require 'ruby-beautify'
require 'securerandom'
require 'monitor'
require 'active_support/core_ext/integer/inflections'
module SonicPi
class Stop < StandardError ; end
module RuntimeMethods
## Not officially part of the API
## Probably should be moved somewhere else
@@stop_job_mutex = Mutex.new
def load_snippets(path=Paths.snippets_path, quiet=false)
path = File.expand_path(path)
Dir["#{path}/**/*.sps"].each do |p|
lines = File.readlines(p)
key = nil
completion = ""
point_line = 0
point_index = 0
while (l = lines.shift) && !(l.start_with? "# --")
res = l.match(/\# ?([_a-z]+):(.*)/)
if res
k = res[1].strip
v = res[2].strip
if !v.empty?
case k
when "key"
key = v
when "point_line"
point_line = v.to_i
when "point_index"
point_index = v.to_i
end
end
end
end
if key
__info "Loading snippet #{key} in #{p}" unless quiet
completion = lines.join
__add_completion(key, completion, point_line, point_index)
end
end
end
### Start - Spider Time Management functions
###
def __layer_spider_time_density!(density)
new_density = __get_spider_time_density * density
__change_spider_time_density!(new_density)
end
def __change_spider_time_density!(new_density)
__thread_locals.set(:sonic_pi_spider_time_density, new_density.to_f)
end
def __with_spider_time_density(density, &blk)
prev_density = __get_spider_time_density
__layer_spider_time_density!(density)
blk.call
__change_spider_time_density!(prev_density)
end
def __in_link_bpm_mode
__system_thread_locals.get(:sonic_pi_spider_bpm) == :link
end
def __change_spider_time_and_beat!(new_time = nil, new_beat = nil)
__system_thread_locals.set :sonic_pi_spider_time, new_time.to_r
__system_thread_locals.set :sonic_pi_spider_beat, new_beat.to_f
end
def __init_spider_time_and_beat!
t = Time.now.to_f
__system_thread_locals.set :sonic_pi_spider_start_time, t
__change_spider_bpm_time_and_beat!(:link, t, 0)
end
def __change_spider_bpm_time_and_beat_to_next_link_phase(phase, quantum)
safety_t = 0.5
beat, time = @tau_api.link_get_next_beat_and_clock_time_at_phase(phase, quantum, safety_t)
__system_thread_locals.set(:sonic_pi_spider_bpm, :link)
__change_spider_time_and_beat!(time - __current_sched_ahead_time, beat)
end
def __change_spider_bpm_time_and_beat!(bpm, time, beat)
# Need to be careful here about how to switch bpm modes.
# We have 4 main cases:
# 1. link -> link
# 2. std -> link
# 3. link -> std
# 4. std -> std
if bpm == :link
if __in_link_bpm_mode
# 1. link -> link
__change_spider_time_and_beat!(time, beat)
else
# 2. std -> link
__system_thread_locals.set(:sonic_pi_spider_bpm, :link)
link_beat = __get_link_beat_at_clock_time(time + __current_sched_ahead_time)
__change_spider_time_and_beat!(time, link_beat)
end
else
# 3. link -> std
# 4. std -> std
__system_thread_locals.set(:sonic_pi_spider_bpm, bpm.to_f)
__change_spider_time_and_beat!(time, beat)
end
end
def __get_link_beat_at_clock_time(clock_time)
@tau_api.link_get_beat_at_clock_time(clock_time)
end
def __change_spider_beat_and_time_by_beat_delta!(beat_delta)
new_beat = __get_spider_beat + (beat_delta / __get_spider_time_density)
if __in_link_bpm_mode
new_time = @tau_api.link_get_clock_time_at_beat(new_beat)
new_time -= __current_sched_ahead_time
__change_spider_time_and_beat!(new_time, new_beat)
else
sleep_mul = __get_spider_sleep_mul
sleep_time = beat_delta * sleep_mul
new_time = __get_spider_time + sleep_time
__change_spider_time_and_beat!(new_time, new_beat)
end
end
def __get_beat_dur_in_ms(beats = 1)
__get_spider_sleep_mul * 1000.0 * beats
end
def __get_spider_time
__system_thread_locals.get(:sonic_pi_spider_time)
end
def __get_spider_time_density
__thread_locals.get(:sonic_pi_spider_time_density, 1)
end
def __get_spider_schedule_time
__get_spider_time + current_sched_ahead_time
end
def __get_spider_sleep_mul
(60.0 / __get_spider_bpm)
end
def __get_spider_bpm
# take into account density
if __in_link_bpm_mode
@tau_api.link_tempo * __get_spider_time_density
else
__system_thread_locals.get(:sonic_pi_spider_bpm) * __get_spider_time_density
end
end
def __get_spider_bpm_mode
if __in_link_bpm_mode
:link
else
__get_spider_bpm
end
end
def __get_spider_beat
__system_thread_locals.get :sonic_pi_spider_beat
end
def __get_spider_start_time
__system_thread_locals.get :sonic_pi_spider_start_time
end
def __current_local_run_time
(__get_spider_time - __get_spider_start_time).to_f.round(6)
end
def __with_preserved_spider_time_and_beat(&blk)
time = __get_spider_time
beat = __get_spider_beat
blk.call
__change_spider_time_and_beat!(time, beat)
end
### End - Spider Time Management functions
###
def __gui_heartbeat(id)
t = Time.now.freeze
@gui_heartbeats[id] = t
@gui_last_heartbeat = t
end
def __extract_git_hash
head_path = Paths.root_path + "/.git/HEAD"
if File.exist? head_path
ref = File.readlines(head_path).first
ref_path = Paths.root_path + "/.git/" + ref[5..-1]
ref_path = ref_path.strip
if File.exist? ref_path
return File.readlines(ref_path).first
end
end
end
def __update_gui_version_info_now
__info "Checking for new version of Sonic Pi"
v = __check_for_server_version_now
if @version < v
__print_version_outdated_info(v)
else
__info "Your version of Sonic Pi is the latest: #{@version}"
end
__msg_queue.push({:type => :version, :version => @version.to_s, :version_num => @version.to_i, :latest_version => v.to_s, :latest_version_num => v.to_i, :last_checked => __last_update_check})
end
def __current_version
@version
end
def __last_update_check
Time.at(@settings.get(:last_update_check_time).to_i)
end
def __check_for_server_version_now
t, t2 = nil
begin
params = {:uuid => global_uuid,
:ruby_platform => RUBY_PLATFORM,
:ruby_version => RUBY_VERSION,
:ruby_patchlevel => RUBY_PATCHLEVEL,
:sonic_pi_version => @version.to_s}
ver_uri = URI.parse(url="http://sonic-pi.net/static/info/latest_version.txt")
msg_uri = URI.parse(url="http://sonic-pi.net/static/info/message.txt")
ver_uri.query = URI.encode_www_form( params )
msg_uri.query = URI.encode_www_form( params )
ver_prom = Promise.new
msg_prom = Promise.new
t = Thread.new do
begin
msg_prom.deliver!(Net::HTTP.get_response(msg_uri).body)
rescue
msg_prom.deliver! ""
end
end
t2 = Thread.new do
begin
ver_prom.deliver!(Net::HTTP.get_response(ver_uri).body)
rescue
ver_prom.deliver! ""
end
end
ver = ver_prom.get(5)
v = Version.init_from_string(ver)
msg = msg_prom.get(5)
@settings.set(:last_update_check_time, Time.now.to_i)
@settings.set(:last_seen_server_version, v.to_s)
@settings.set(:message, msg)
v
rescue
t.kill if t
t2.kill if t2
__local_cached_server_version
end
end
def __server_version
return Version.new(0) if @settings.get(:no_update_checking)
# Only check for updates at most once every 2 weeks
last_update = @settings.get(:last_update_check_time).to_i
if (last_update > 0) &&
(Time.at(last_update) < Time.now)
two_weeks_in_seconds = 60 * 60 * 24 * 14
ts_2_weeks_later = Time.at(last_update + two_weeks_in_seconds)
return __local_cached_server_version if Time.now < ts_2_weeks_later
end
__check_for_server_version_now
end
def __local_cached_server_version
begin
return Version.init_from_string(@settings.get(:last_seen_server_version))
rescue
return Version.new(0)
end
end
def __print_version_outdated_info(v=@server_version)
__info "--- IMPORTANT NOTICE ---\n\n Your version of Sonic Pi is outdated\n The latest is #{v}\n Please consider updating:\n\n http://sonic-pi.net\n\n", 1
end
def __info(s, style=0)
__msg_queue.push({:type => :info, :style => style, :val => s.to_s}) unless __system_thread_locals.get :sonic_pi_spider_silent
end
def __multi_message(m, thread_name="")
__msg_queue.push({:type => :multi_message, :val => m, :jobid => __current_job_id, :jobinfo => __current_job_info, :runtime => __current_local_run_time.round(4), :thread_name => thread_name}) unless __system_thread_locals.get :sonic_pi_spider_silent
end
def __delayed(&block)
raise "Can only use __delayed in a job thread" unless __current_job_id
delayed_blocks = __system_thread_locals.get :sonic_pi_local_spider_delayed_blocks
delayed_blocks << block
end
def __delayed_message(s)
__enqueue_multi_message(0, s)
end
def __delayed_highlight_message(s)
__enqueue_multi_message(4, s)
end
def __delayed_highlight2_message(s)
__enqueue_multi_message(5, s)
end
def __delayed_highlight3_message(s)
__enqueue_multi_message(6, s)
end
def __delayed_user_message(s)
s = s.inspect unless s.is_a? String
__enqueue_multi_message(1, s)
end
def __delayed_serious_warning(s)
__enqueue_multi_message(3, s)
end
def __delayed_warning(s)
__enqueue_multi_message(2, s)
end
def __current_sched_ahead_time
#TODO: insert thread id and delta correctly
__system_thread_locals.get(:sonic_pi_spider_sched_ahead_time) ||
@system_state.get(__get_spider_time, 0, __current_thread_id, 0, __get_spider_beat, __get_spider_bpm, :sched_ahead_time,).val
end
def __schedule_delayed_blocks_and_messages!
delayed_messages = __system_thread_locals.get(:sonic_pi_local_spider_delayed_messages, [])
__system_thread_locals.set_local(:sonic_pi_local_spider_delayed_messages, [])
__system_thread_locals.set_local(:sonic_pi_local_spider_delayed_blocks, [])
if (delayed_messages && (!delayed_messages.empty?) && (!__system_thread_locals.get(:sonic_pi_spider_silent)))
msg = {:type => :multi_message,
:val => delayed_messages,
:jobid => __current_job_id,
:jobinfo => __current_job_info,
:runtime => __current_local_run_time.round(4),
:thread_name => __current_thread_name}
last_vt = __get_spider_time
sched_ahead_sync_t = last_vt + __current_sched_ahead_time
sleep_time = sched_ahead_sync_t.to_f - Time.now.to_f
Thread.new do
Kernel.sleep(sleep_time) if sleep_time > 0
__msg_queue.push msg
#We're now in sync with the sched_ahead time
end
end
end
def __enqueue_multi_message(m_type, m)
raise "Can only use __enqueue_multi_message in a job thread" unless __current_job_id
delayed_messages = __system_thread_locals.get :sonic_pi_local_spider_delayed_messages
delayed_messages << [m_type, m]
end
def __extract_linenum_of_error(e)
trace = e.backtrace
return -1 unless trace
l = trace.find {|line| line.include?("in __spider_eval")}
unless l
return -1
else
m = l.match(/.*:([0-9]+):/)
if m
return m[1].to_i
else
return -1
end
end
end
def __error(e, m=nil)
linenum = __extract_linenum_of_error(e)
if e.respond_to?(:detailed_message)
err_msg = e.detailed_message(highlight: false)
else
err_msg = e.message
end
info = __current_job_info
err_msg.gsub!(/for Runtime:[A-Za-z0-9:]+ /, '')
res = ""
w = info[:workspace]
if linenum != -1
# TODO: Remove this hack when we have projects
w = normalise_buffer_name(w)
w = "buffer " + w
# TODO: end of hack
res = res + "[#{w}, line #{linenum}]"
else
res = res + "[#{w}]"
end
res = res + " - " + m if m
res = res + "\n #{err_msg}"
__msg_queue.push({type: :error, val: res, backtrace: e.backtrace, jobid: __current_job_id, jobinfo: __current_job_info, linenum: linenum})
end
def __syntax_error(e, m=nil)
info = __current_job_info
_, linenum, err_msg = *e.message.match(/\A.*:([0-9]+): (.*)/)
linenum = linenum.to_i
error_line = info[:code].lines.to_a[linenum - info[:first_line_num]] || ""
res = ""
w = info[:workspace]
if linenum != -1
# TODO: Remove this hack when we have projects
w = normalise_buffer_name(w)
w = "buffer " + w
# TODO: end of hack
res = res + "[#{w}, line #{linenum}]"
else
res = res + "[#{w}]"
end
res = res + "\n" + m if m
res = res + "\n #{err_msg}"
__msg_queue.push({type: :syntax_error, val: res, backtrace: e.backtrace, jobid: __current_job_id, jobinfo: __current_job_info, error_line: error_line, linenum: linenum})
# _, line, message = *e.message.match(/\A.*:([0-9]+): (.*)/)
# error_line = ""
# if line
# line = line.to_i
# # TODO: Remove this hack when we have projects
# w = info[:workspace]
# w = normalise_buffer_name(w)
# w = "buffer #{w}"
# # TODO: end of hack
# err_msg = "[#{w}, line #{line}] \n #{message}"
# error_line = code.lines.to_a[line - firstline] || ""
# else
# line = -1
# err_msg = "\n #{e.message}"
# end
# __msg_queue.push({type: :job, jobid: id, action: :completed, jobinfo: info})
# __msg_queue.push({type: :syntax_error, val: err_msg, error_line: error_line , jobid: id , jobinfo: info, line: line})
# __msg_queue.push({type: :syntax_error, val: "yo no!", error_line: error_line , jobid: id , jobinfo: info, line: line})
# __info("Syntax error in run #{id}. Code ignored.")
end
def __current_thread_name
__system_thread_locals.get(:sonic_pi_local_spider_users_thread_name) || ""
end
def __current_job_id
__system_thread_locals.get :sonic_pi_spider_job_id
end
def __current_job_info
__system_thread_locals.get(:sonic_pi_spider_job_info) || {}
end
def __stop_start_cue_server!(stop)
@tau_api.start_stop_cue_server!(stop)
end
def __cue_server_internal!(internal)
@tau_api.cue_server_internal!(internal)
end
def __stop_job(j)
__info "Stopping run #{j}"
# Only allow a job to be stopped once
@@stop_job_mutex.synchronize do
if @user_jobs.running?(j)
job_subthreads_kill(j)
@life_hooks.killed(j)
@user_jobs.kill_job j
__msg_queue.push({type: :job, jobid: j, action: :killed})
end
end
end
def __stop_jobs
__info "Stopping all runs..."
@user_jobs.each_id do |id|
__stop_job id
end
# Flush OSC messages on Erlang scheduler
__osc_flush!
# Flush MIDI messages within sp_midi nif
__midi_flush!
# Force a GC collection now everything has stopped
GC.start
GC.compact if RUBY_VERSION >= "2.7.0"
end
def __midi_flush!
@tau_api.midi_flush!
end
def __midi_system_start(silent=false)
__info "Enabling incoming MIDI cues..." unless silent
__schedule_delayed_blocks_and_messages!
@tau_api.midi_system_start!
end
def __midi_system_stop(silent=false)
__info "Stopping incoming MIDI cues..." unless silent
__schedule_delayed_blocks_and_messages!
@tau_api.midi_system_stop!
end
def __set_global_timewarp!(time)
__info "Setting global timewarp to #{time}"
__schedule_delayed_blocks_and_messages!
set_mixer_global_timewarp!(time)
@tau_api.set_global_timewarp!(time)
end
def __update_midi_ins(ins)
end
def __update_midi_outs(outs)
end
def __osc_flush!
@tau_api.osc_flush!
end
def __stop_other_jobs
__info "Stopping all runs other than #{__current_job_id}..."
@user_jobs.each_id do |id|
__stop_job id unless id == __current_job_id
end
end
def __load_buffer(id)
id = id.to_s
raise "Aborting load: file name is blank" if id.empty?
path = File.expand_path("#{Paths.project_path}/#{id}.spi")
s = "# Welcome to Sonic Pi\n\n"
if File.exist? path
s = IO.read(path)
end
__replace_buffer(id, s)
end
def __replace_buffer(id, content)
id = id.to_s
content = content.to_s
__msg_queue.push({type: "replace-buffer", buffer_id: id, val: content, line: 0, index: 0, first_line: 0})
end
def __replace_buffer_idx(idx, content)
idx = idx.to_i
content = content.to_s
__msg_queue.push({type: "replace-buffer-idx", buffer_idx: idx, val: content, line: 0, index: 0, first_line: 0})
end
# def __run_buffer_idx(idx)
# idx = idx.to_i
# __msg_queue.push({type: "run-buffer-idx", buffer_idx: idx})
# end
def __add_completion(k, text, point_line_offset=0, point=0)
@snippets[k] = [text, point_line_offset, point]
end
def __snippet_completion?(text)
text = text.rstrip
@snippets.each do |k, v|
if text.end_with?(k) && ((text.length == k.length) || (text[((k.length * -1) - 1)] == " "))
return [k, v]
end
end
return nil
end
def __buffer_indent_lines(workspace_id, buf, start_line, finish_line, point_line, point_index)
__buffer_complete_snippet_or_indent_lines(workspace_id, buf, start_line, finish_line, point_line, point_index, false)
end
def __complete_snippet_or_indent_lines(buf, start_line, finish_line, point_line, point_index, complete_snippet=true)
orig_finish_line = finish_line
snippet_completion = false
buf = buf + "\n"
buf_lines = buf.lines.to_a
if (start_line == finish_line)
completion_line = buf_lines[start_line].to_s.rstrip
c = complete_snippet && __snippet_completion?(completion_line[0...point_index])
if c
snippet_completion = true
completion_key, val = *c
completion_text, point_line_offset, orig_new_point_index = *val
new_point_index = orig_new_point_index
orig_completion_lines = completion_text.lines.to_a
completion_line_pre = completion_line[0...(point_index - completion_key.length)]
completion_line_post = completion_line[point_index..-1]
completion_text = completion_line_pre + completion_text + completion_line_post + (completion_line_post.empty? ? "" : "\n")
completion_lines = completion_text.lines.to_a
point_line = point_line + point_line_offset
buf_lines = buf_lines[0...start_line] + completion_lines + buf_lines[(start_line + 1)..-1]
new_point_line_content = buf_lines[point_line].to_s
new_point_line_content_len = new_point_line_content.length
if point_line_offset == 0
if new_point_index < 0
new_point_index = [0, completion_line_pre.length + orig_completion_lines[0].length + new_point_index + 1].max
else
new_point_index += completion_line_pre.length
end
else
if new_point_index < 0
new_point_index = [0, (new_point_line_content_len + new_point_index)].max
else
new_point_index = [new_point_index, buf_lines[point_line].to_s.length].min
end
end
point_index = new_point_index
finish_line = start_line + completion_lines.size - 1
end
end
if (start_line <= point_line) && (point_line <= finish_line)
manipulate_point = true
# Calculate amount of whitespace at start of original line
orig_point_line = buf_lines[point_line]
orig_point_line_ws_len = orig_point_line[/\A */].size
dummy_lines = false
dummy_point_line = false
(start_line..finish_line).each do |line_idx|
b = buf_lines[line_idx]
if b.match(/\A\s*\Z/)
#line is just whitespace, put in a dummy line so it gets autoindented
buf_lines[line_idx] = "#___sonic_pi_dummy_line___\n"
dummy_lines = true
dummy_point_line = true if point_line == line_idx
end
end
else
manipulate_point = false
end
# Beautify buffer
beautiful = beautify_ruby_source(buf_lines.join)
# calculate amount of whitespace at start of beautified line
beautiful_lines = beautiful.lines.to_a
if manipulate_point
if dummy_point_line
# remove dummy line and extract leading whitespace
indented_dummy = beautiful_lines[point_line]
indented_dummy_whitespace = indented_dummy.match(/\A(\s*)/)[1]
beautiful_lines[point_line] = indented_dummy_whitespace + "\n"
point_index = indented_dummy_whitespace.size
else
new_point_line = beautiful_lines[point_line]
new_point_line_ws_len = new_point_line[/\A */].size
# shift index based on how much the line was indented so the
# cursor stays in the same place relative to the original line
# whilst ensuring it stays within line bounds
point_index = point_index + (new_point_line_ws_len - orig_point_line_ws_len)
point_index = new_point_line.size - 1 if point_index > new_point_line.size
point_index = orig_point_line_ws_len if point_index < orig_point_line_ws_len
end
if dummy_lines
# remove other dummy lines
(start_line..finish_line).each do |line_idx|
line = beautiful_lines[line_idx]
m = line.match(/\A(\s*)#___sonic_pi_dummy_line___/)
beautiful_lines[line_idx] = m[1] + "\n" if m
end
end
end
indented_lines = beautiful_lines[start_line..finish_line].join
finish_line = orig_finish_line if snippet_completion
return {val: indented_lines, start_line: start_line, finish_line: finish_line, point_line: point_line, point_index: point_index}
end
def __buffer_complete_snippet_or_indent_lines(workspace_id, buf, start_line, finish_line, point_line, point_index, complete_snippet=true)
id = workspace_id.to_s
res = __complete_snippet_or_indent_lines(buf, start_line, finish_line, point_line, point_index, true)
__msg_queue.push(res.merge({type: "replace-lines", buffer_id: id}))
end
def __buffer_newline_and_indent(workspace_id, buf, point_line, point_index, first_line)
id = workspace_id.to_s
lines = buf.lines.to_a
if lines == []
lines = ["\n"]
else
if lines[point_line]
lines[point_line].insert(point_index , "\n")
else
lines[point_line] = "\n"
end
end
buf = lines.join
__buffer_beautify(id, buf, point_line + 1, 0, first_line)
end
def __toggle_comment(workspace_id, buf, start_line, finish_line, point_line, point_index)
id = workspace_id.to_s
buf_lines = buf.lines.to_a
# Check to see if we need to comment or uncomment:
# If all lines in selection start with a # (after whitespace)
# or are whitespace we need to uncomment.
# Otherwise comment
lines = buf_lines[start_line..finish_line]
if(lines.all?{|el| el.match(/^\s*#.*?/) || el.match(/^\s*$/)})
# need to uncomment ##| style comments
lines = lines.map do |l|
m = l.match(/^(\s*)(#(#\|)?\s?)(.*)/)
if m
m[1] + m[4] + "\n"
else
l
end
end
else
# need to comment
# find shortest amount of whitespace at beginning of line
ws = Float::INFINITY
lines.each do |l|
m = l.match(/^(\s*).*/)
ws = m[1].size if m && m[1].size < ws unless l.match(/^(\s*)$/)
end
lines.each do |l|
l[ws] = "##| #{l[ws]}" unless l.match(/^(\s*)$/)
end
end
__msg_queue.push({type: "replace-lines", buffer_id: id, val: lines.join, start_line: start_line, finish_line: finish_line, point_line: point_line, point_index: point_index})
end
def __buffer_beautify(id, buf, line, index, first_line)
id = id.to_s
buf = buf + "\n"
buf_lines = buf.lines.to_a
buf = buf_lines.inspect
buf_lines = buf_lines.map! do |l|
if l.match(/^\s*$/)
"_____sonic_pi_tmp_insert_____\n"
else
l
end
end
buf = buf_lines.join
## ensure point isn't beyond buffer
max_buf_idx = buf_lines.size - 1
line = max_buf_idx if line > max_buf_idx
# Calculate amount of whitespace at start of original line
prev_line = buf_lines[line]
prev_ws_len = prev_line[/\A */].size
# Beautify buffer
beautiful = beautify_ruby_source(buf)
# calculate amount of whitespace at start of beautified line
beautiful_lines = beautiful.lines.to_a
beautiful_len = beautiful_lines.size
beautiful_lines.map! {|l| l.slice! "_____sonic_pi_tmp_insert_____" ; l}
post_line = beautiful_lines[line]
post_ws_len = post_line[/\A */].size
beautiful = beautiful_lines.join
# shift index based on how much the line was indented so the
# cursor stays in the same place relative to the original line
# whilst ensuring it stays within line bounds
index = index + (post_ws_len - prev_ws_len)
index = post_line.size - 1 if index > post_line.size
# adjust line number based on how many lines were removed as a
# result of the whitespace stripping
post_lstrip_len = beautiful.lines.to_a.size
line = line - (beautiful_len - post_lstrip_len)
line = 0 if line < 0
beautiful.chomp!
__msg_queue.push({type: "replace-buffer", buffer_id: id, val: beautiful, line: line, index: index, first_line: first_line})
end
def __save_buffer(id, content)
@save_queue << [id, content]
end
def __disable_update_checker
@settings.set(:no_update_checking, true)
end
def __enable_update_checker
@settings.del(:no_update_checking)
end
def __set_default_system_thread_locals!
# Give new thread a new subthread mutex
__system_thread_locals.set_local :sonic_pi_local_spider_subthread_mutex, Mutex.new
__system_thread_locals.set_local :sonic_pi_local_spider_subthread_empty, Promise.new
# Give new thread a new no_kill mutex This reduces contention
# over the alternative of a global no_kill mutex. Killing a Run
# then essentially turns into waiting for each no_kill mutext for
# every sub-in_thread before killing them.
__system_thread_locals.set_local :sonic_pi_local_spider_no_kill_mutex, Monitor.new
# Reset subthreads thread local to the empty set. This shouldn't
# be inherited from the parent thread.
__system_thread_locals.set_local :sonic_pi_local_spider_subthreads, Set.new
__system_thread_locals.set_local :sonic_pi_local_spider_delayed_blocks, []
__system_thread_locals.set_local :sonic_pi_local_spider_delayed_messages, []
__system_thread_locals.set_local :sonic_pi_local_control_deltas, {}
__system_thread_locals.set_local(:sonic_pi_spider_num_threads_spawned, 0)
__system_thread_locals.set_local(:sonic_pi_spider_thread_delta, 0)
end
def __set_default_user_thread_locals!
__thread_locals.set :sonic_pi_spider_arg_bpm_scaling, true
__thread_locals.set :sonic_pi_spider_new_thread_random_gen_idx, 0
__system_thread_locals.set(:sonic_pi_spider_thread_priority, 0)
end
def __spider_eval(code, info={})
now = Time.now.freeze
# skip __nosave lines for error reporting
firstline = 1
firstline -= code.lines.to_a.take_while{|l| l.include? "#__nosave__"}.count
start_t_prom = Promise.new
info[:workspace] = 'eval' unless info[:workspace]
info[:workspace].freeze
info[:code] = code.clone
info[:code].freeze
info[:first_line_num] = firstline
info.freeze
silent = info.fetch(:silent, false)
job_in_thread = nil
id = @job_counter.next
job = Thread.new do
Thread.current.priority = 20
begin
num_running_jobs = register_job!(id, Thread.current)
__system_thread_locals.set_local :sonic_pi_local_thread_group, "job-#{id}"
__system_thread_locals.set_local :sonic_pi_spider_thread_id_path, ThreadId.new(id)
__system_thread_locals.set_local :sonic_pi_spider_num_threads_spawned, 0
__system_thread_locals.set :sonic_pi_spider_job_id, id
__system_thread_locals.set :sonic_pi_spider_silent, silent
__system_thread_locals.set :sonic_pi_spider_job_info, info
__set_default_system_thread_locals!
__set_default_user_thread_locals!
__msg_queue.push({type: :job, jobid: id, action: :start, jobinfo: info})
@life_hooks.init(id, {:thread => Thread.current})
## fix this for link
__init_spider_time_and_beat!
if num_running_jobs == 1
# Force a GC collection before we start making music!
GC.start
end
__info "Starting run #{id}" unless silent
code = PreParser.preparse(code, SonicPi::Lang::Core.vec_fns)
job_in_thread = __in_thread seed: 0 do
eval(code, nil, info[:workspace], firstline)
end
start_t_prom.deliver! now
__schedule_delayed_blocks_and_messages!
rescue Stop => e
__no_kill_block do
__info("Stopping Run #{id}") unless silent
end
rescue SyntaxError => e
__no_kill_block do
__syntax_error(e)
end
rescue Exception => e
__schedule_delayed_blocks_and_messages!
__no_kill_block do
__info("Aborted Run #{id}")
__error(e)
__msg_queue.push({type: :job, jobid: id, action: :completed, jobinfo: info})
end
end
end
@user_jobs.add_job(id, job, info)
Thread.new do
Thread.current.priority = -10
__system_thread_locals.set_local(:sonic_pi_local_thread_group, "job-#{id}-GC")
job.join
__system_thread_locals(job_in_thread).get(:sonic_pi_local_spider_subthread_empty).get if job_in_thread
# wait until all synths are dead
@life_hooks.completed(id)
start_t = start_t_prom.get
@life_hooks.exit(id, {:start_t => start_t})
deregister_job_and_return_subthreads(id)
@user_jobs.job_completed(id)
Kernel.sleep default_sched_ahead_time
__info "Completed run #{id}" unless silent
unless @user_jobs.any_jobs_running?
__info "All runs completed" unless silent
__msg_queue.push({type: :all_jobs_completed})
@life_hooks.all_completed(silent)
end