This repository has been archived by the owner on Apr 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAdobeLibraryAPI.js
6077 lines (5410 loc) · 193 KB
/
AdobeLibraryAPI.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* This is the access-point for all calls into the API.
* <strong>An instance of this class, named adobeDPS, is automatically created in the global namespace.</strong>
* @namespace <strong>ADOBE CONFIDENTIAL</strong>
* <br/>________________________________________________
*
* <br/>Copyright 2012 Adobe Systems Incorporated
* <br/>All Rights Reserved.
* <br/>
* <br/>NOTICE: All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated and its
* suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
*
* AdobePatentID="2472US01"
**/
var adobeDPS = (function () {
"use strict";
// Directives for JSLint
/*global window */
/*global document */
/*global printStackTrace */
/*global setTimeout */
/*global clearTimeout */
/**
* This particular directive is added because the Interface is used everywhere and will be initialized by the time
* it is called, but because of the dependencies involved, it cannot be defined before it is used in the code.
*/
/*global Interface */
/**
* Creates an instance of the Bridge class.
* <br />- <strong>This is an internal constructor and shouldn't be called by regular users.</strong>
* AdobePatentID="2472US01"
* @class Class used to communicate with the native application.
* @private
*/
function Bridge() {
var that;
this.BRIDGE_PREFIX_URI = "bridge://";
this.bridgeBusy = true;
this.bridgeMessageQueue = [];
this.messageBuffer = [];
// Performance Metrics
this.sentData = 0;
this.sendTime = 0;
this.totalSends = 0;
this.metrics = [Infinity, -Infinity, 0];
this.metricsLogTimeout = null;
// Would be nice to auto-detect this at some point
this.location = "adobeDPS._bridge";
// Don't allow bridge communication until DOM has finished loading
if (document.body !== null) {
this.bridgeBusy = false;
this.out({event: {type: "BridgeInitialized", bridgeLocation: this.location}});
Log.instance.info("BridgeInitialized - LOC: " + this.location);
} else {
that = this;
window.addEventListener("DOMContentLoaded",
function () {
that.handleDomLoaded.call(that);
}
);
}
}
/**
* Function to handle the dom loading when the bridge initializes before the document body.
* This should almost always be the case.
* @memberOf adobeDPS-Bridge
*/
Bridge.prototype.handleDomLoaded = function () {
this.bridgeBusy = false;
this.out({event: {type: "BridgeInitialized", bridgeLocation: this.location}});
Log.instance.info("BridgeInitialized - LOC: " + this.location);
};
/**
* Sends a JSON object to the JSBridgingWebView via a special URL protocol.
* Since only one object can be sent at a time using document.location, if
* the bridge is busy, the object is queued until the bridge is free.
* @memberOf adobeDPS-Bridge
*/
Bridge.prototype.out = function (data, force) {
var i, stringData;
// approx 1Kb of data
// garbage = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvw" +
// "xyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" +
// "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabc" +
// "defghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdef" +
// "ghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghi" +
// "jklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl" +
// "mnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmno" +
// "pqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqr" +
// "stuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstu" +
// "vwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx" +
// "yzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
if (!this.bridgeBusy || force) {
this.bridgeBusy = true;
if (data instanceof Array) {
stringData = "[";
for (i = 0; i < data.length; i++) {
// data.garbage = (new Array(1024 * 2 + 1)).join(garbage);
stringData += JSON.stringify(data[i]) + (i < data.length - 1 ? "," : "");
}
stringData += "]";
} else {
// data.garbage = (new Array(1024 * 2 + 1)).join(garbage);
stringData = JSON.stringify(data);
}
// Update sentData, sendTime, and totalSends
this.sentData = stringData.length;
this.sendTime = (new Date()).getTime();
this.totalSends++;
window.location = this.BRIDGE_PREFIX_URI + encodeURIComponent(stringData);
Log.instance.bridge("OUT - " + stringData);
} else {
this.bridgeMessageQueue.push(data);
}
};
/**
* Function used to accept incoming communication from the Bridge in partial strings. When
* the 'execute' parameter is false, the 'data' string is stored for the 'messageid' in the
* 'index' position. When the 'execute' parameter is true, the 'messageid' stored strings
* are concatenated up to the 'index' parameter. The concatenated string is parsed into a
* JSON object and passed to the Bridge input function using the endpoint passed in the
* 'data' parameter.
* @param messageid A unique identifier for the whole message.
* @param index The index of the data part. If 'execute' is true, index
* is the total number of data parts.
* @param data A string of partial data. If 'execute' is true, data
* is the endpoint selector to be executed.
* @param execute If false, 'data' is stored in the bridge. If true,
* the data parts are concatenated and a JSON object is created
* from the string. The input function is called with the endpoint
* (passed in the data parameter).
*/
Bridge.prototype.partialInput = function (messageid, index, data, execute) {
var messageString = "";
try {
if (execute === true) {
// concatenate all of the data parts into one message string
if (this.messageBuffer[messageid] && this.messageBuffer[messageid].length) {
for (var i = 0; i < index; ++i) {
messageString += this.messageBuffer[messageid][i];
}
Log.instance.bridge("EXECUTE (" + messageid + " [ " + index.toString() + " ]) - " + data);
// parse the string into a JSON object and call input
// with the selector passed in the data parameter
this.input(JSON.parse(messageString), data);
this.messageBuffer[messageid].length = 0;
}
}
else {
// if this is a new message, create an array to hold it
if (!this.messageBuffer[messageid]) {
this.messageBuffer[messageid] = new Array();
}
Log.instance.bridge("APPEND (" + messageid + " [ " + index.toString() + " ]) - " + data.length.toString());
// store the data in the array at the index
this.messageBuffer[messageid][index] = data;
}
} catch (e) {
Log.instance.error(e);
}
};
/**
* Function used to accept incoming communication from the Bridge and send the data to certain
* endpoints on the interface. Although it is typically easy to call methods directly on the
* interface, this dynamic bottleneck will allow the Interface instance to be renamed in the
* global namespace without preventing the Bridge from communicating.
* @param data Data to be sent to the bridge from native
* @param endpoint The endpoint that should accept the data to be sent, as defined on the Interface
*/
Bridge.prototype.input = function (data, endpoint) {
try {
Log.instance.bridge("INPUT(" + endpoint + ") - " + JSON.stringify(data));
switch(endpoint) {
case "_initialize":
Interface.instance._initialize(data);
break;
case "_update":
Interface.instance._update(data);
break;
default:
Log.instance.warn("Bridge.input received call for unknown endpoint: " + endpoint);
break;
}
} catch (e) {
Log.instance.error(e);
}
};
/**
* Callback function from JSBridgingWebView. The web view must call this
* function to notify that it receive the last JSON object and that the
* bridge is now free to use.
* @memberOf adobeDPS-Bridge
*/
Bridge.prototype.notifyReceivedBridgeData = function () {
this.bridgeBusy = false;
this.updateMetrics();
this.processQueue();
};
Bridge.prototype.updateMetrics = function () {
var transmitTime, dataSize, throughput;
transmitTime = ((new Date()).getTime() - this.sendTime) / 1000; // seconds
dataSize = this.sentData / 1024; // Bs -> KBs
throughput = dataSize / transmitTime;
if (this.metrics[0] > throughput) {
this.metrics[0] = throughput;
}
if (this.metrics[1] < throughput) {
this.metrics[1] = throughput;
}
// Calculate new average
this.metrics[2] = ((this.metrics[2] * (this.totalSends - 1)) + throughput) / this.totalSends;
this.logMetrics();
};
Bridge.prototype.logMetrics = function () {
if (this.metricsLogTimeout) {
clearTimeout(this.metricsLogTimeout);
}
var that = this;
// If we haven't been updated in over a second, print out the metrics to the log. The idea here is that the metrics
// will be printer out after a bunch of communication completes. This way, hopefully we are giving a good
// representation of actual performance.
this.metricsLogTimeout = setTimeout(
function () {
// Reset the average metric. This will basically just make future throughputs have more weight so that if bridge
// speed increases, we will see the increase in the logs.
that.totalSends = 1;
Log.instance.info("Bridge BW - Min: " + that.metrics[0].toFixed(2) + "KB/s, Max: " + that.metrics[1].toFixed(2) + "KB/s, Avg: " + that.metrics[2].toFixed(2) + "KB/s");
}
, 1000);
};
/**
* Function to process and send the next message in the bridge queue.
* @memberOf adobeDPS-Bridge
*/
Bridge.prototype.processQueue = function () {
if (this.bridgeMessageQueue.length > 0) {
this.out(this.bridgeMessageQueue);
this.bridgeMessageQueue.length = 0;
}
};
/**
* The singleton of the Bridge.
* @static
* @name instance
* @memberOf adobeDPS-Bridge
*/
Bridge.instance = new Bridge();
/**
* Create a single log message to be added to the log.
* @Class Object used to store a single log message.
* @private
*/
function LogMessage(lvl, msg) {
this.lvl = lvl;
this.msg = msg;
this.timestamp = new Date();
}
/**
* Creates an instance of the Log class.
* <br />- <strong>This is an internal constructor and shouldn't be called by regular users.</strong>
* @class Class used for logging within the Adobe Library API.
*/
function Log() {
/**
* Enable logging service. Defaults to true. If it is false
* all calls to the Logging service will be disabled
* @type Boolean
* @memberOf adobeDPS-Log.prototype
*/
this.enableLogging = true;
/**
* An object to keep track of all the profile timers currently in use.
* @memberOf adobeDPS-Log.prototype
*/
this._profileTimers = {};
/**
* This is the log used by the entire Library API. New log messages will be appended here.
* @memberOf adobeDPS-Log.prototype
*/
this._logList = [];
}
/**
* Log an error. This will also try to print a stackTrace if printStackTrace is
* available.
* @memberOf adobeDPS-Log.prototype
* @param {Error} error The error that you wish to log
*/
Log.prototype.error = function (error) {
if (this.enableLogging) {
var _logged = false;
try {
if (error) {
this._logList.push(new LogMessage(this.logLevels.ERROR, error.message + "\n" + printStackTrace({e: error}).join("\n")));
} else {
this._logList.push(new LogMessage(this.logLevels.ERROR, error.message + "\n" + printStackTrace().join("\n")));
}
_logged = true;
} catch (e) {
// no-op
} finally {
if (!_logged) {
this._logList.push(new LogMessage(this.logLevels.ERROR, error.message));
}
}
}
};
/**
* Log an message at warning level.
* @memberOf adobeDPS-Log.prototype
* @param {String} msg The message that you wish to log
*/
Log.prototype.warn = function (msg) {
if (this.enableLogging) {
this._logList.push(new LogMessage(this.logLevels.WARN, msg));
}
};
/**
* Log an message at info level.
* @memberOf adobeDPS-Log.prototype
* @param {String} msg The message that you wish to log
*/
Log.prototype.info = function (msg) {
if (this.enableLogging) {
this._logList.push(new LogMessage(this.logLevels.INFO, msg));
}
};
/**
* Log an message at debug level.
* @memberOf adobeDPS-Log.prototype
* @param {String} msg The message that you wish to log
*/
Log.prototype.debug = function (msg) {
if (this.enableLogging) {
this._logList.push(new LogMessage(this.logLevels.DEBUG, msg));
}
};
/**
* Function used to create and execute profilers. Each profiler is given an id. When this is called again with the same
* id, the profiler will be executed and the time between calls will be logged along with the id of the profiler. For
* this reason, id's should be used that are descriptive of what is being profiled.
* @memberOf adobeDPS-Log.prototype
* @param {String} id The id of the profiler to be created or executed
*/
Log.prototype.profile = function (id) {
if (this.enableLogging) {
var time;
if (this._profileTimers.hasOwnProperty(id)) {
time = Date.now() - this._profileTimers[id];
this._logList.push(new LogMessage(this.logLevels.PROFILE, id + ': ' + time + 'ms'));
} else {
this._profileTimers[id] = Date.now();
}
}
};
/**
* Function used to send bridge specific log information. This should only be used within the API to log all
* communications across the bridge. This should not be used outside of the API because it will pollute the bridge
* specific logs.
* @memberOf adobeDPS-Log.prototype
* @param msg The message that you wish to log
*/
Log.prototype.bridge = function (msg) {
if (this.enableLogging) {
this._logList.push(new LogMessage(this.logLevels.BRIDGE, msg));
}
};
/**
* Function used to get log information for some subset of the available LogLevels. Multiple levels can be requested by
* creating a bitmask of the LogLevels to be returned. I.E. LogLevels.ERROR | LogLevels.WARN.
* @memberOf adobeDPS-Log.prototype
* @param {Number} lvls The bitmask of the levels that should be returned
* @param {Boolean} timestamp Whether the log messages should be timestamped
*/
Log.prototype.print = function (lvls, timestamp) {
if (this.enableLogging) {
var i, log, ret = '';
for (i = 0; i < this._logList.length; i++) {
log = this._logList[i];
if (lvls & log.lvl) {
ret += this._lvlToStr(log.lvl);
if (timestamp) {
ret += " [" + log.timestamp.getTime() + "] ";
} else {
ret += " - ";
}
ret += log.msg + "\n";
}
}
return ret;
} else {
return '';
}
};
/**
* Function used to clear the log
* @memberOf adobeDPS-Log.prototype
*/
Log.prototype.clear = function () {
if (this.enableLogging) {
this._logList.length = 0;
}
};
/**
* Function to generate the log level string associated with each log message. Used by the print function when
* outputting the log string.
* @param lvl
* @return {String}
* @private
*/
Log.prototype._lvlToStr = function (lvl) {
switch (lvl) {
case this.logLevels.BRIDGE:
return "BRIDGE";
case this.logLevels.DEBUG:
return "DEBUG";
case this.logLevels.PROFILE:
return "PROFILE";
case this.logLevels.INFO:
return "INFO";
case this.logLevels.WARN:
return "WARN";
case this.logLevels.ERROR:
return "ERROR";
default:
return "LOG";
}
};
/**
* The singleton of the Log.
* @static
* @name instance
* @memberOf adobeDPS-Log
*/
Log.instance = new Log();
/**
* The log levels that may be used.
* @memberOf adobeDPS-Log.prototype
*/
Log.prototype.logLevels = {
/**
* Log level to specifically log all bridge communications
*/
BRIDGE: 0x1,
/**
* Low-level information about all incoming messages.
*/
DEBUG: 0x2,
/**
* Information about initialization times, throughput, and performance.
*/
PROFILE: 0x4,
/**
* Info about any processes that may be of interest.
*/
INFO: 0x8,
/**
* Warnings, usually to indicate potential misuse of the API.
*/
WARN: 0x10,
/**
* Errors which are thrown.
*/
ERROR: 0x20
};
/**
* Start profiling bridge initialization
*/
Log.instance.profile("InitializationTime");
// Base classes
/**
* @import Wrapper.js
*
* Create an instance of a class.
* <br />- <strong>This is an internal constructor and shouldn't be called by regular users.</strong>
* @class Base class for all classes using inheritance
*/
function Class() {
throw new Error('Class object should never be directly constructed');
}
/**
* Gets the string representation of this instance. By default, this will just be the
* name of the class. If the class has an id property, it will be in the format: name[id].
* @override
* @return {String} The string representation of this instance.
* @memberOf adobeDPS-Class.prototype
*/
Class.prototype.toString = function () {
var className = /(\w+)\(/.exec(this.constructor.toString())[1];
if (this.hasOwnProperty('id')) {
className += '[' + this.id + ']';
}
return className;
};
/**
* Used to extend this class with another class. The class that is passed in will be
* given the extend function as well.
* @private
* @param {function} clazz A class to extend this class
*/
Class.extend = function (clazz) {
var _super, fakeClass, prototype;
// Setup a fake class so we can create a prototype instance without calling the
// parent constructor
_super = this.prototype;
fakeClass = function () {};
fakeClass.prototype = _super;
// Create our prototype instance
prototype = new fakeClass();
// Setup the prototype and the constructor
clazz.prototype = prototype;
clazz.prototype.constructor = clazz;
// Make sure the new class has the static extend method
clazz.extend = Class.extend;
};
//Signals
/**
* Object that represents a binding between a Signal and a listener function.
* <br />- <strong>This is an internal constructor and shouldn't be called by regular users.</strong>
* <br />- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes.
* @author Miller Medeiros
* @constructor
* @param {adobeDPS-Signal} signal Reference to Signal object that listener is currently bound to.
* @param {Function} listener Handler function bound to the signal.
* @param {boolean} isOnce If binding should be executed just once.
* @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param {Number} [priority] The priority level of the event listener. (default = 0).
*/
function SignalBinding(signal, listener, isOnce, listenerContext, priority) {
/**
* Handler function bound to the signal.
* @type Function
* @private
*/
this._listener = listener;
/**
* If binding should be executed just once.
* @type boolean
* @private
*/
this._isOnce = isOnce;
/**
* Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @memberOf adobeDPS-SignalBinding.prototype
* @name context
* @type Object|undefined|null
*/
this.context = listenerContext;
/**
* Reference to Signal object that listener is currently bound to.
* @type signals.Signal
* @private
*/
this._signal = signal;
/**
* Listener priority
* @type Number
* @private
*/
this._priority = priority || 0;
}
SignalBinding.prototype = /** @lends adobeDPS-SignalBinding.prototype */ {
/**
* If binding is active and should be executed.
* @type Boolean
*/
active : true,
/**
* Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters)
* @type Array|null
*/
params : null,
/**
* Call listener passing arbitrary parameters.
* <p>If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.</p>
* @param {Array} [paramsArr] Array of parameters that should be passed to the listener
* @return {*} Value returned by the listener.
*/
execute : function (paramsArr) {
var handlerReturn, params;
if (this.active && !!this._listener) {
params = this.params? this.params.concat(paramsArr) : paramsArr;
var context = (this.context !== undefined) ? this.context : window;
handlerReturn = this._listener.apply(context, params);
if (this._isOnce) {
this.detach();
}
}
return handlerReturn;
},
/**
* Detach binding from signal.
* - alias to: mySignal.remove(myBinding.getListener());
* @return {Function|null} Handler function bound to the signal or `null` if binding was previously detached.
*/
detach : function () {
return this.isBound()? this._signal.remove(this._listener, this.context) : null;
},
/**
* @return {Boolean} `true` if binding is still bound to the signal and have a listener.
*/
isBound : function () {
return (!!this._signal && !!this._listener);
},
/**
* @return {Function} Handler function bound to the signal.
*/
getListener : function () {
return this._listener;
},
/**
* Delete instance properties
* @private
*/
_destroy : function () {
delete this._signal;
delete this._listener;
delete this.context;
},
/**
* @return {Boolean} If SignalBinding will only be executed once.
*/
isOnce : function () {
return this._isOnce;
},
/**
* @return {String} String representation of the object.
*/
toString : function () {
return '[SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']';
}
};
/**
* Custom event broadcaster
* <br />- inspired by Robert Penner's AS3 Signals.
* @author Miller Medeiros
* @constructor
*/
function Signal() {
/**
* @type Array.<adobeDPS-SignalBinding>
* @private
*/
this._bindings = [];
this._prevParams = null;
}
Signal.validateListener = function (listener, fnName) {
if (typeof listener !== 'function') {
throw new Error( 'listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName) );
}
};
Signal.prototype =
/** @lends adobeDPS-Signal.prototype */
{
/**
* If Signal should keep record of previously dispatched parameters and
* automatically execute listener during `add()`/`addOnce()` if Signal was
* already dispatched before.
* @type Boolean
*/
memorize : false,
/**
* @type Boolean
* @private
*/
_shouldPropagate : true,
/**
* If Signal is active and should broadcast events.
* <p><strong>IMPORTANT:</strong> Setting this property during a dispatch will only affect the next dispatch, if you want to stop the propagation of a signal use `halt()` instead.</p>
* @type Boolean
*/
active : true,
/**
* @param {Function} listener
* @param {Boolean} isOnce
* @param {Object} [listenerContext]
* @param {Number} [priority]
* @return {adobeDPS-SignalBinding}
* @private
*/
_registerListener : function (listener, isOnce, listenerContext, priority) {
var prevIndex = this._indexOfListener(listener, listenerContext),
binding;
if (prevIndex !== -1) {
binding = this._bindings[prevIndex];
if (binding.isOnce() !== isOnce) {
throw new Error('You cannot add'+ (isOnce? '' : 'Once') +'() then add'+ (!isOnce? '' : 'Once') +'() the same listener without removing the relationship first.');
}
} else {
binding = new SignalBinding(this, listener, isOnce, listenerContext, priority);
this._addBinding(binding);
}
if(this.memorize && this._prevParams){
binding.execute(this._prevParams);
}
return binding;
},
/**
* @param {adobeDPS-SignalBinding} binding
* @private
*/
_addBinding : function (binding) {
//simplified insertion sort
var n = this._bindings.length;
do { --n; } while (this._bindings[n] && binding._priority <= this._bindings[n]._priority);
this._bindings.splice(n + 1, 0, binding);
},
/**
* @param {Function} listener
* @return {Number}
* @private
*/
_indexOfListener : function (listener, context) {
var n = this._bindings.length,
cur;
while (n--) {
cur = this._bindings[n];
if (cur._listener === listener && cur.context === context) {
return n;
}
}
return -1;
},
/**
* Check if listener was attached to Signal.
* @param {Function} listener
* @param {Object} [context]
* @return {Boolean} if Signal has the specified listener.
*/
has : function (listener, context) {
return this._indexOfListener(listener, context) !== -1;
},
/**
* Add a listener to the signal.
* @param {Function} listener Signal handler function.
* @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
* @return {adobeDPS-SignalBinding} An Object representing the binding between the Signal and listener.
*/
add : function (listener, listenerContext, priority) {
Signal.validateListener(listener, 'add');
return this._registerListener(listener, false, listenerContext, priority);
},
/**
* Add listener to the signal that should be removed after first execution (will be executed only once).
* @param {Function} listener Signal handler function.
* @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
* @return {adobeDPS-SignalBinding} An Object representing the binding between the Signal and listener.
*/
addOnce : function (listener, listenerContext, priority) {
Signal.validateListener(listener, 'addOnce');
return this._registerListener(listener, true, listenerContext, priority);
},
/**
* Remove a single listener from the dispatch queue.
* @param {Function} listener Handler function that should be removed.
* @param {Object} [context] Execution context (since you can add the same handler multiple times if executing in a different context).
* @return {Function} Listener handler function.
*/
remove : function (listener, context) {
Signal.validateListener(listener, 'remove');
var i = this._indexOfListener(listener, context);
if (i !== -1) {
this._bindings[i]._destroy(); //no reason to a SignalBinding exist if it isn't attached to a signal
this._bindings.splice(i, 1);
}
return listener;
},
/**
* Remove all listeners from the Signal.
*/
removeAll : function () {
var n = this._bindings.length;
while (n--) {
this._bindings[n]._destroy();
}
this._bindings.length = 0;
},
/**
* @return {Number} Number of listeners attached to the Signal.
*/
getNumListeners : function () {
return this._bindings.length;
},
/**
* Stop propagation of the event, blocking the dispatch to next listeners on the queue.
* <p><strong>IMPORTANT:</strong> should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.</p>
* @see adobeDPS-Signal.prototype.disable
*/
halt : function () {
this._shouldPropagate = false;
},
/**
* Dispatch/Broadcast Signal to all listeners added to the queue.
* @param {...*} [params] Parameters that should be passed to each handler.
*/
dispatch : function (params) {
if (! this.active) {
return;
}
var paramsArr = Array.prototype.slice.call(arguments),
n = this._bindings.length,
bindings;
if (this.memorize) {
this._prevParams = paramsArr;
}
if (! n) {
//should come after memorize
return;
}
bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch
this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch.
//execute all callbacks until end of the list or until a callback returns `false` or stops propagation
//reverse loop since listeners with higher priority will be added at the end of the list
do { n--; } while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false);
},
/**
* Forget memorized arguments.
* @see adobeDPS-Signal.memorize
*/
forget : function(){
this._prevParams = null;
},
/**
* Remove all bindings from signal and destroy any reference to external objects (destroy Signal object).
* <p><strong>IMPORTANT:</strong> calling any method on the signal instance after calling dispose will throw errors.</p>
*/
dispose : function () {
this.removeAll();
delete this._bindings;
delete this._prevParams;
},
/**
* @return {String} String representation of the object.
*/
toString : function () {
return '[Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']';
}
};
/**
* Enum for the possible errors coming from the LibraryAPI transactions
* @see adobeDPS-TransactionError#code
* @namespace
* @enum {Number}
*/
var TransactionErrorType = {
/**
* <strong>Value: -100</strong>
* <br/>Indicates the Library could not connect to the Internet to complete a transaction.
*/
TransactionCannotConnectToInternetError:-100,
/**
* <strong>Value: -110</strong>
* <br/>Indicates the Library could not connect to the particular server needed to complete a transaction.
*/
TransactionCannotConnectToServerError:-110,
/**
* <strong>Value: -150</strong>
* <br/>Indicates the provided credentials were not recognized by the entitlement server.
*/
TransactionAuthenticationUnrecognizedCredentialsError: -150,
/**
* <strong>Value: -200</strong>
* <br/>Indicates folio and subscription purchasing is disabled on this device.
*/
TransactionFolioPurchasingDisabledError: -200,
/**
* <strong>Value: -210</strong>
* <br/>Indicates a single folio purchase transaction failed because an error occurred communicating with the in-app purchase system.
*/
TransactionFolioCannotPurchaseError: -210,
/**
* <strong>Value: -220</strong>
* <br/>Indicates a subscription purchase transaction failed because an error occurred communicating with the in-app purchase system.
*/
TransactionSubscriptionCannotPurchaseError: -220,
/**
* <strong>Value: -225</strong>
* <br/>Indicates there was an error attempting to resolve the valid date ranges for a subscription.
*/
TransactionSubscriptionResolveError: -225,
/**