/
Browser.js
1746 lines (1522 loc) · 63.2 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
define( [
'dojo/_base/lang',
'dojo/on',
'dojo/_base/Deferred',
'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/Autocomplete',
'JBrowse/GenomeView',
'JBrowse/TouchScreenSupport',
'JBrowse/ConfigManager',
'JBrowse/View/InfoDialog',
'JBrowse/View/FileDialog'
],
function(
lang,
on,
Deferred,
topic,
aspect,
array,
dijitContentPane,
dijitBorderContainer,
dijitDialog,
dijitComboBox,
dijitButton,
dijitSelectBox,
dijitDropDownButton,
dijitDropDownMenu,
dijitMenuItem,
Util,
LazyTrie,
AutocompleteStore,
GenomeView,
Touch,
ConfigManager,
InfoDialog,
FileDialog
) {
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.deferredFunctions = [];
this.globalKeyboardShortcuts = {};
this.isInitialized = false;
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;
// init our touch device support
this.addDeferred( Touch.loadTouch );
// schedule the config load, the first step in the initialization
// process, to happen when the page is done loading
this._deferred = {};
var thisB = this;
dojo.addOnLoad( function() {
thisB.loadConfig().then( function() {
thisB.loadNames();
thisB.loadUserCSS().then( function() {
thisB.initPlugins().then( function() {
thisB.loadRefSeqs().then( function() {
thisB.initView();
thisB.reportUsageStats();
});
});
});
});
});
};
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.initPlugins().then(dojo.hitch( this, function() {
callback( this.plugins[name] );
}));
};
/**
* Load and instantiate any plugins defined in the configuration.
*/
Browser.prototype.initPlugins = function() {
return this._deferredFunction( 'plugin initalization', 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;
});
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];
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'});
// instantiate the plugin
var plugin = new pluginClass( args );
this.plugins[ pluginName ] = plugin;
}
}, this );
deferred.resolve({success: true});
}));
});
};
/**
* 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._deferredFunction( 'refseq loading', 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._deferredFunction( 'load user css', function( deferred ) {
if( this.config.css && ! dojo.isArray( this.config.css ) )
this.config.css = [ this.config.css ];
var css = this.config.css || [];
var toLoad = css.length;
if( toLoad ) {
dojo.forEach( this.config.css || [], dojo.hitch( this, '_loadCSS', function() {
if( ! --toLoad )
deferred.resolve({success:true});
}));
} else {
deferred.resolve({success:true});
}
});
};
Browser.prototype._loadCSS = function( css, callback ) {
if( typeof css == 'string' ) {
dojo.create('style', { type: 'text/css', innerHTML: css }, this.container );
callback();
} else if( typeof css == 'object' ) {
var link = dojo.create('link', { rel: 'stylesheet', href: css.url, type: 'text/css'}, document.head );
on( link, 'load', callback );
on( link, 'error', callback );
}
};
/**
* Load our name index.
*/
Browser.prototype.loadNames = function() {
return this._deferredFunction( 'name store loading', function( deferred ) {
// load our name index
if (this.config.nameUrl)
this.names = new LazyTrie(this.config.nameUrl, "lazy-{Chunk}.json");
deferred.resolve({success: true});
});
};
Browser.prototype.initView = function() {
//set up top nav/overview pane and main GenomeView pane
dojo.addClass(document.body, this.config.theme || "tundra");
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'
}
);
( 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.
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);
//create location trapezoid
if( this.config.show_nav ) {
this.locationTrap = dojo.create('div', {className: 'locationTrap'}, topPane );
this.locationTrap.className = "locationTrap";
}
// hook up GenomeView
this.view = this.viewElem.view =
new GenomeView(this, this.viewElem, 250, this.refSeq, 1/200,
this.config.browserRoot);
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.loadRefSeqs().then( dojo.hitch( this, function() {
this.initTrackMetadata().then( dojo.hitch( this, function() {
this.createTrackList().then( dojo.hitch( this, function() {
this.containerWidget.startup();
this.onResize();
this.view.onResize();
var oldLocMap = dojo.fromJson( this.cookie('location') ) || {};
if (this.config.location) {
this.navigateTo(this.config.location);
} else if (oldLocMap[this.refSeq.name]) {
this.navigateTo( oldLocMap[this.refSeq.name].l || oldLocMap[this.refSeq.name] );
} else if (this.config.defaultLocation){
this.navigateTo(this.config.defaultLocation);
} else {
this.navigateTo( Util.assembleLocString({
ref: this.refSeq.name,
start: 0.4 * ( this.refSeq.start + this.refSeq.end ),
end: 0.6 * ( this.refSeq.start + this.refSeq.end )
})
);
}
// make our global keyboard shortcut handler
dojo.connect( document.body, 'onkeypress', this, 'globalKeyHandler' );
// configure our event routing
this._initEventRouting();
this.isInitialized = true;
//if someone calls methods on this browser object
//before it's fully initialized, then we defer
//those functions until now
dojo.forEach( this.deferredFunctions, function(f) {
f.call(this);
},this );
this.deferredFunctions = [];
}));
}));
}));
};
Browser.prototype.openFileDialog = function() {
new FileDialog({ browser: this }).open();
};
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 event routing, which is mostly echoing logical
* commands from the user interacting with the views.
* @private
*/
Browser.prototype._initEventRouting = function() {
this.subscribe('/jbrowse/v1/v/tracks/hide', dojo.hitch( this, function( trackConfigs ) {
this.publish( '/jbrowse/v1/c/tracks/hide', trackConfigs );
}));
this.subscribe('/jbrowse/v1/v/tracks/show', dojo.hitch( this, function( trackConfigs ) {
this.addRecentlyUsedTracks( dojo.map(trackConfigs, function(c){ return c.label;}) );
this.publish( '/jbrowse/v1/c/tracks/show', 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( dojo.clone(conf),
{
browser: this,
refSeq: this.refSeq
});
var store = new storeClass( storeArgs );
this._storeCache[ storeName ] = { refCount: 1, store: store };
callback( store );
}));
};
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,
// 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;
};
Browser.prototype._deferredFunction = function( name, func ) {
var args = Array.prototype.slice.call( arguments, 2 );
var thisB = this;
this._deferred[name] = this._deferred[name] || (function() {
var d = new Deferred();
args.unshift( d );
try {
func.apply( thisB, args ) ;
} catch(e) {
console.error(''+e, e.stack);
d.resolve({ success:false, error: e });
}
return d;
}());
return this._deferred[name];
};
/**
* 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._deferredFunction( 'configuration loading', function( deferred ) {
var c = new ConfigManager({ config: this.config, defaults: this._configDefaults(), browser: this });
c.getFinalConfig( dojo.hitch(this, function( finishedConfig ) {
this.config = finishedConfig;
// index the track configurations by name
this.trackConfigsByName = {};
dojo.forEach( this.config.tracks || [], function(conf){
this.trackConfigsByName[conf.label] = conf;
},this);
// coerce some config keys to boolean
dojo.forEach( ['show_tracklist','show_nav','show_overview'], function(v) {
this.config[v] = this._coerceBoolean( this.config[v] );
},this);
// set empty tracks array if we have none
if( ! this.config.tracks )
this.config.tracks = [];
deferred.resolve({success:true});
}));
});
};
Browser.prototype._configDefaults = function() {
return {
tracks: [],
show_tracklist: true,
show_nav: true,
show_overview: true
};
};
/**
* Coerce a value of unknown type to a boolean, treating string 'true'
* and 'false' as the values they indicate, and string numbers as
* numbers.
* @private
*/
Browser.prototype._coerceBoolean = function(val) {
if( typeof val == 'string' ) {
val = val.toLowerCase();
if( val == 'true' ) {
return true;
}
else if( val == 'false' )
return false;
else
return parseInt(val);
}
else if( typeof val == 'boolean' ) {
return val;
}
else if( typeof val == 'number' ) {
return !!val;
}
else {
return true;
}
};
/**
* Add a function to be executed once JBrowse is initialized
* @param f function to be executed
*/
Browser.prototype.addDeferred = function(f) {
if (this.isInitialized)
f();
else
this.deferredFunctions.push(f);
};
/**
* @param refSeqs {Array} array of refseq records to add to the browser
*/
Browser.prototype.addRefseqs = function( refSeqs ) {
this.allRefs = this.allRefs || {};
this.refSeqOrder = this.refSeqOrder || [];
var refCookie = this.cookie('refseq');
dojo.forEach( refSeqs, function(r) {
if( ! this.allRefs[r.name] )
this.refSeqOrder.push(r.name);
this.allRefs[r.name] = r;
if( refCookie && r.name.toLowerCase() == refCookie.toLowerCase() ) {
this.refSeq = r;
}
},this);
this.refSeqOrder = this.refSeqOrder.sort();
this.refSeq = this.refSeq || refSeqs[0];
};
Browser.prototype.getCurrentRefSeq = function( name, callback ) {
return this.refSeq || {};
};
Browser.prototype.getRefSeq = function( name, callback ) {
if( typeof name != 'string' )
name = this.refSeqOrder[0];
callback( this.allRefs[ name ] );
};
/**
* @private
*/
Browser.prototype.onFineMove = function(startbp, endbp) {
if( this.locationTrap ) {
var length = this.view.ref.end - this.view.ref.start;
var trapLeft = Math.round((((startbp - this.view.ref.start) / length)
* this.view.overviewBox.w) + this.view.overviewBox.l);
var trapRight = Math.round((((endbp - this.view.ref.start) / length)
* this.view.overviewBox.w) + this.view.overviewBox.l);
var locationTrapStyle = dojo.isIE
? "top: " + this.view.overviewBox.t + "px;"
+ "height: " + this.view.overviewBox.h + "px;"
+ "left: " + trapLeft + "px;"
+ "width: " + (trapRight - trapLeft) + "px;"
+ "border-width: 0px"
: "top: " + this.view.overviewBox.t + "px;"
+ "height: " + this.view.overviewBox.h + "px;"
+ "left: " + this.view.overviewBox.l + "px;"
+ "width: " + (trapRight - trapLeft) + "px;"
+ "border-width: " + "0px "
+ (this.view.overviewBox.w - trapRight) + "px "
+ this.view.locationTrapHeight + "px " + trapLeft + "px;";
this.locationTrap.style.cssText = locationTrapStyle;
}
};
/**
* Asynchronously initialize our track metadata.
*/
Browser.prototype.initTrackMetadata = function( callback ) {
return this._deferredFunction( 'track metadata initialization', function( deferred ) {
var metaDataSourceClasses = dojo.map(
(this.config.trackMetadata||{}).sources || [],
function( sourceDef ) {
var url = sourceDef.url || 'trackMeta.csv';
var type = sourceDef.type || (
/\.csv$/i.test(url) ? 'csv' :
/\.js(on)?$/i.test(url) ? 'json' :
'csv'
);
var storeClass = sourceDef['class']
|| { csv: 'dojox/data/CsvStore', json: 'dojox/data/JsonRestStore' }[type];
if( !storeClass ) {
console.error( "No store class found for type '"
+type+"', cannot load track metadata from URL "+url);
return null;
}
return { class_: storeClass, url: url };
});
require( Array.prototype.concat.apply( ['JBrowse/Store/TrackMetaData'],
dojo.map( metaDataSourceClasses, function(c) { return c.class_; } ) ),
dojo.hitch(this,function( MetaDataStore ) {
var mdStores = [];
for( var i = 1; i<arguments.length; i++ ) {
mdStores.push( new (arguments[i])({url: metaDataSourceClasses[i-1].url}) );
}
this.trackMetaDataStore = new MetaDataStore(
dojo.mixin( dojo.clone(this.config.trackMetadata || {}), {
trackConfigs: this.config.tracks,
browser: this,
metadataStores: mdStores
})
);
deferred.resolve({success:true});
}));
});
};
/**
* Asynchronously create the track list.
* @private
*/
Browser.prototype.createTrackList = function() {
return this._deferredFunction('create tracklist', function( deferred ) {
// find the tracklist class to use
var tl_class = !this.config.show_tracklist ? 'Null' :
(this.config.trackSelector||{}).type ? this.config.trackSelector.type :
'Simple';
// load all the classes we need
require( ['JBrowse/View/TrackList/'+tl_class],
dojo.hitch( this, function( trackListClass ) {
// instantiate the tracklist and the track metadata object
this.trackListView = new trackListClass(
dojo.mixin(
dojo.clone( this.config.trackSelector ) || {},
{
trackConfigs: this.config.tracks,
browser: this,
trackMetaData: this.trackMetaDataStore
}
)
);
// bind the 't' key as a global keyboard shortcut
this.setGlobalKeyboardShortcut( 't', this.trackListView, 'toggle' );
// listen for track-visibility-changing messages from
// views and update our tracks cookie
this.subscribe( '/jbrowse/v1/v/tracks/changed', dojo.hitch( this, function() {
this.cookie( "tracks",
this.view.visibleTrackNames().join(','),
{expires: 60});
}));
// figure out what initial track list we will use:
// from a param passed to our instance, or from a cookie, or
// the passed defaults, or the last-resort default of "DNA"?
var origTracklist =
this.config.forceTracks
|| this.cookie( "tracks" )
|| this.config.defaultTracks
|| "DNA";
this.showTracks( origTracklist );
deferred.resolve({ success: true });
}));
});
};
/**
* @private
*/
Browser.prototype.onVisibleTracksChanged = function() {
};
/**
* navigate to a given location
* @example
* gb=dojo.byId("GenomeBrowser").genomeBrowser
* gb.navigateTo("ctgA:100..200")
* gb.navigateTo("f14")
* @param loc can be either:<br>
* <chromosome>:<start> .. <end><br>
* <start> .. <end><br>
* <center base><br>
* <feature name/ID>
*/
Browser.prototype.navigateTo = function(loc) {
if (!this.isInitialized) {
this.deferredFunctions.push(function() { this.navigateTo(loc); });
return;
}
// if it's a foo:123..456 location, go there
var location = Util.parseLocString( loc );
if( location ) {
this.navigateToLocation( location );
}
// otherwise, if it's just a word, try to figure out what it is