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