/
KrollProxy.java
1362 lines (1194 loc) Β· 40.3 KB
/
KrollProxy.java
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
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2016 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package org.appcelerator.kroll;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.kroll.common.AsyncResult;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.kroll.common.TiMessenger;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiBaseActivity;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.proxy.ActivityProxy;
import org.appcelerator.titanium.proxy.TiWindowProxy;
import org.appcelerator.titanium.TiLifecycle.OnLifecycleEvent;
import org.appcelerator.titanium.util.TiConvert;
import org.appcelerator.titanium.util.TiRHelper;
import org.appcelerator.titanium.util.TiUrl;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Pair;
import org.json.JSONObject;
/**
* This is the parent class of all proxies. A proxy is a dynamic object that can be created or
* queried by the user through a module or another proxy's API. When you create a native view with
* <a href="http://developer.appcelerator.com/apidoc/mobile/latest/Titanium.UI.createView-method.html">Titanium.UI.createView </a>,
* the view object is a proxy itself.
*/
@Kroll.proxy(name = "KrollProxy", propertyAccessors = { KrollProxy.PROPERTY_HAS_JAVA_LISTENER })
public class KrollProxy implements Handler.Callback, KrollProxySupport, OnLifecycleEvent
{
private static final String TAG = "KrollProxy";
private static final int INDEX_NAME = 0;
private static final int INDEX_OLD_VALUE = 1;
private static final int INDEX_VALUE = 2;
private static final String ERROR_CREATING_PROXY = "Error creating proxy";
protected static final int MSG_MODEL_PROPERTY_CHANGE = KrollObject.MSG_LAST_ID + 100;
protected static final int MSG_LISTENER_ADDED = KrollObject.MSG_LAST_ID + 101;
protected static final int MSG_LISTENER_REMOVED = KrollObject.MSG_LAST_ID + 102;
protected static final int MSG_MODEL_PROCESS_PROPERTIES = KrollObject.MSG_LAST_ID + 103;
protected static final int MSG_MODEL_PROPERTIES_CHANGED = KrollObject.MSG_LAST_ID + 104;
protected static final int MSG_INIT_KROLL_OBJECT = KrollObject.MSG_LAST_ID + 105;
protected static final int MSG_SET_PROPERTY = KrollObject.MSG_LAST_ID + 106;
protected static final int MSG_FIRE_EVENT = KrollObject.MSG_LAST_ID + 107;
protected static final int MSG_FIRE_SYNC_EVENT = KrollObject.MSG_LAST_ID + 108;
protected static final int MSG_CALL_PROPERTY_ASYNC = KrollObject.MSG_LAST_ID + 109;
protected static final int MSG_CALL_PROPERTY_SYNC = KrollObject.MSG_LAST_ID + 110;
protected static final int MSG_LAST_ID = MSG_CALL_PROPERTY_SYNC;
protected static final String PROPERTY_NAME = "name";
protected static final String PROPERTY_HAS_JAVA_LISTENER = "_hasJavaListener";
protected static AtomicInteger proxyCounter = new AtomicInteger();
protected AtomicInteger listenerIdGenerator;
protected Map<String, HashMap<Integer, KrollEventCallback>> eventListeners;
protected KrollObject krollObject;
protected WeakReference<Activity> activity;
protected String proxyId;
protected TiUrl creationUrl;
protected KrollProxyListener modelListener;
protected KrollModule createdInModule;
protected boolean coverageEnabled;
protected KrollDict properties = new KrollDict();
protected KrollDict defaultValues = new KrollDict();
protected Handler mainHandler = null;
protected Handler runtimeHandler = null;
private KrollDict langConversionTable = null;
private boolean bubbleParent = true;
public static final String PROXY_ID_PREFIX = "proxy$";
/**
* The default KrollProxy constructor. Equivalent to <code>KrollProxy("")</code>
* @module.api
*/
public KrollProxy()
{
this("");
}
/**
* Constructs a KrollProxy, using the passed in creation URL.
* @param baseCreationUrl the creation URL for this proxy, which can be used to resolve relative paths
* @module.api
*/
public KrollProxy(String baseCreationUrl)
{
creationUrl = new TiUrl(baseCreationUrl);
this.listenerIdGenerator = new AtomicInteger(0);
this.eventListeners = Collections.synchronizedMap(new HashMap<String, HashMap<Integer, KrollEventCallback>>());
this.langConversionTable = getLangConversionTable();
}
private void setupProxy(KrollObject object, Object[] creationArguments, TiUrl creationUrl)
{
// Store reference to the native object that represents this proxy so we can drive changes to the JS
// object
krollObject = object;
object.setProxySupport(this);
this.creationUrl = creationUrl;
// Associate the activity with the proxy. if the proxy needs activity association delayed until a
// later point then initActivity should be overridden to be a no-op and then call setActivity directly
// at the appropriate time
initActivity(TiApplication.getInstance().getCurrentActivity());
// Setup the proxy according to the creation arguments TODO - pass in createdInModule
handleCreationArgs(null, creationArguments);
}
// entry point for generator code
public static KrollProxy createProxy(Class<? extends KrollProxy> proxyClass, KrollObject object, Object[] creationArguments, String creationUrl)
{
try {
KrollProxy proxyInstance = proxyClass.newInstance();
proxyInstance.setupProxy(object, creationArguments, TiUrl.createProxyUrl(creationUrl));
return proxyInstance;
} catch (Exception e) {
Log.e(TAG, ERROR_CREATING_PROXY, e);
}
return null;
}
protected void initActivity(Activity activity)
{
this.activity = new WeakReference<Activity>(activity);
}
public void setActivity(Activity activity)
{
this.activity = new WeakReference<Activity>(activity);
}
public void attachActivityLifecycle(Activity activity)
{
setActivity(activity);
((TiBaseActivity) activity).addOnLifecycleEventListener(this);
}
/**
* @return the activity associated with this proxy. It can be null.
* @module.api
*/
public Activity getActivity()
{
if (activity == null) {
return null;
}
return activity.get();
}
/**
* Handles the arguments passed into the "create" method for this proxy.
* If your proxy simply needs to handle a KrollDict, see {@link KrollProxy#handleCreationDict(KrollDict)}
* @param args
* @module.api
*/
public void handleCreationArgs(KrollModule createdInModule, Object[] args)
{
this.createdInModule = createdInModule;
if (args.length == 0 || !(args[0] instanceof HashMap)) {
handleDefaultValues();
return;
}
KrollDict dict;
if (args[0] instanceof KrollDict) {
dict = (KrollDict) args[0];
} else {
dict = new KrollDict((HashMap) args[0]);
}
handleCreationDict(dict);
}
/**
* Handles initialization of the proxy's default property values.
* @module.api
*/
protected void handleDefaultValues()
{
for (String key : defaultValues.keySet()) {
if (!properties.containsKey(key)) {
setProperty(key, defaultValues.get(key));
}
}
}
/**
* @return the language conversion table used to load localized values for certain properties from the locale files.
* For each localizable property, such as "title," the proxy should define a second property, such as "titleid", used to specify a
* localization key for that property. If the user specifies a localization key in "titleid", the corresponding localized text from the locale file
* is used for "title."
*
* Subclasses should override this method to return a table mapping localizable properties to the corresponding localization key properties.
*
* For example, if the proxy has two properties, "title" and "text", and the corresponding localization key properties are "titleid" and "textid", this might look like:
* </br>
*
* <pre><code>protected KrollDict getLangConversionTable()
*{
* KrollDict table = new KrollDict();
* table.put("title", "titleid");
* table.put("text", "textid");
* return table;
*} </pre> </code>
*
* @module.api
*
*/
protected KrollDict getLangConversionTable()
{
return null;
}
/**
* Handles initialization of the proxy's locale string properties.
*
* @see #getLangConversionTable()
*/
private void handleLocaleProperties()
{
if (langConversionTable == null) {
return;
}
/*
* Iterate through the language conversion table.
* This table maps target properties to their locale lookup property.
* Example: title -> titleid
*
* The lookup identifier stored in the locale property (titleid) will be used
* to query the locale strings file to get the localized value.
* This localized value will be set to the targeted property (title).
*/
for (Map.Entry<String, Object> entry : langConversionTable.entrySet()) {
// Get the lookup identifier stored in the locale property.
String localeProperty = entry.getValue().toString();
String lookupId = properties.getString(localeProperty);
if (lookupId == null) {
// If no locale lookup identifier is provided, skip this entry.
continue;
}
// Lookup the localized string from the locale file.
String localizedValue = getLocalizedText(lookupId);
if (localizedValue == null) {
// If there is no localized value for this identifier,
// log a warning and skip over the entry.
Log.w(TAG, "No localized string found for identifier: " + lookupId);
continue;
}
// Set the localized value to the targeted property.
String targetProperty = entry.getKey();
setProperty(targetProperty, localizedValue);
}
}
/**
* Updates the lookup identifier value of a locale property.
* This will also update the targeted value with the string found
* using the new lookup identifier.
*
* @param localeProperty name of the locale property (example: titleid)
* @param newLookupId the new lookup identifier
* @return a pair containing the name of the target property which was updated and the new value set on it.
*/
public Pair<String, String> updateLocaleProperty(String localeProperty, String newLookupId)
{
if (langConversionTable == null) {
return null;
}
properties.put(localeProperty, newLookupId);
// Determine which localized property this locale property updates.
for (Map.Entry<String, Object> entry : langConversionTable.entrySet()) {
if (entry.getValue().toString().equals(localeProperty)) {
String targetProperty = entry.getKey();
String localizedValue = getLocalizedText(newLookupId);
if (localizedValue == null) {
return null;
}
setProperty(targetProperty, localizedValue);
return Pair.create(targetProperty, localizedValue);
}
}
// If we reach this point, the provided locale property is not valid.
return null;
}
/**
* Return true if the given property is a locale property.
* @param propertyName name of the property to check (ex: titleid)
* @return true if this property is a locale property
*/
public boolean isLocaleProperty(String propertyName)
{
return propertyName.endsWith("id");
}
/**
* Looks up a localized string given an identifier.
*
* @param lookupId the identifier of the localized value to look up.
* @return the localized string if found, otherwise null.
*/
private String getLocalizedText(String lookupId)
{
try {
int resid = TiRHelper.getResource("string." + lookupId);
if (resid != 0) {
return getActivity().getString(resid);
}
return null;
} catch (TiRHelper.ResourceNotFoundException e) {
return null;
}
}
/**
* Handles the creation {@link KrollDict} passed into the create method for this proxy.
* This is usually the first (and sometimes only) argument to the proxy's create method.
*
* To set default property values, add them to the {@link KrollProxy#defaultValues map}
* @param dict
* @module.api
*/
public void handleCreationDict(KrollDict dict)
{
if (dict == null) {
return;
}
if (dict.containsKey(TiC.PROPERTY_BUBBLE_PARENT)) {
bubbleParent = TiConvert.toBoolean(dict, TiC.PROPERTY_BUBBLE_PARENT, true);
}
if (dict.containsKey(TiC.PROPERTY_LIFECYCLE_CONTAINER)) {
KrollProxy lifecycleProxy = (KrollProxy) dict.get(TiC.PROPERTY_LIFECYCLE_CONTAINER);
if (lifecycleProxy instanceof TiWindowProxy) {
ActivityProxy activityProxy = ((TiWindowProxy) lifecycleProxy).getWindowActivityProxy();
if (activityProxy != null) {
attachActivityLifecycle(activityProxy.getActivity());
} else {
((TiWindowProxy) lifecycleProxy).addProxyWaitingForActivity(this);
}
} else {
Log.e(TAG, TiC.PROPERTY_LIFECYCLE_CONTAINER + " must be a WindowProxy or TabGroupProxy (TiWindowProxy)");
}
}
properties.putAll(dict);
handleDefaultValues();
handleLocaleProperties();
if (modelListener != null) {
modelListener.processProperties(properties);
}
}
public Handler getMainHandler()
{
if (mainHandler == null) {
mainHandler = new Handler(TiMessenger.getMainMessenger().getLooper(), this);
}
return mainHandler;
}
public Handler getRuntimeHandler()
{
if (runtimeHandler == null) {
runtimeHandler = new Handler(TiMessenger.getRuntimeMessenger().getLooper(), this);
}
return runtimeHandler;
}
public void setKrollObject(KrollObject object)
{
this.krollObject = object;
}
/**
* @return the KrollObject associated with this proxy if it exists. Otherwise create it in the KrollRuntime thread.
* @module.api
*/
public KrollObject getKrollObject()
{
if (krollObject == null) {
if (KrollRuntime.getInstance().isRuntimeThread()) {
initKrollObject();
} else {
TiMessenger.sendBlockingRuntimeMessage(getRuntimeHandler().obtainMessage(MSG_INIT_KROLL_OBJECT));
}
}
return krollObject;
}
public void initKrollObject()
{
KrollRuntime.getInstance().initObject(this);
}
/**
* @return the absolute URL of the location in code where the proxy was created in Javascript.
* @module.api
*/
public TiUrl getCreationUrl()
{
return creationUrl;
}
@Kroll.method
public void setCreationUrl(String url)
{
creationUrl = TiUrl.createProxyUrl(url);
}
// native extending support allows us to whole-sale apply properties and only fire one event / job
@Kroll.method
public void extend(KrollDict options)
{
if (options == null || options.isEmpty()) {
return;
}
ArrayList<KrollPropertyChange> propertyChanges = new ArrayList<KrollPropertyChange>();
for (String name : options.keySet()) {
Object oldValue = properties.get(name);
Object value = options.get(name);
// dont just fire the change event, make sure we set the property back on the KrollObject
// since the property change may not be driven from JS (KrollObject->Java proxy)
setProperty(name, value);
if (shouldFireChange(oldValue, value)) {
KrollPropertyChange pch = new KrollPropertyChange(name, oldValue, value);
propertyChanges.add(pch);
}
}
// convert to two dimensional array
int changeSize = propertyChanges.size();
Object[][] changeArray = new Object[changeSize][];
for (int i = 0; i < changeSize; i++) {
KrollPropertyChange propertyChange = propertyChanges.get(i);
changeArray[i] = new Object[] {propertyChange.name, propertyChange.oldValue, propertyChange.newValue};
}
if (KrollRuntime.getInstance().isRuntimeThread()) {
firePropertiesChanged(changeArray);
} else {
Message message = getMainHandler().obtainMessage(MSG_MODEL_PROPERTIES_CHANGED, changeArray);
message.sendToTarget();
}
}
private void firePropertiesChanged(Object[][] changes)
{
if (modelListener == null) {
return;
}
int changesLength = changes.length;
for (int i = 0; i < changesLength; ++i) {
Object[] change = changes[i];
if (change.length != 3) {
continue;
}
Object name = change[INDEX_NAME];
if (name == null || !(name instanceof String)) {
continue;
}
if (modelListener != null) {
modelListener.propertyChanged((String) name, change[INDEX_OLD_VALUE], change[INDEX_VALUE], this);
}
}
}
public Object getIndexedProperty(int index)
{
// TODO(josh): return undefined value
return 0;
}
public void setIndexedProperty(int index, Object value)
{
// no-op
}
/**
* @param name the lookup key.
* @return true if the proxy contains this property, false otherwise.
* @module.api
*/
public boolean hasProperty(String name)
{
return properties.containsKey(name);
}
/**
* @param name the lookup key.
* @return true if the proxy contains this property and it is not null, false otherwise.
* @module.api
*/
public boolean hasPropertyAndNotNull(String name)
{
return properties.containsKeyAndNotNull(name);
}
/**
* Returns the property value given its key.
* Properties are cached on the Proxy and updated from JS for relevant annotated APIs
* @param name the lookup key.
* @return the property object or null if a property for the given key does not exist.
* @module.api
*/
public Object getProperty(String name)
{
return properties.get(name);
}
/**
* This sets the named property as well as updating the actual JS object.
* @module.api
*/
public void setProperty(String name, Object value)
{
properties.put(name, value);
if (KrollRuntime.getInstance().isRuntimeThread()) {
doSetProperty(name, value);
} else {
Message message = getRuntimeHandler().obtainMessage(MSG_SET_PROPERTY, value);
message.getData().putString(PROPERTY_NAME, name);
message.sendToTarget();
}
}
public class KrollPropertyChangeSet extends KrollPropertyChange {
public int entryCount;
public String[] keys;
public Object[] oldValues;
public Object[] newValues;
public KrollPropertyChangeSet(int capacity) {
super(null,null,null);
entryCount = 0;
keys = new String[capacity];
oldValues = new Object[capacity];
newValues = new Object[capacity];
}
public void addChange(String key, Object oldValue, Object newValue){
keys[entryCount] = key;
oldValues[entryCount] = oldValue;
newValues[entryCount] = newValue;
entryCount ++;
}
public void fireEvent(KrollProxy proxy, KrollProxyListener listener) {
if (listener == null) {
return;
}
for (int i = 0; i < entryCount; i++) {
listener.propertyChanged(keys[i], oldValues[i], newValues[i], proxy);
}
}
}
@Kroll.method
public void applyProperties(Object arg)
{
if (!(arg instanceof HashMap)) {
Log.w(TAG, "Cannot apply properties: invalid type for properties", Log.DEBUG_MODE);
return;
}
HashMap props = (HashMap) arg;
if (modelListener == null) {
for (Object name : props.keySet()) {
setProperty(TiConvert.toString(name), props.get(name));
}
return;
}
if (TiApplication.isUIThread()) {
for (Object key : props.keySet()) {
String name = TiConvert.toString(key);
Object value = props.get(key);
Object current = getProperty(name);
setProperty(name, value);
if (shouldFireChange(current, value)) {
modelListener.propertyChanged(name, current, value, this);
}
}
return;
}
KrollPropertyChangeSet changes = new KrollPropertyChangeSet(props.size());
for (Object key : props.keySet()) {
String name = TiConvert.toString(key);
Object value = props.get(key);
Object current = getProperty(name);
setProperty(name, value);
if (shouldFireChange(current, value)) {
changes.addChange(name, current, value);
}
}
if (changes.entryCount > 0) {
getMainHandler().obtainMessage(MSG_MODEL_PROPERTY_CHANGE, changes).sendToTarget();
}
}
/**
* Asynchronously calls a function referenced by a property on this object.
* This may be called safely on any thread.
*
* @see KrollObject#callProperty(String, Object[])
* @param name the property that references the function
* @param args the arguments to pass when calling the function.
*/
public void callPropertyAsync(String name, Object[] args) {
Message msg = getRuntimeHandler().obtainMessage(MSG_CALL_PROPERTY_ASYNC, args);
msg.getData().putString(PROPERTY_NAME, name);
msg.sendToTarget();
}
/**
* Synchronously calls a function referenced by a property on this object.
* This may be called safely on any thread.
*
* @see KrollObject#callProperty(String, Object[])
* @param name the property that references the function
* @param args the arguments to pass when calling the function.
*/
public void callPropertySync(String name, Object[] args)
{
if (KrollRuntime.getInstance().isRuntimeThread()) {
getKrollObject().callProperty(name, args);
} else {
Message msg = getRuntimeHandler().obtainMessage(MSG_CALL_PROPERTY_SYNC);
msg.getData().putString(PROPERTY_NAME, name);
TiMessenger.sendBlockingRuntimeMessage(msg, args);
}
}
protected void doSetProperty(String name, Object value)
{
getKrollObject().setProperty(name, value);
}
@Kroll.getProperty @Kroll.method
public boolean getBubbleParent()
{
return bubbleParent;
}
@Kroll.setProperty @Kroll.method
public void setBubbleParent(Object value)
{
bubbleParent = TiConvert.toBoolean(value);
}
/**
* Fires an event asynchronously via KrollRuntime thread, which can be intercepted on JS side.
* @param event the event to be fired.
* @param data the data to be sent.
* @return whether this proxy has an eventListener for this event.
* @module.api
*/
public boolean fireEvent(String event, Object data)
{
if (hierarchyHasListener(event)) {
Message message = getRuntimeHandler().obtainMessage(MSG_FIRE_EVENT, data);
message.getData().putString(PROPERTY_NAME, event);
message.sendToTarget();
return true;
}
return false;
}
/**
* Send an event to the view who is next to receive the event.
*
* @param eventName event to send to the next view
* @param data the data to include in the event
* @return true if the event was handled
*/
@Kroll.method(name = "_fireEventToParent")
public boolean fireEventToParent(String eventName, Object data)
{
if (bubbleParent) {
KrollProxy parentProxy = getParentForBubbling();
if (parentProxy != null) {
return parentProxy.fireEvent(eventName, data);
}
}
return false;
}
/**
* Fires an event synchronously via KrollRuntime thread, which can be intercepted on JS side.
* @param event the event to be fired.
* @param data the data to be sent.
* @return whether this proxy has an eventListener for this event.
* @module.api
*/
public boolean fireSyncEvent(String event, Object data)
{
if (KrollRuntime.getInstance().isRuntimeThread()) {
return doFireEvent(event, data);
} else {
Message message = getRuntimeHandler().obtainMessage(MSG_FIRE_SYNC_EVENT);
message.getData().putString(PROPERTY_NAME, event);
return (Boolean) TiMessenger.sendBlockingRuntimeMessage(message, data);
}
}
/**
* Fires an event synchronously via KrollRuntime thread, which can be intercepted on JS side.
* @param event the event to be fired.
* @param data the data to be sent.
* @param maxTimeout the maximum time to wait for the result to return, in the unit of milliseconds.
* @return whether this proxy has an eventListener for this event.
* @module.api
*/
public boolean fireSyncEvent(String event, Object data, long maxTimeout)
{
if (KrollRuntime.getInstance().isRuntimeThread()) {
return doFireEvent(event, data);
} else {
Message message = getRuntimeHandler().obtainMessage(MSG_FIRE_SYNC_EVENT);
message.getData().putString(PROPERTY_NAME, event);
Object result = TiMessenger.sendBlockingRuntimeMessage(message, data, maxTimeout);
return TiConvert.toBoolean(result, false);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public boolean doFireEvent(String event, Object data)
{
if (!hierarchyHasListener(event)) {
return false;
}
boolean bubbles = false;
boolean reportSuccess = false;
int code = 0;
KrollObject source = null;
String message = null;
KrollDict krollData = null;
/* TODO: Is eventListeners still used? */
if (!eventListeners.isEmpty()) {
HashMap<String, Object> dict = (HashMap) data;
if (dict == null) {
dict = new KrollDict();
dict.put(TiC.EVENT_PROPERTY_SOURCE, this);
}
else if (dict instanceof HashMap)
{
Object sourceProxy = dict.get(TiC.EVENT_PROPERTY_SOURCE);
if (sourceProxy == null) {
dict.put(TiC.EVENT_PROPERTY_SOURCE, this);
}
}
onEventFired(event, dict);
}
if (data != null) {
if (data instanceof KrollDict) {
krollData = (KrollDict) data;
} else if (data instanceof HashMap) {
try {
krollData = new KrollDict((HashMap)data);
} catch(Exception e) {
}
} else if (data instanceof JSONObject) {
try {
krollData = new KrollDict((JSONObject)data);
} catch(Exception e) {
}
}
}
if (krollData != null) {
Object hashValue = krollData.get(TiC.PROPERTY_BUBBLES);
if (hashValue != null) {
bubbles = TiConvert.toBoolean(hashValue);
krollData.remove(TiC.PROPERTY_BUBBLES);
}
hashValue = krollData.get(TiC.PROPERTY_SUCCESS);
if (hashValue instanceof Boolean) {
boolean successValue = ((Boolean)hashValue).booleanValue();
hashValue = krollData.get(TiC.PROPERTY_CODE);
if (hashValue instanceof Integer) {
int codeValue = ((Integer)hashValue).intValue();
if (successValue == (codeValue == 0)) {
reportSuccess = true;
code = codeValue;
krollData.remove(TiC.PROPERTY_SUCCESS);
krollData.remove(TiC.PROPERTY_CODE);
} else {
Log.w(TAG, "DEPRECATION WARNING: Events with 'code' and 'success' should have success be true if and only if code is nonzero. For java modules, consider the putCodeAndMessage() method to do this for you. The capability to use other types will be removed in a future version.", Log.DEBUG_MODE);
}
} else if ( successValue ) {
Log.w(TAG, "DEPRECATION WARNING: Events with 'success' of true should have an integer 'code' property that is 0. For java modules, consider the putCodeAndMessage() method to do this for you. The capability to use other types will be removed in a future version.", Log.DEBUG_MODE);
} else {
Log.w(TAG, "DEPRECATION WARNING: Events with 'success' of false should have an integer 'code' property that is nonzero. For java modules, consider the putCodeAndMessage() method to do this for you. The capability to use other types will be removed in a future version.", Log.DEBUG_MODE);
}
} else if (hashValue != null) {
Log.w(TAG, "DEPRECATION WARNING: The 'success' event property is reserved to be a boolean. For java modules, consider the putCodeAndMessage() method to do this for you. The capability to use other types will be removed in a future version.", Log.DEBUG_MODE);
}
hashValue = krollData.get(TiC.EVENT_PROPERTY_ERROR);
if (hashValue instanceof String) {
message = (String) hashValue;
krollData.remove(TiC.EVENT_PROPERTY_ERROR);
} else if (hashValue != null) {
Log.w(TAG, "DEPRECATION WARNING: The 'error' event property is reserved to be a string. For java modules, consider the putCodeAndMessage() method to do this for you. The capability to use other types will be removed in a future version.", Log.DEBUG_MODE);
}
hashValue = krollData.get(TiC.EVENT_PROPERTY_SOURCE);
if (hashValue instanceof KrollProxy) {
if (hashValue != this) {
source = ((KrollProxy)hashValue).getKrollObject();
}
krollData.remove(TiC.EVENT_PROPERTY_SOURCE);
}
if (krollData.size() == 0){
krollData = null;
}
}
return getKrollObject().fireEvent(source, event, krollData, bubbles, reportSuccess, code, message);
}
public void firePropertyChanged(String name, Object oldValue, Object newValue)
{
if (modelListener != null) {
if (TiApplication.isUIThread()) {
modelListener.propertyChanged(name, oldValue, newValue, this);
} else {
KrollPropertyChange pch = new KrollPropertyChange(name, oldValue, newValue);
getMainHandler().obtainMessage(MSG_MODEL_PROPERTY_CHANGE, pch).sendToTarget();
}
}
}
public void onHasListenersChanged(String event, boolean hasListeners)
{
Message msg = getMainHandler().obtainMessage(hasListeners ? MSG_LISTENER_ADDED : MSG_LISTENER_REMOVED);
msg.obj = event;
TiMessenger.getMainMessenger().sendMessage(msg);
}
/**
* @param event the event to check
* @return whether the associated KrollObject has an event listener for the passed in event.
* @module.api
*/
public boolean hasListeners(String event)
{
return getKrollObject().hasListeners(event);
}
/**
* Returns true if any view in the hierarchy has the event listener.
*/
public boolean hierarchyHasListener(String event)
{
boolean hasListener = hasListeners(event);
// Checks whether the parent has the listener or not
if (!hasListener) {
KrollProxy parentProxy = getParentForBubbling();
if (parentProxy != null && bubbleParent) {
return parentProxy.hierarchyHasListener(event);
}
}
return hasListener;
}
public boolean shouldFireChange(Object oldValue, Object newValue)
{
if (!(oldValue == null && newValue == null)) {
if ((oldValue == null && newValue != null) || (newValue == null && oldValue != null) || (!oldValue.equals(newValue))) {
return true;
}
}
return false;
}
/**
* Same behavior as {@link #setProperty(String, Object)}, but also invokes
* {@link KrollProxyListener#propertyChanged(String, Object, Object, KrollProxy)}.
* @param name the property name.
* @param value the property value.
* @module.api
*/
public void setPropertyAndFire(String name, Object value)
{
Object current = getProperty(name);
setProperty(name, value);
if (shouldFireChange(current, value)) {
firePropertyChanged(name, current, value);
}
}
public void onPropertyChanged(String name, Object value)
{
String propertyName = name;
Object newValue = value;
if (isLocaleProperty(name)) {
Log.i(TAG, "Updating locale: " + name, Log.DEBUG_MODE);
Pair<String, String> update = updateLocaleProperty(name, TiConvert.toString(value));
if (update != null) {
propertyName = update.first;
newValue = update.second;
}
}
Object oldValue = properties.get(propertyName);
properties.put(propertyName, newValue);
firePropertyChanged(propertyName, oldValue, newValue);
}
public void onPropertiesChanged(Object[][] changes)
{
int changesLength = changes.length;
boolean isUiThread = TiApplication.isUIThread();
for (int i = 0; i < changesLength; ++i) {
Object[] change = changes[i];
if (change.length != 3) {
continue;
}
Object name = change[INDEX_NAME];
if (name == null || !(name instanceof String)) {
continue;
}
String nameString = (String) name;
Object value = change[INDEX_VALUE];
properties.put(nameString, change[INDEX_VALUE]);
if (isUiThread && modelListener != null) {
modelListener.propertyChanged(nameString, change[INDEX_OLD_VALUE], value, this);
}
}
if (isUiThread || modelListener == null) {
return;
}
Message message = getMainHandler().obtainMessage(MSG_MODEL_PROPERTIES_CHANGED, changes);
message.sendToTarget();