-
Notifications
You must be signed in to change notification settings - Fork 48
/
js9.js
11194 lines (10949 loc) · 315 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 module (December 10, 2012)
*
* Principals: Eric Mandel, Alexey Vikhlinin
* Organization: Harvard Smithsonian Center for Astrophysics, Cambridge MA
* Contact: saord@cfa.harvard.edu
*
* Copyright (c) 2012 - 2015 Smithsonian Astrophysical Observatory
*
* Utilizes: jquery.js
* jquery.contextMenu.js
* jquery.flot.js, jquery.flot.errorbars.js
* socket.io.js
* fabric.js
* dhtmlwindow.js
* sprintf.js
* astroem.js (includes cfitsio, wcslib)
* fitsy.js
*
*/
/*jslint plusplus: true, vars: true, white: true, continue: true, unparam: true, regexp: true, browser: true, devel: true, nomen: true */
/*global $, jQuery, Event, fabric, io, CanvasRenderingContext2D, sprintf, Blob, ArrayBuffer, Uint8Array, Uint16Array, Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, DataView, FileReader, Fitsy, Astroem, Module, dhtmlwindow, saveAs */
/*jshint smarttabs:true */
// check for already-loaded module
var JS9;
if( JS9 && (typeof JS9 !== "object" || JS9.NAME) ){
throw new Error("Namespace 'JS9' already exists");
}
// create the module and seed with standard values
var JS9 = {};
JS9.NAME = "JS9"; // The name of this namespace
JS9.VERSION = "1.5"; // The version of this namespace
JS9.COPYRIGHT = "Copyright (c) 2012-2015 Smithsonian Institution";
// use the module augmentation pattern, passing in our already-defined module
JS9 = (function(JS9){
"use strict";
// internal defaults (not usually changed by users)
JS9.DEFID = "JS9"; // default JS9 display id
JS9.ANON = "[anonymous]"; // name to use for images with no name
JS9.PREFSFILE = "js9Prefs.json";// prefs file to load
JS9.ZINDEX = 0; // z-index of image canvas: on bottom of js9
JS9.SHAPEZINDEX = 7; // z-index of 2d graphics (regions is +2)
JS9.MESSZINDEX = 8; // z-index of messages: above graphics
JS9.BTNZINDEX = 10; // 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.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 = 500; // milliseconds for double-click
JS9.TIMEOUT = 250; // ms before assuming light window is up
JS9.SUPERMENU = /^_SUPERMENU/; // base of supermenu id
// modified from:
// http://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;
}());
// global options
JS9.globalOpts = {
helperType: "sock.io", // one of: sock.io, get, post
helperPort: 2718, // default port for node.js helper
winType: "light", // plugin window: "light" or "new"
rgb: {mode: 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?
fits2png: false, // do we convert FITS to PNG representation?
alerts: true, // set to false to turn off alerts
internalValPos: true, // a fancy info plugin can turns this off
xtimeout: 1000, // connection timeout for xhr requests
extlist: "EVENTS STDEVT", // list of binary table extensions
dims: [1024, 1024], // dims of extracted images
helperProtocol: location.protocol,// http: or https:
maxMemory: 450000000, // max heap memory to allocate for a fits image
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
alpha: 255, // alpha for this image
alpha1: 100, // alpha for masked pixels
alpha2: 255, // alpha for unmasked 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
listonchange: false // whether to list after a reg change
};
// 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 = {
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",
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",
imageWin: "width=512px,height=542px,center=1,resize=1,scrolling=1",
lineWin: "width=400px,height=10px,center=1,resize=1,scrolling=1"
}
};
// colors for text messages
JS9.textColorOpts = {
regions: "#00FF00",
info: "#00FF00"
};
// defaults for plot creation
JS9.plotOpts = {
zoomStack: true,
selection: {
mode: "xy"
},
series: {
clickable: true,
hoverable: true,
lines: { show: true },
points: { show: false }
}
};
// help pages
JS9.helpOpts = {
user: {
type: "help", url:"user.html",
title: "JS9 User Manual"
},
install: {
type: "help", url:"install.html",
title: "Installing JS9"
},
webpage: {
type: "help", url:"webpage.html",
title: "Adding JS9 To A Web Page"
},
yourdata: {
type: "help", url:"yourdata.html",
title: "Adding Data To A Web Page"
},
localtasks: {
type: "help", url:"localtasks.html",
title: "Local Analysis with JS9"
},
publicapi: {
type: "help", url:"publicapi.html",
title: "The JS9 Public API"
},
helper: {
type: "help", url:"helper.html",
title: "Adding Server-side Analysis"
},
serverside: {
type: "help", url:"serverside.html",
title: "Server-side Analysis with JS9"
},
regions: {
type: "help", url:"regions.html",
title: "JS9 Regions Format"
},
extmsg: {
type: "help", url:"extmsg.html",
title: "JS9 External Messaging"
},
preferences: {
type: "help", url:"preferences.html",
title: "JS9 Site Preferences"
},
repfile: {
type: "help", url:"repfile.html",
title: "The PNG Represention File"
},
changelog: {
type: "help", url:"changelog.html",
title: "JS9 ChangeLog"
},
issues: {
type: "help", url:"knownissues.html",
title: "Known Issues"
}
};
// menu buttons in the menubar
// NB: names must match actual menus, menu labels are arbitrary
JS9.menuButtonOptsArr = [{name: "file", label: "File"},
{name: "view", label: "View"},
{name: "zoom", label: "Zoom"},
{name: "scale", label: "Scale"},
{name: "color", label: "Color"},
{name: "region", label: "Region"},
{name: "wcs", label: "WCS"},
{name: "analysis", label: "Analysis"},
{name: "help", label: "Help"}];
// misc arrays (mostly) holding instances of various primary 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", "pow", "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"];
// html used by the menubar plugin
JS9.menubarHTML = "";
// html used by the console plugin
JS9.consoleHTML =
"<form name='form' onsubmit='return false;' class='JS9CmdForm' action=''>" +
"<table class='JS9CmdTable'>" +
"<tr class='JS9Tr'>"+
"<td><div id='JS9CmdPrompt' class='JS9CmdPrompt'>@@PR@@</div></td>" +
"<td class='JS9CmdTd'><input type='text' class='JS9CmdIn' autocomplete='off' value='' /></td>" +
"</tr>" +
"</table>" +
"</form>";
// known bugs and work-arounds
JS9.bugs = {};
// sometimes hiding the menu does not refresh the image properly
JS9.bugs.hide_menu = true;
// 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;
}
// chrome 31 broke disableStrokeScale so that the shape border is not drawn
// fixed in chrome canary 33.0.1729.3 (12/5/2013)
if( (JS9.BROWSER[0] === "Chrome") ){
JS9.bugs.tval = parseInt(JS9.BROWSER[1].split(".").shift(), 10);
if( (JS9.bugs.tval >= 31) && (JS9.bugs.tval <= 33) ){
JS9.bugs.chrome_31 = true;
}
}
// ---------------------------------------------------------------------
// JS9 Image object to manage images
// ---------------------------------------------------------------------
JS9.Image = function(file, params, func){
var sarr;
var display;
var pname, pinst, popts;
var that = this;
var localOpts=null;
var mksect = function(that, localOpts){
var zoom;
var arr = [];
// make up section array from default values
if( localOpts.xcen !== undefined ){
arr.push(localOpts.xcen);
}
if( localOpts.ycen !== undefined ){
arr.push(localOpts.ycen);
}
if( localOpts.zoom !== undefined ){
zoom = that.parseZoom(localOpts.zoom);
if( zoom ){
arr.push(zoom);
}
}
return arr;
};
// 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);
// copy image parameters
this.params = $.extend(true, {}, JS9.imageOpts, localOpts);
// set the colormap object from colormap name (text string)
this.cmapObj = JS9.lookupColormap(this.params.colormap);
// do we display?
this.displayMode = true;
// mouse event state
this.evstate = -1;
// no region clicks yet
this.rclick = 0;
// no helper queried yet
this.queried = false;
// offsets into canvas to display
this.ix = 0;
this.iy = 0;
// init some new parameters
this.params.scalemin = Number.Nan;
this.params.scalemax = Number.Nan;
// xeq callback for region changes?
this.params.xeqonchange = true;
// copy plot parameters
this.params.plotOpts = $.extend(true, {}, JS9.plotOpts);
// create the png object
this.png = {};
// image element to hold png file, from which array data is generated
this.png.image = new Image();
// init menubar, if necessary
// this.initMenubar();
// init status object
this.status = {};
// primary image
this.primary = {};
// section parameters
this.primary.sect = {zoom: 1, ozoom: 1};
// graphical layers
this.layers = {};
// no logical coordinate systems
this.lcs = {};
// array of aux file pointers
this.aux = {};
// binning parameters
this.binning = {bin: 1, obin: 1};
// temp flag determines if we should update shapes at end of this call
this.updateshapes = false;
// 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 = "fits";
// generate the raw data array from the hdu
this.mkRawDataFromHDU(file, file.filename);
// do zscale, if necessary
if( this.params.scaleclipping === "zscale" ){
this.zscale(true);
}
// set up initial section
this.mkSection();
// change center and zoom if necessary
sarr = mksect(this, localOpts);
if( sarr.length ){
this.mkSection.apply(this, sarr);
}
// display image, 2D graphics, etc.
this.displayImage("all");
// clear previous messages
this.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
for( pname in this.display.pluginInstances ){
if( this.display.pluginInstances.hasOwnProperty(pname) ){
pinst = this.display.pluginInstances[pname];
popts = pinst.plugin.opts;
if( pinst.isActive("onimageload") ){
try{ popts.onimageload.call(pinst, this); }
catch(e){ pinst.errLog("onimageload", e); }
}
}
}
// 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);
break;
case "string":
// save source
this.source = "fits2png";
// image or table
this.imtab = "image";
// downloaded image file
this.file = file;
// take file but discard path (or scheme) up to slashes
this.oid = this.file.split("/").reverse()[0];
// save id in case we have to change it for uniqueness
this.id = JS9.getImageID(this.oid, this.display.id);
// load status
this.status.load = "loading";
// change the cursor to show the waiting status
JS9.waiting(true);
// callback to fire when image is loaded (do this before setting src)
$(this.png.image).on("load", function(evt){
var ppname, ppinst, ppopts;
// 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);
}
// 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");
// clear previous messages
that.clearMessage();
// add to list of images
JS9.images.push(that);
// call function, if necessary
if( func ){
try{ JS9.xeqByName(func, window, that); }
catch(e){ JS9.error("in image onload callback", e, false); }
}
// plugin callbacks
for( ppname in that.display.pluginInstances ){
if( that.display.pluginInstances.hasOwnProperty(ppname) ){
ppinst = that.display.pluginInstances[ppname];
ppopts = ppinst.plugin.opts;
if( ppinst.isActive("onimageload") ){
try{ ppopts.onimageload.call(ppinst, that); }
catch(e){ pinst.errLog("onimageload", e); }
}
}
}
// load is complete
that.status.load = "complete";
// done loading, reset wait cursor
JS9.waiting(false);
// 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(evt){
// 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);
}
};
// undisplay the image, release resources
JS9.Image.prototype.closeImage = function(){
var i, tim, key;
var pname, pinst, popts;
var ilen= JS9.images.length;
var display = this.display;
// look for an image and remove it
for(i=0; i<ilen; i++){
if( this === JS9.images[i] ){
tim = JS9.images[i];
// nothing on the screen
tim.clearMessage();
tim.display.context.clear();
// plugin callbacks
for( pname in tim.display.pluginInstances ){
if( tim.display.pluginInstances.hasOwnProperty(pname) ){
pinst = tim.display.pluginInstances[pname];
popts = pinst.plugin.opts;
if( pinst.isActive("onimageclose") ){
try{ popts.onimageclose.call(pinst, tim); }
catch(e){ pinst.errLog("onimageclose", e); }
}
}
}
// remove all layers
for( key in tim.layers ){
if( tim.layers.hasOwnProperty(key) ){
tim.layers[key].canvas.dispose();
tim.layers[key] = null;
}
}
// clear image from display
tim.display.image = null;
// remove from rgb, 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 ){
JS9.fits.cleanupFITSFile(tim.raw.hdu.fits, true);
}
// good hints to the garbage collector
tim.primary = null;
tim.offscreen = null;
tim.raw = null;
tim.colorData = null;
tim.colorCells = null;
tim.psColors = null;
tim = null;
// remove image from active list
JS9.images.splice(i,1);
break;
}
}
// display another image, if available
for(i=0; i<JS9.images.length; i++){
tim = JS9.images[i];
if( display === tim.display ){
// display image, 2D graphics, etc.
tim.displayImage("display");
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;
}
// draw the png to the offscreen canvas
this.offscreen.context.drawImage(this.png.image,
0, 0,
this.png.image.width,
this.png.image.height,
0, 0,
this.png.image.width,
this.png.image.height);
// 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.BROWSER[0] === "Chrome") && (document.domain === "") ){
alert("When using the file:// URI, Chrome must be run with the --allow-file-access-from-files switch to permit JS9 to access data.");
} else {
alert("could not read JS9 data");
}
}
// allow chaining
return this;
};
// initialize keywords for various logical coordinate systems
JS9.Image.prototype.initLCS = function(header){
var arr = [[0,0,0], [0,0,0], [0,0,0]];
var invertm3 = function(xin){
var i, j;
var det_1;
var prec = 1.0e-15;
var pos = 0.0;
var neg = 0.0;
var xout = [[0,0,0], [0,0,0], [0,0,0]];
var temp = xin[0][0] * xin[1][1];
var accum = function(){
if( temp >= 0.0 ){
pos += temp;
} else {
neg += temp;
}
};
// sanity check for a header param missing or NaN
for(i=0; i<3; i++){
for(j=0; j<2; j++){
if( (xin[i][j] === undefined) || isNaN(xin[i][j]) ){
return null;
}
}
}
accum();
temp = -xin[0][1] * xin[1][0];
accum();
det_1 = pos + neg;
// Is the submatrix A singular?
if( (det_1 === 0.0) || (Math.abs(det_1 / (pos - neg)) < prec) ){
// Matrix M has no inverse
return null;
}
// Calculate inverse(A) = adj(A) / det(A)
det_1 = 1.0 / det_1;
xout[0][0] = xin[1][1] * det_1;
xout[1][0] = - xin[1][0] * det_1;
xout[0][1] = - xin[0][1] * det_1;
xout[1][1] = xin[0][0] * det_1;
// Calculate -C * inverse(A)
xout[2][0] = - (xin[2][0] * xout[0][0] + xin[2][1] * xout[1][0]);
xout[2][1] = - (xin[2][0] * xout[0][1] + xin[2][1] * xout[1][1]);
return xout;
};
// sanity check
if( !header ){
return;
}
// 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: invertm3(arr)};
if( !this.lcs.physical.reverse ){
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: invertm3(arr)};
if( !this.lcs.detector.reverse ){
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: invertm3(arr)};
if( !this.lcs.amplifier.reverse ){
delete this.lcs.amplifier;
}
// reset lcs to image, if necessary
if( !this.lcs[this.params.lcs] ){
this.params.lcs = "image";
}
// set current, if not already done
if( !this.params.wcssys0 ){
this.setWCSSys("physical");
this.params.wcssys0 = this.params.lcs;
}
};
// unpack IMG data and convert to JS9 image data
JS9.Image.prototype.mkRawDataFromIMG = function(img){
var i, h, w, ibuf, x, y, v;
// sanity check
if( !img ){
return;
}
// convenience variables
h = img.height;
w = img.width;
ibuf = img.data;
// create a raw array to hold the reconsituted data
this.raw.data = new Float32Array(h*w);
// get data value from RGB
for(i=0, y=0; y<h; y++){
for(x=0; x<w; x++){
// NTSC
v = 0.299 * ibuf[i] + 0.587 * ibuf[i+1] + 0.114 * ibuf[i+2];
// "Modern"
// v = 0.212 * ibuf[i] + 0.715 * ibuf[i+1] + 0.073 * ibuf[i+2];
this.raw.data[(h-y)*w+x] = v;
i += 4;
}
}
// fill in the raw info
this.raw.width = w;
this.raw.height = h;
this.raw.bitpix = -32;
this.raw.dmin = Number.MAX_VALUE;
this.raw.dmax = Number.MIN_VALUE;
// find data min and max
for(i=0; i<h*w; i++) {
if( !isNaN(this.raw.data[i]) ){
this.raw.dmin = Math.min(this.raw.dmin, this.raw.data[i]);
this.raw.dmax = Math.max(this.raw.dmax, this.raw.data[i]);
}
}
// set initial scaling values if not done already
if( isNaN(this.params.scalemin) ){
this.params.scalemin = this.raw.dmin;
}
if( isNaN(this.params.scalemax) ){
this.params.scalemax = this.raw.dmax;
}
// change data source
this.source = "png";
// there is no header
this.raw.header = null;
// allow chaining
return this;
};
// unpack PNG data and convert to image data
JS9.Image.prototype.mkRawDataFromPNG = function(){
var i, s, idx, offscreen, dlen, mode, tval, getfunc, littleEndian;
var card, pars, clen;
var realpng, hstr, hstrs = [];
// memory array of 8 bytes
var abuf = new ArrayBuffer(8);
// we will transfer unsigned bytes from the png file into the mem array
var u = new Uint8Array(abuf);
// we will use the DataView api to access these bytes as typed data
// (including possible endian conversion)
var dv = new DataView(abuf);
// sanity check (we will null out the png image when we are done with it)
if( !this.offscreen.img ){
return this;
}
// create the object to hold raw data
this.raw = {};
// offscreen image data
offscreen = this.offscreen.img.data;
// gather up the json header (until we hit a null, skipping bogus values)
for(idx=0, i=0; idx<offscreen.length; idx++) {
// null is the end of the string
if( offscreen[idx] === 0 ){
break;
}
if( offscreen[idx] !== 255 ){
hstrs[i] = String.fromCharCode(offscreen[idx]);
i++;
}
// check for a JS9 header on a representation file
if( (i === 15) && (hstrs.join("") !== '{"js9Protocol":') ){
realpng = true;
break;
}
}
// see if we have a real PNG file instead of a representation file
if( (i < 15) || realpng ){
// holy moly, its a real png file!
this.mkRawDataFromIMG(this.offscreen.img);
// having the real image, we can ask to release the offscreen image
this.offscreen.img = null;
return;
}
// its a representation file
// create and try to parse the json header
hstr = hstrs.join("");
if( JS9.DEBUG > 2 ){
JS9.log("jsonHeader: %s", hstr);
}
try{ s = JSON.parse(hstr); }
catch(e){
JS9.error("can't read FITS header from PNG file: "+hstr, e);
}
if( s.js9Protocol === 1.0 ){
this.raw.header = s;
this.raw.endian = this.raw.header.js9Endian;
this.raw.protocol = this.raw.header.js9Protocol;
} else {
this.raw.endian = s.js9Endian;
this.raw.protocol = s.js9Protocol;
this.raw.cardstr = s.cardstr;
this.raw.ncard = s.ncard;
this.raw.header = {};
// make up header from string containing 80-char raw cards
clen = this.raw.ncard;
for(i=0; i<clen; i++){
card = this.raw.cardstr.slice(i*80, (i+1)*80);
pars = JS9.cardpars(card);
if ( pars !== undefined ) {
this.raw.header[pars[0]] = pars[1];
}
}
}
// set the pointer to start of "real" image data
idx = idx + 1;
// make sure we have a valid FITS header
if( this.raw.header.NAXIS1 ){
this.raw.width = this.raw.header.NAXIS1;
} else {
JS9.error("NAXIS1 missing from PNG-based FITS header");
}
if( this.raw.header.NAXIS2 ){
this.raw.height = this.raw.header.NAXIS2;
} else {
JS9.error("NAXIS2 missing from PNG-based FITS header");
}
if( this.raw.header.BITPIX ){
this.raw.bitpix = this.raw.header.BITPIX;
} else {
JS9.error("BITPIX missing from PNG-based FITS header");
}
if( this.raw.endian === "little" ){
littleEndian = true;
} else if( this.raw.endian === "big" ){
littleEndian = false;
} else {
JS9.error("js9Endian missing from PNG-based FITS header");
}
// object name
this.object = this.raw.header.OBJECT;
// no min or max yet
this.raw.dmin = Number.MAX_VALUE;
this.raw.dmax = Number.MIN_VALUE;
// number of data pixels
dlen = this.raw.width * this.raw.height;
// mode: process the next imge pixel based on starting index into RGBA pixel
mode = idx % 4;
// image pixels are packed into RGBA array, in little-endian format.
// The A value is supplied by the browser and has to be skipped.
switch(this.raw.bitpix){
case 8:
// 8-bit unsigned char data
this.raw.data = new Uint8Array(dlen);
for(i=0; i<dlen; i++){
switch(mode){
case 0:
tval = offscreen[idx];
idx += 1;
mode = 1;
break;
case 1:
tval = offscreen[idx];
idx += 1;
mode = 2;
break;
case 2:
tval = offscreen[idx];
idx += 2;
mode = 0;
break;
case 3:
tval = offscreen[idx+1];
idx += 2;
mode = 1;
break;
}
// save current pixel value
this.raw.data[i] = tval;
// save min and max data values as we convert
if( !isNaN(tval) ){
this.raw.dmin = Math.min(this.raw.dmin, tval);
this.raw.dmax = Math.max(this.raw.dmax, tval);
}
}
break;
case 16:
case -16:
if( this.raw.bitpix === 16 ){
this.raw.data = new Int16Array(dlen);
getfunc = DataView.prototype.getInt16;
} else {
this.raw.data = new Uint16Array(dlen);
getfunc = DataView.prototype.getUint16;
}
// 16-bit signed short int data
for(i=0; i<dlen; i++){
switch(mode){
case 0:
u[0] = offscreen[idx];
u[1] = offscreen[idx+1];
tval = getfunc.call(dv, 0, littleEndian);
idx += 2;
mode = 2;
break;
case 1:
u[0] = offscreen[idx];
u[1] = offscreen[idx+1];
tval = getfunc.call(dv, 0, littleEndian);
idx += 3;
mode = 0;
break;
case 2:
u[0] = offscreen[idx];
u[1] = offscreen[idx+2];
tval = getfunc.call(dv, 0, littleEndian);
idx += 3;
mode = 1;
break;
case 3:
u[0] = offscreen[idx+1];
u[1] = offscreen[idx+2];
tval = getfunc.call(dv, 0, littleEndian);
idx += 3;
mode = 2;
break;
}
// save current pixel value
this.raw.data[i] = tval;
// save min and max data values as we convert
if( !isNaN(tval) ){
this.raw.dmin = Math.min(this.raw.dmin, tval);
this.raw.dmax = Math.max(this.raw.dmax, tval);
}
}
break;
case 32:
case -32:
// 32-bit signed int data
// 32-bit float data
if( this.raw.bitpix === 32 ){
this.raw.data = new Int32Array(dlen);
getfunc = DataView.prototype.getInt32;
} else {
this.raw.data = new Float32Array(dlen);
getfunc = DataView.prototype.getFloat32;
}
for(i=0; i<dlen; i++){