forked from ericmandel/js9
-
Notifications
You must be signed in to change notification settings - Fork 1
/
js9.js
executable file
·17283 lines (16946 loc) · 527 KB
/
js9.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
/*
*
* JS9: astronomical image display everywhere (December 10, 2012)
*
* Principals: Eric Mandel, Alexey Vikhlinin
* Organization: Harvard Smithsonian Center for Astrophysics, Cambridge MA
* Contact: [email protected]
*
* Copyright (c) 2012 - 2017 Smithsonian Astrophysical Observatory
*
*/
/*global JS9Prefs, $, jQuery, Event, fabric, io, CanvasRenderingContext2D, sprintf, Blob, ArrayBuffer, Uint8Array, Uint16Array, Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, DataView, FileReader, Fitsy, Astroem, dhtmlwindow, saveAs, Spinner, ResizeSensor, Jupyter, gaussBlur, ImageFilters, Plotly */
// define Escripten Module so we can pass properties (e.g. wasmBinary)
// eslint-disable-next-line no-unused-vars
var Module = {};
// JS9 module
var JS9 = (function(){
"use strict";
// module header
var JS9 = {};
JS9.NAME = "JS9"; // The name of this namespace
JS9.VERSION = "1.12"; // The version of this namespace
JS9.COPYRIGHT = "Copyright (c) 2012-2017 Smithsonian Institution";
// internal defaults (not usually changed by users)
JS9.DEFID = "JS9"; // default JS9 display id
JS9.WIDTH = 512; // width of js9 canvas
JS9.HEIGHT = 512; // height of js9 canvas
JS9.ANON = "Anonymous"; // name to use for images with no name
JS9.PREFSFILE = "js9Prefs.json";// prefs file to load
JS9.WORKERFILE = "js9worker.js";// js9 web worker file to load
JS9.ZINDEX = 0; // z-index of image canvas: on bottom of js9
JS9.SHAPEZINDEX = 4; // base z-index of shape layers layers
JS9.MESSZINDEX = 80; // z-index of messages: above graphics
JS9.BTNZINDEX = 90; // z-index of buttons on top of plugin canvases
JS9.MENUZINDEX = 1000; // z-index of menus: always on top!
JS9.COLORSIZE = 1024; // size of contrast/biased color array
JS9.SCALESIZE = 16384; // size of scaled color array
JS9.INVSIZE = 1024; // size of inverse array
JS9.HISTSIZE = 16384; // size of histogram equalization array
JS9.INSTALLDIR=""; // prefix to get to js9 install directory
JS9.TOROOT=""; // prefix to get to data file from install
JS9.PLUGINS=""; // regexp list of plugins
JS9.LIGHTWIN = "dhtml"; // light window type: choice of dhtml
JS9.ANTIALIAS = false; // use anti-aliasing?
JS9.SCALEIREG = true; // scale interactive regions by zoom factor?
JS9.NOMOVE = 3; // number of pixels before we recognize movement
JS9.DBLCLICK = 300; // millisec for double-click
JS9.TIMEOUT = 250; // millisec before assuming light window is up
JS9.SPINOUT = 250; // millisec before assuming spinner is up
JS9.SUPERMENU = /^SUPERMENU_/; // base of supermenu id
JS9.RESIZEDIST = 20; // size of rectangle defining resize handle
JS9.RESIZEFUDGE = 5; // fudge for webkit resize problems
JS9.RAWID0 = "raw0"; // default raw id
JS9.RAWIDX = "alt"; // default "alternate" raw id
JS9.REPROJDIM = 2300; // max dimension for reprojection
JS9.IDFMT = " (%s)"; // format for light window id
JS9.MINZOOM = 0.125; // min zoom using scrool wheel
JS9.MAXZOOM = 16.0; // max zoom using scrool wheel
JS9.ADDZOOM = 0.05; // add/subtract amount per mouse wheel click
JS9.CHROMEFILEWARNING = true; // whether to alert chrome users about file URI
// https://hacks.mozilla.org/2013/04/detecting-touch-its-the-why-not-the-how/
JS9.TOUCHSUPPORTED = ( window.hasOwnProperty("ontouchstart") ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0));
// modified from:
// http:https://stackoverflow.com/questions/2400935/browser-detection-in-javascript
JS9.BROWSER = (function(){
var P= navigator.platform;
var N= navigator.appName, ua= navigator.userAgent, tem;
var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
tem= ua.match(/version\/([\.\d]+)/i);
if(M && tem !== null){ M[2]= tem[1]; }
M= M? [M[1], M[2], P]: [N, navigator.appVersion,'-?', P];
M.push(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(ua));
return M;
}());
// convenience to allow plugins to deal with HiDPI ratio blurring
// http:https://stackoverflow.com/questions/15661339/how-do-i-fix-blurry-text-in-my-html5-canvas
JS9.PIXEL_RATIO = (function(){
var ctx = document.createElement("canvas").getContext("2d"),
dpr = window.devicePixelRatio || 1,
bsr = ctx.webkitBackingStorePixelRatio ||
ctx.mozBackingStorePixelRatio ||
ctx.msBackingStorePixelRatio ||
ctx.oBackingStorePixelRatio ||
ctx.backingStorePixelRatio || 1;
return dpr / bsr;
}());
// global options
JS9.globalOpts = {
helperType: "none", // one of: sock.io, get, post, none
helperPort: 2718, // default port for node.js helper
useWasm: true, // use WebAssembly if available?
winType: "light", // plugin window: "light" or "new"
rgb: {active: false, // RGB mode
rim: null,
gim: null,
bim: null},
defcolor: "#00FF00", // graphics color when all else fails
pngisfits: true, // are PNGs really PNG representation files?
fits2fits: "size>100", // convert to repfile? always|never|size>x Mb
fits2png: false, // convert FITS to PNG rep files? true|false
alerts: true, // set to false to turn off alerts
internalValPos: true, // a fancy info plugin can turns this off
internalContrastBias: true, // a fancy colorbar plugin can turns this off
containContrastBias: false, // contrast/bias only when mouse is in display?
htimeout: 5000, // connection timeout for the helper connect
lhtimeout: 1000, // connection timeout for local helper connect
ehtimeout: 1000, // connection timeout for Electron connect
ehretries: 10, // connection retries Electron connect
xtimeout: 180000, // connection timeout for fetch data requests
extlist: "EVENTS STDEVT", // list of binary table extensions
table: {xdim: 2048, ydim: 2048, bin: 1},// image section size to extract from table
image: {xdim: 2048, ydim: 2048, bin: 1},// image section size (0 for unlimited)
clearImageMemory: "never", // rm vfile: always|never|auto|noExt|noCube|size>x Mb
helperProtocol: location.protocol, // http: or https:
maxMemory: 750000000, // max heap memory to allocate for a fits image
corsURL: "params/loadcors.html", // location of param html file
proxyURL: "params/loadproxy.html", // location of param html file
loadProxy: false, // do we allow proxy load requests to server?
archivesURL: "help/archives.html", // location of archives help file
imsectionURL: "params/imsection.html", // location of param html file
postMessage: false, // allow communication through iframes?
waitType: "spinner", // "spinner" or "mouse"
spinColor: "#FF0000", // color of spinner
spinOpacity: 0.35, // opacity of spinner
resize: true, // allow resize of display?
resizeHandle: true, // add resize handle to display?
resizeRedisplay: true, // redisplay image while resizing?
regionConfigSize: "medium", // "small", "medium"
mouseActions: ["display value/position", "change contrast/bias", "pan the image"],// 0,1,2 mousepress
touchActions: ["display value/position", "change contrast/bias", "pan the image"],// 1,2,3 fingers
keyboardActions: {
b: "toggle selected region: source/background",
e: "toggle selected region: include/exclude",
r: "make regions layer active",
"/": "copy wcs position to clipboard",
"?": "copy value and position to clipboard",
"0": "reset zoom",
"=": "zoom in",
"+": "zoom in",
"-": "zoom out",
">": "display next image",
"<": "display previous image",
"delete": "remove selected region",
"leftArrow": "move selected region left",
"upArrow": "move selected region up",
"rightArrow": "move selected region right",
"downArrow": "move selected region down"
}, // keyboard actions
mousetouchZoom: false, // use mouse wheel, pinch to zoom?
centerDivs: ["JS9Menubar"], // divs that take part in JS9.Display.center()
pinchWait: 8, // number of events to wait before testing pinch
pinchThresh: 6, // threshold for pinch test
extendedPlugins: true, // enable extended plugin support?
corsProxy: "http:https://js9.si.edu/cgi-bin/CORS-proxy.cgi", // CORS proxy url
simbadProxy: "http:https://js9.si.edu/cgi-bin/simbad-proxy.cgi",//simbad proxy url
catalogs: {ras: ["RA", "_RAJ2000", "RAJ2000"], // cols to search for ..
decs: ["Dec", "_DEJ2000", "DEJ2000"],// when loading catalogs
shape: "circle", // object shape
color: "yellow", // object color
width: 7, // box object width
height: 7, // box object height
radius: 3.5, // circle object radius
r1: 5.0, // ellipse object r1
r2: 3.5, // ellipse object r2
wcssys: "ICRS", // wcs system
skip: "#\n", // skip # and blank lines
save: true, // save cat cols in shapes
tooltip: "$xreg.data.ra $xreg.data.dec"}, // tooltip format
topColormaps: ["grey", "heat", "cool", "viridis", "magma", "sls", "a", "b", "red", "green", "blue"], // toplevel colormaps
infoBox: ["file", "object", "wcsfov", "wcscen", "wcspos", "impos", "physpos", "value", "regions", "progress"],
menuBar: ["file", "view", "zoom", "scale", "color", "region", "wcs", "analysis", "help"],
hiddenPluginDivs: [], // which static plugin divs start hidden
imageTemplates: ".fits,.fts,.png,.jpg,.jpeg", // templates for local images
regionTemplates: ".reg", // templates for local region file input
sessionTemplates: ".ses", // templates for local session file input
colormapTemplates: ".cmap", // templates for local colormap file input
catalogTemplates: ".cat,.tab", // templates for local catalog file input
controlsMatchRegion: "corner", // true or "corner" or "border"
newWindowWidth: 530, // width of LoadWindow("new")
newWindowHeight: 625, // height of LoadWindow("new")
debug: 0 // debug level
};
// image param defaults
JS9.imageOpts = {
contrast: 1.0, // default color contrast
bias: 0.5, // default color bias
invert: false, // default colormap invert
exp: 1000, // default exp value for scaling
colormap: "grey", // default color map
scale: "linear", // default scale algorithm
scaleclipping: "dataminmax", // "dataminmax" or "zscale" to start
zscalecontrast: 0.25, // default from ds9
zscalesamples: 600, // default from ds9
zscaleline: 120, // default from ds9
wcssys: "native", // default WCS sys
wcsunits: "sexagesimal", // default WCS units
lcs: "physical", // default logical coordinate system
valpos: true, // whether to display value/position
opacity: 1.0, // opacity between 0 and 1
sigma: "none", // gauss blur sigma or none
maskOpacity: 0.4, // opacity for masked pixels
alpha: 255, // alpha for image (but use opacity!)
alpha1: 100, // alpha for masked pixels
// xcen: 0, // default x center pos to pan to
// ycen: 0, // default y center pos to pan to
zoom: 1, // default zoom factor
zooms: 5, // how many zooms in each direction?
nancolor: "#000000", // 6-digit #hex color for NaN values
wcsalign: true, // align image using wcs after reproj?
rotationMode: "relative", // default: relative or absolute?
listonchange: false // whether to list after a reg change
};
// allows regions opts to be overridden in preferences
JS9.regionOpts = {
};
// defaults for analysis (macro expansion)
JS9.analOpts = {
// if this pattern is matched in stderr, throw a real error
epattern: /^(ERROR:[^\n]*)\n/,
// location of datapath's param html file
dpathURL: "params/datapath.html",
// prepend $JS9_DIR to relative fitsFile paths?
prependJS9Dir: true,
// use as path to FITS data or use incoming path if not set
dataDir: null
};
// light window opts
JS9.lightOpts = {
nclick: 0,
dhtml: {
top: ".dhtmlwindow",
drag: ".drag-contentarea",
dragBar: "drag-handle",
format: "width=%spx,height=%spx,center=1,resize=%s,scrolling=0",
textWin: "width=830px,height=400px,center=1,resize=1,scrolling=1",
// NB: dimensions are tied to .JS9Plot CSS params
plotWin: "width=830px,height=420px,center=1,resize=1,scrolling=1",
dpathWin: "width=830px,height=175px,center=1,resize=1,scrolling=1",
paramWin: "width=830px,height=230px,center=1,resize=1,scrolling=1",
regWin0: "width=600px,height=72px,center=1,resize=1,scrolling=1",
regWin: "width=600px,height=235px,center=1,resize=1,scrolling=1",
imageWin: "width=512px,height=598px,center=1,resize=1,scrolling=1",
lineWin: "width=400px,height=60px,center=1,resize=1,scrolling=1"
}
};
// colors for text messages
JS9.textColorOpts = {
regions: "#00FF00",
info: "#00FF00",
inimage: "#000000"
};
// defaults for plot creation
JS9.plotOpts = {
// generic options
annotate: false,
annotateColor: "#FF0000",
color: "blue",
// flot options
zoomStack: {
enabled: true
},
selection: {
mode: "xy"
},
series: {
clickable: true,
hoverable: true,
lines: { show: true },
points: { show: false }
},
legend: {
backgroundColor: null,
backgroundOpacity: 0
},
// plotly options
xaxis: {
autorange: true
},
yaxis: {
autorange: true
}
};
// help pages
JS9.helpOpts = {
user: {
heading: "JS9Help",
type: "help", url:"user.html",
title: "User Manual"
},
install: {
heading: "JS9Help",
type: "help", url:"install.html",
title: "Installing JS9"
},
webpage: {
heading: "JS9Help",
type: "help", url:"webpage.html",
title: "Adding JS9 To A Web Page"
},
yourdata: {
heading: "JS9Help",
type: "help", url:"yourdata.html",
title: "Adding Data To A Web Page"
},
localtasks: {
heading: "JS9Help",
type: "help", url:"localtasks.html",
title: "Adding Local Analysis Tasks and Plugins"
},
helper: {
heading: "JS9Help",
type: "help", url:"helper.html",
title: "Adding Server-side Analysis Tasks"
},
serverside: {
heading: "JS9Help",
type: "help", url:"serverside.html",
title: "Server-side Analysis with JS9"
},
publicapi: {
heading: "JS9Help",
type: "help", url:"publicapi.html",
title: "The JS9 Public API"
},
repfile: {
heading: "JS9Help",
type: "help", url:"repfile.html",
title: "Dealing with Large Files"
},
memory: {
heading: "JS9Help",
type: "help", url:"memory.html",
title: "Dealing with Memory Limitations"
},
regions: {
heading: "JS9Help",
type: "help", url:"regions.html",
title: "Regions Format"
},
extmsg: {
heading: "JS9Help",
type: "help", url:"extmsg.html",
title: "External Messaging"
},
python: {
heading: "JS9Help",
type: "help", url:"python.html",
title: "JS9 with Python and Jupyter"
},
preferences: {
heading: "JS9Help",
type: "help", url:"preferences.html",
title: "Setting Site Preferences"
},
changelog: {
heading: "JS9Help",
type: "help", url:"changelog.html",
title: "ChangeLog"
},
issues: {
heading: "JS9Help",
type: "help", url:"knownissues.html",
title: "Known Issues"
}
};
// containers for groups of JS9 objects
JS9.images = []; // array of current images
JS9.displays = []; // array of current display canvases
JS9.colormaps = []; // array of current colormaps
JS9.commands = []; // array of commands
JS9.plugins = []; // array of defined plugins
JS9.preloads = []; // array of images to preload
JS9.auxFiles = []; // array of auxiliary files
JS9.publics = {}; // object containing defined public API calls
JS9.helper = {}; // only one helper per page, please
JS9.fits = {}; // object holding FITS access routines
JS9.userOpts = {}; // object to hold localStorage opts
// misc params
// list of scales in mkScaledCells
JS9.scales = ["linear", "log", "histeq", "power", "sqrt", "squared", "asinh", "sinh"];
// list of known wcs systems
JS9.wcssyss = ["FK4", "FK5", "ICRS", "galactic", "ecliptic", "native",
"image", "physical"];
// list of known wcs units
JS9.wcsunitss = ["degrees", "sexagesimal", "pixels"];
// known bugs and work-arounds
JS9.bugs = {};
// sometimes hiding the menu does not refresh the image properly
// JS9.bugs.hide_menu = true;
// turned off: 6/30/16
JS9.bugs.hide_menu = false;
// firefox does not repaint as needed (last checked FF 24.0 on 10/20/13)
if( (JS9.BROWSER[0] === "Firefox") && JS9.BROWSER[2].search(/Linux/) >=0 ){
JS9.bugs.firefox_linux = true;
}
// webkit resize is not quite up to par
if( (JS9.BROWSER[0] === "Chrome") || (JS9.BROWSER[0] === "Safari") ){
JS9.bugs.webkit_resize = true;
}
// chrome does not deal with ".gz" file templates, but other browsers do
if( (JS9.BROWSER[0] !== "Chrome") ){
JS9.globalOpts.imageTemplates += ",.gz";
}
// iOS has severe memory limits (05/2017)
if( JS9.BROWSER[3] ){
JS9.globalOpts.maxMemory = Math.min(JS9.globalOpts.maxMemory, 350000000);
JS9.globalOpts.image.xdim = 2048 * 2;
JS9.globalOpts.image.ydim = 2048 * 2;
}
// ---------------------------------------------------------------------
// JS9 Image object to manage images
// ---------------------------------------------------------------------
JS9.Image = function(file, params, func){
var i, card, pars, sarr, nzoom;
var display;
var that = this;
var localOpts=null;
var mksect = function(that, localOpts){
var zoom;
var arr = [];
// make up section array from default values
if( localOpts && (localOpts.xcen !== undefined) ){
arr.push(localOpts.xcen);
}
if( localOpts && (localOpts.ycen !== undefined) ){
arr.push(localOpts.ycen);
}
if( localOpts && (localOpts.zoom !== undefined) ){
zoom = that.parseZoom(localOpts.zoom);
if( zoom ){
arr.push(zoom);
}
}
return arr;
};
var finishUp = function(func){
// clear previous messages
this.display.clearMessage();
// add to list of images
JS9.images.push(this);
// call function, if necessary
if( func ){
try{ JS9.xeqByName(func, window, this); }
catch(e){ JS9.error("in image onload callback", e, false); }
}
// plugin callbacks
this.xeqPlugins("image", "onimageload");
// update shapes?
if( this.updateshapes ){
this.updateShapes("regions", "all", "update");
}
// load is complete
this.status.load = "complete";
// done loading, reset wait cursor
JS9.waiting(false);
};
// params can be an object containing local params, or the display string
if( params ){
if( typeof params === "object" ){
localOpts = params;
if( localOpts.display ){
display = localOpts.display;
}
} else {
display = params;
}
}
// make sure we have a valid display
if( !display ){
if( JS9.displays.length > 0 ){
display = JS9.displays[0].id;
} else {
display = JS9.DEFID;
}
}
// it's an image
this.type = "image";
// set the display
this.display = JS9.lookupDisplay(display);
// initialize image params
this.params = {};
// image-specific scratch space
this.tmp = {};
// scale min and max to impossible numbers
this.params.scalemin = Number.Nan;
this.params.scalemax = Number.Nan;
// xeq callback for region changes?
this.params.xeqonchange = true;
// copy image parameters
this.params = $.extend(true, this.params, JS9.imageOpts, localOpts);
// set the colormap object from colormap name (text string)
// this.cmapObj = JS9.lookupColormap(this.params.colormap);
this.setColormap(this.params.colormap);
// do we display?
this.displayMode = true;
// initialize click state
this.clickState = 0;
// initialize click in region
this.clickInRegion = false;
this.clickInLayer = null;
// no helper queried yet
this.queried = false;
// is this a proxy image?
if( localOpts && localOpts.proxyFile ){
this.proxyFile = localOpts.proxyFile;
}
// was a "parent" FITS file specified?
if( localOpts && localOpts.parentFile ){
this.parentFile = localOpts.parentFile;
}
// was "parent" info specified?
if( localOpts && localOpts.parent ){
this.parent = localOpts.parent;
// convert card string to header
if( this.parent.cardstr && this.parent.ncard ){
this.parent.raw = {header: {}};
for(i=0; i<this.parent.ncard; i++){
card = this.parent.cardstr.slice(i*80, (i+1)*80);
pars = JS9.cardpars(card);
if( pars !== undefined ){
this.parent.raw.header[pars[0]] = pars[1];
}
}
// initialize LCS for this parent header
this.parent.lcs = {};
JS9.Image.prototype.initLCS.call(this.parent,
this.parent.raw.header);
}
}
// was an id specified?
if( localOpts && localOpts.id ){
this.id = localOpts.id;
}
// offsets into canvas to display
this.ix = 0;
this.iy = 0;
// create the png object
this.png = {};
// image element to hold png file, from which array data is generated
this.png.image = new Image();
// init status object
this.status = {};
// RGB image
this.rgb = {};
// section parameters
this.rgb.sect = {zoom: 1, ozoom: 1};
// graphical layers
this.layers = {};
// current zindex for main layers
this.zlayer = JS9.SHAPEZINDEX;
// no logical coordinate systems
this.lcs = {};
// array of aux file pointers
this.aux = {};
// binning parameters
this.binning = {bin: 1, obin: 1};
// array to hold raw data as we create it (original raw data at index 0)
this.raws = [];
// initial blend mode
this.blend = {active: undefined, mode: "normal", opacity: 1};
// temp flag determines if we should update shapes at end of this call
this.updateshapes = false;
// change the cursor to show the waiting status
JS9.waiting(true, this.display);
// file argument can be an object containing raw data or
// a string containing a URL of a PNG image
switch( typeof file ){
case "object":
// save source
this.source = localOpts.source || "fits";
// generate the raw data array from the hdu
this.mkRawDataFromHDU(file,
$.extend({}, {file: file.filename}, localOpts));
// do zscale, if necessary
if( this.params.scaleclipping === "zscale" ){
this.zscale(true);
} else if( this.params.scaleclipping === "zmax" ){
this.zscale("zmax");
}
// set up initial zoom
if( this.params.zoom ){
nzoom = this.parseZoom(this.params.zoom);
this.rgb.sect.zoom = nzoom;
this.rgb.sect.ozoom = nzoom;
}
// set up initial section
this.mkSection();
// change center and zoom if necessary
sarr = mksect(this, localOpts);
if( sarr.length ){
this.mkSection.apply(this, sarr);
}
// was a static RGB file specified?
if( localOpts && localOpts.rgbFile ){
this.rgbFile = localOpts.rgbFile;
// callback to fire when static RGB image is loaded
$(this.png.image).on("load", function(){
var ss;
if( (that.png.image.width !== that.raw.width) ||
(that.png.image.height !== that.raw.height) ){
ss = sprintf("rgb dims [%s,%s] don't match image [%s,%s]",
that.png.image.width,
that.png.image.height,
that.raw.width,
that.raw.height);
JS9.error(ss);
}
// store png data in an offscreen canvas
that.mkOffScreenCanvas();
// display image, 2D graphics, etc.
that.displayImage("all", localOpts);
// finish up
finishUp.call(that, func);
}).on("error", function(){
// done loading, reset wait cursor
JS9.waiting(false);
// error on load
that.status.load = "error";
JS9.error("could not load image: "+that.id);
});
// set src to download the display file
this.png.image.src = this.rgbFile;
} else {
// display image, 2D graphics, etc.
this.displayImage("all", localOpts);
// finish up
finishUp.call(this, func);
}
break;
case "string":
// save source
this.source = localOpts.source || "fits2png";
// image or table
this.imtab = "image";
// downloaded image file, path relative to displayed Web page
this.file = JS9.cleanPath(file);
// take file but discard path (or scheme) up to slashes
this.id0 = this.file.split("/").reverse()[0];
// save id in case we have to change it for uniqueness
this.id = JS9.getImageID(this.id0, this.display.id);
// load status
this.status.load = "loading";
// callback to fire when image is loaded (do this before setting src)
$(this.png.image).on("load", function(){
// populate the image data array from RGB values
that.mkOffScreenCanvas();
// populate the raw image data array from RGB values
that.mkRawDataFromPNG();
// do zscale, if necessary
if( that.params.scaleclipping === "zscale" ){
that.zscale(true);
} else if( that.params.scaleclipping === "zmax" ){
that.zscale("zmax");
}
// set up initial zoom
if( that.params.zoom ){
nzoom = that.parseZoom(that.params.zoom);
that.rgb.sect.zoom = nzoom;
that.rgb.sect.ozoom = nzoom;
}
// set up initial section
that.mkSection();
// change center and zoom if necessary
sarr = mksect(that, localOpts);
if( sarr.length ){
that.mkSection.apply(that, sarr);
}
// display image, 2D graphics, etc.
that.displayImage("all", localOpts);
// finish up
finishUp.call(that, func);
// debugging
if( JS9.DEBUG ){
JS9.log("JS9 image: %s dims(%d,%d) min/max(%d,%d)",
that.file, that.raw.width, that.raw.height,
that.raw.dmin, that.raw.dmax);
}
}).on("error", function(){
// done loading, reset wait cursor
JS9.waiting(false);
// error on load
that.status.load = "error";
JS9.error("could not load image: "+that.id);
});
// set src to download the png and eventually display the image data
this.png.image.src = file;
break;
default:
JS9.log("unknown specification type for Load: "+ typeof file);
}
};
// return the image data in a relatively standard format
JS9.Image.prototype.getImageData = function(dflag){
var data = null;
var atob64 = function(a){
var i;
var s = '';
var bytes = new Uint8Array(a.buffer);
var len = bytes.byteLength;
for(i=0; i<len; i++){
s += String.fromCharCode(bytes[i]);
}
return window.btoa(s);
};
// return data and auxiliary info
if( dflag ){
// return an array for IPC, since python mangles the typed array
if( dflag === "array" ){
data = Array.prototype.slice.call(this.raw.data);
} else if( dflag === "base64" ){
// NB: this seems to be the fastest method for IPC!
data = atob64(this.raw.data);
} else if( dflag && (dflag !== "false") ) {
// use this for javascript programming on the web page itself
data = this.raw.data;
}
}
return {id: this.id,
file: this.file,
fits: this.fitsFile || "",
source: this.source,
imtab: this.imtab,
width: this.raw.width,
height: this.raw.height,
bitpix: this.raw.bitpix,
header: this.raw.header,
hdus: this.hdus,
data: data
};
};
// undisplay the image, release resources
JS9.Image.prototype.closeImage = function(){
var i, j, tim, key, raw, carr;
var iscurrent = false;
var ilen= JS9.images.length;
var display = this.display;
// look for the image in the image list, and remove it
for(i=0; i<ilen; i++){
if( this === JS9.images[i] ){
tim = JS9.images[i];
// is this the currently displayed image?
if( tim === tim.display.image ){
iscurrent = i+1;
}
// clear display if this is the currently displayed image
if( iscurrent ){
// nothing on the screen
tim.display.clearMessage();
tim.display.context.clear();
// clear all layers
for( key in tim.layers ){
if( tim.layers.hasOwnProperty(key) ){
// tim.layers[key].canvas.clear();
tim.showShapeLayer(key, false);
}
}
}
// plugin callbacks
tim.xeqPlugins("image", "onimageclose");
// after callbacks, we can unset the image from the display
if( iscurrent ){
// clear image from display
tim.display.image = null;
}
// remove from RGB mode, if necessary
switch(tim.cmapObj.name){
case "red":
JS9.globalOpts.rgb.rim = null;
break;
case "green":
JS9.globalOpts.rgb.gim = null;
break;
case "blue":
JS9.globalOpts.rgb.bim = null;
break;
}
// cleanup FITS file support, if necessary
if( JS9.fits.cleanupFITSFile ){
for(j=0; j<tim.raws.length; j++){
raw = tim.raws[j];
if( raw.hdu && raw.hdu.fits ){
carr = JS9.lookupVfile(raw.hdu.fits.vfile);
if( carr.length <= 1 ){
JS9.fits.cleanupFITSFile(raw.hdu.fits, true);
}
}
// free wcs info
if( raw.altwcs ){
this.freeWCS(raw);
}
}
}
// remove proxy image from server, if necessary
tim.removeProxyFile();
// good hints to the garbage collector
tim.rgb = null;
tim.offscreen = null;
tim.raw = null;
tim.colorData = null;
tim.colorCells = null;
tim.psColors = null;
tim.psInverse = null;
tim = null;
// remove image from active list
JS9.images.splice(i,1);
// found and removed the specified image
break;
}
}
// display another image, if necessary and if possible
if( iscurrent ){
iscurrent -= 2;
for(i=iscurrent; i>=0; i--){
tim = JS9.images[i];
if( display === tim.display ){
// display image, 2D graphics, etc.
tim.displayImage("all");
tim.refreshLayers();
// signal that we're done
iscurrent = JS9.images.length;
break;
}
}
for(i=JS9.images.length-1; i>iscurrent; i--){
tim = JS9.images[i];
if( display === tim.display ){
// display image, 2D graphics, etc.
tim.displayImage("all");
tim.refreshLayers();
break;
}
}
}
};
// make offscreen canvas to hold RGB data from the png file
JS9.Image.prototype.mkOffScreenCanvas = function(){
// sanity check
if( !this.png || !this.png.image ){
return this;
}
// offscreen object holds canvas into which we draw to get RGB values
// no need for jquery here, we only manipulate this via the canvas API
this.offscreen = {};
this.offscreen.canvas = document.createElement("canvas");
this.offscreen.canvas.setAttribute("width", this.png.image.width);
this.offscreen.canvas.setAttribute("height", this.png.image.height);
this.offscreen.context = this.offscreen.canvas.getContext("2d");
// turn off anti-aliasing
if( !JS9.ANTIALIAS ){
this.offscreen.context.imageSmoothingEnabled = false;
// this.offscreen.context.mozImageSmoothingEnabled = false;
this.offscreen.context.webkitImageSmoothingEnabled = false;
this.offscreen.context.msImageSmoothingEnabled = false;
}
// draw the png to the offscreen canvas
this.offscreen.context.drawImage(this.png.image, 0, 0);
// read the RGBA data from offscreen
try{
this.offscreen.img = this.offscreen.context.getImageData(0, 0,
this.png.image.width, this.png.image.height);
} catch(e){
if( JS9.CHROMEFILEWARNING &&
(JS9.BROWSER[0] === "Chrome") && (document.domain === "") ){
alert("When using the file:https:// URI, Chrome must be run with the --allow-file-access-from-files switch to permit JS9 to access data.");
} else {
alert("could not read off-screen image data [same-origin policy violation?]");
}
}
// allow chaining
return this;
};
// initialize keywords for various logical coordinate systems
JS9.Image.prototype.initLCS = function(iheader){
var rrot, frot;
var arr = [[0,0,0], [0,0,0], [0,0,0]];
// header usually is raw header
var header = iheader || this.raw.header;
var cx = header.CRPIX1 || 1;
var cy = header.CRPIX2 || 1;
// screen rotation angle is reversed from FITS convention
var a = -(header.CROTA2||0) * Math.PI / 180.0;
var sina = Math.sin(a);
var cosa = Math.cos(a);
// seed rotation matrix and its inverse, if necessary
if( a ){
frot = [[0,0,0], [0,0,0], [0,0,0]];
frot[0][0] = cosa;
frot[0][1] = -sina;
frot[0][2] = 0;
frot[1][0] = sina;
frot[1][1] = cosa;
frot[1][2] = 0;
rrot = JS9.invertMatrix3(frot);
if( !rrot ){
frot = null;
}
}
// physical coords
arr[0][0] = header.LTM1_1 || 1.0;
arr[1][0] = header.LTM2_1 || 0.0;
arr[0][1] = header.LTM1_2 || 0.0;
arr[1][1] = header.LTM2_2 || 1.0;
arr[2][0] = header.LTV1 || 0.0;
arr[2][1] = header.LTV2 || 0.0;
this.lcs.physical = {forward: $.extend(true, [], arr),
reverse: JS9.invertMatrix3(arr)};
if( this.lcs.physical.reverse ){
if( frot ){
this.lcs.physical.frot = $.extend(true, [], frot);
this.lcs.physical.rrot = $.extend(true, [], rrot);
// zero-index center
this.lcs.physical.cx = cx - arr[2][0] - 1;
this.lcs.physical.cy = cy - arr[2][1] - 1;
}
} else {
delete this.lcs.physical;
}
// detector coordinates
arr[0][0] = header.DTM1_1 || 1.0;
arr[1][0] = header.DTM2_1 || 0.0;
arr[0][1] = header.DTM1_2 || 0.0;
arr[1][1] = header.DTM2_2 || 1.0;
arr[2][0] = header.DTV1 || 0.0;
arr[2][1] = header.DTV2 || 0.0;
this.lcs.detector = {forward: $.extend(true, [], arr),
reverse: JS9.invertMatrix3(arr)};
if( this.lcs.detector.reverse ){
if( frot ){
this.lcs.detector.frot = $.extend(true, [], frot);
this.lcs.detector.rrot = $.extend(true, [], rrot);
// zero-index center
this.lcs.detector.cx = cx - arr[2][0] - 1;
this.lcs.detector.cy = cy - arr[2][1] - 1;
}
} else {
delete this.lcs.detector;
}
// amplifier coordinates
arr[0][0] = header.ATM1_1 || 1.0;
arr[1][0] = header.ATM2_1 || 0.0;
arr[0][1] = header.ATM1_2 || 0.0;
arr[1][1] = header.ATM2_2 || 1.0;
arr[2][0] = header.ATV1 || 0.0;
arr[2][1] = header.ATV2 || 0.0;
this.lcs.amplifier = {forward: $.extend(true, [], arr),
reverse: JS9.invertMatrix3(arr)};
if( this.lcs.amplifier.reverse ){
if( frot ){
this.lcs.amplifier.frot = $.extend(true, [], frot);
this.lcs.amplifier.rrot = $.extend(true, [], rrot);
// zero-index center
this.lcs.amplifier.cx = cx - arr[2][0] - 1;
this.lcs.amplifier.cy = cy - arr[2][1] - 1;
}
} else {
delete this.lcs.amplifier;
}
// reset lcs to image, if necessary
if( this.params && !this.lcs[this.params.lcs] ){
this.params.lcs = "image";
}
// set current, if not already done
if( this.params && !this.params.wcssys0 ){
this.setWCSSys("physical");
this.params.wcssys0 = this.params.lcs;
}
// save original physical
if( this.lcs.physical && !this.lcs.ophysical ){
this.lcs.ophysical = $.extend(true, {}, this.lcs.physical);
}
// allow chaining
return this;
};