forked from GMOD/docker-apollo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AnnotTrack.js
6008 lines (5575 loc) · 293 KB
/
AnnotTrack.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
define([
'dojo/_base/declare',
'dojo/_base/array',
'dojo/on',
'dojo/request',
'jquery',
'jqueryui/draggable',
'jqueryui/droppable',
'jqueryui/resizable',
'jqueryui/autocomplete',
'jqueryui/dialog',
'dijit/registry',
'dijit/Menu',
'dijit/MenuItem',
'dijit/MenuSeparator',
'dijit/PopupMenuItem',
'dijit/form/Button',
'dijit/form/DropDownButton',
'dijit/DropDownMenu',
'dijit/form/ComboBox',
'dijit/form/TextBox',
'dijit/form/ValidationTextBox',
'dijit/form/RadioButton',
'dojox/widget/DialogSimple',
'dojox/grid/DataGrid',
'dojox/grid/cells/dijit',
'dojo/data/ItemFileWriteStore',
'WebApollo/View/Track/DraggableHTMLFeatures',
'WebApollo/FeatureSelectionManager',
'WebApollo/JSONUtils',
'WebApollo/BioFeatureUtils',
'WebApollo/Permission',
'WebApollo/SequenceSearch',
'WebApollo/EUtils',
'WebApollo/SequenceOntologyUtils',
'JBrowse/Model/SimpleFeature',
'JBrowse/Util',
'JBrowse/View/GranularRectLayout',
'JBrowse/View/ConfirmDialog',
'dojo/request/xhr',
'dojox/widget/Standby',
'dijit/Tooltip',
'WebApollo/FormatUtils',
'dijit/form/Select',
'dojo/store/Memory',
'dojo/data/ObjectStore'
],
function (declare,
array,
on,
request,
$,
draggable,
droppable,
resizable,
autocomplete,
dialog,
registry,
dijitMenu,
dijitMenuItem,
dijitMenuSeparator,
dijitPopupMenuItem,
dijitButton,
dijitDropDownButton,
dijitDropDownMenu,
dijitComboBox,
dijitTextBox,
dijitValidationTextBox,
dijitRadioButton,
dojoxDialogSimple,
dojoxDataGrid,
dojoxCells,
dojoItemFileWriteStore,
DraggableFeatureTrack,
FeatureSelectionManager,
JSONUtils,
BioFeatureUtils,
Permission,
SequenceSearch,
EUtils,
SequenceOntologyUtils,
SimpleFeature,
Util,
Layout,
ConfirmDialog,
xhr,
Standby,
Tooltip,
FormatUtils,
Select,
Memory,
ObjectStore) {
var listener;
var client;
var annot_context_menu;
var contextMenuItems;
var context_path = "..";
var AnnotTrack = declare(DraggableFeatureTrack, {
constructor: function (args) {
this.isWebApolloAnnotTrack = true;
this.has_custom_context_menu = true;
this.exportAdapters = [];
this.selectionManager = this.setSelectionManager(this.webapollo.annotSelectionManager);
this.selectionClass = "selected-annotation";
this.annot_under_mouse = null;
/**
* only show residues overlay if "pointer-events" CSS property is
* supported (otherwise will interfere with passing of events to
* features beneath the overlay)
*/
this.useResiduesOverlay = 'pointerEvents' in document.body.style;
this.FADEIN_RESIDUES = false;
var thisB = this;
this.annotMouseDown = function (event) {
thisB.onAnnotMouseDown(event);
};
this.verbose_create = false;
this.verbose_add = false;
this.verbose_delete = false;
this.verbose_drop = false;
this.verbose_click = false;
this.verbose_resize = false;
this.verbose_mousedown = false;
this.verbose_mouseenter = false;
this.verbose_mouseleave = false;
this.verbose_render = false;
this.verbose_server_notification = false;
var track = this;
this.gview.browser.subscribe("/jbrowse/v1/n/navigate", dojo.hitch(this, function (currRegion) {
if (currRegion.ref != this.refSeq.name) {
// we socket changes
if (this.listener) {
this.listener.close();
}
}
}));
this.gview.browser.setGlobalKeyboardShortcut('[', track, 'scrollToPreviousEdge');
this.gview.browser.setGlobalKeyboardShortcut(']', track, 'scrollToNextEdge');
this.gview.browser.setGlobalKeyboardShortcut('}', track, 'scrollToNextTopLevelFeature');
this.gview.browser.setGlobalKeyboardShortcut('{', track, 'scrollToPreviousTopLevelFeature');
this.topLevelParents = {};
},
renderExonSegments: function (subfeature, subDiv, cdsMin, cdsMax,
displayStart, displayEnd, priorCdsLength, reverse) {
var utrClass;
var parentType = subfeature.parent().afeature.parent_type;
if (!this.isProteinCoding(subfeature.parent())) {
var clsName = parentType && parentType.name == "pseudogene" ? "pseudogene" : subfeature.parent().get("type");
var cfg = this.config.style.alternateClasses[clsName];
utrClass = cfg.className;
}
return this.inherited(arguments, [subfeature, subDiv, cdsMin, cdsMax, displayStart, displayEnd, priorCdsLength, reverse, utrClass]);
},
_defaultConfig: function () {
var thisConfig = this.inherited(arguments);
thisConfig.menuTemplate = null;
thisConfig.noExport = true; // turn off default "Save track data" "
thisConfig.style.centerChildrenVertically = false;
thisConfig.pinned = true;
return thisConfig;
},
setViewInfo: function (genomeView, numBlocks,
trackDiv, labelDiv,
widthPct, widthPx, scale) {
this.inherited(arguments);
var track = this;
// to initAnnotContextMenu() once permissions are returned by server
var success = this.getPermission(function () {
track.initAnnotContextMenu();
});
var standby = new Standby({
target: track.div,
color: "transparent",
image: "plugins/WebApollo/img/loading.gif"
});
document.body.appendChild(standby.domNode);
standby.startup();
standby.show();
if (!this.webapollo.loginMenuInitialized && this.browser.config.show_nav && this.browser.config.show_menu) {
this.webapollo.initLoginMenu(this.username);
}
if (!this.webapollo.searchMenuInitialized && this.permission && this.browser.config.show_nav && this.browser.config.show_menu) {
this.webapollo.initSearchMenu();
}
this.initSaveMenu();
this.initPopupDialog();
if (success) {
track.createAnnotationChangeListener(0);
var query = {
"clientToken": track.getClientToken(),
"track": track.getUniqueTrackName(),
"operation": "get_features",
"organism": track.webapollo.organism
};
xhr(context_path + "/AnnotationEditorService", {
handleAs: "json",
data: JSON.stringify(query),
method: "post"
}).then(function (response, ioArgs) {
var responseFeatures = response.features;
if (!responseFeatures) {
alert("Error: " + JSON.stringify(response));
console.log(response);
return;
}
for (var i = 0; i < responseFeatures.length; i++) {
var jfeat = JSONUtils.createJBrowseFeature(responseFeatures[i]);
track.store.insert(jfeat);
track.processParent(responseFeatures[i], "ADD");
}
track.changed();
standby.hide();
}, function (response, ioArgs) {
console.log("Annotation server error--maybe you forgot to login to the server?");
track.handleError({responseText: response.response.text});
return response;
});
}
if (success) {
this.makeTrackDroppable();
this.hide();
this.show();
}
else {
this.hide();
if (this.browser.config.disableJBrowseMode) {
this.login();
}
}
},
generateRandomNumber: function(length){
var string = '';
while(string.length<length){
string += Math.floor(Math.random()*1000);
}
return string ;
},
getClientToken: function () {
if (this.runningApollo()) {
return this.getApollo().getClientToken();
}
else{
var returnItem = window.sessionStorage.getItem("clientToken");
if (!returnItem) {
var randomNumber = this.generateRandomNumber(20);
window.sessionStorage.setItem("clientToken", randomNumber);
}
return window.sessionStorage.getItem("clientToken");
}
},
createAnnotationChangeListener: function (numTry) {
//this.listener = new SockJS(context_path+"/stomp");
var stomp_url = window.location.href;
var index = stomp_url.search('/jbrowse');
stomp_url = stomp_url.substr(0, index) + '/stomp/';
var numberIndex = stomp_url.search('/[0-9]+/');
var stompIndex = stomp_url.search('/stomp/');
stomp_url = stomp_url.substr(0,numberIndex) + stomp_url.substr(stompIndex);
this.listener = new SockJS(stomp_url);
this.client = Stomp.over(this.listener);
this.client.debug = function (str) {
if (this.verbose_server_notification) {
console.log(str);
}
};
var client = this.client;
var track = this;
var browser = this.gview.browser;
var apolloMainPanel = this.getApollo();
console.log('Registering Apollo listeners.');
browser.subscribe("/jbrowse/v1/n/navigate", dojo.hitch(this, function (currRegion) {
apolloMainPanel.handleNavigationEvent(JSON.stringify(currRegion));
}));
var navigateToLocation = function(urlObject) {
if(urlObject.exact){
browser.callLocation(urlObject.url);
}
else{
var location = Util.parseLocString( urlObject.url);
browser.showRegion(location);
}
};
var sendTracks = function (trackList, visibleTrackNames, showLabels) {
var filteredTrackList = [];
for (var trackConfigIndex in trackList) {
var filteredTrack = {};
var trackConfig = trackList[trackConfigIndex];
var visible = visibleTrackNames.indexOf(trackConfig.label) >= 0 || showLabels.indexOf(trackConfig.label) >= 0;
filteredTrack.label = trackConfig.label;
filteredTrack.key = trackConfig.key;
filteredTrack.name = trackConfig.name;
filteredTrack.type = trackConfig.type;
filteredTrack.category = trackConfig.category;
filteredTrack.urlTemplate = trackConfig.urlTemplate;
filteredTrack.visible = visible;
filteredTrackList.push(filteredTrack);
}
// if for some reason this method is called in the wrong place, we catch the error
if(apolloMainPanel){
apolloMainPanel.loadTracks(JSON.stringify(filteredTrackList));
}
};
var handleTrackVisibility = function (trackInfo) {
var command = trackInfo.command;
if (command == "show") {
browser.publish('/jbrowse/v1/v/tracks/show', [browser.trackConfigsByName[trackInfo.label]]);
}
else if (command == "hide") {
browser.publish('/jbrowse/v1/v/tracks/hide', [browser.trackConfigsByName[trackInfo.label]]);
}
else if (command == "list") {
var trackList = browser.trackConfigsByName;
var visibleTrackNames = browser.view.visibleTrackNames();
var showLabels = array.map(trackInfo.labels, function (track) {
return track.label;
});
sendTracks(trackList, visibleTrackNames, showLabels);
}
else {
console.error('unknown command: ' + command);
}
};
browser.subscribe('/jbrowse/v1/c/tracks/show', function (labels) {
console.log("show update");
handleTrackVisibility({command: "list", labels: labels});
});
browser.subscribe('/jbrowse/v1/c/tracks/hide', function () {
console.log("hide update");
handleTrackVisibility({command: "list"});
});
function handleMessage(event){
var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object.
var hostUrl = window.location.protocol +"//" + window.location.hostname ;
// if non-80 or non-specified
if(window.location.port && window.location.port!= "" && window.location.port != "80"){
hostUrl = hostUrl + ":" + window.location.port;
}
if (origin !== hostUrl){
console.error("Bad Host Origin: "+origin );
return;
}
if(event.data.description === "navigateToLocation"){
navigateToLocation(event.data);
}
else
if(event.data.description === "handleTrackVisibility"){
handleTrackVisibility(event.data);
}
else{
console.log("Unknown command: "+event.data.description);
}
}
window.addEventListener("message",handleMessage,true);
client.connect({}, function () {
// TODO: at some point enable "user" to websockets for chat, private notes, notify @someuser, etc.
var organism = JSON.parse(apolloMainPanel.getCurrentOrganism());
var sequence = JSON.parse(apolloMainPanel.getCurrentSequence());
var user = JSON.parse(apolloMainPanel.getCurrentUser());
client.subscribe("/topic/AnnotationNotification/" + organism.id + "/" + sequence.id, dojo.hitch(track, 'annotationNotification'));
client.subscribe("/topic/AnnotationNotification/user/" + user.email, dojo.hitch(track, 'annotationNotification'));
});
console.log('connection established');
},
annotationNotification: function (message) {
var track = this;
var changeData;
try {
changeData = JSON.parse(JSON.parse(message.body));
if (track.verbose_server_notification) {
console.log(changeData.operation + " command from server: ");
console.log(JSON.stringify(changeData));
}
if (changeData.operation == "logout" && changeData.username == track.username) {
if(track.getClientToken()!=changeData.clientToken){
track.logout();
}
else{
alert("You have been logged out or your session has expired");
if (this.getApollo()) {
parent.location.reload();
}
else {
location.reload();
}
}
return;
}
if (changeData.operation == "ERROR" && changeData.username == track.username) {
var myDialog = new dijit.Dialog({
title: "Error Performing Operation",
// content: "test content",
content: changeData.error_message,
style: "width: 300px"
}).show();
return;
}
if (changeData.operation == "ADD") {
if (changeData.sequenceAlterationEvent) {
track.getSequenceTrack().annotationsAddedNotification(changeData.features);
}
else {
track.annotationsAddedNotification(changeData.features);
}
if (this.runningApollo()) this.getApollo().handleFeatureAdded(JSON.stringify(changeData.features));
}
else if (changeData.operation == "DELETE") {
if (changeData.sequenceAlterationEvent) {
track.getSequenceTrack().annotationsDeletedNotification(changeData.features);
}
else {
track.annotationsDeletedNotification(changeData.features);
}
if (this.runningApollo()) this.getApollo().handleFeatureDeleted(JSON.stringify(changeData.features));
}
else if (changeData.operation == "UPDATE") {
if (changeData.sequenceAlterationEvent) {
track.getSequenceTrack().annotationsUpdatedNotification(changeData.features);
}
else {
track.annotationsUpdatedNotification(changeData.features);
}
// changes are not propagated to the selection, so we are doing that here and the re-adding
// see: https://github.com/GMOD/Apollo/issues/645
var selections = track.selectionManager.getSelection();
for(var sin in selections){
// track.selectionRemoved(selections[sin],track.selectionManager);
var selection = selections[sin];
var uniqueId = selection.feature._uniqueID;
for(var featureIndex in changeData.features){
var changedFeature = changeData.features[featureIndex];
// if they are both transcripts
if(changedFeature.uniquename===uniqueId){
selection.feature.data.strand = changedFeature.location.strand;
}
else
// if we select an exon, then let's see what happens here
if(selection.feature.data.parent_type.indexOf('gene')<0){
// we want the uniqueId to be the parent
if(selection.feature._parent._uniqueID==changedFeature.uniquename){
selection.feature._parent.strand = changedFeature.location.strand ;
selection.feature._parent.data.strand = changedFeature.location.strand ;
selection.feature.data.strand = changedFeature.location.strand ;
}
}
}
track.selectionAdded(selection,track.selectionManager);
}
if (this.runningApollo()) this.getApollo().handleFeatureDeleted(JSON.stringify(changeData.features));
}
else {
console.log('unknown command: ', changeData.operation);
}
track.changed();
} catch (e) {
console.log(e);
}
},
/**
* received notification from server ChangeNotificationListener that
* annotations were added
*/
annotationsAddedNotification: function (responseFeatures) {
for (var i = 0; i < responseFeatures.length; ++i) {
var feat = JSONUtils.createJBrowseFeature(responseFeatures[i]);
var id = responseFeatures[i].uniquename;
if (!this.store.getFeatureById(id)) {
this.store.insert(feat);
this.processParent(responseFeatures[i], "ADD");
}
}
},
/**
* received notification from server ChangeNotificationListener that
* annotations were deleted
*/
annotationsDeletedNotification: function (responseFeatures) {
for (var i = 0; i < responseFeatures.length; ++i) {
var id_to_delete = responseFeatures[i].uniquename;
this.store.deleteFeatureById(id_to_delete);
this.processParent(responseFeatures[i], "DELETE");
}
},
/*
* received notification from server ChangeNotificationListener that
* annotations were updated currently handled as if receiving DELETE
* followed by ADD command
*/
annotationsUpdatedNotification: function (responseFeatures) {
// this.annotationsDeletedNotification(annots);
// this.annotationsAddedNotification(annots);
var selfeats = this.selectionManager.getSelectedFeatures();
for (var i = 0; i < responseFeatures.length; ++i) {
var id = responseFeatures[i].uniquename;
var feat = JSONUtils.createJBrowseFeature(responseFeatures[i]);
this.store.replace(feat);
this.processParent(responseFeatures[i], "UPDATE");
}
},
/**
* overriding renderFeature to add event handling right-click context menu
*/
renderFeature: function (feature, uniqueId, block, scale, labelScale, descriptionScale,
containerStart, containerEnd, history) {
// if (uniqueId.length > 20) {
// feature.short_id = uniqueId;
// }
var track = this;
// var featDiv = this.inherited( arguments );
var rclass;
var clsName;
var type = feature.afeature.type;
if (!this.isProteinCoding(feature)) {
var topLevelAnnotation = AnnotTrack.getTopLevelAnnotation(feature);
var parentType = feature.afeature.parent_type ? feature.afeature.parent_type.name : null;
var cfg = this.config.style.alternateClasses[feature.get("type")] || this.config.style.alternateClasses[parentType];
if (cfg) {
rclass = cfg.renderClassName;
if (!topLevelAnnotation.afeature.parent_type) {
clsName = cfg.className;
}
}
}
var featDiv = DraggableFeatureTrack.prototype.renderFeature.call(this, feature, uniqueId, block, scale, labelScale, descriptionScale, containerStart, containerEnd, rclass, clsName);
if (featDiv && featDiv != null && !history) {
annot_context_menu.bindDomNode(featDiv);
$(featDiv).droppable({
accept: ".selected-feature", // only accept draggables that
// are selected feature divs
tolerance: "pointer",
hoverClass: "annot-drop-hover",
over: function (event, ui) {
track.annot_under_mouse = event.target;
},
out: function (event, ui) {
track.annot_under_mouse = null;
},
drop: function (event, ui) {
// ideally in the drop() on annot div is where would handle
// adding feature(s) to annot,
// but JQueryUI droppable doesn't actually call drop unless
// draggable helper div is actually
// over the droppable -- even if tolerance is set to pointer
// tolerance=pointer will trigger hover styling when over
// droppable,
// as well as call to over method (and out when leave
// droppable)
// BUT location of pointer still does not influence actual
// dropping and drop() call
// therefore getting around this by handling hover styling
// here based on pointer over annot,
// but drop-to-add part is handled by whole-track droppable,
// and uses annot_under_mouse
// tracking variable to determine if drop was actually on
// top of an annot instead of
// track whitespace
if (track.verbose_drop) {
console.log("dropped feature on annot:");
console.log(featDiv);
}
}
})
.click(function (event) {
if (event.altKey) {
track.getAnnotationInfoEditor();
}
})
;
}
if (!history) {
var label = "Type: " + type.name + "<br/>Owner: " + feature.afeature.owner + "<br/>Last modified: " + FormatUtils.formatDate(feature.afeature.date_last_modified) + " " + FormatUtils.formatTime(feature.afeature.date_last_modified);
new Tooltip({
connectId: featDiv,
label: label,
position: ["above"],
showDelay: 600
});
}
if (feature.get("locked")) {
dojo.addClass(featDiv, "locked-annotation");
}
return featDiv;
},
renderSubfeature: function (feature, featDiv, subfeature,
displayStart, displayEnd, block) {
var subdiv = this.inherited(arguments);
if (this.canEdit(feature)) {
/**
* setting up annotation resizing via pulling of left/right edges but if
* subfeature is not selectable, do not bind mouse down
*/
if (subdiv && subdiv != null && (!this.selectionManager.unselectableTypes[subfeature.get('type')])) {
$(subdiv).bind("mousedown", this.annotMouseDown);
}
}
return subdiv;
},
/**
* get the GenomeView's sequence track -- maybe move this to GenomeView?
* WebApollo assumes there is only one SequenceTrack if there are multiple
* SequenceTracks, getSequenceTrack returns first one found iterating
* through tracks list
*/
getSequenceTrack: function () {
if (this.seqTrack) {
return this.seqTrack;
}
else {
var tracks = this.gview.tracks;
for (var i = 0; i < tracks.length; i++) {
// if (tracks[i] instanceof SequenceTrack) {
// if (tracks[i].config.type == "WebApollo/View/Track/AnnotSequenceTrack") {
if (tracks[i].isWebApolloSequenceTrack) {
this.seqTrack = tracks[i];
// tracks[i].setAnnotTrack(this);
break;
}
}
}
return this.seqTrack;
},
onFeatureMouseDown: function (event) {
// _not_ calling DraggableFeatureTrack.prototyp.onFeatureMouseDown --
// don't want to allow dragging (at least not yet)
// event.stopPropagation();
this.last_mousedown_event = event;
var ftrack = this;
if (ftrack.verbose_selection || ftrack.verbose_drag) {
console.log("AnnotTrack.onFeatureMouseDown called, genome coord: " + this.getGenomeCoord(event));
}
this.handleFeatureSelection(event);
},
/**
* handles mouse down on an annotation subfeature to make the annotation
* resizable by pulling the left/right edges
*/
onAnnotMouseDown: function (event) {
var track = this;
// track.last_mousedown_event = event;
var verbose_resize = track.verbose_resize;
if (verbose_resize || track.verbose_mousedown) {
console.log("AnnotTrack.onAnnotMouseDown called");
}
event = event || window.event;
var elem = (event.currentTarget || event.srcElement);
// need to redo getLowestFeatureDiv
// var featdiv = DraggableFeatureTrack.prototype.getLowestFeatureDiv(elem);
var featdiv = track.getLowestFeatureDiv(elem);
this.currentResizableFeature = featdiv.subfeature;
this.makeResizable(featdiv);
event.stopPropagation();
},
makeResizable: function (featdiv) {
var track = this;
var verbose_resize = this.verbose_resize;
if (featdiv && (featdiv != null)) {
if (dojo.hasClass(featdiv, "ui-resizable")) {
if (verbose_resize) {
console.log("already resizable");
console.log(featdiv);
}
}
else {
if (verbose_resize) {
console.log("making annotation resizable");
console.log(featdiv);
}
var scale = track.gview.bpToPx(1);
// if zoomed int to showing sequence residues, then make
// edge-dragging snap to interbase pixels
var gridvals;
var charSize = track.webapollo.getSequenceCharacterSize();
if (scale === charSize.width) {
gridvals = [track.gview.charWidth, 1];
}
else {
gridvals = false;
}
$(featdiv).resizable({
handles: "e, w",
helper: "ui-resizable-helper",
autohide: false,
grid: gridvals,
stop: function (event, ui) {
if (verbose_resize) {
console.log("resizable.stop() called, event:");
console.dir(event);
console.log("ui:");
console.dir(ui);
}
var gview = track.gview;
var oldPos = ui.originalPosition;
var newPos = ui.position;
var oldSize = ui.originalSize;
var newSize = ui.size;
var leftDeltaPixels = newPos.left - oldPos.left;
var leftDeltaBases = Math.round(gview.pxToBp(leftDeltaPixels));
var oldRightEdge = oldPos.left + oldSize.width;
var newRightEdge = newPos.left + newSize.width;
var rightDeltaPixels = newRightEdge - oldRightEdge;
var rightDeltaBases = Math.round(gview.pxToBp(rightDeltaPixels));
if (verbose_resize) {
console.log("left edge delta pixels: " + leftDeltaPixels);
console.log("left edge delta bases: " + leftDeltaBases);
console.log("right edge delta pixels: " + rightDeltaPixels);
console.log("right edge delta bases: " + rightDeltaBases);
}
var subfeat = ui.originalElement[0].subfeature;
var fmin = subfeat.get('start') + leftDeltaBases;
var fmax = subfeat.get('end') + rightDeltaBases;
var operation = subfeat.get("type") == "exon" ? "set_exon_boundaries" : "set_boundaries";
var postData = {
"track": track.getUniqueTrackName(),
"features": [
{
"uniquename": subfeat.getUniqueName(),
"location": {
"fmin": fmin, "fmax": fmax
}
}
],
"operation": operation
};
track.executeUpdateOperation(JSON.stringify(postData));
track.changed();
}
});
}
}
},
/**
* feature click no-op (to override FeatureTrack.onFeatureClick, which
* conflicts with mouse-down selection
*/
onFeatureClick: function (event) {
if (this.verbose_click) {
console.log("in AnnotTrack.onFeatureClick");
}
event = event || window.event;
var elem = (event.currentTarget || event.srcElement);
var featdiv = this.getLowestFeatureDiv(elem);
if (featdiv && (featdiv != null)) {
if (this.verbose_click) {
console.log(featdiv);
}
}
// do nothing
// event.stopPropagation();
},
/* feature_records ==> { feature: the_feature, track: track_feature_is_from } */
addToAnnotation: function (annot, feature_records) {
var target_track = this;
var subfeats = [];
var allSameStrand = 1;
for (var i = 0; i < feature_records.length; ++i) {
var feature_record = feature_records[i];
var original_feat = feature_record.feature;
var feat = JSONUtils.makeSimpleFeature(original_feat);
var isSubfeature = !!feat.parent(); // !! is
// shorthand for
// returning
// true if value
// is defined
// and non-null
var annotStrand = annot.get('strand');
if (isSubfeature) {
var featStrand = feat.get('strand');
var featToAdd = feat;
if (featStrand != annotStrand) {
allSameStrand = 0;
featToAdd.set('strand', annotStrand);
}
subfeats.push(featToAdd);
}
else { // top-level feature
var source_track = feature_record.track;
var subs = feat.get('subfeatures');
if (subs && subs.length > 0) { // top-level
// feature with
// subfeatures
for (var i = 0; i < subs.length; ++i) {
var subfeat = subs[i];
var featStrand = subfeat.get('strand');
var featToAdd = subfeat;
if (featStrand != annotStrand) {
allSameStrand = 0;
featToAdd.set('strand', annotStrand);
}
subfeats.push(featToAdd);
}
// $.merge(subfeats, subs);
}
else { // top-level feature without subfeatures
// make exon feature
var featStrand = feat.get('strand');
var featToAdd = feat;
if (featStrand != annotStrand) {
allSameStrand = 0;
featToAdd.set('strand', annotStrand);
}
featToAdd.set('type', 'exon');
subfeats.push(featToAdd);
}
}
}
if (!allSameStrand && !confirm("Adding features of opposite strand. Continue?")) {
return;
}
var featuresString = "";
for (var i = 0; i < subfeats.length; ++i) {
var subfeat = subfeats[i];
// if (subfeat[target_track.subFields["type"]] !=
// "wholeCDS")
var source_track = subfeat.track;
if (subfeat.get('type') != "wholeCDS") {
var jsonFeature = JSONUtils.createApolloFeature(subfeats[i], "exon");
featuresString += ", " + JSON.stringify(jsonFeature);
}
}
// var parent = JSONUtils.createApolloFeature(annot, target_track.fields,
// target_track.subfields);
// parent.uniquename = annot[target_track.fields["name"]];
var postData = '{ "track": "' + target_track.getUniqueTrackName() + '", "features": [ {"uniquename": "' + annot.id() + '"}' + featuresString + '], "operation": "add_exon" }';
target_track.executeUpdateOperation(postData);
},
makeTrackDroppable: function () {
var target_track = this;
var target_trackdiv = target_track.div;
if (target_track.verbose_drop) {
console.log("making track a droppable target: ");
console.log(this);
console.log(target_trackdiv);
}
$(target_trackdiv).droppable({
// only accept draggables that are selected feature divs
accept: ".selected-feature",
// switched to using deactivate() rather than drop() for drop
// handling
// this fixes bug where drop targets within track (feature divs)
// were lighting up as drop target,
// but dropping didn't actually call track.droppable.drop()
// (see explanation in feature droppable for why we catch drop at
// track div rather than feature div child)
// cause is possible bug in JQuery droppable where droppable over(),
// drop() and hoverclass
// collision calcs may be off (at least when tolerance=pointer)?
//
// Update 3/2012
// deactivate behavior changed? Now getting called every time
// dragged features are release,
// regardless of whether they are over this track or not
// so added another hack to get around drop problem
// combination of deactivate and keeping track via over()/out() of
// whether drag is above this track when released
// really need to look into actual drop calc fix -- maybe fixed in
// new JQuery releases?
//
// drop: function(event, ui) {
over: function (event, ui) {
target_track.track_under_mouse_drag = true;
if (target_track.verbose_drop) {
console.log("droppable entered AnnotTrack")
}
;
},
out: function (event, ui) {
target_track.track_under_mouse_drag = false;
if (target_track.verbose_drop) {
console.log("droppable exited AnnotTrack")
}
;
},
deactivate: function (event, ui) {
// console.log("trackdiv droppable detected: draggable
// deactivated");
// "this" is the div being dropped on, so same as
// target_trackdiv
if (target_track.verbose_drop) {
console.log("draggable deactivated");
}
var dropped_feats = target_track.webapollo.featSelectionManager.getSelection();
// problem with making individual annotations droppable, so
// checking for "drop" on annotation here,
// and if so re-routing to add to existing annotation
if (target_track.annot_under_mouse != null) {
if (target_track.verbose_drop) {
console.log("draggable dropped onto annot: ");
console.log(target_track.annot_under_mouse.feature);
}
target_track.addToAnnotation(target_track.annot_under_mouse.feature, dropped_feats);
}
else if (target_track.track_under_mouse_drag) {
if (target_track.verbose_drop) {
console.log("draggable dropped on AnnotTrack");
}
target_track.createAnnotations(dropped_feats);
}
// making sure annot_under_mouse is cleared
// (should do this in the drop? but need to make sure _not_ null
// when
target_track.annot_under_mouse = null;
target_track.track_under_mouse_drag = false;
}
});
if (target_track.verbose_drop) {
console.log("finished making droppable target");
}
},
createAnnotations: function (selection_records) {