JAL-1807 update
[jalviewjs.git] / site / swingjs / js / SwingJS.js
1 // SwingJS.js
2
3 // BH 4/28/2015 10:15:32 PM adds getAppletHtml 
4 // BH 4/2/2015 5:17:44 PM  adds SwingJS.getJavaResource(path)
5
6 // BH 3/27/2015 6:34:49 AM  just a shell
7
8 if(typeof(jQuery)=="undefined") alert ("Note -- jQuery is required for SwingJS, but it's not defined.")
9
10 if (typeof(SwingJS) == "undefined") {
11
12   SwingJS = {};
13
14 (function (SwingJS, $) {
15
16         SwingJS.getApplet = function(id, Info, checkOnly) {
17                 return SwingJS._Applet._get(id, Info, checkOnly);
18         }
19
20   SwingJS.getJavaResource = function(path) {
21                 if (path.indexOf("http") != 0) {
22       var applet = Jmol._applets[java.lang.Thread.currentThread().getName()];
23       path = (applet.__Info.resourcePath || applet.__Info.j2sPath) + "/" + path
24       }      
25     System.out.println("Swingjs.js getJavaResource " + path)
26     var s = Jmol._getFileData(path);
27     if (s.indexOf("[Exception") == 0)
28       return null; 
29     if (path.lastIndexOf(".css") == path.length - 4) {
30       path = path.substring(0, path.lastIndexOf("/") + 1) + "images/";
31       s = s.replace(/images\//g, path)
32       jQuery("head").append(jQuery("<style type='text/css'>" + s + "</style>"));
33       return s;
34     } else if (path.lastIndexOf(".js") == path.length - 3) {
35       try {
36         eval(s);
37       } catch (e) {
38       alert("error processing " + s)
39         return null;
40       }
41     }
42     return s; 
43   }
44
45         // optional Info here   
46         SwingJS.getAppletHtml = function(applet, Info) {
47                 if (Info) {
48                         var d = SwingJS._document;
49                         SwingJS._document = null;
50                         applet = SwingJS.getApplet(applet, Info);
51                         SwingJS._document = d;
52                 }  
53                 return applet._code;
54         }
55
56         SwingJS._Applet = function(id, Info, checkOnly){
57                 window[id] = this;
58                 this._appletType = "SwingJS._Applet" + (Info.isSigned ? " (signed)" : "");
59                 this._isJava = true;
60                 this._availableParams = null; // all allowed
61                 if (checkOnly)
62                         return this;
63                 this._isSigned = Info.isSigned;
64                 this._readyFunction = Info.readyFunction;
65                 this._ready = false;
66                 this._isJava = true; 
67                 this._isInfoVisible = false;
68                 this._applet = null;
69                 this._memoryLimit = Info.memoryLimit || 512;
70                 this._canScript = function(script) {return true;};
71                 this._savedOrientations = [];
72                 this._initialize = function(jarPath, jarFile) {
73                         var doReport = false;
74                         SwingJS._jarFile && (jarFile = SwingJS._jarFile);
75                         if(this._jarFile) {
76                                 var f = this._jarFile;
77                                 if(f.indexOf("/") >= 0) {
78                                         alert ("This web page URL is requesting that the applet used be " + f + ". This is a possible security risk, particularly if the applet is signed, because signed applets can read and write files on your local machine or network.");
79                                         var ok = prompt("Do you want to use applet " + f + "? ", "yes or no")
80                                         if(ok == "yes") {
81                                                 jarPath = f.substring(0, f.lastIndexOf("/"));
82                                                 jarFile = f.substring(f.lastIndexOf("/") + 1);
83                                         } else {
84                                                 doReport = true;
85                                         }
86                                 } else {
87                                         jarFile = f;
88                                 }
89                                 this_isSigned = Info.isSigned = (jarFile.indexOf("Signed") >= 0);
90                         }
91                         this._jarPath = Info.jarPath = jarPath || ".";
92                         this._jarFile = Info.jarFile = jarFile;
93                         if (doReport)
94                                 alert ("The web page URL was ignored. Continuing using " + this._jarFile + ' in directory "' + this._jarPath + '"');
95                         // could do something like this: Jmol.controls == undefined || Jmol.controls._onloadResetForms();               
96                 }               
97                 this._create(id, Info);
98                 return this;
99         }
100
101         ;(function(Applet, proto) {
102   
103         Applet._get = function(id, Info, checkOnly) {
104
105                 checkOnly || (checkOnly = false);
106                 Info || (Info = {});
107                 var DefaultInfo = {
108       code: "swingjs.test.TanSugd3S",
109       uncompressed: true,
110                         color: "#FFFFFF", // applet object background color
111                         width: 300,
112                         height: 300,
113                         serverURL: "http://your.server.here/jsmol.php",
114           console: null,  // div for where the JavaScript console will be.
115                         readyFunction: null,
116                         use: "HTML5",//other options include JAVA
117                         jarPath: "java",
118                         jarFile: "[code].jar",
119                         j2sPath: "j2s",
120                         disableJ2SLoadMonitor: false,
121                         disableInitialConsole: false,
122                         debug: false
123                 };       
124     
125     // Jmol here
126     
127                 Jmol._addDefaultInfo(Info, DefaultInfo);
128     Info.jarFile && Info.code && Info.jarFile.replace(/\[code\]/,Info.code);
129                 Jmol._debugAlert = Info.debug;
130                 Info.serverURL && (Jmol._serverUrl = Info.serverURL);
131
132                 var javaAllowed = false;
133                 var applet = null;
134                 var List = Info.use.toUpperCase().split("#")[0].split(" ");
135                 for (var i = 0; i < List.length; i++) {
136                         switch (List[i]) {
137                         case "JAVA":
138                                 javaAllowed = true;
139                                 if (Jmol.featureDetection.supportsJava())
140                                         applet = new Applet(id, Info, checkOnly);
141                                 break;
142                         case "HTML5":               
143                         if (Jmol.featureDetection.allowHTML5){
144                                   applet = Applet._getCanvas(id, Info, checkOnly);
145         } else {
146           List.push("JAVA");
147         }
148                                 break;
149                         }
150                         if (applet != null)
151                                 break;            
152                 }
153                 if (applet == null) {
154                         if (checkOnly || !javaAllowed)
155                                 applet = {_appletType : "none" };
156                         else if (javaAllowed)
157                         applet = new Applet(id, Info);
158                 }
159
160                 // keyed to both its string id and itself
161                 return (checkOnly ? applet : Jmol._registerApplet(id, applet));  
162         }
163
164         Applet._getCanvas = function(id, Info, checkOnly) {
165     Info._isLayered = true;
166     Info._isSwing = true;
167     Info._platform = "";
168                 Jmol._Canvas2D.prototype = Jmol._jsSetPrototype(new Applet(id, Info, true));
169                 return new Jmol._Canvas2D(id, Info, Info.code, checkOnly);
170         };
171
172         /*  AngelH, mar2007:
173                 By (re)setting these variables in the webpage before calling Jmol.getApplet(),
174                 a custom message can be provided (e.g. localized for user's language) when no Java is installed.
175         */
176         Applet._noJavaMsg =
177                         "Either you do not have Java applets enabled in your web<br />browser or your browser is blocking this applet.<br />\
178                         Check the warning message from your browser and/or enable Java applets in<br />\
179                         your web browser preferences, or install the Java Runtime Environment from <a href='http://www.java.com'>www.java.com</a>";
180
181         Applet._setCommonMethods = function(p) {
182                 p._showInfo = proto._showInfo;  
183 ///             p._search = proto._search;
184                 p._getName = proto._getName;
185                 p._readyCallback = proto._readyCallback;
186         }
187
188         Applet._createApplet = function(applet, Info, params) {
189                 applet._initialize(Info.jarPath, Info.jarFile);
190                 var jarFile = applet._jarFile;
191                 var jnlp = ""
192                 if (Jmol._isFile) {
193                         // local installations need jnlp here and should reference JmolApplet(Signed).jar, not JmolApplet(Signed)0.jar  
194                         jarFile = jarFile.replace(/0\.jar/,".jar");
195                         //jnlp = " jnlp_href=\"" + jarFile.replace(/\.jar/,".jnlp") + "\"";
196                 }
197                 // size is set to 100% of containers' size, but only if resizable. 
198                 // Note that resizability in MSIE requires: 
199                 // <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
200                 var w = (applet._containerWidth.indexOf("px") >= 0 ? applet._containerWidth : "100%");
201                 var h = (applet._containerHeight.indexOf("px") >= 0 ? applet._containerHeight : "100%");
202                 var widthAndHeight = " style=\"width:" + w + ";height:" + h + "\" ";
203                 var attributes = "name='" + applet._id + "_object' id='" + applet._id + "_object' " + "\n"
204                                 + widthAndHeight + jnlp + "\n"
205                 params.codebase = applet._jarPath;
206                 params.codePath = params.codebase + "/";
207                 if (params.codePath.indexOf("://") < 0) {
208                         var base = document.location.href.split("#")[0].split("?")[0].split("/");
209                         base[base.length - 1] = params.codePath;
210                         params.codePath = base.join("/");
211                 }
212                 params.archive = jarFile;
213                 params.mayscript = 'true';
214                 params.java_arguments = "-Xmx" + Math.round(Info.memoryLimit || applet._memoryLimit) + "m";
215                 params.permissions = (applet._isSigned ? "all-permissions" : "sandbox");
216                 params.documentLocation = document.location.href;
217                 params.documentBase = document.location.href.split("#")[0].split("?")[0];
218
219                 params.jarPath = Info.jarPath;
220                 Jmol._syncedApplets.length && (params.synccallback = "Jmol._mySyncCallback");
221                 applet._startupScript && (params.script = applet._startupScript);
222                 var t = "\n"; 
223                 for (var i in params)
224                         if(params[i])
225                                 t += "  <param name='"+i+"' value='"+params[i]+"' />\n";
226                 if (Jmol.featureDetection.useIEObject || Jmol.featureDetection.useHtml4Object) {
227                         t = "<object " + attributes
228                                 + (Jmol.featureDetection.useIEObject ? 
229                                          " classid='clsid:8AD9C840-044E-11D1-B3E9-00805F499D93' codebase='http://java.sun.com/update/1.6.0/jinstall-6u22-windows-i586.cab'>"
230                                  : " type='application/x-java-applet'>")
231                                  + t + "<p style='background-color:yellow;" + widthAndHeight.split('"')[1] 
232                                 + ";text-align:center;vertical-align:middle;'>\n" + Applet._noJavaMsg + "</p></object>\n";
233                 } else { // use applet tag
234                         t = "<applet " + attributes
235                                 + " code='" + params.code + "' codebase='" + applet._jarPath + "' archive='" + jarFile + "' mayscript='true'>\n"
236                                 + t + "<table bgcolor='yellow'><tr><td align='center' valign='middle' " + widthAndHeight + ">\n"
237                                 + Applet._noJavaMsg + "</td></tr></table></applet>\n";
238                 }
239                 if (applet._deferApplet)
240                         applet._javaCode = t, t="";
241                 t = Jmol._getWrapper(applet, true) + t + Jmol._getWrapper(applet, false) 
242                         + (Info.addSelectionOptions ? Jmol._getGrabberOptions(applet) : "");
243                 if (Jmol._debugAlert)
244                         alert (t);
245                 applet._code = Jmol._documentWrite(t);
246         }
247
248         proto._newApplet = function(viewerOptions) {
249                 this._viewerOptions = viewerOptions;
250     // for now assigning this._applet here instead of in readyCallback
251                 this._appletPanel = new swingjs.JSAppletPanel(viewerOptions);
252     this._appletPanel.start();
253         }
254         
255         proto._addCoreFiles = function() {
256                 Jmol._addCoreFile("swingjs", this._j2sPath, this.__Info.preloadCore);
257                 if (Jmol._debugCode) {
258                 // no min package for that
259                         Jmol._addExec([this, null, "swingjs.JSAppletPanel", "load " + this.__Info.code]);
260       
261                 }
262   }
263   
264         proto._create = function(id, Info){
265                 Jmol._setObject(this, id, Info);
266                 var params = {
267                         syncId: Jmol._syncId,
268                         progressbar: "true",                      
269                         progresscolor: "blue",
270                         boxbgcolor: this._color || "black",
271                         boxfgcolor: "white",
272                         boxmessage: "Downloading Applet ...",
273                         //script: (this._color ? "background \"" + this._color +"\"": ""),
274                         code: Info.appletClass + ".class"
275                 };
276
277                 Jmol._setAppletParams(this._availableParams, params, Info);
278                 function sterilizeInline(model) {
279                         model = model.replace(/\r|\n|\r\n/g, (model.indexOf("|") >= 0 ? "\\/n" : "|")).replace(/'/g, "&#39;");
280                         if(Jmol._debugAlert)
281                                 alert ("inline model:\n" + model);
282                         return model;
283                 }
284
285                 params.loadInline = (Info.inlineModel ? sterilizeInline(Info.inlineModel) : "");
286                 params.appletReadyCallback = "Jmol._readyCallback";
287                 if (Jmol._syncedApplets.length)
288                         params.synccallback = "Jmol._mySyncCallback";
289                 params.java_arguments = "-Xmx" + Math.round(Info.memoryLimit || this._memoryLimit) + "m";
290
291                 this._initialize(Info.jarPath, Info.jarFile);
292                 Applet._createApplet(this, Info, params);
293         }
294
295
296         proto._restoreState = function(clazzName, state) {
297    // applet-dependent
298         }
299
300         proto._readyCallback = function(id, fullid, isReady) {
301                 if (!isReady)
302                         return; // ignore -- page is closing
303                 Jmol._setDestroy(this);
304                 this._ready = true;
305                 var script = this._readyScript;
306                 if (this._defaultModel)
307                         Jmol._search(this, this._defaultModel, (script ? ";" + script : ""));
308                 else if (script)
309                         this._script(script);
310                 else if (this._src)
311                         this._script('load "' + this._src + '"');
312                 this._showInfo(true);
313                 this._showInfo(false);
314                 Jmol.Cache.setDragDrop(this);
315                 this._readyFunction && this._readyFunction(this);
316                 Jmol._setReady(this);
317                 var app = this._2dapplet;
318                 if (app && app._isEmbedded && app._ready && app.__Info.visible)
319                         this._show2d(true);
320         }
321
322         proto._showInfo = function(tf) {
323                 if(tf && this._2dapplet)
324                         this._2dapplet._show(false);
325                 Jmol.$html(Jmol.$(this, "infoheaderspan"), this._infoHeader);
326                 if (this._info)
327                         Jmol.$html(Jmol.$(this, "infodiv"), this._info);
328                 if ((!this._isInfoVisible) == (!tf))
329                         return;
330                 this._isInfoVisible = tf;
331                 // 1px does not work for MSIE
332                 if (this._isJava) {
333                         var x = (tf ? 2 : "100%");
334                         Jmol.$setSize(Jmol.$(this, "appletdiv"), x, x);
335                 }
336                 Jmol.$setVisible(Jmol.$(this, "infotablediv"), tf);
337                 Jmol.$setVisible(Jmol.$(this, "infoheaderdiv"), tf);
338                 this._show(!tf);
339         }
340
341         proto._show = function(tf) {
342                 var x = (!tf ? 2 : "100%");
343                 Jmol.$setSize(Jmol.$(this, "object"), x, x);
344                 if (!this._isJava)
345                         Jmol.$setVisible(Jmol.$(this, "appletdiv"), tf);
346         }
347
348         proto._clearConsole = function () {
349                         if (this._console == this._id + "_infodiv")
350                                 this.info = "";
351                         if (!self.Clazz)return;
352                         Jmol._setConsoleDiv(this._console);
353                         Clazz.Console.clear();
354                 }
355
356         proto._resizeApplet = function(size) {
357                 // See _jmolGetAppletSize() for the formats accepted as size [same used by jmolApplet()]
358                 //  Special case: an empty value for width or height is accepted, meaning no change in that dimension.
359
360                 /*
361                  * private functions
362                  */
363                 function _getAppletSize(size, units) {
364                         /* Accepts single number, 2-value array, or object with width and height as mroperties, each one can be one of:
365                          percent (text string ending %), decimal 0 to 1 (percent/100), number, or text string (interpreted as nr.)
366                          [width, height] array of strings is returned, with units added if specified.
367                          Percent is relative to container div or element (which should have explicitly set size).
368                          */
369                         var width, height;
370                         if(( typeof size) == "object" && size != null) {
371                                 width = size[0]||size.width;
372                                 height = size[1]||size.height;
373                         } else {
374                                 width = height = size;
375                         }
376                         return [_fixDim(width, units), _fixDim(height, units)];
377                 }
378
379                 function _fixDim(x, units) {
380                         var sx = "" + x;
381                         return (sx.length == 0 ? (units ? "" : Jmol._allowedJmolSize[2]) 
382                                 : sx.indexOf("%") == sx.length - 1 ? sx 
383                                 : (x = parseFloat(x)) <= 1 && x > 0 ? x * 100 + "%" 
384                                 : (isNaN(x = Math.floor(x)) ? Jmol._allowedJmolSize[2] 
385                                 : x < Jmol._allowedJmolSize[0] ? Jmol._allowedJmolSize[0] 
386                                 : x > Jmol._allowedJmolSize[1] ? Jmol._allowedJmolSize[1] 
387                                 : x)
388                                 + (units ? units : "")
389                         );
390                 }
391
392                 var sz = _getAppletSize(size, "px");
393                 var d = Jmol._getElement(this, "appletinfotablediv");
394                 d.style.width = sz[0];
395                 d.style.height = sz[1];
396                 this._containerWidth = sz[0];
397                 this._containerHeight = sz[1];
398                 if (this._is2D)
399                         Jmol._repaint(this, true);
400         }
401
402         proto._cover = function (doCover) {
403     // from using getAppletHtml()
404                 this._newCanvas(false);
405                 this._showInfo(false);
406                 this._init();
407         };
408
409
410   
411 })(SwingJS._Applet, SwingJS._Applet.prototype);
412
413 })(SwingJS, jQuery);
414
415 } // SwingJS undefined