forked from chilipeppr/widget-xbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauto-generated-widget.html
1879 lines (1657 loc) · 59.9 KB
/
auto-generated-widget.html
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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Widget / Xbox</title>
<!-- ChiliPeppr is based on bootstrap CSS. -->
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<!-- Customized version of require.js for ChiliPeppr. Please see require.js docs for how
ChiliPeppr's dependency system works as it's based on require.js. -->
<script type='text/javascript' src="//i2dcui.appspot.com/js/require.js"></script>
<style type='text/css'>
/* CSS for ChiliPeppr Widget */
#com-chilipeppr-widget-xbox {
}
#com-chilipeppr-widget-xbox .nav-tabs>li>a {
padding: 2px 6px;
}
</style>
<script type='text/javascript'>
//<![CDATA[
/* global requirejs cprequire cpdefine chilipeppr THREE */
// Defining the globals above helps Cloud9 not show warnings for those variables
// ChiliPeppr Widget/Element Javascript
requirejs.config({
/*
Dependencies can be defined here. ChiliPeppr uses require.js so
please refer to http://requirejs.org/docs/api.html for info.
Most widgets will not need to define Javascript dependencies.
Make sure all URLs are https and http accessible. Try to use URLs
that start with // rather than http:// or https:// so they simply
use whatever method the main page uses.
Also, please make sure you are not loading dependencies from different
URLs that other widgets may already load like jquery, bootstrap,
three.js, etc.
You may slingshot content through ChiliPeppr's proxy URL if you desire
to enable SSL for non-SSL URL's. ChiliPeppr's SSL URL is
https://i2dcui.appspot.com which is the SSL equivalent for
http://chilipeppr.com
*/
paths: {
// Example of how to define the key (you make up the key) and the URL
// Make sure you DO NOT put the .js at the end of the URL
// SmoothieCharts: '//smoothiecharts.org/smoothie',
},
shim: {
// See require.js docs for how to define dependencies that
// should be loaded before your script/widget.
}
});
cprequire_test(["inline:com-chilipeppr-widget-xbox"], function(myWidget) {
// Test this element. This code is auto-removed by the chilipeppr.load()
// when using this widget in production. So use the cpquire_test to do things
// you only want to have happen during testing, like loading other widgets or
// doing unit tests. Don't remove end_test at the end or auto-remove will fail.
// Please note that if you are working on multiple widgets at the same time
// you may need to use the ?forcerefresh=true technique in the URL of
// your test widget to force the underlying chilipeppr.load() statements
// to referesh the cache. For example, if you are working on an Add-On
// widget to the Eagle BRD widget, but also working on the Eagle BRD widget
// at the same time you will have to make ample use of this technique to
// get changes to load correctly. If you keep wondering why you're not seeing
// your changes, try ?forcerefresh=true as a get parameter in your URL.
console.log("test running of " + myWidget.id);
$('body').prepend('<div id="testDivForFlashMessageWidget"></div>');
chilipeppr.load(
"#testDivForFlashMessageWidget",
"http://raw.githubusercontent.com/chilipeppr/element-flash/master/auto-generated-widget.html",
function() {
console.log("mycallback got called after loading flash msg module");
cprequire(["inline:com-chilipeppr-elem-flashmsg"], function(fm) {
//console.log("inside require of " + fm.id);
fm.init();
});
}
);
// init my widget
myWidget.init();
$('#' + myWidget.id).css('margin', '20px');
$('title').html(myWidget.name);
} /*end_test*/ );
// This is the main definition of your widget. Give it a unique name.
cpdefine("inline:com-chilipeppr-widget-xbox", ["chilipeppr_ready", /* other dependencies here */ ], function() {
return {
/**
* The ID of the widget. You must define this and make it unique.
*/
id: "com-chilipeppr-widget-xbox", // Make the id the same as the cpdefine id
name: "Widget / Xbox", // The descriptive name of your widget.
desc: "This widget lets you control ChiliPeppr from an Xbox controller.", // A description of what your widget does
url: "http://raw.githubusercontent.com/https://master/auto-generated-widget.html", // The final URL of the working widget as a single HTML file with CSS and Javascript inlined. You can let runme.js auto fill this if you are using Cloud9.
fiddleurl: "http://ide.c9.io/root/lenne0815", // The edit URL. This can be auto-filled by runme.js in Cloud9 if you'd like, or just define it on your own to help people know where they can edit/fork your widget
githuburl: "http://github.com/https:/", // The backing github repo
testurl: "http://lenne0815-root.c9users.io/widget.html", // The standalone working widget so can view it working by itself
/**
* Define pubsub signals below. These are basically ChiliPeppr's event system.
* ChiliPeppr uses amplify.js's pubsub system so please refer to docs at
* http://amplifyjs.com/api/pubsub/
*/
/**
* Define the publish signals that this widget/element owns or defines so that
* other widgets know how to subscribe to them and what they do.
*/
publish: {
// Define a key:value pair here as strings to document what signals you publish.
'/onExampleGenerate': 'Example: Publish this signal when we go to generate gcode.'
},
/**
* Define the subscribe signals that this widget/element owns or defines so that
* other widgets know how to subscribe to them and what they do.
*/
subscribe: {
// Define a key:value pair here as strings to document what signals you subscribe to
// so other widgets can publish to this widget to have it do something.
// '/onExampleConsume': 'Example: This widget subscribe to this signal so other widgets can send to us and we'll do something with it.'
},
/**
* Document the foreign publish signals, i.e. signals owned by other widgets
* or elements, that this widget/element publishes to.
*/
foreignPublish: {
// Define a key:value pair here as strings to document what signals you publish to
// that are owned by foreign/other widgets.
// '/jsonSend': 'Example: We send Gcode to the serial port widget to do stuff with the CNC controller.'
},
/**
* Document the foreign subscribe signals, i.e. signals owned by other widgets
* or elements, that this widget/element subscribes to.
*/
foreignSubscribe: {
// Define a key:value pair here as strings to document what signals you subscribe to
// that are owned by foreign/other widgets.
// '/com-chilipeppr-elem-dragdrop/ondropped': 'Example: We subscribe to this signal at a higher priority to intercept the signal. We do not let it propagate by returning false.'
},
/**
* All widgets should have an init method. It should be run by the
* instantiating code like a workspace or a different widget.
*/
init: function() {
console.log("I am being initted. Thanks.");
this.setupUiFromLocalStorage();
this.btnSetup();
this.forkSetup();
this.setupGamepad();
this.setupBody();
console.log("I am done being initted.");
},
// This is all by Lenne and Deniz ----v
accelBaseval: 1.00,
isPausedByPlanner: false, // keeps track of whether we've been told to pause sending by the planner buffer
sendCtr: 0,
publishSend: function(gcode) {
var jsonSend = {
D: gcode,
Id: "jog" + this.sendCtr
};
chilipeppr.publish("/com-chilipeppr-widget-serialport/jsonSend", jsonSend);
this.sendCtr++;
if (this.sendCtr > 999999) this.sendCtr = 0;
},
jog: function (direction, isFast, is100xFast, is1000xFast, is10000xFast) {
var key = direction;
var cmd = "G91 G0 ";
var feedrate = 200;
var mult = 1;
var xyz = "";
//var val = 0.001;
var val = 1.00;
//var baseval = 1.00;
var baseval = this.accelBaseval;
// adjust feedrate relative to acceleration
//feedrate = feedrate * ((this.accelBaseval / this.baseval) / 2);
if (key == "Y+") {
// up arrow. Y+
xyz = "Y";
val = baseval; //0.001;
} else if (key == "Y-") {
// down arrow. Y-
xyz = "Y";
val = -1 * baseval; //0.001;
} else if (key == "X+") {
// right arrow. X+
xyz = "X";
val = baseval; //0.001;
} else if (key == "X-") {
// left arrow. X-
xyz = "X";
val = -1 * baseval; //0.001;
} else if (key == "Z+") {
// page up. Z+
xyz = "Z";
val = baseval; //0.001;
} else if (key == "Z-") {
// page down. Z-
xyz = "Z";
val = -1 * baseval; //0.001;
}
val = val * mult;
if (xyz.length > 0) {
//cmd += xyz + val + " F" + feedrate + "\nG90\n";
cmd += xyz + val + "\nG90\n";
// do last minute check to see if planner buffer is too full, if so ignore this cmd
if (!(this.isPausedByPlanner)) {
//chilipeppr.publish("/com-chilipeppr-widget-serialport/send", cmd);
this.publishSend(cmd);
} else {
console.log("planner buffer full, so not sending jog cmd");
}
}
},
// END - This is all by Lenne and Deniz. ----^
/**
* Keep track of whether we sent flood/coolant on or off last time
*/
lastCoolantCmd: "",
/**
* This object holds the Gamepad library from https://github.com/kallaspriit/HTML5-JavaScript-Gamepad-Controller-Library
*/
Gamepad: null, // library
/**
* This object holds the instance of Gamepad library in a usable object.
*/
gamepad: null, // instance
/**
* This method sets up the events we bind to for receiving incoming actions from the
* Xbox controller.
*/
setupGamepad: function() {
// We used code from https://github.com/kallaspriit/HTML5-JavaScript-Gamepad-Controller-Library
// This gets up the library object
this.Gamepad = new this.initGamepadLibrary();
console.log("Gamepad:", this.Gamepad);
// This instantiates a usable object
this.gamepad = new this.Gamepad();
console.log("gamepad:", this.gamepad);
// Create convenience variables
var Gamepad = this.Gamepad;
var gamepad = this.gamepad;
// Keep reference to main "this" object so we can reference inside inner functions
var that = this;
// Attach to events
gamepad.bind(Gamepad.Event.CONNECTED, function(device) {
// a new gamepad connected
console.log("new gamepad connected. device:", device);
if (device.id.match(/xbox/i)) {
console.log("found xbox controller;");
chilipeppr.publish('/com-chilipeppr-elem-flashmsg/flashmsg',
"Xbox Controller Found", "Device: " + JSON.stringify(device, null, "\t"), 500, false);
}
});
gamepad.bind(Gamepad.Event.DISCONNECTED, function(device) {
// gamepad disconnected
console.log("gamepad disconnected. device:", device);
});
gamepad.bind(Gamepad.Event.UNSUPPORTED, function(device) {
// an unsupported gamepad connected (add new mapping)
console.log("an unsupported gamepad connected (add new mapping). device:", device);
});
gamepad.bind(Gamepad.Event.BUTTON_DOWN, function(e) {
// e.control of gamepad e.gamepad pressed down
console.log("e.control of gamepad e.gamepad pressed down. e:", e);
chilipeppr.publish('/com-chilipeppr-elem-flashmsg/flashmsg',
"Xbox Controller Button Down", "Control: " + e.control, 500, true);
// // Lenne und Deniz Test ----v
// var direction = null;
// if (e.control == "FACE_3") {
// // up arrow. Y+
// direction = "Y+";
// $('#com-chilipeppr-widget-xyz-ftr .jogy').addClass("hilite");
// }
// if (direction) {
// //that.jog(direction, isFast, is100xFast, is1000xFast, is10000xFast);
// that.jog(direction);
// }
// // Lenne und Deniz Test ----^
if (e.control == "SELECT_BACK") {
// Got Select button for Feedhold
that.sendGcode("!");
}
else if (e.control == "START_FORWARD") {
// Got Start button for Cycle-start
chilipeppr.publish('/com-chilipeppr-widget-gcode/onPlay', null);
}
if (e.control == "FACE_4") {
// Got Y button for Coolant
that.sendGcode("M7");
}
// else if (e.control == "FACE_4") {
// // Got coolant toggle
// // See what we sent last time and send other cmd
// if (that.lastCoolantCmd == "M7") {
// that.sendGcode("M9");
// that.lastCoolantCmd = "M9";
// }
// else {
// that.sendGcode("M7");
// that.lastCoolantCmd = "M7";
// }
// }
});
gamepad.bind(Gamepad.Event.BUTTON_UP, function(e) {
// e.control of gamepad e.gamepad released
console.log(" e.control of gamepad e.gamepad released. e:", e);
});
gamepad.bind(Gamepad.Event.AXIS_CHANGED, function(e) {
// e.axis changed to value e.value for gamepad e.gamepad
console.log(" e.axis changed to value e.value for gamepad e.gamepad. e:", e);
chilipeppr.publish('/com-chilipeppr-elem-flashmsg/flashmsg',
"Xbox Controller Axis Changed", "Axis: " + e.axis + ", Value:" + e.value, 500, true);
});
// gamepad.bind(Gamepad.Event.TICK, function(gamepads) {
// gamepads were updated (around 60 times a second)
// });
if (!gamepad.init()) {
// Your browser does not support gamepads, get the latest Google Chrome or Firefox
console.log("Your browser does not support gamepads, get the latest Google Chrome or Firefox");
} else {
// setTimeout(function() {
// chilipeppr.publish('/com-chilipeppr-elem-flashmsg/flashmsg',
// "Xbox Controller Initted", "Your browser supports Gamepad controllers.", null, 3000, true);
// }, 2000);
}
},
/**
* Send Gcode to the CNC controller using the awesome pubsub commands available
* throughout the ChiliPeppr environment. Check any widget to see what pubsubs they
* support for other widgets to publish to.
*/
sendGcode: function(gcode) {
// make sure there is a newline
if (gcode.match(/\n$/)) {
// already a newline at end
// console.log("already has newline");
} else {
gcode += "\n";
// console.log("added newline");
}
chilipeppr.publish("/com-chilipeppr-widget-serialport/send", gcode);
},
/**
* This method sets up the body of the widget, which at this time just allows you to
* click the image to get a modal popup for a larger version of the image.
*/
setupBody: function() {
// Make image clickable to show modal
var mainImg = $('#' + this.id + " .panel-body img");
mainImg.on('click', this.onMainBodyImgClick.bind(this));
},
onMainBodyImgClick: function(evt) {
console.log("got click on main image body. evt:", evt);
var modal = $('#com-chilipeppr-widget-xbox-modal');
modal.modal();
},
/**
* Call this method from init to setup all the buttons when this widget
* is first loaded. This basically attaches click events to your
* buttons. It also turns on all the bootstrap popovers by scanning
* the entire DOM of the widget.
*/
btnSetup: function() {
// Chevron hide/show body
var that = this;
$('#' + this.id + ' .hidebody').click(function(evt) {
console.log("hide/unhide body");
if ($('#' + that.id + ' .panel-body').hasClass('hidden')) {
// it's hidden, unhide
that.showBody(evt);
}
else {
// hide
that.hideBody(evt);
}
});
// Ask bootstrap to scan all the buttons in the widget to turn
// on popover menus
$('#' + this.id + ' .btn').popover({
delay: 1000,
animation: true,
placement: "auto",
trigger: "hover",
container: 'body'
});
// Init Say Hello Button on Main Toolbar
// We are inlining an anonymous method as the callback here
// as opposed to a full callback method in the Hello Word 2
// example further below. Notice we have to use "that" so
// that the this is set correctly inside the anonymous method
$('#' + this.id + ' .btn-sayhello').click(function() {
console.log("saying hello");
// Make sure popover is immediately hidden
$('#' + that.id + ' .btn-sayhello').popover("hide");
// Show a flash msg
chilipeppr.publish(
"/com-chilipeppr-elem-flashmsg/flashmsg",
"Hello Title",
"Hello World from widget " + that.id,
1000
);
});
// Init Hello World 2 button on Tab 1. Notice the use
// of the slick .bind(this) technique to correctly set "this"
// when the callback is called
$('#' + this.id + ' .btn-helloworld2').click(this.onHelloBtnClick.bind(this));
},
/**
* onHelloBtnClick is an example of a button click event callback
*/
onHelloBtnClick: function(evt) {
console.log("saying hello 2 from btn in tab 1");
chilipeppr.publish(
'/com-chilipeppr-elem-flashmsg/flashmsg',
"Hello 2 Title",
"Hello World 2 from Tab 1 from widget " + this.id,
2000 /* show for 2 second */
);
},
/**
* User options are available in this property for reference by your
* methods. If any change is made on these options, please call
* saveOptionsLocalStorage()
*/
options: null,
/**
* Call this method on init to setup the UI by reading the user's
* stored settings from localStorage and then adjust the UI to reflect
* what the user wants.
*/
setupUiFromLocalStorage: function() {
// Read vals from localStorage. Make sure to use a unique
// key specific to this widget so as not to overwrite other
// widgets' options. By using this.id as the prefix of the
// key we're safe that this will be unique.
// Feel free to add your own keys inside the options
// object for your own items
var options = localStorage.getItem(this.id + '-options');
if (options) {
options = $.parseJSON(options);
console.log("just evaled options: ", options);
}
else {
options = {
showBody: true,
tabShowing: 1,
customParam1: null,
customParam2: 1.0
};
}
this.options = options;
console.log("options:", options);
// show/hide body
if (options.showBody) {
this.showBody();
}
else {
this.hideBody();
}
},
/**
* When a user changes a value that is stored as an option setting, you
* should call this method immediately so that on next load the value
* is correctly set.
*/
saveOptionsLocalStorage: function() {
// You can add your own values to this.options to store them
// along with some of the normal stuff like showBody
var options = this.options;
var optionsStr = JSON.stringify(options);
console.log("saving options:", options, "json.stringify:", optionsStr);
// store settings to localStorage
localStorage.setItem(this.id + '-options', optionsStr);
},
/**
* Show the body of the panel.
* @param {jquery_event} evt - If you pass the event parameter in, we
* know it was clicked by the user and thus we store it for the next
* load so we can reset the user's preference. If you don't pass this
* value in we don't store the preference because it was likely code
* that sent in the param.
*/
showBody: function(evt) {
$('#' + this.id + ' .panel-body').removeClass('hidden');
$('#' + this.id + ' .panel-footer').removeClass('hidden');
$('#' + this.id + ' .hidebody span').addClass('glyphicon-chevron-up');
$('#' + this.id + ' .hidebody span').removeClass('glyphicon-chevron-down');
if (!(evt == null)) {
this.options.showBody = true;
this.saveOptionsLocalStorage();
}
// this will send an artificial event letting other widgets know to resize
// themselves since this widget is now taking up more room since it's showing
$(window).trigger("resize");
},
/**
* Hide the body of the panel.
* @param {jquery_event} evt - If you pass the event parameter in, we
* know it was clicked by the user and thus we store it for the next
* load so we can reset the user's preference. If you don't pass this
* value in we don't store the preference because it was likely code
* that sent in the param.
*/
hideBody: function(evt) {
$('#' + this.id + ' .panel-body').addClass('hidden');
$('#' + this.id + ' .panel-footer').addClass('hidden');
$('#' + this.id + ' .hidebody span').removeClass('glyphicon-chevron-up');
$('#' + this.id + ' .hidebody span').addClass('glyphicon-chevron-down');
if (!(evt == null)) {
this.options.showBody = false;
this.saveOptionsLocalStorage();
}
// this will send an artificial event letting other widgets know to resize
// themselves since this widget is now taking up less room since it's hiding
$(window).trigger("resize");
},
/**
* This method loads the pubsubviewer widget which attaches to our
* upper right corner triangle menu and generates 3 menu items like
* Pubsub Viewer, View Standalone, and Fork Widget. It also enables
* the modal dialog that shows the documentation for this widget.
*
* By using chilipeppr.load() we can ensure that the pubsubviewer widget
* is only loaded and inlined once into the final ChiliPeppr workspace.
* We are given back a reference to the instantiated singleton so its
* not instantiated more than once. Then we call it's attachTo method
* which creates the full pulldown menu for us and attaches the click
* events.
*/
forkSetup: function() {
var topCssSelector = '#' + this.id;
$(topCssSelector + ' .panel-title').popover({
title: this.name,
content: this.desc,
html: true,
delay: 1000,
animation: true,
trigger: 'hover',
placement: 'auto'
});
var that = this;
chilipeppr.load("http://raw.githubusercontent.com/chilipeppr/widget-pubsubviewer/master/auto-generated-widget.html", function() {
require(['inline:com-chilipeppr-elem-pubsubviewer'], function(pubsubviewer) {
pubsubviewer.attachTo($(topCssSelector + ' .panel-heading .dropdown-menu'), that);
});
});
},
/**
* Load the Gamepad library from: https://github.com/kallaspriit/HTML5-JavaScript-Gamepad-Controller-Library
*/
initGamepadLibrary: function() {
// Trick this library into instantiating locally so we have a reference to it
var module = {
exports: {},
};
/*
* Copyright 2012 Priit Kallas <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function(exports) {
'use strict';
/**
* A null function - does nothing, returns nothing
*/
var nullFunction = function() {};
/**
* The null platform, which doesn't support anything
*/
var nullPlatform = {
getType: function() {
return 'null';
},
isSupported: function() {
return false;
},
update: nullFunction
};
/**
* This strategy uses a timer function to call an update function.
* The timer (re)start function can be provided or the strategy reverts to
* one of the window.*requestAnimationFrame variants.
*
* @class AnimFrameUpdateStrategy
* @constructor
* @param {Function} [requestAnimationFrame] function to use for timer creation
* @module Gamepad
*/
var AnimFrameUpdateStrategy = function(requestAnimationFrame) {
var that = this;
var win = window;
this.update = nullFunction;
this.requestAnimationFrame = requestAnimationFrame || win.requestAnimationFrame ||
win.webkitRequestAnimationFrame || win.mozRequestAnimationFrame;
/**
* This method calls the (user) update and restarts itself
* @method tickFunction
*/
this.tickFunction = function() {
that.update();
that.startTicker();
};
/**
* (Re)Starts the ticker
* @method startTicker
*/
this.startTicker = function() {
that.requestAnimationFrame.apply(win, [that.tickFunction]);
};
};
/**
* Starts the update strategy using the given function
*
* @method start
* @param {Function} updateFunction the function to call at each update
*/
AnimFrameUpdateStrategy.prototype.start = function(updateFunction) {
this.update = updateFunction || nullFunction;
this.startTicker();
};
/**
* This strategy gives the user the ability to call the library internal
* update function on request. Use this strategy if you already have a
* timer function running by requestAnimationFrame and you need fine control
* over when the gamepads are updated.
*
* @class ManualUpdateStrategy
* @constructor
* @module Gamepad
*/
var ManualUpdateStrategy = function() {
};
/**
* Calls the update function in the started state. Does nothing otherwise.
* @method update
*/
ManualUpdateStrategy.prototype.update = nullFunction;
/**
* Starts the update strategy using the given function
*
* @method start
* @param {Function} updateFunction the function to call at each update
*/
ManualUpdateStrategy.prototype.start = function(updateFunction) {
this.update = updateFunction || nullFunction;
};
/**
* This platform is for webkit based environments that need to be polled
* for updates.
*
* @class WebKitPlatform
* @constructor
* @param {Object} listener the listener to provide _connect and _disconnect callbacks
* @param {Function} gamepadGetter the poll function to return an array of connected gamepads
* @module Gamepad
*/
var WebKitPlatform = function(listener, gamepadGetter) {
this.listener = listener;
this.gamepadGetter = gamepadGetter;
this.knownGamepads = [];
};
/**
* Provides a platform object that returns true for isSupported() if valid.
* @method factory
* @static
* @param {Object} listener the listener to use
* @return {Object} a platform object
*/
WebKitPlatform.factory = function(listener) {
var platform = nullPlatform;
var navigator = window && window.navigator;
if (navigator) {
if (typeof(navigator.getGamepads) !== 'undefined') {
platform = new WebKitPlatform(listener, function() {
return navigator.getGamepads();
});
} else if (typeof(navigator.webkitGamepads) !== 'undefined') {
platform = new WebKitPlatform(listener, function() {
return navigator.webkitGamepads();
});
} else if (typeof(navigator.webkitGetGamepads) !== 'undefined') {
platform = new WebKitPlatform(listener, function() {
return navigator.webkitGetGamepads();
});
}
}
return platform;
};
/**
* @method getType()
* @static
* @return {String} 'WebKit'
*/
WebKitPlatform.getType = function() {
return 'WebKit';
},
/**
* @method getType()
* @return {String} 'WebKit'
*/
WebKitPlatform.prototype.getType = function() {
return WebKitPlatform.getType();
},
/**
* @method isSupported
* @return {Boolean} true
*/
WebKitPlatform.prototype.isSupported = function() {
return true;
};
/**
* Queries the currently connected gamepads and reports any changes.
* @method update
*/
WebKitPlatform.prototype.update = function() {
var that = this;
var gamepads = Array.prototype.slice.call(this.gamepadGetter(), 0);
var gamepad;
var i;
for (i = this.knownGamepads.length - 1; i >= 0; i--) {
gamepad = this.knownGamepads[i];
if (gamepads.indexOf(gamepad) < 0) {
this.knownGamepads.splice(i, 1);
this.listener._disconnect(gamepad);
}
}
for (i = 0; i < gamepads.length; i++) {
gamepad = gamepads[i];
if (gamepad && (that.knownGamepads.indexOf(gamepad) < 0)) {
that.knownGamepads.push(gamepad);
that.listener._connect(gamepad);
}
}
};
/**
* This platform is for mozilla based environments that provide gamepad
* updates via events.
*
* @class FirefoxPlatform
* @constructor
* @module Gamepad
*/
var FirefoxPlatform = function(listener) {
this.listener = listener;
window.addEventListener('gamepadconnected', function(e) {
listener._connect(e.gamepad);
});
window.addEventListener('gamepaddisconnected', function(e) {
listener._disconnect(e.gamepad);
});
};
/**
* Provides a platform object that returns true for isSupported() if valid.
* @method factory
* @static
* @param {Object} listener the listener to use
* @return {Object} a platform object
*/
FirefoxPlatform.factory = function(listener) {
var platform = nullPlatform;
if (window && (typeof(window.addEventListener) !== 'undefined')) {
platform = new FirefoxPlatform(listener);
}
return platform;
};
/**
* @method getType()
* @static
* @return {String} 'Firefox'
*/
FirefoxPlatform.getType = function() {
return 'Firefox';
},
/**
* @method getType()
* @return {String} 'Firefox'
*/
FirefoxPlatform.prototype.getType = function() {
return FirefoxPlatform.getType();
},
/**
* @method isSupported
* @return {Boolean} true
*/
FirefoxPlatform.prototype.isSupported = function() {
var navigator = window && window.navigator;
return navigator.userAgent.indexOf('Firefox') !== -1;
};
/**
* Does nothing on the Firefox platform
* @method update
*/
FirefoxPlatform.prototype.update = nullFunction;
/**
* Provides simple interface and multi-platform support for the gamepad API.
*
* You can change the deadzone and maximizeThreshold parameters to suit your
* taste but the defaults should generally work fine.
*
* @class Gamepad
* @constructor
* @param {Object} [updateStrategy] an update strategy, defaulting to
* {{#crossLink "AnimFrameUpdateStrategy"}}{{/crossLink}}
* @module Gamepad
* @author Priit Kallas <[email protected]>
*/
var Gamepad = function(updateStrategy) {
this.updateStrategy = updateStrategy || new AnimFrameUpdateStrategy();
this.gamepads = [];
this.listeners = {};
this.platform = nullPlatform;
this.deadzone = 0.03;
this.maximizeThreshold = 0.97;
};
/**
* The available update strategies
* @property UpdateStrategies
* @param {AnimFrameUpdateStrategy} AnimFrameUpdateStrategy
* @param {ManualUpdateStrategy} ManualUpdateStrategy
*/
Gamepad.UpdateStrategies = {
AnimFrameUpdateStrategy: AnimFrameUpdateStrategy,
ManualUpdateStrategy: ManualUpdateStrategy
};
/**
* List of factories of supported platforms. Currently available platforms:
* {{#crossLink "WebKitPlatform"}}{{/crossLink}},
* {{#crossLink "FirefoxPlatform"}}{{/crossLink}},
* @property PlatformFactories
* @type {Array}
*/
Gamepad.PlatformFactories = [FirefoxPlatform.factory, WebKitPlatform.factory];
/**
* List of supported controller types.
*
* @property Type
* @param {String} Type.N64 Retrolink N64 controller
* @param {String} Type.PLAYSTATION Playstation controller
* @param {String} Type.LOGITECH Logitech controller
* @param {String} Type.XBOX XBOX controller
* @param {String} Type.UNKNOWN Unknown controller
*/
Gamepad.Type = {
N64: 'n64',
PLAYSTATION: 'playstation',
LOGITECH: 'logitech',
XBOX: 'xbox',
UNKNOWN: 'unknown'
};
/*
* List of events you can expect from the library.
*
* CONNECTED, DISCONNECTED and UNSUPPORTED events include the gamepad in
* question and tick provides the list of all connected gamepads.
*
* BUTTON_DOWN and BUTTON_UP events provide an alternative to polling button states at each tick.
*
* AXIS_CHANGED is called if a value of some specific axis changes.
*/
Gamepad.Event = {
/**
* Triggered when a new controller connects.
*
* @event connected
* @param {Object} device
*/
CONNECTED: 'connected',
/**
* Called when an unsupported controller connects.
*
* @event unsupported
* @param {Object} device
* @deprecated not used anymore. Any controller is supported.
*/
UNSUPPORTED: 'unsupported',
/**
* Triggered when a controller disconnects.
*
* @event disconnected