/
runtime.scm
3672 lines (3127 loc) · 156 KB
/
runtime.scm
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
;;; Copyright 2009-2011 Google, All Rights reserved
;;; Copyright 2011-2021 MIT, All rights reserved
;;; Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt
;;; These are the functions that define the YAIL (Young Android Intermediate Language) runtime They
;;; provide an abstraction of the Kawa interface to Java and the Simple component model used by
;;; Young Android.
;;; MACROS library
;;;
;;; Note that in some cases we distinguish the cases when we are evaluating within an externally
;;; connected REPL and code that's loaded and run within ordinary app initialization. There
;;; are some timing considerations that account for the different processing but we should endeavor
;;; to minimize the differences when we can and abstract them when we can't eliminate them.
;;; TODO(markf): figure out how to enable top-level property setting and getting. The problem is that
;;; the assignment of component values to component names isn't done until after the run() call in $define()
;;; but the top-level forms are evaluated in that run() function.
;;;
;;; also see *debug-form* below
(define *debug* #f)
(define *this-is-the-repl* #f)
;;; If set we avoid calling to java components such as Form
;;; because we are running in a test environment that is not
;;; inside a phone, so components are not defined
(define *testing* #f)
(define (android-log message)
(when *debug* (android.util.Log:i "YAIL" message)))
;;;; add-component
(define-constant simple-component-package-name "com.google.appinventor.components.runtime")
;;; (gen-simple-component-type Label)
;;; ==> "com.google.appinventor.components.runtime.Label"
(define-syntax gen-simple-component-type
(lambda (stx)
(syntax-case stx ()
((_ short-component-type-name)
(datum->syntax-object stx
(string-append ""
""
(symbol->string #'short-component-type-name)))))))
;;; (add-component Screen1 Label Label1)
;;; ==>
;;; (define Label1 :: "com.google.appinventor.components.runtime.Label" #!null)
(define-syntax add-component
;; TODO(opensource): It's quite possible that we can now dispense with defining the <component-name>
;; variable/field entirely, since I believe that it is no longer used by anything. If that's true
;; then I think that add-component can just become a regular procedure rather than a macro if we
;; call it with an init-property lambda rather than just an init-property form
(syntax-rules ()
((_ container component-type component-name)
(begin
(define component-name :: (gen-simple-component-type component-type) #!null)
(if *this-is-the-repl*
(add-component-within-repl 'container
(gen-simple-component-type component-type)
'component-name
#f)
(add-to-components 'container
(gen-simple-component-type component-type)
'component-name
#f))))
((_ container component-type component-name init-property-form ...)
(begin
(define component-name :: (gen-simple-component-type component-type) #!null)
(if *this-is-the-repl*
(add-component-within-repl 'container
(gen-simple-component-type component-type)
'component-name
(lambda () init-property-form ...))
(add-to-components 'container
(gen-simple-component-type component-type)
'component-name
(lambda () init-property-form ...)))))))
;; The following code will create a new instance of a component, bind
;; it to its name, then create and register a thunk to set any
;; non-default properties entered in the UI designer (provided here
;; via the init-props-thunk) the thunk will also copy any properties
;; from its old instance to the new instance (if there was an old
;; instance bound to its name). That thunk gets executed when
;; call-Initialize-of-components is called, which is done by the code
;; sent from the the blocks editor
(define (add-component-within-repl container-name component-type component-name init-props-thunk)
(define-alias SimpleContainer <com.google.appinventor.components.runtime.ComponentContainer>)
(define-alias SimplePropertyUtil <com.google.appinventor.components.runtime.util.PropertyUtil>)
(let* ((container :: SimpleContainer (lookup-in-current-form-environment container-name))
(existing-component (lookup-in-current-form-environment component-name))
(component-to-add (make component-type container)))
(add-to-current-form-environment component-name component-to-add)
(add-init-thunk component-name
(lambda ()
(when init-props-thunk (init-props-thunk))
(when existing-component
(android-log (format #f "Copying component properties for ~A" component-name))
(SimplePropertyUtil:copyComponentProperties existing-component component-to-add))))))
(define-alias SimpleForm <com.google.appinventor.components.runtime.Form>)
(define-alias TypeUtil <com.google.appinventor.components.runtime.util.TypeUtil>)
(define (call-Initialize-of-components . component-names)
;; Do any inherent/implied initializations
(for-each (lambda (component-name)
(let ((init-thunk (get-init-thunk component-name)))
(when init-thunk (init-thunk))))
component-names)
;; Do the explicit component initialization methods and events
(for-each (lambda (component-name)
(*:callInitialize (as SimpleForm *this-form*)
(lookup-in-current-form-environment component-name)))
component-names))
(define *init-thunk-environment* (gnu.mapping.Environment:make 'init-thunk-environment))
(define (add-init-thunk component-name thunk)
(gnu.mapping.Environment:put *init-thunk-environment* component-name thunk))
(define (get-init-thunk component-name)
(and (gnu.mapping.Environment:isBound *init-thunk-environment* component-name)
(gnu.mapping.Environment:get *init-thunk-environment* component-name)))
(define (clear-init-thunks)
(set! *init-thunk-environment* (gnu.mapping.Environment:make 'init-thunk-environment)))
;;; (get-component comp1)
;;; ==> (lookup-in-current-form-environment 'comp1)
(define-syntax get-component
(syntax-rules ()
((_ component-name)
(lookup-in-current-form-environment 'component-name))))
;;; (get-all-components comptype)
;;; ==> (filter-type-in-current-form-environment 'comptype)
(define-syntax get-all-components
(syntax-rules ()
((_ component-type)
(filter-type-in-current-form-environment 'component-type))))
;; We'd like to do something like the following which could re-use existing components
;; and thereore avoid overriding property changes that the user might have made via
;; the REPL but it just didn't work. Some components just wouldn't show up. It seemed
;; to be somewhat related to the use of HVArrangements (and sub-forms) but I couldn't really
;; pin it down. Note though, that even if the below did work we would have to deal with
;; deleting and then potentially reusing component names. Our working appoach of reconstructing
;; components every time nicely sidesteps that issue.
;;
;; (define (add-component-within-repl container-name component-type component-name init-thunk)
;; (define-alias SimpleView <com.google.appinventor.components.runtime.AndroidViewComponent>)
;; (define-alias SimpleContainer <com.google.appinventor.components.runtime.ComponentContainer>)
;; (let ((container :: SimpleContainer (lookup-in-current-form-environment container-name))
;; (existing-component (lookup-in-current-form-environment component-name)))
;; (if (and existing-component (instance? existing-component SimpleView))
;; (container:$add ((as SimpleView existing-component):getView))
;; ;; We're creating a new component. The components constructor will take care of
;; ;; adding itself to it's container.
;; (let ((component-to-add (make component-type container)))
;; (add-to-current-form-environment component-name component-to-add)
;; (when init-thunk (init-thunk))))))
;;; Component names, global variables, event handlers and procedure names are global:
;;; get-property, set-property!, call, define-event and def all explicitly
;;; reference the form environment.
;;;
;;; NOTE: As a convenience within a direct REPL you can add the form
;;; environment as a parent to the REPL environment and directly
;;; reference variable, procedures, components, etc without doing an
;;; explicit get-var or set-var! For example you can do something
;;; like the following:
;;;
;;; #|kawa:1|# (require com.google.youngandroid.runtime)
;;; #!null
;;; #|kawa:2|# (define env (*:.form-environment *this-form*))
;;; #|kawa:3|# (define-alias KawaEnvironment gnu.mapping.Environment)
;;; #|kawa:4|# (*:addParent (KawaEnvironment:getCurrent) env)
;;; #|kawa:5|# Button1
;;; com.google.appinventor.components.runtime.Button@44f2f230
;;;
;;; We do something like the above in the setup-repl-environment procedure.
;;; This creates a better runtime error message in the case where there is
;;; a problem, and the component cannot be found.
(define (lookup-component comp-name)
;; we explicitly pass #f as the default, even though that's the standard default
(let ((verified (lookup-in-current-form-environment comp-name #f)))
(if verified
verified
*non-coercible-value*)))
;;; Call a component's property setter method with argument coercion
;;; Ex: (set-and-coerce-property! 'Button3 'FontSize 14 'number)
;;; Note: see also %set-expanded-property below
(define (set-and-coerce-property! component prop-sym property-value property-type)
(let ((component (coerce-to-component-and-verify component)))
(%set-and-coerce-property! component prop-sym property-value property-type)))
;;; (get-property 'Label1 'Text)
(define (get-property component prop-name)
(let ((component (coerce-to-component-and-verify component)))
(sanitize-return-value component prop-name (invoke component prop-name))))
(define (coerce-to-component-and-verify possible-component)
(let ((component (coerce-to-component possible-component)))
(if (not (instance? component com.google.appinventor.components.runtime.Component))
(signal-runtime-error
(string-append "Cannot find the component: "
(get-display-representation possible-component))
"Problem with application")
component)))
(define (get-property-and-check possible-component component-type prop-name)
(let ((component (coerce-to-component-of-type possible-component component-type)))
(if (not (instance? component com.google.appinventor.components.runtime.Component))
(signal-runtime-error
(format #f "Property getter was expecting a ~A component but got a ~A instead."
component-type
(*:getSimpleName (*:getClass possible-component)))
"Problem with application")
(sanitize-return-value component prop-name (invoke component prop-name)))))
(define (set-and-coerce-property-and-check! possible-component comp-type prop-sym property-value property-type)
(let ((component (coerce-to-component-of-type possible-component comp-type)))
(if (not (instance? component com.google.appinventor.components.runtime.Component))
(signal-runtime-error
(format #f "Property setter was expecting a ~A component but got a ~A instead."
comp-type
(*:getSimpleName (*:getClass possible-component)))
"Problem with application")
(%set-and-coerce-property! component prop-sym property-value property-type))))
;;; Global variables
;;; (get-var var1)
;;; ==> (lookup-global-var-in-current-form-environment 'var1)
(define-syntax get-var
(syntax-rules ()
((_ var-name)
;; unbound global variables default to *the-null-value*
(lookup-global-var-in-current-form-environment 'var-name *the-null-value*))))
;;; (set-var! var1 10)
;;; ==> (add-global-var-to-current-form-environment 'var1 10)
;;; note that set-var! will create the binding if it doesn't exist
(define-syntax set-var!
(syntax-rules ()
((_ var-name value)
(add-global-var-to-current-form-environment 'var-name value))))
;;; Lexical variables
;;; A lexical variable is looked up in the current environment
;;; following Kawa's ordinary rules.
(define-syntax lexical-value
(syntax-rules ()
((_ var-name)
(if (instance? var-name <java.lang.Package>)
(signal-runtime-error
(string-append "The variable " (get-display-representation `var-name)
" is not bound in the current context")
"Unbound Variable")
var-name))))
;;; Lexical Set Variable
;;; (set-lexical! var 10)
(define-syntax set-lexical!
(syntax-rules ()
((_ var value)
(set! var value))))
;;; We can't use Kawa's and/or directly here, because we want to enforce that
;;; the argument types are booleans. So we delay the arguments and check the types
;;; as we force them, left to right.
(define-syntax and-delayed
(syntax-rules ()
((_ conjunct ...)
(process-and-delayed (lambda () conjunct) ...))))
(define-syntax or-delayed
(syntax-rules ()
((_ disjunct ...)
(process-or-delayed (lambda () disjunct) ...))))
;;;; define-form
;; Note: This definition cannot refer directly to lexically enclosing variable names because
;; of Kawa's opinions about compiling it as a module. However, you can refer to them
;; as (name:get) if the reference is for the Repl. Otherwise you must use the form-environment.
(define-syntax define-form
(syntax-rules ()
((_ class-name form-name)
(define-form-internal class-name form-name 'com.google.appinventor.components.runtime.Form #f #t))
((_ class-name form-name classic-theme)
(define-form-internal class-name form-name 'com.google.appinventor.components.runtime.Form #f classic-theme))))
(define-syntax define-repl-form
(syntax-rules ()
((_ class-name form-name)
(define-form-internal class-name form-name 'com.google.appinventor.components.runtime.ReplForm #t #f))))
(define-syntax define-form-internal
(syntax-rules ()
((_ class-name form-name subclass-name isrepl classic-theme)
(begin
(module-extends subclass-name)
(module-name class-name)
(module-static form-name)
(require <com.google.youngandroid.runtime>)
(define (get-simple-name object)
(*:getSimpleName (*:getClass object)))
(define (onCreate icicle :: android.os.Bundle) :: void
;(android.util.Log:i "AppInventorCompatActivity" "in YAIL oncreate")
(com.google.appinventor.components.runtime.AppInventorCompatActivity:setClassicModeFromYail classic-theme)
(invoke-special subclass-name (this) 'onCreate icicle))
(define *debug-form* #f)
(define (android-log-form message)
(when *debug-form* (android.util.Log:i "YAIL" message)))
;; An environment containing the form's components, functions and event handlers
;; We're using Kawa Environments here mostly as just a convenient dictionary implementation.
;; As noted near the top of this file it is useful for attaching the environment to the REPL.
(define form-environment :: gnu.mapping.Environment
(gnu.mapping.Environment:make (symbol->string 'form-name)))
(define (add-to-form-environment name :: gnu.mapping.Symbol object)
(android-log-form (format #f "Adding ~A to env ~A with value ~A" name form-environment object))
(gnu.mapping.Environment:put form-environment name object))
(define (lookup-in-form-environment name :: gnu.mapping.Symbol #!optional (default-value #f))
(if (and (not (eq? form-environment #!null))
(gnu.mapping.Environment:isBound form-environment name))
(gnu.mapping.Environment:get form-environment name)
default-value))
(define (is-bound-in-form-environment name :: gnu.mapping.Symbol)
(gnu.mapping.Environment:isBound form-environment name))
(define global-var-environment :: gnu.mapping.Environment
(gnu.mapping.Environment:make (string-append
(symbol->string 'form-name)
"-global-vars")))
(define (add-to-global-var-environment name :: gnu.mapping.Symbol object)
(android-log-form (format #f "Adding ~A to env ~A with value ~A" name global-var-environment object))
(gnu.mapping.Environment:put global-var-environment name object))
;; Simple wants there to be a variable named the same as the class. It will
;; later get initialized to an instance of the class.
(define form-name :: class-name #!null)
;; The REPL would like to know what the current name of the form is
(define form-name-symbol :: gnu.mapping.Symbol 'form-name)
;; List of events to get registered in the $define method.
(define events-to-register :: gnu.lists.LList '())
;; List of components to get created in the $define method.
;; Each component item is the component is represented as a list
;; (container-name component-type component-name init-thunk)
(define components-to-create :: gnu.lists.LList '())
;; A call to add-to-events is generated by define-event to add the event to
;; events-to-register
(define (add-to-events component-name event-name)
(set! events-to-register
(cons (cons component-name event-name)
events-to-register)))
;; A call to add-to-components is generated by add-component to add the component to
;; components-to-create
(define (add-to-components container-name component-type component-name init-thunk)
(set! components-to-create
(cons (list container-name component-type component-name init-thunk)
components-to-create)))
;; List of global variables to be initialized in the $define method.
(define global-vars-to-create :: gnu.lists.LList '())
;; Add to the list of global variable to create.
(define (add-to-global-vars var val-thunk)
(set! global-vars-to-create
(cons (list var val-thunk)
global-vars-to-create)))
;; List of expressions to evaluate after the form has been created.
;; Used for setting properties
(define form-do-after-creation :: gnu.lists.LList '())
(define (add-to-form-do-after-creation thunk)
(set! form-do-after-creation
(cons thunk
form-do-after-creation)))
(define (send-error error)
(com.google.appinventor.components.runtime.util.RetValManager:sendError error))
(define (process-exception ex)
(define-alias YailRuntimeError <com.google.appinventor.components.runtime.errors.YailRuntimeError>)
;; The call below is a no-op unless we are in the wireless repl
;; Commented out -- we only send reports from the setting menu choice
;; (com.google.appinventor.components.runtime.ReplApplication:reportError ex)
(if isrepl
(when ((this):toastAllowed)
(let ((message (if (instance? ex java.lang.Error) (ex:toString) (ex:getMessage))))
(send-error message)
((android.widget.Toast:makeText (this) message 5):show)))
(com.google.appinventor.components.runtime.util.RuntimeErrorAlert:alert
(this)
(ex:getMessage)
(if (instance? ex YailRuntimeError) ((as YailRuntimeError ex):getErrorType) "Runtime Error")
"End Application")))
;; For the HandlesEventDispatching interface
(define (dispatchEvent componentObject :: com.google.appinventor.components.runtime.Component
registeredComponentName :: java.lang.String
eventName :: java.lang.String
args :: java.lang.Object[]) :: boolean
;; Check that the component object that generated the event
;; matches the component object associated with the
;; component name that registered the event. This is
;; necessary, in part, due to the late binding that we want
;; for event handlers and component names.
(let ((registeredObject (string->symbol registeredComponentName)))
(if (is-bound-in-form-environment registeredObject)
(if (eq? (lookup-in-form-environment registeredObject) componentObject)
(let ((handler (lookup-handler registeredComponentName eventName)))
;; Note: This try-catch was originally part of the
;; generated handler from define-event. It was moved
;; here because Kawa seems be unable to eval a
;; try-catch without compiling it and we can't support
;; compilation in anything (e.g. define-event) that
;; might get sent to the REPL!
(try-catch
(begin
(apply handler (gnu.lists.LList:makeList args 0))
#t)
(exception com.google.appinventor.components.runtime.errors.StopBlocksExecution
#f)
;; PermissionException should be caught by a permissions-aware component and
;; handled correctly at the point it is caught. However, older extensions
;; might not be updated yet for SDK 23's dangerous permissions model, so if
;; an exception bubbles all the way up to here we can still catch and report
;; it. However, the best context we have for the PermissionDenied event is
;; that it occurred in the just-exited event handler code.
(exception com.google.appinventor.components.runtime.errors.PermissionException
(begin
(exception:printStackTrace)
;; Test to see if the event we are handling is the
;; PermissionDenied of the current form. If so, then we will
;; need to avoid re-invoking PermissionDenied.
(if (and (eq? (this) componentObject)
(equal? eventName "PermissionNeeded"))
;; Error is occurring in the PermissionDenied handler, so we
;; use the more general exception handler to prevent going
;; into an infinite loop.
(process-exception exception)
((this):PermissionDenied componentObject eventName
(exception:getPermissionNeeded)))
#f))
(exception java.lang.Throwable
(begin
(android-log-form (exception:getMessage))
;;; Comment out the line below to inhibit a stack trace on a RunTimeError
(exception:printStackTrace)
(process-exception exception)
#f))))
#f)
;; else unregister event for registeredComponentName
(begin
(com.google.appinventor.components.runtime.EventDispatcher:unregisterEventForDelegation
(as com.google.appinventor.components.runtime.HandlesEventDispatching (this))
registeredComponentName eventName)
#f))))
(define (dispatchGenericEvent componentObject :: com.google.appinventor.components.runtime.Component
eventName :: java.lang.String
notAlreadyHandled :: boolean
args :: java.lang.Object[]) :: void
; My first attempt was to use the gen-generic-event-name
; here, but unfortunately the version of Kawa that we use
; does not correctly import functions from the runtime module
; into the form. The macro expands, but the symbol-append
; function is not found. Below is an "optimization" that
; concatenates the strings first and then calls
; string->symbol, which is effectively the same thing. Most
; of the logic then follows that of dispatchEvent above.
(let* ((handler-symbol (string->symbol (string-append "any$" (get-simple-name componentObject) "$" eventName)))
(handler (lookup-in-form-environment handler-symbol)))
(if handler
(try-catch
(begin
(apply handler (cons componentObject (cons notAlreadyHandled (gnu.lists.LList:makeList args 0))))
#t)
(exception com.google.appinventor.components.runtime.errors.StopBlocksExecution
#f)
(exception com.google.appinventor.components.runtime.errors.PermissionException
(begin
(exception:printStackTrace)
;; Test to see if the event we are handling is the
;; PermissionDenied of the current form. If so, then we will
;; need to avoid re-invoking PermissionDenied.
(if (and (eq? (this) componentObject)
(equal? eventName "PermissionNeeded"))
;; Error is occurring in the PermissionDenied handler, so we
;; use the more general exception handler to prevent going
;; into an infinite loop.
(process-exception exception)
((this):PermissionDenied componentObject eventName
(exception:getPermissionNeeded)))
#f))
(exception java.lang.Throwable
(begin
(android-log-form (exception:getMessage))
;;; Comment out the line below to inhibit a stack trace on a RunTimeError
(exception:printStackTrace)
(process-exception exception)
#f))))))
(define (lookup-handler componentName eventName)
(lookup-in-form-environment
(string->symbol
(com.google.appinventor.components.runtime.EventDispatcher:makeFullEventName
componentName eventName))))
;; This defines the Simple Form's abstract $define method. The Simple Form
;; implementation will call this to cause initialization.
(define ($define) :: void
;; Register the events with the Simple event dispatcher
(define (register-events events)
(define-alias SimpleEventDispatcher
<com.google.appinventor.components.runtime.EventDispatcher>)
(for-each (lambda (event-info)
;; Tell the Simple event dispatcher to delegate dispatching of this event to this class
(SimpleEventDispatcher:registerEventForDelegation
(as com.google.appinventor.components.runtime.HandlesEventDispatching (this))
(car event-info)
(cdr event-info)))
events))
;; Add the initial global variable bindings to the global variable environment
(define (init-global-variables var-val-pairs)
;; (android-log-form (format #f "initializing global vars: ~A" var-val-pairs))
(for-each (lambda (var-val)
(let ((var (car var-val))
(val-thunk (cadr var-val)))
(add-to-global-var-environment var (val-thunk))))
var-val-pairs))
;; Create each component and set its corresponding field
(define (create-components component-descriptors)
(for-each (lambda (component-info)
(let ((component-name (caddr component-info))
(init-thunk (cadddr component-info))
(component-type (cadr component-info))
(component-container (lookup-in-form-environment (car component-info))))
;; (android-log-form
;; (format #f "making component: ~A of type: ~A with container: ~A (container-name: ~A)"
;; component-name component-type component-container (car component-info)))
(let ((component-object (make component-type component-container)))
;; Construct the component and assign it to its corresponding field
(set! (field (this) component-name) component-object)
;; Add the mapping from component name -> component object to the
;; form-environment
(add-to-form-environment component-name component-object))))
component-descriptors))
;; Initialize all of the components
(define (init-components component-descriptors)
;; First all the init-thunks
(for-each (lambda (component-info)
(let ((component-name (caddr component-info))
(init-thunk (cadddr component-info)))
;; Execute the component's init-thunk.
(when init-thunk (init-thunk))))
component-descriptors)
;; Now the Initialize methods
(for-each (lambda (component-info)
(let ((component-name (caddr component-info))
(init-thunk (cadddr component-info)))
;; Invoke the component's Initialize() method
((this):callInitialize (field (this) component-name))))
component-descriptors))
;; A helper function
(define (symbol-append . symbols)
(string->symbol
(apply string-append
(map symbol->string symbols))))
;; Hack. There's a bug in Kawa in their dynamic method lookup (done in
;; the call to make in init-components, above) which throws an NPE if the language
;; is not set.
(gnu.expr.Language:setDefaults (kawa.standard.Scheme:getInstance))
;; Note (halabelson); I wanted to simply do this, rather than install the do-after-creation mechanism.
;; But it doesn't work to do this here, because the form environment is null at this point.
;;(add-to-form-environment 'form-name (this))
;; Another hack. The run() method is defined internally by Kawa to eval the
;; top-level forms but it's not getting properly executed, so we force it here.
(try-catch
(invoke (this) 'run)
(exception java.lang.Exception
(android-log-form (exception:getMessage))
(process-exception exception)))
(set! form-name (this))
;; add a mapping from the form name to the Form into the form-environment
(add-to-form-environment 'form-name (this))
(register-events events-to-register)
(try-catch
(let ((components (reverse components-to-create)))
;; We need this binding because the block parser sends this symbol
;; to represent an uninitialized value
;; We have to explicity write #!null here, rather than
;; *the-null-value* because that external defintion hasn't happened yet
(add-to-global-vars '*the-null-value* (lambda () #!null))
;; The Form has been created (we're in its code), so we should run
;; do-after-form-creation thunks now. This is important because we
;; need the theme set before creating components.
(for-each force (reverse form-do-after-creation))
(create-components components)
;; These next three clauses need to be in this order:
;; Properties can't be set until after the global variables are
;; assigned. And some properties can't be set after the components are
;; created: For example, the form's layout can't be changed after the
;; components have been installed. (This gives an error.)
(init-global-variables (reverse global-vars-to-create))
;; Now that all the components are constructed we can call
;; their init-thunk and their Initialize methods. We need
;; to do this after all the construction steps because the
;; init-thunk (i.e. design-time initializations) and
;; Initialize methods may contain references to other
;; components.
(init-components components))
(exception com.google.appinventor.components.runtime.errors.YailRuntimeError
;;(android-log-form "Caught exception in define-form ")
(process-exception exception))))))))
;;;; define-event
;;; (symbol-append foo bar)
;;; ==> foobar
(define (symbol-append . symbols)
(string->symbol
(apply string-append
(map symbol->string symbols))))
;;; (gen-event-name Button2 Click)
;;; ==> Button2$Click
(define-syntax gen-event-name
(lambda (stx)
(syntax-case stx ()
((_ component-name event-name)
(datum->syntax-object stx #'(symbol-append component-name '$ event-name))))))
;;; (gen-generic-event-name Button Click)
;;; ==> any$Button$Click
(define-syntax gen-generic-event-name
(lambda (stx)
(syntax-case stx ()
((_ component-type event-name)
(datum->syntax-object stx #'(symbol-append 'any$ component-type '$ event-name))))))
;;; define-event-helper looks suspiciously like define, but we need it because
;;; if we use define directly in the define-event definition below, the call
;;; to gen-event-name makes it look like we're just defining a function called
;;; 'gen-event-name'
;;; Note that Joe Marshall came up with a more elegant way to deal with this
;;; problem using a continuation passing style macro definition but for this
;;; particular case it seemed a little easier to understand by using a helper
;;; like this. If we end up with a lot of these helpers then it might be better
;;; generalize with the CPS approach.
(define-syntax define-event-helper
(syntax-rules ()
((_ event-func-name (arg ...) (expr ...))
;; Note that if we expand directly into a lambda expression below we expose
;; an error in the Kawa compiler and the function doesn't get defined properly.
;; I think that it ends up not becoming a public method in the generated class.
(begin
(define (event-func-name arg ...)
;; The arguments to the handler come from the components and
;; need to be sanitized before we can operate on them in Yail. See
;; the comments on sanitize below
(let ((arg (sanitize-component-data arg)) ...)
expr ...))
(if *this-is-the-repl*
(add-to-current-form-environment 'event-func-name event-func-name)
(add-to-form-environment 'event-func-name event-func-name))))))
;;; We make the compiler generate the calling code using the identifier *list-for-runtime* rather
;;; than list. Otherwise, the call-yail-primitive code would break if it were a line in the body
;;; of a procedure with a parameter named "list".
(define-syntax *list-for-runtime*
(syntax-rules ()
((_ args ...)
(list args ...))))
;;; (define-event Button2 Click (arg1 ...) ...)
;;; ==>
;;; (define (Button2$Click arg1 ...) ...))
;;;
;;; Note that we could maybe just use the following, though it is unhygenic (and
;;; the Kawa doc says something about defmacro/define-macro not allowing the "use
;;; of the macro in the same compilation as the definition", which I'm not sure
;;; applies if the definition is in a different file as the use:
;;; (define-macro define-event
;;; (lambda (component-name event-name args . body)
;;; `(define ,(symbol-append comp-name event-name) (lambda (,@args) ,@body))))
(define-syntax define-event
(lambda (stx)
(syntax-case stx ()
((_ component-name event-name args . body)
#`(begin
(define-event-helper ,(gen-event-name #`component-name #`event-name) args body)
;; TODO(markf): consider breaking this out as a procedure
;; that is parallel to add-to-current-form-environment,
;; which would make define-event look more like def, which
;; might be easier for people coming back to the code later.
(if *this-is-the-repl*
(com.google.appinventor.components.runtime.EventDispatcher:registerEventForDelegation
(as com.google.appinventor.components.runtime.HandlesEventDispatching *this-form*)
'component-name
'event-name)
;; If it's not the REPL the form's $define() method will do the registration
(add-to-events 'component-name 'event-name)))))))
(define-syntax define-generic-event
(lambda (stx)
(syntax-case stx ()
((_ component-type event-name args . body)
#`(begin
(define-event-helper ,(gen-generic-event-name #`component-type #`event-name) args body))))))
;;;; def
;;; Def here is putting things (1) in the form environment; (2) in a
;;; list of vars to put into the environment when the form is created.
;;; Note that we have to worry about the case where a procedure P
;;; initially defined from codeblocks get redefined from the
;;; repl. If we have another procedure Q that calls P, we have
;;; to make sure that Q will see the new binding for P. Currentl,
;;; "call" is set up to always look up the procedure name in the form
;;; environment, EXCEPT for calling primitives, where it just looks up
;;; the name.
;;; def
;;; (def var1 ...) ==> (define var1 ...)
(define-syntax def
(syntax-rules ()
;; There's some Kawa bug that gets exposed if you change the clause ordering here
;; and put the var def rule before the func def rule.
((_ (func-name args ...) body ...)
(begin
(if *this-is-the-repl*
(add-global-var-to-current-form-environment 'func-name
(lambda (args ...) body ...))
(add-to-global-vars 'func-name
(lambda ()
(lambda (args ...) body ...))))))
((_ var-name value)
(begin
(if *this-is-the-repl*
(add-global-var-to-current-form-environment 'var-name value)
(add-to-global-vars 'var-name
(lambda () value)))))))
;;; Arrange for a sequence of expressions to be evaluated after the
;;; form has been created. Used for setting the inital form properties
(define-syntax do-after-form-creation
(syntax-rules ()
((_ expr ...)
(if *this-is-the-repl*
(begin expr ...)
(add-to-form-do-after-creation (delay (begin expr ...)))))))
;; The following environments are really just for testing.
(define *test-environment* (gnu.mapping.Environment:make 'test-env))
(define *test-global-var-environment* (gnu.mapping.Environment:make 'test-global-var-env))
(define (add-to-current-form-environment name :: gnu.mapping.Symbol object)
; (android-log (format #f "Adding ~A to env ~A with value ~A" name
; (if (not (eq? *this-form* #!null)) (*:.form-environment *this-form*) 'null)
; object))
(if (not (eq? *this-form* #!null))
(gnu.mapping.Environment:put (*:.form-environment *this-form*) name object)
;; The following is really for testing. In normal situations *this-form* should be non-null
(gnu.mapping.Environment:put *test-environment* name object)))
(define (lookup-in-current-form-environment name :: gnu.mapping.Symbol #!optional (default-value #f))
; (android-log (format #f "Looking up ~A in env ~A" name
; (if (not (eq? *this-form* #!null)) (*:.form-environment *this-form*) 'null)))
(let ((env (if (not (eq? *this-form* #!null))
(*:.form-environment *this-form*)
;; The following is just for testing. In normal situations *this-form* should be non-null
*test-environment*)))
(if (gnu.mapping.Environment:isBound env name)
(gnu.mapping.Environment:get env name)
default-value)))
(define (filter-type-in-current-form-environment type :: gnu.mapping.Symbol)
(define-alias ComponentUtil <com.google.appinventor.components.runtime.util.ComponentUtil>)
(let ((env (if (not (eq? *this-form* #!null))
(*:.form-environment *this-form*)
;; The following is just for testing. In normal situations *this-form* should be non-null
*test-environment*)))
(sanitize-component-data (ComponentUtil:filterComponentsOfType env type))))
(define (delete-from-current-form-environment name :: gnu.mapping.Symbol)
(if (not (eq? *this-form* #!null))
(gnu.mapping.Environment:remove (*:.form-environment *this-form*) name)
;; The following is really for testing. In normal situations *this-form* should be non-null
(gnu.mapping.Environment:remove *test-environment* name)))
(define (rename-in-current-form-environment old-name :: gnu.mapping.Symbol new-name :: gnu.mapping.Symbol)
(when (not (eqv? old-name new-name))
(let ((old-value (lookup-in-current-form-environment old-name)))
(if (not (eq? *this-form* #!null))
(gnu.mapping.Environment:put (*:.form-environment *this-form*) new-name old-value)
;; The following is really for testing. In normal situations *this-form* should be non-null
(gnu.mapping.Environment:put *test-environment* new-name old-value))
(delete-from-current-form-environment old-name))))
(define (add-global-var-to-current-form-environment name :: gnu.mapping.Symbol object)
(begin
(if (not (eq? *this-form* #!null))
(gnu.mapping.Environment:put (*:.global-var-environment *this-form*) name object)
;; The following is really for testing. In normal situations *this-form* should be non-null
(gnu.mapping.Environment:put *test-global-var-environment* name object))
;; return *the-null-value* rather than #!void, which would show as a blank in the repl balloon
*the-null-value*))
(define (lookup-global-var-in-current-form-environment name :: gnu.mapping.Symbol #!optional (default-value #f))
(let ((env (if (not (eq? *this-form* #!null))
(*:.global-var-environment *this-form*)
;; The following is just for testing. In normal situations *this-form* should be non-null
*test-global-var-environment*)))
(if (gnu.mapping.Environment:isBound env name)
(gnu.mapping.Environment:get env name)
default-value)))
(define (reset-current-form-environment)
(if (not (eq? *this-form* #!null))
(let ((form-name (*:.form-name-symbol *this-form*)))
;; Create a new environment
(set! (*:.form-environment *this-form*)
(gnu.mapping.Environment:make (symbol->string form-name)))
;; Add a binding from the form name to the form object
(add-to-current-form-environment form-name *this-form*)
;; Create a new global variable environment
(set! (*:.global-var-environment *this-form*)
(gnu.mapping.Environment:make (string-append
(symbol->string form-name)
"-global-vars"))))
(begin
;; The following is just for testing. In normal situations *this-form* should be non-null
(set! *test-environment* (gnu.mapping.Environment:make 'test-env))
(*:addParent (KawaEnvironment:getCurrent) *test-environment*)
(set! *test-global-var-environment* (gnu.mapping.Environment:make 'test-global-var-env)))))
;; Note: (Jeff Schiller) The macro below is intentionally
;; unhygienic. We need to make sure that if there is a *yail-break*
;; form inside bodyform that it does not get shadowed by the macro
;; (which it would if this was a hygienic macro).
(define-macro (foreach arg-name bodyform list-of-args)
`(call-with-current-continuation
(lambda (*yail-break*)
(let ((proc (lambda (,arg-name) ,bodyform)))
(yail-for-each proc ,list-of-args)))))
;; This yail procedure should be called only if "*yail-break*" is used
;; outside of a foreach, forrange or while macro. The blocks editor
;; should give an error if the break block is placed outside of a
;; loop. So the only way this yail procedure would be called should
;; be by running do-it on an isolated break block. See
;; blocklyeditor/src/warninghandler.js checkIsNotInLoop
(define (*yail-break* ignore)
(signal-runtime-error
"Break should be run only from within a loop"
"Bad use of Break"))
;; Also unhygienic (see comment above about foreach)
(define-macro (forrange lambda-arg-name body-form start end step)
`(call-with-current-continuation
(lambda (*yail-break*)
(yail-for-range (lambda (,lambda-arg-name) ,body-form) ,start ,end ,step))))
;; Also unhygienic (see comment above about foreach)
;; The structure of this macro is important. If the argument to
;; call-with-current-continuation is a lambda expression, then Kawa
;; attempts to optimize it. This optimization fails spectacularly when
;; the lambda expression is tail-recursive (like ours is). By binding
;; the lambda expression to a variable and then calling via the
;; variable, the optimizer is not invoked and the code produced, while
;; not optmized, is correct.
(define-macro (while condition body . rest)
`(let ((cont (lambda (*yail-break*)
(let *yail-loop* ()
(if ,condition
(begin (begin ,body . ,rest)
(*yail-loop*))
#!null)))))
(call-with-current-continuation cont)))
;; Below are hygienic versions of the forrange, foreach and while
;; macros. They are here to be "future aware". A future version of
;; MIT App Inventor will use these hygienic versions which require
;; and additional argument, and therefore different YAIL generation
(define-syntax foreach-with-break
(syntax-rules ()
((_ escapename arg-name bodyform list-of-args)
(call-with-current-continuation
(lambda (escapename)
(let ((proc (lambda (arg-name) bodyform)))
(yail-for-each proc list-of-args)))))))
;; To call this foreach-with-break macro, we must pass a symbol that
;; will be the name of an escape procedure referenced in the body of
;; the proc argument. For example
;;
;; (foreach-with-break
;; *yail-break*
;; x
;; (if (= x 17)
;; (begin (display "escape") (*yail-break* #f))
;; (begin (display x) (display " "))
;; )
;; '(100 200 17 300))
(define-syntax map_nondest
(syntax-rules ()
((_ lambda-arg-name body-form list)
(yail-list-map (lambda (lambda-arg-name) body-form) list))))
(define-syntax filter_nondest
(syntax-rules ()
((_ lambda-arg-name body-form list)
(yail-list-filter (lambda (lambda-arg-name) body-form) list))))
(define-syntax reduceovereach
(syntax-rules ()
((_ initialAnswer lambda-arg1-name lambda-arg2-name body-form list)
(yail-list-reduce initialAnswer (lambda (lambda-arg1-name lambda-arg2-name) body-form) list))))
(define-syntax sortcomparator_nondest
(syntax-rules ()
((_ lambda-arg1-name lambda-arg2-name body-form list)
(yail-list-sort-comparator (lambda (lambda-arg1-name lambda-arg2-name) body-form) list))))
(define-syntax mincomparator-nondest
(syntax-rules ()
((_ lambda-arg1-name lambda-arg2-name body-form list)
(yail-list-min-comparator (lambda (lambda-arg1-name lambda-arg2-name) body-form) list))))
(define-syntax maxcomparator-nondest
(syntax-rules ()
((_ lambda-arg1-name lambda-arg2-name body-form list)
(yail-list-max-comparator (lambda (lambda-arg1-name lambda-arg2-name) body-form) list))))
(define-syntax sortkey_nondest
(syntax-rules ()
((_ lambda-arg-name body-form list)
(yail-list-sort-key (lambda (lambda-arg-name) body-form) list))))
(define-syntax forrange-with-break
(syntax-rules ()
((_ escapename lambda-arg-name body-form start end step)
(call-with-current-continuation