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