-
Notifications
You must be signed in to change notification settings - Fork 199
/
Browser.js
2091 lines (1819 loc) · 75.3 KB
/
Browser.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
var _gaq = _gaq || []; // global task queue for Google Analytics
require( {
packages: [ 'dijit', 'dojox', 'jszlib',
{ name: 'lazyload', main: 'lazyload' },
'dgrid', 'xstyle', 'put-selector'
]
},
[],
function() {
define( [
'dojo/_base/lang',
'dojo/on',
'dojo/_base/Deferred',
'dojo/DeferredList',
'dojo/topic',
'dojo/aspect',
'dojo/_base/array',
'dijit/layout/ContentPane',
'dijit/layout/BorderContainer',
'dijit/Dialog',
'dijit/form/ComboBox',
'dijit/form/Button',
'dijit/form/Select',
'dijit/form/DropDownButton',
'dijit/DropDownMenu',
'dijit/MenuItem',
'JBrowse/Util',
'JBrowse/Store/LazyTrie',
'JBrowse/Store/Names/LazyTrieDojoData',
'dojo/store/DataStore',
'JBrowse/Store/Names/Hash',
'JBrowse/GenomeView',
'JBrowse/TouchScreenSupport',
'JBrowse/ConfigManager',
'JBrowse/View/InfoDialog',
'JBrowse/View/FileDialog',
'JBrowse/View/LocationChoiceDialog',
'dijit/focus',
'lazyload', // for dynamic CSS loading
'dojo/domReady!'
],
function(
lang,
on,
Deferred,
DeferredList,
topic,
aspect,
array,
dijitContentPane,
dijitBorderContainer,
dijitDialog,
dijitComboBox,
dijitButton,
dijitSelectBox,
dijitDropDownButton,
dijitDropDownMenu,
dijitMenuItem,
Util,
LazyTrie,
NamesLazyTrieDojoDataStore,
DojoDataStore,
NamesHashStore,
GenomeView,
Touch,
ConfigManager,
InfoDialog,
FileDialog,
LocationChoiceDialog,
dijitFocus,
LazyLoad
) {
var dojof = Util.dojof;
/**
* Construct a new Browser object.
* @class This class is the main interface between JBrowse and embedders
* @constructor
* @param params an object with the following properties:<br>
* <ul>
* <li><code>config</code> - list of objects with "url" property that points to a config JSON file</li>
* <li><code>containerID</code> - ID of the HTML element that contains the browser</li>
* <li><code>refSeqs</code> - object with "url" property that is the URL to list of reference sequence information items</li>
* <li><code>browserRoot</code> - (optional) URL prefix for the browser code</li>
* <li><code>tracks</code> - (optional) comma-delimited string containing initial list of tracks to view</li>
* <li><code>location</code> - (optional) string describing the initial location</li>
* <li><code>defaultTracks</code> - (optional) comma-delimited string containing initial list of tracks to view if there are no cookies and no "tracks" parameter</li>
* <li><code>defaultLocation</code> - (optional) string describing the initial location if there are no cookies and no "location" parameter</li>
* <li><code>show_nav</code> - (optional) string describing the on/off state of navigation box</li>
* <li><code>show_tracklist</code> - (optional) string describing the on/off state of track bar</li>
* <li><code>show_overview</code> - (optional) string describing the on/off state of overview</li>
* </ul>
*/
var Browser = function(params) {
this.globalKeyboardShortcuts = {};
this.config = params;
if( ! this.config.baseUrl )
this.config.baseUrl = Util.resolveUrl( window.location.href, '.' ) + '/data/';
this.startTime = Date.now();
this.container = dojo.byId(this.config.containerID);
this.container.onselectstart = function() { return false; };
this.container.genomeBrowser = this;
// schedule the config load, the first step in the initialization
// process, to happen when the page is done loading
var thisB = this;
dojo.addOnLoad( function() {
thisB.loadConfig().then( function() {
thisB.loadNames();
thisB.loadUserCSS().then( function() {
thisB.initPlugins().then( function() {
thisB.initTrackMetadata();
thisB.loadRefSeqs().then( function() {
thisB.initView().then( function() {
Touch.loadTouch(); // init touch device support
thisB.navigateTo( thisB._initialLocation() );
thisB.passMilestone( 'completely initialized', { success: true } );
});
thisB.reportUsageStats();
});
});
});
});
});
};
Browser.prototype._initialLocation = function() {
var oldLocMap = dojo.fromJson( this.cookie('location') ) || {};
if( this.config.location ) {
return this.config.location;
} else if( oldLocMap[this.refSeq.name] ) {
return oldLocMap[this.refSeq.name].l || oldLocMap[this.refSeq.name];
} else if( this.config.defaultLocation ){
return this.config.defaultLocation;
} else {
return Util.assembleLocString({
ref: this.refSeq.name,
start: 0.4 * ( this.refSeq.start + this.refSeq.end ),
end: 0.6 * ( this.refSeq.start + this.refSeq.end )
});
}
};
Browser.prototype.version = function() {
var BUILD_SYSTEM_JBROWSE_VERSION;
return BUILD_SYSTEM_JBROWSE_VERSION || 'development';
}.call();
/**
* Get a plugin, if it is present. Note that, if plugin
* initialization is not yet complete, it may be a while before the
* callback is called.
*
* Callback is called with one parameter, the desired plugin object,
* or undefined if it does not exist.
*/
Browser.prototype.getPlugin = function( name, callback ) {
this.afterMilestone( 'initPlugins', dojo.hitch( this, function() {
callback( this.plugins[name] );
}));
};
/**
* Load and instantiate any plugins defined in the configuration.
*/
Browser.prototype.initPlugins = function() {
return this._milestoneFunction( 'initPlugins', function( deferred ) {
this.plugins = {};
var plugins = this.config.plugins || [];
if( ! plugins ) {
deferred.resolve({success: true});
return;
}
// coerce plugins to array of objects
plugins = array.map( dojo.isArray(plugins) ? plugins : [plugins], function( p ) {
return typeof p == 'object' ? p : { 'name': p };
});
var pluginNames = array.map( plugins, function( p ) {
return p.name;
});
var pluginDeferreds = array.map( plugins, function(p) {
return new Deferred();
});
// fire the "all plugins done" deferred when all of the plugins are done loading
(new DeferredList( pluginDeferreds ))
.then( function() { deferred.resolve({success: true}); });
require( {
packages: array.map( pluginNames, function(c) { return { name: c, location: "../plugins/"+c+"/js" }; })
},
pluginNames,
dojo.hitch( this, function() {
array.forEach( arguments, function( pluginClass, i ) {
var pluginName = pluginNames[i];
var thisPluginDone = pluginDeferreds[i];
if( typeof pluginClass == 'string' ) {
console.error("could not load plugin "+pluginName+": "+pluginClass);
} else {
// make the plugin's arguments out of
// its little obj in 'plugins', and
// also anything in the top-level
// conf under its plugin name
var args = dojo.mixin(
dojo.clone( plugins[i] ),
this.config[pluginName]||{});
args.browser = this;
args = dojo.mixin( args, { browser: this } );
// load its css
this._loadCSS(
{url: 'plugins/'+pluginName+'/css/main.css'},
function() {
thisPluginDone.resolve({success:true});
},
function() {
// succeed loading even if the css load failed. not all plugins necessarily have css
thisPluginDone.resolve({success:true});
}
);
// instantiate the plugin
var plugin = new pluginClass( args );
this.plugins[ pluginName ] = plugin;
}
}, this );
}));
});
};
/**
* Displays links to configuration help in the main window. Called
* when the main browser cannot run at all, due to configuration
* errors or whatever.
*/
Browser.prototype.fatalError = function( error ) {
if( error ) {
error = error+'';
if( ! /\.$/.exec(error) )
error = error + '.';
}
if( ! this.hasFatalErrors ) {
var container =
dojo.byId(this.config.containerID || 'GenomeBrowser')
|| document.body;
container.innerHTML = ''
+ '<div class="fatal_error">'
+ ' <h1>Congratulations, JBrowse is on the web!</h1>'
+ " <p>However, JBrowse could not start, either because it has not yet been configured"
+ " and loaded with data, or because of an error.</p>"
+ " <p style=\"font-size: 110%; font-weight: bold\"><a title=\"View the tutorial\" href=\"docs/tutorial/\">If this is your first time running JBrowse, click here to follow the Quick-start Tutorial to get up and running.</a></p>"
+ " <p>Otherwise, please refer to the following resources for help in getting JBrowse up and running.</p>"
+ ' <ul><li><a target="_blank" href="docs/tutorial/">Quick-start tutorial</a></li>'
+ ' <li><a target="_blank" href="http://gmod.org/wiki/JBrowse">JBrowse wiki</a></li>'
+ ' <li><a target="_blank" href="docs/config.html">Configuration reference</a></li>'
+ ' <li><a target="_blank" href="docs/featureglyphs.html">Feature glyph reference</a></li>'
+ ' </ul>'
+ ' <div id="fatal_error_list" class="errors"> <h2>Error message(s):</h2>'
+ ( error ? '<div class="error"> '+error+'</div>' : '' )
+ ' </div>'
+ '</div>'
;
this.hasFatalErrors = true;
} else {
var errors_div = dojo.byId('fatal_error_list') || document.body;
dojo.create('div', { className: 'error', innerHTML: error+'' }, errors_div );
}
};
Browser.prototype.loadRefSeqs = function() {
return this._milestoneFunction( 'loadRefSeqs', function( deferred ) {
// load our ref seqs
if( typeof this.config.refSeqs == 'string' )
this.config.refSeqs = { url: this.config.refSeqs };
dojo.xhrGet(
{
url: this.config.refSeqs.url,
handleAs: 'json',
load: dojo.hitch( this, function(o) {
this.addRefseqs( o );
deferred.resolve({success:true});
}),
error: dojo.hitch( this, function(e) {
this.fatalError('Failed to load reference sequence info: '+e);
deferred.resolve({ success: false, error: e });
})
});
});
};
/**
* Event that fires when the reference sequences have been loaded.
*/
Browser.prototype.onRefSeqsLoaded = function() {};
Browser.prototype.loadUserCSS = function() {
return this._milestoneFunction( 'loadUserCSS', function( deferred ) {
if( this.config.css && ! dojo.isArray( this.config.css ) )
this.config.css = [ this.config.css ];
var css = this.config.css || [];
if( ! css.length ) {
deferred.resolve({success:true});
return;
}
var that = this;
var cssDeferreds = array.map( css, function( css ) {
var d = new Deferred();
that._loadCSS(
css,
function() { d.resolve({success:true}); },
function() { d.resolve({success:false}); }
);
return d;
});
new DeferredList(cssDeferreds)
.then( function() { deferred.resolve({success:true}); } );
});
};
Browser.prototype._loadCSS = function( css, successCallback, errorCallback ) {
if( typeof css == 'string' ) {
// if it has '{' in it, it probably is not a URL, but is a string of CSS statements
if( css.indexOf('{') > -1 ) {
dojo.create('style', { "data-from": 'JBrowse Config', type: 'text/css', innerHTML: css }, document.head );
successCallback && successCallback();
}
// otherwise, it must be a URL
else {
css = { url: css };
}
}
if( typeof css == 'object' ) {
LazyLoad.css( css.url, successCallback );
}
};
/**
* Load our name index.
*/
Browser.prototype.loadNames = function() {
return this._milestoneFunction( 'loadNames', function( deferred ) {
var conf = dojo.mixin( dojo.clone( this.config.names || {} ),
this.config.autocomplete || {} );
if( ! conf.url )
conf.url = this.config.nameUrl || 'data/names/';
if( conf.baseUrl )
conf.url = Util.resolveUrl( conf.baseUrl, conf.url );
if( conf.type == 'Hash' )
this.nameStore = new NamesHashStore( dojo.mixin({ browser: this }, conf) );
else
// wrap the older LazyTrieDojoDataStore with
// dojo.store.DataStore to conform with the dojo/store API
this.nameStore = new DojoDataStore({
store: new NamesLazyTrieDojoDataStore({
browser: this,
namesTrie: new LazyTrie( conf.url, "lazy-{Chunk}.json"),
stopPrefixes: conf.stopPrefixes,
resultLimit: conf.resultLimit || 15,
tooManyMatchesMessage: conf.tooManyMatchesMessage
})
});
deferred.resolve({success: true});
});
};
Browser.prototype.initView = function() {
var thisObj = this;
return this._milestoneFunction('initView', function( deferred ) {
//set up top nav/overview pane and main GenomeView pane
dojo.addClass( this.container, "jbrowse"); // browser container has an overall .jbrowse class
dojo.addClass( document.body, this.config.theme || "tundra"); //< tundra dijit theme
var topPane = dojo.create( 'div',{ style: {overflow: 'hidden'}}, this.container );
// make our top menu bar
var menuBar = dojo.create(
'div',
{
className: this.config.show_nav ? 'menuBar' : 'topLink'
}
);
thisObj.menuBar = menuBar;
( this.config.show_nav ? topPane : this.container ).appendChild( menuBar );
var overview = dojo.create( 'div', { className: 'overview', id: 'overview' }, topPane );
this.overviewDiv = overview;
// overview=0 hides the overview, but we still need it to exist
if( ! this.config.show_overview )
overview.style.cssText = "display: none";
if( this.config.show_nav )
this.navbox = this.createNavBox( topPane );
// make our little top-links box with links to help, etc.
this.poweredByLink = dojo.create('a', {
className: 'powered_by',
innerHTML: 'JBrowse',
href: 'http://jbrowse.org',
title: 'powered by JBrowse'
}, menuBar );
if( this.config.show_nav ) {
this.addGlobalMenuItem( 'file',
new dijitMenuItem(
{
label: 'Open',
iconClass: 'dijitIconFolderOpen',
onClick: dojo.hitch( this, 'openFileDialog' )
})
);
var fileMenu = this.makeGlobalMenu('file');
if( fileMenu ) {
var fileButton = new dijitDropDownButton(
{ className: 'file',
innerHTML: 'File',
//title: '',
dropDown: fileMenu
});
dojo.addClass( fileButton.domNode, 'menu' );
menuBar.appendChild( fileButton.domNode );
}
var configMenu = this.makeGlobalMenu('options');
if( configMenu ) {
var configLink = new dijitDropDownButton(
{ className: 'config',
innerHTML: '<span class="icon"></span> Options',
title: 'configure JBrowse',
dropDown: configMenu
});
menuBar.appendChild( configLink.domNode );
}
}
if( this.config.show_nav && this.config.show_tracklist && this.config.show_overview )
menuBar.appendChild( this.makeShareLink() );
else
menuBar.appendChild( this.makeFullViewLink() );
if( this.config.show_nav )
menuBar.appendChild( this.makeHelpDialog() );
this.viewElem = document.createElement("div");
this.viewElem.className = "dragWindow";
this.container.appendChild( this.viewElem);
this.containerWidget = new dijitBorderContainer({
liveSplitters: false,
design: "sidebar",
gutters: false
}, this.container);
var contentWidget =
new dijitContentPane({region: "top"}, topPane);
// hook up GenomeView
this.view = this.viewElem.view =
new GenomeView(this, this.viewElem, 250, this.refSeq, 1/200 );
dojo.connect( this.view, "onFineMove", this, "onFineMove" );
dojo.connect( this.view, "onCoarseMove", this, "onCoarseMove" );
this.browserWidget =
new dijitContentPane({region: "center"}, this.viewElem);
dojo.connect( this.browserWidget, "resize", this, 'onResize' );
dojo.connect( this.browserWidget, "resize", this.view, 'onResize' );
//set initial location
this.afterMilestone( 'loadRefSeqs', dojo.hitch( this, function() {
this.afterMilestone( 'initTrackMetadata', dojo.hitch( this, function() {
this.createTrackList().then( dojo.hitch( this, function() {
this.containerWidget.startup();
this.onResize();
this.view.onResize();
// make our global keyboard shortcut handler
on( document.body, 'keypress', dojo.hitch( this, 'globalKeyHandler' ));
// configure our event routing
this._initEventRouting();
// done with initView
deferred.resolve({ success: true });
}));
}));
}));
});
};
/**
* Track type registry, used by GUI elements that need to offer
* options regarding selecting track types. Can register a track
* type, and get the data structure describing what track types are
* known.
*/
Browser.prototype.registerTrackType = function( args ) {
var types = this.getTrackTypes();
var typeName = args.type;
var defaultFor = args.defaultForStoreTypes || [];
var humanLabel = args.label;
// add it to known track types
types.knownTrackTypes.push( typeName );
// add its label
if( args.label )
types.trackTypeLabels[typeName] = args.label;
// uniqify knownTrackTypes
var seen = {};
types.knownTrackTypes = array.filter( types.knownTrackTypes, function( type ) {
var s = seen[type];
seen[type] = true;
return !s;
});
// set it as default for the indicated types, if any
array.forEach( defaultFor, function( storeName ) {
types.trackTypeDefaults[storeName] = typeName;
});
// store the whole structure in this object
this._knownTrackTypes = types;
};
Browser.prototype.getTrackTypes = function() {
// create the default types if necessary
if( ! this._knownTrackTypes )
this._knownTrackTypes = {
// map of store type -> default track type to use for the store
trackTypeDefaults: {
'JBrowse/Store/SeqFeature/BAM' : 'JBrowse/View/Track/Alignments',
'JBrowse/Store/SeqFeature/NCList' : 'JBrowse/View/Track/HTMLFeatures',
'JBrowse/Store/SeqFeature/BigWig' : 'JBrowse/View/Track/Wiggle/XYPlot',
'JBrowse/Store/Sequence/StaticChunked': 'JBrowse/View/Track/Sequence'
},
knownTrackTypes: [
'JBrowse/View/Track/Alignments',
'JBrowse/View/Track/FeatureCoverage',
'JBrowse/View/Track/HTMLFeatures',
'JBrowse/View/Track/Wiggle/XYPlot',
'JBrowse/View/Track/Wiggle/Density',
'JBrowse/View/Track/Sequence'
],
trackTypeLabels: {
}
};
return this._knownTrackTypes;
};
Browser.prototype.openFileDialog = function() {
new FileDialog({ browser: this })
.show({
openCallback: dojo.hitch( this, function( results ) {
var confs = results.trackConfs || [];
if( confs.length ) {
// tuck away each of the store configurations in
// our store configuration, and replace them with
// their names.
array.forEach( confs, function( conf ) {
var storeConf = conf.store;
if( storeConf && typeof storeConf == 'object' ) {
delete conf.store;
var name = this._addStoreConfig( storeConf.name, storeConf );
conf.store = name;
}
},this);
// send out a message about how the user wants to create the new tracks
this.publish( '/jbrowse/v1/v/tracks/new', confs );
// if requested, send out another message that the user wants to show them
if( results.trackDisposition == 'openImmediately' )
this.publish( '/jbrowse/v1/v/tracks/show', confs );
}
})
});
};
Browser.prototype.addTracks = function( confs ) {
// just register the track configurations right now
this._addTrackConfigs( confs );
};
Browser.prototype.replaceTracks = function( confs ) {
// just add-or-replace the track configurations
this._replaceTrackConfigs( confs );
};
Browser.prototype.deleteTracks = function( confs ) {
// de-register the track configurations
this._deleteTrackConfigs( confs );
};
Browser.prototype.makeGlobalMenu = function( menuName ) {
var items = ( this._globalMenuItems || {} )[menuName] || [];
if( ! items.length )
return null;
var menu = new dijitDropDownMenu({ leftClickToOpen: true });
dojo.forEach( items, function( item ) {
menu.addChild( item );
});
dojo.addClass( menu.domNode, 'globalMenu' );
menu.startup();
return menu;
};
Browser.prototype.addGlobalMenuItem = function( menuName, item ) {
if( ! this._globalMenuItems )
this._globalMenuItems = {};
if( ! this._globalMenuItems[ menuName ] )
this._globalMenuItems[ menuName ] = [];
this._globalMenuItems[ menuName ].push( item );
};
/**
* Initialize our message routing, subscribing to messages, forwarding
* them around, and so forth.
*
* "v" (view)
* Requests from the user. These go only to the browser, which is
* the central point forx deciding what to do about them. This is
* usually just forwarding the command as one or more "c" messages.
*
* "c" (command)
* Commands from authority, like the Browser object. These cause
* things to actually happen in the UI: things to be shown or
* hidden, actions taken, and so forth.
*
* "n" (notification)
* Notification that something just happened.
*
* @private
*/
Browser.prototype._initEventRouting = function() {
var that = this;
that.subscribe('/jbrowse/v1/v/tracks/hide', function( trackConfigs ) {
that.publish( '/jbrowse/v1/c/tracks/hide', trackConfigs );
});
that.subscribe('/jbrowse/v1/v/tracks/show', function( trackConfigs ) {
that.addRecentlyUsedTracks( dojo.map(trackConfigs, function(c){ return c.label;}) );
that.publish( '/jbrowse/v1/c/tracks/show', trackConfigs );
});
that.subscribe('/jbrowse/v1/v/tracks/new', function( trackConfigs ) {
that.addTracks( trackConfigs );
that.publish( '/jbrowse/v1/c/tracks/new', trackConfigs );
});
that.subscribe('/jbrowse/v1/v/tracks/replace', function( trackConfigs ) {
that.replaceTracks( trackConfigs );
that.publish( '/jbrowse/v1/c/tracks/replace', trackConfigs );
});
that.subscribe('/jbrowse/v1/v/tracks/delete', function( trackConfigs ) {
that.deleteTracks( trackConfigs );
that.publish( '/jbrowse/v1/c/tracks/delete', trackConfigs );
});
};
/**
* Reports some anonymous usage statistics about this browsing
* instance. Currently reports the number of tracks in the instance
* and their type (feature, wiggle, etc), and the number of reference
* sequences and their average length.
*/
Browser.prototype.reportUsageStats = function() {
if( this.config.suppressUsageStatistics )
return;
var stats = this._calculateClientStats();
this._reportGoogleUsageStats( stats );
this._reportCustomUsageStats( stats );
};
// phones home to google analytics
Browser.prototype._reportGoogleUsageStats = function( stats ) {
_gaq.push.apply( _gaq, [
['_setAccount', 'UA-7115575-2'],
['_setDomainName', 'none'],
['_setAllowLinker', true],
['_setCustomVar', 1, 'tracks-count', stats['tracks-count'], 3 ],
['_setCustomVar', 2, 'refSeqs-count', stats['refSeqs-count'], 3 ],
['_setCustomVar', 3, 'refSeqs-avgLen', stats['refSeqs-avgLen'], 3 ],
['_setCustomVar', 4, 'jbrowse-version', stats['ver'], 3 ],
['_setCustomVar', 5, 'loadTime', stats['loadTime'], 3 ],
['_trackPageview']
]);
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www')
+ '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
};
// phones home to custom analytics at jbrowse.org
Browser.prototype._reportCustomUsageStats = function(stats) {
// phone home with a GET request made by a script tag
dojo.create(
'img',
{ style: {
display: 'none'
},
src: 'http://jbrowse.org/analytics/clientReport?'
+ dojo.objectToQuery( stats )
},
document.body
);
};
/**
* Get a store object from the store registry, loading its code and
* instantiating it if necessary.
*/
Browser.prototype.getStore = function( storeName, callback ) {
if( !callback ) throw 'invalid arguments';
var storeCache = this._storeCache || {};
this._storeCache = storeCache;
var storeRecord = storeCache[ storeName ];
if( storeRecord ) {
storeRecord.refCount++;
callback( storeRecord.store );
return;
}
var conf = this.config.stores[storeName];
if( ! conf ) {
console.error( "store "+storeName+" not defined" );
callback( null );
return;
}
var storeClassName = conf.type;
if( ! storeClassName ) {
console.warn( "store "+storeName+" has no type defined" );
callback( null );
return;
}
require( [ storeClassName ], dojo.hitch( this, function( storeClass ) {
var storeArgs = dojo.mixin( conf,
{
browser: this,
refSeq: this.refSeq
});
var store = new storeClass( storeArgs );
this._storeCache[ storeName ] = { refCount: 1, store: store };
callback( store );
}));
};
/**
* Add a store configuration to the browser. If name is falsy, will
* autogenerate one.
* @private
*/
var uniqCounter = 0;
Browser.prototype._addStoreConfig = function( /**String*/ name, /**Object*/ storeConfig ) {
name = name || 'addStore'+uniqCounter++;
if( ! this.config.stores )
this.config.stores = {};
if( ! this._storeCache )
this._storeCache = {};
if( this.config.stores[name] || this._storeCache[name] ) {
throw "store "+name+" already exists!";
}
this.config.stores[name] = storeConfig;
return name;
};
Browser.prototype.clearStores = function() {
this._storeCache = {};
};
/**
* Notifies the browser that the given named store is no longer being
* used by the calling component. Decrements the store's reference
* count, and if the store's reference count reaches zero, the store
* object will be discarded, to be recreated again later if needed.
*/
Browser.prototype.releaseStore = function( storeName ) {
var storeRecord = this._storeCache[storeName];
if( storeRecord && ! --storeRecord.refCount )
delete this._storeCache[storeName];
};
Browser.prototype._calculateClientStats = function() {
var scn = screen || window.screen;
// make a flat (i.e. non-nested) object for the stats, so that it
// encodes compactly in the query string
var date = new Date();
var stats = {
ver: this.version || 'dev',
'refSeqs-count': this.refSeqOrder.length,
'refSeqs-avgLen':
! this.refSeqOrder.length
? null
: dojof.reduce(
dojo.map( this.refSeqOrder,
function(name) {
var ref = this.allRefs[name];
if( !ref )
return 0;
return ref.end - ref.start;
},
this
),
'+'
),
'tracks-count': this.config.tracks.length,
'plugins': dojof.keys( this.plugins ).sort().join(','),
// screen geometry
'scn-h': scn ? scn.height : null,
'scn-w': scn ? scn.width : null,
// window geometry
'win-h':document.body.offsetHeight,
'win-w': document.body.offsetWidth,
// container geometry
'el-h': this.container.offsetHeight,
'el-w': this.container.offsetWidth,
// time param to prevent caching
t: date.getTime()/1000,
// also get local time zone offset
tzoffset: date.getTimezoneOffset(),
loadTime: (date.getTime() - this.startTime)/1000
};
// count the number and types of tracks
dojo.forEach( this.config.tracks, function(trackConfig) {
var typeKey = 'track-types-'+ trackConfig.type || 'null';
stats[ typeKey ] =
( stats[ typeKey ] || 0 ) + 1;
});
return stats;
};
Browser.prototype.publish = function() {
return topic.publish.apply( topic, arguments );
};
Browser.prototype.subscribe = function() {
return topic.subscribe.apply( topic, arguments );
};
Browser.prototype.onResize = function() {
if( this.navbox )
this.view.locationTrapHeight = dojo.marginBox( this.navbox ).h;
};
/**
* Get the list of the most recently used tracks, stored for this user
* in a cookie.
* @returns {Array[Object]} as <code>[{ time: (integer), label: (track label)}]</code>
*/
Browser.prototype.getRecentlyUsedTracks = function() {
return dojo.fromJson( this.cookie( 'recentTracks' ) || '[]' );
};
/**
* Add the given list of tracks as being recently used.
* @param trackLabels {Array[String]} array of track labels to add
*/
Browser.prototype.addRecentlyUsedTracks = function( trackLabels ) {
var seen = {};
var newRecent =
Util.uniq(
dojo.map( trackLabels, function(label) {
return {
label: label,
time: Math.round( new Date() / 1000 ) // secs since epoch
};
},this)
.concat( dojo.fromJson( this.cookie('recentTracks')) || [] ),
function(entry) {
return entry.label;
}
)
// limit by default to 20 recent tracks
.slice( 0, this.config.maxRecentTracks || 10 );
// set the recentTracks cookie, good for one year
this.cookie( 'recentTracks', newRecent, { expires: 365 } );
return newRecent;
};
/**
* Run a function that will eventually resolve the named Deferred
* (milestone).
* @param {String} name the name of the Deferred
*/
Browser.prototype._milestoneFunction = function( /**String*/ name, func ) {
var thisB = this;
var args = Array.prototype.slice.call( arguments, 2 );
var d = thisB._getDeferred( name );
args.unshift( d );
try {
func.apply( thisB, args ) ;
} catch(e) {
console.error(''+e, e.stack);
d.resolve({ success:false, error: e });
}
return d;
};
/**
* Fetch or create a named Deferred, which is how milestones are implemented.
*/
Browser.prototype._getDeferred = function( name ) {
if( ! this._deferred )
this._deferred = {};
return this._deferred[name] = this._deferred[name] || new Deferred();
};
/**
* Attach a callback to a milestone.
*/
Browser.prototype.afterMilestone = function( name, func ) {
return this._getDeferred(name)
.then( function() {
try {
func();
} catch( e ) {
console.error( ''+e, e.stack, e );
}
});
};
/**
* Indicate that we've reached a milestone in the initalization
* process. Will run all the callbacks associated with that
* milestone.
*/
Browser.prototype.passMilestone = function( name, result ) {
return this._getDeferred(name).resolve( result );
};
/**
* Return true if we have reached the named milestone, false otherwise.
*/
Browser.prototype.reachedMilestone = function( name ) {
return this._getDeferred(name).fired >= 0;
};
/**
* Load our configuration file(s) based on the parameters thex
* constructor was passed. Does not return until all files are
* loaded and merged in.
* @returns nothing meaningful
*/
Browser.prototype.loadConfig = function () {
return this._milestoneFunction( 'loadConfig', function( deferred ) {
var c = new ConfigManager({ config: this.config, defaults: this._configDefaults(), browser: this });
c.getFinalConfig( dojo.hitch(this, function( finishedConfig ) {
this.config = finishedConfig;