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