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