Difference between revisions of "Recycling Corner"

From Jmol
Jump to navigation Jump to search
(update Opening a duplicate of the model in a resizable pop-up window)
(Jmol "pop-up" and "pop-in")
Line 70: Line 70:
 
For an alternative method, see [http://www.cem.msu.edu/~reusch/VirtTxtJml/strcopen.htm Bill Reusch's page] that uses innerHTML.
 
For an alternative method, see [http://www.cem.msu.edu/~reusch/VirtTxtJml/strcopen.htm Bill Reusch's page] that uses innerHTML.
  
 +
For other pop-up solutions, see also [[#Opening_a_duplicate_of_the_model_in_a_resizable_pop-up_window|below]].
  
 
=== Dynamically resized panels layout ===
 
=== Dynamically resized panels layout ===

Revision as of 11:55, 8 May 2013

This section intends to collect material by some users that may be useful to other users.

Feel free to add your material!

Jmol / JSmol Applications

For example:

Jmol icons

New 2008 Jmol icon

128px 94px 48px 32px 16px
png Jmol icon 128.png Jmol icon 94.png Jmol icon 48.png Jmol icon 32.png Jmol icon 16.png
gif Jmol icon 128.gif
jpg Jmol icon 128.jpg Jmol icon 94.jpg
ico File:Jmol icon win.ico *

(*) Windows multiresource icon (includes several resolutions and color depths); .ico files cannot be shown on this webpage, but you can download them.


Other

These are not very good-looking, but something for a start.

File:Jmol75x29x8.ico Windows icon, with just "Jm" taken from Jmol logo. 256 colors, transparent background.

File:Jmol 16 32.ico Windows icon, "J" from Jmol logo, together with a ball&sticks small model. 2 resolutions (16, 32px), 256 colors, transparent background.

Jmol icon Mac.png PNG icon (useful for Mac or Linux), Jmol logo over a tilted bluish square. 141x119 px, full color.

Jmol images, graphics or logos

on a separate page


Templates for creating Jmol webpages

Jmol_Web_Page_Maker

Jonathan Gutow has written a Java program that automates generation of webpages that include Jmol. The two templates below are among the types of web pages that can be generated. When using Jmol_Web_Page_Maker for the templates below, you can choose the view(s) to be displayed inside the Jmol application and have the necessary scripts, images plus .html code generated and saved automatically. Visit his website.

This is now superceeded by the "export to web page" ability included within recent versions of Jmol application (11.3.x).

Easy assignments for students or quick building of a simple page!

SChiSM2

SChiSM2 is a program running in a web server that lets you easily create a web page that includes interactive molecular models using JmolApplet.

S. Cammer (2007) SChiSM2: creating interactive web page annotations of molecular structure models using Jmol. Bioinformatics 23:383-384. doi:10.1093/bioinformatics/btl603 [1]

Jmol "pop-up" and "pop-in"

Delays the appearance of Jmol panel until the user requests it. An image or caption is shown and upon user's choice it is replaced by the applet.

No more waiting for Java and Jmol to load if you are not interested in the 3D model!

Two methods have been developed:

  • Method A - versatile: The user clicks to see the 3D model, and chooses whether it will be opened inline within the page (“pop-in”), or in a common pop-up window, or in separate pop-up windows for each model. (Uses <iframe>.)
  • Method B - simpler: The user clicks to see the 3D model, always inline within the page (“pop-in”). (Uses <div>.) (A similar method is used on Jmol home webpage.)

You can find more details, demo pages and downloadable templates for both methods at Biomodel website.

For an alternative method, see Bill Reusch's page that uses innerHTML.

For other pop-up solutions, see also below.

Dynamically resized panels layout

Six templates for dividing the screen into two or more panels, either for Jmol or for content, all sized in percent relative to window size, using the whole window space, and automatically resized when the window is resized; no scrollbars in Jmol section, scrollbars in content if needed, no duplicate parallel scrollbars.

No more guessing the user's screen resolution, browser chrome, default font size!

Resizable-panels.png

You can find more details, demo pages and downloadable templates at Biomodel website.

Reusable scripts

Molecule color picker

Molcolpicker.gif Appcolpicker.gif

The code below was used to create the palettes shown above. It's a pure javascript color picker that can be used for changing color of selected part of molecule, applet background, or any feature of the model (cartoons, surfaces, etc.).

Sample of use:

Pick color for currently selected part of molecule:
<script type="text/javascript">
writeColorPicker("atoms", "0", "h")
</script>
<br>
Pick color for background:
<script type="text/javascript">
writeColorPicker("background", "0", "h", "D9EBFF")
</script>
<br>
Pick color for cartoons:
<script type="text/javascript">
writeColorPicker("cartoons", "0", "v")
</script>

JavaScript code needed:

/* Color picker for Jmol, by Sérgio Ceroni da Silva, April 2007
   Code modifications by Angel Herráez; extraction into a function to generalize its use.

   Use according to Creative Commons "Attribution-ShareAlike" License, 
   http://creativecommons.org/licenses/by-sa/3.0/
*/

// These messages can be customized:
var msg1 = "click on the desired color"
var msg2 = "default"
var msg3 = "click here for the default color"


/* Instructions for calling function:
      objectToBeColored = 'atoms', 'background', etc.
                          (any object in Jmol syntax, to which the picked color will be applied)
      jmolAppletID = any ID assigned to the applet upon which the function must act
                     (by default, applets get the ID 0, 1, etc. in the order they are written to the page)
      makeVerticalTable = 'v' or 'vert' for vertical table, 'h' or none for horizontal table
      defaultColor = RRGGBB color code, or false (don't offer picking the default color)
*/

function writeColorPicker(objectToBeColored, jmolAppletID, makeVerticalTable, defaultColor)
{ if (arguments.length<1) { objectToBeColored="" }
  if (arguments.length<2) { jmolAppletID="0" }
  if (arguments.length<3) { makeVerticalTable="h" }
  if (arguments.length<4) { defaultColor=false }
  if (!jmolAppletID || jmolAppletID=="") { jmolAppletID="0" }
  if (makeVerticalTable.charAt(0) == "v") { makeVerticalTable=true }
  else { makeVerticalTable = false }
  var paletteColors = new Array('00', '66', '99', 'cc', 'ff');
  var hexColor;
  var htmlCode = '<table border="0" cellpadding="0" cellspacing="0">';
  if (defaultColor)
  { htmlCode += '<tr><td colspan="25" align="center" '
      + ' style="background-color:#' + defaultColor + '; border:1px solid #000; cursor:pointer;"'
      + ' onClick="jmolScript(\'color ' + objectToBeColored + ' [x' + defaultColor + ']\');"'
      + ' onMouseOver="window.status=\'' + msg3 + '\';"'
      + ' onMouseOut="window.status=\' \';"'
      + ' title="' + msg3 + '">' + msg2 + '</td></tr>'
      + '<tr><td colspan="25"></td></tr>'; 
  }
  for (gValue = 0; gValue < 5; gValue++)
  { if (!makeVerticalTable) { htmlCode += '<tr>' }
    for (rValue = 0; rValue < 5; rValue++) 
    { if (makeVerticalTable) { htmlCode += '<tr>' }
      for (bValue = 0; bValue < 5; bValue++) 
      { hexColor = paletteColors[rValue] + paletteColors[gValue] + paletteColors[bValue];
        htmlCode += '<td width="6" height="8"'
          + ' style="background-color:#' + hexColor + '; cursor:pointer;"'
          + ' onClick="jmolScript(\'color ' + objectToBeColored + '[x' + hexColor + ']\',' + jmolAppletID + ');"'
          + ' onMouseOver="window.status=\'' + msg1 + '\';"'
          + ' onMouseOut="window.status=\' \';"'
          + ' title="' + msg1 + '"'
          + '></td>';
      }
      if (makeVerticalTable) { htmlCode += '</tr>'; }
    }
    if (!makeVerticalTable) { htmlCode += '</tr>'; }
  }
  htmlCode += '</table>';

  document.writeln(htmlCode);
}

See it in action.

"Basic" spin toggle

Quite trivial, but compact and useful. However, if other scripts, controls, or the user change the spin status, the checkbox will need to be reset accordingly using javascript. (To avoid this limitation, see the "foolproof" solution below)

It will work with any version of Jmol (as long as Jmol.js is being used in the web page).

jmolCheckbox("spin on", "spin off", "spin", false)

if the model is initially not spinning (the default);

or

jmolCheckbox("spin on", "spin off", "spin", true)

if the model is initially spinning (due to another script).

(The word "spin" above can be changed to any other text you like.)


"Foolproof" spin toggle

Reads the current spin status from the applet and changes it, so it can cope with any other previous change via script, popup menu, page controls, etc.

The best and simplest trick:

Valid for recent versions of Jmol:

jmolButton("if(_spinning);spin off;else;spin on;endif","toggle spin")

(If you prefer jmolLink, it can be used in the same manner. If you don't use Jmol.js, and you have a good reason for not using it, you will know how to modify this code.)

(The words "toggle spin" above can be changed to any other text you like.)

The old trick:

Only compatible with Jmol 11.x (as long as Jmol.js is being used in the web page).

jmolButton("show spin", "toggle spin")

(If you prefer jmolLink, it can be used in the same manner.)

(The words "toggle spin" above can be changed to any other text you like.)

You must include these additional pieces of code:

Somewhere between <script> tags (recommended: within the head section):

function messageProcess(a_,b_)
{	// Convert both parameters from Java strings to JavaScript strings:
        var a = (""+a_).substring("jmolApplet".length)	
        var b = ""+b_
        // a_ will start with "jmolApplet": strip and leave just the ID part
	/*  SPIN DETECTION AND TOGGLE */
	if ( b.indexOf("set spin") != -1 )
	{	if ( b.indexOf("spin on") != -1 ) //was spinning
		{	jmolScript("spin off", a) 
		}
		else //was not spinning
		{ 	jmolScript("spin on", a) 
		}
	}
	/*  END of SPIN DETECTION AND TOGGLE  */
}

and somewhere between <script> tags, after the call to jmolInitialize() and before the call to jmolApplet():

jmolSetCallback("messageCallback", "messageProcess")

(The word "messageProcess" above can be changed to any other text you like, as long as it is the same in the above two sections of code.)

Slider controls for Jmol

Version (A)

This has an amazing look-and-feel. Uses javascript, Jmol.js and Walter Zorn's Drag'n'Drop & DHTML Library, © Walter Zorn under GNU LGPL.

See it in action.

Steps to follow:

  1. Download Walter Zorn's library from http://www.walterzorn.com/dragdrop/dragdrop_e.htm (You need the wz_dragdrop.js file.)
  2. Get a copy of the image files, Track.giftrack.gif and Sliderthumb.gifsliderthumb.gif. You could use your own, but size is important since the code is related to it.
  3. Include this code in your webpage:
<head>
<script src="../../Jmol.js" type="text/javascript"></script>
<script type="text/javascript">
/* Uses Walter Zorn's Drag'n'Drop & DHTML Library (GNU LGPL). 
   Integration with Jmol by Angel Herráez.
*/
function slabSlider()
{
  jmolScript( 'slab ' + eval(100-(20+dd.elements.thumb.x-dd.elements.thumb.defx)) )
   document.getElementById("posi").innerHTML = 100-(20+dd.elements.thumb.x-dd.elements.thumb.defx)
}
</script>
</head>

<body>
<script type="text/javascript" src="wz_dragdrop.js"></script>
<script type="text/javascript">
jmolInitialize("../../")
jmolApplet(300, "load lysozyme.pdb; spacefill;")
</script>
<input type="button"  value="prepare for slabbing"
onClick='jmolScript("spin off; slab on; slab 80;"); document.getElementById("posi").innerHTML="80"; dd.elements.thumb.moveTo(dd.elements.track.x+20, dd.elements.track.y); '>
<br>
<img name="track" src="track.gif" width="104" height="29" alt="" title="" align="absmiddle">
<img name="thumb" src="sliderthumb.gif" width="18" height="29" alt="" title="move me" align="absmiddle">
<span id="posi">80</span>%
<br>
<input type="button" value="cancel slabbing"
onClick='jmolScript("slab off;")'>

<script type="text/javascript">
/*  Courtesy of Walter Zorn; 
	Drag'nDrop & DHTML Library  (c)Walter Zorn under the LGPL (Lesser General Public License, http://www.gnu.org/copyleft/lesser.html
*/
SET_DHTML("thumb"+MAXOFFLEFT+20+MAXOFFRIGHT+80+HORIZONTAL,"track"+NO_DRAG)
dd.elements.thumb.moveTo(dd.elements.track.x+20, dd.elements.track.y);
dd.elements.thumb.setZ(dd.elements.track.z+1);
dd.elements.track.addChild("thumb");
dd.elements.thumb.defx = dd.elements.track.x+20; 
dd.elements.thumb.setDragFunc(slabSlider);
//dd.elements.thumb.setDropFunc(slabSlider); //alternative, if it cannot cope with the other
</script>
</body>

Important Notes:

  1. You must adjust the path to Jmol.js, jmolInitialize() and wz_dragdrop.js according to your set-up.
  2. The order of the code element in the above example is crucial. In particular, wz_dragdrop.js must be included in the body, not in the head. If in the head, the slider works in Firefox and Safari, but not in Internet Explorer. Also, the block starting with SET_DHTML(...) must follow the block that displays the slider itself on the page.

Version (B)

This looks excellent too, and has some more versatility. Uses javascript, CSS, Jmol.js and WebFX Slider, © Erik Arvidsson under Apache Software License.

See instructions and several examples here, applied to slabbing, bond thickness, translucency, ribbon width and thickness.


Echoing PDB "Title" to the applet window

The following JavaScript code snippet will report the title of a PDB entry to the applet window when a PDB file is loaded. This should be included within a JavaScript portion of the html file that loads the applet and the PDB file. One caveat: the "TITLE" in a PDB file is depositor-generated and may or may not be "useful" to the end user! :)

var headerInfo = jmolGetPropertyAsString("fileHeader");
var cutUp = headerInfo.split("\n");
var headerstring="";
for (l=0;l<cutUp.length;l++) {
  var regexp = new RegExp("TITLE.{5}(.*)\s*");
  var temp = cutUp[l];           
  if (temp.search(regexp) == 0) {
    temp2 = RegExp.$1;
    temp2.replace(/^\s+|\s+$/g, "").replace(/\s+/g, " ");
    temp2 = temp2 + "|";
    headerstring += temp2;                          }
  }
}
headerstring.replace(/TITLE/, "");
jmolScript("set echo depth 0; set echo headerecho 2% 2%; font echo 12 sanserif bolditalic; color echo green");
jmolScript('echo "' + headerstring + '"');

Bob Hanson has also contributed this much more elegant way to accomplish the same thing all within JmolScript:

function getHeader()
  var titleLines = getProperty("fileHeader").split().find("TITLE").split()
  for (var i = 1; i <= titleLines.size;i = i + 1)
    titleLines[i] = (titleLines[i])[11][0].trim()
  end for
  return titleLines.join("|")
end function
set echo bottom left
echo @{getheader()}

Providing a 'please wait' notice while the applet loads

in a separate page

Exporting an image from the applet

An image of the current view may be exported from the Jmol applet, either


Opening a duplicate of the model in a resizable pop-up window

The model, with is current state, is duplicated or cloned into a new (pop-up) window so it may be displayed at a larger size (and the user may resize that window at will).

The classic version (not shown here) is good for Jmol.js-based JmolApplet.

This version is for JSmol (in either HTML5 or Java modalities; WebGL untested yet).

You need a portion of JavaScript code included in your page and a separate html file (for the pop-up), also with the relevant code.

1. Code in your page:

<script type="text/javascript">
var JSmolCloneData = {};
function cloneJSmol(JSmolObject) {
  var t = JSmolObject._jmolType; //temp
  if ( /_Canvas2D/.test(t) ) { t = 'HTML5'; }
  else if ( /_Canvas3D/.test(t) ) { t = 'WebGL'; }
  else if ( /_Applet/.test(t) ) { t = 'Java'; }
  else { t = null; }
  JSmolCloneData.type = t;
  JSmolCloneData.state = Jmol.getPropertyAsString(JSmolObject, 'stateInfo');
  window.open('JSmolPopup.htm','JSmolPopup','resizable, width=500, height=500');
}
</script>

<input type="button" value="clone JSmol in a popup window" onClick="cloneJSmol(myJmol)">

Note: myJmol should be changed to whatever you have named your JSmol object.

2. Code in the File icon.gifJSmolPopup.htm file:

<!DOCTYPE html>
<html>
<title>cloned JSmol</title>
<head>
<meta charset="utf-8">
<style type="text/css">
html , body { height:100%; overflow:hidden; margin:0; padding:0; }
</style>
<script type="text/javascript" src="jsmol.min.js"></script>
</head>
<body>
<script type="text/javascript">
var cloneInfo = {
  height: '100%',
  width: '100%',
  isSigned: false,
  jarFile: 'JmolApplet0.jar',
  jarPath: 'java',
  j2sPath: 'j2s',
  script: opener.JSmolCloneData.state.replace(/zoomLarge true/i,'zoomLarge false'),
  use: opener.JSmolCloneData.type
};
Jmol.getApplet("JSmolClone", cloneInfo);
</script>
</body>

Note: you need to adjust the path to File icon.gifjsmol.min.js, Folder icon.gifj2s and Folder icon.gifjava


Style transitions

Smooth transitions from one rendering style to another.

Spacefill to ball & stick

for (var i=0;i<=9;i++) {
 s=100-80*i/9;
 spacefill @s%;
 w=0.9-0.75*i/9;
 wireframe @w;
 delay 0.2;
}

Can be given in a single line:

for(var i=0;i<=9;i++){s=100-80*i/9;spacefill @s%;w=0.9-0.75*i/9;wireframe @w;delay 0.2;}


Replacing applet with signed applet upon demand

The signed applet has certain capabilities that the unsigned applet lacks, but using the signed applet will raise some dialogs with security warnings that the general user may find scary and, if permission is denied, the expanded features will not be available and hence the page will fail to do what is expected.

This may lead to a situation where webpage authors wish to use the unsigned applet by default and make the switch to the signed applet if and when the users requests a certain capability (like saving a model to disk). The code here will do that.

The rationale is:

  1. Store the current state of the model in the applet so that it can be restored after the applet switch.
  2. Destroy the applet object.
  3. Insert the signed applet in the same place.
  4. Load back the model and state.

Latest Jmol.js (post-26 Sep 2011, Jmol_12.2.RC8 or later) includes a new jmolSwitchToSignedApplet() function to do this replacement easier:

The code (html + JavaScript, relying on Jmol.js):

<script type="text/javascript">
  jmolInitialize(".");
  jmolApplet(400, 'load example.mol;', 'ABC');
</script>
<br>
<input type="button" value="make the switch" onClick="jmolSwitchToSignedApplet('ABC')">

That's all! Note that 'ABC' is an example of an applet suffix ID, and if omitted will default to '0' (zero) in both jmolApplet() and jmolSwitchToSignedApplet().

Warning!

  • This method has not been thoroughly tested and might fail or break the page; particularly, testing under different browsers and OS's is needed.

Including special characters in echo

Non-keyboard characters may be included in echo texts using their Unicode character number, like this:

echo "\u03B1 is the alpha letter";
echo "\u2192 is an arrow pointing right";
echo "\u00B2 is the superscript two, or square power";

Center of mass

Jmol centers the model around its geometric center, i.e. the center of the boundbox. If you are interested in the mass center of the molecule:

1. Run or define or load from a script file this content in JmolScript:

function CoM(atomSet) {
  if (atomSet=="") {
    print "Warning: there are no atoms in the provided set. Using all atoms in the model."; 
    atomSet = {*}; 
  }
  var n = atomSet.size;
  var mx = 0; var my = 0; var mz = 0;
  for (i=0; i<n; i+=1) {
    mx = mx + atomSet[i].x * atomSet[i].mass;
    my = my + atomSet[i].y * atomSet[i].mass;
    mz = mz + atomSet[i].z * atomSet[i].mass;
  }
  var m = atomSet.mass.sum;
  mx = mx / m;
  my = my / m;
  mz = mz / m;
  return {@mx @my @mz};
}

function drawCoM(atomSet) {
  draw ctr diameter 0.9 color translucent yellowTint @{CoM(atomSet)};
}

function axesCoM(atomSet) {
  axes center @{CoM(atomSet)};
  axes on;
}

2. after that has been executed, you can

  • retrieve the coordinates of the center:
c = CoM(); // using all atoms
print @c;
c = CoM( {_C},{_O} ); // just the carbon and oxygen atoms
print @c;
  • draw a sphere in the center of mass:
drawCoM();
drawCoM( {_C},{_O} );
  • place axes in the center of mass:
axesCoM();
axesCoM( {_C},{_O} );


Custom pop-up menus

Starting on v. 11.3.15, Jmol (both application and applet) allows a customized pop-up menu instead of the standard default menu. Their definition and use are explained in Custom Menus.

Examples:

Users, if you design a new menu, please, share it here.

SimpleBio

SimpleBio menu.jpg

This is devised to ease the handling of the menu by inexperienced users with only basic tasks, in tutorial pages of simple biomolecules.

It includes just these entries:

  • Style - with simplified contents.
  • Color - compacted to have less submenu nesting.
  • Spin - just with on/off, no axes or speed options.
  • Select - a bit simplified.
  • Advanced (*) - a new entry including:
    • Choose menu (*) - that allows to revert to the standard full menu.
    • Language
    • Console
  • About

(*) These are new entries, and so will not be localized; you may wish to edit them for your intended language.

You can get this custom menu here.

SimpleChem

SimpleChem menu.jpg

This is devised to ease the handling of the menu by inexperienced users with only basic tasks, in tutorial pages of organic/inorganic molecules (no crystallography, symmetry, vibration or animation, no pdb-related options).

It includes just these entries:

  • Style - with simplified contents.
  • Color - simplified.
  • Spin - just with on/off, no axes or speed options.
  • Select - a bit simplified.
  • Measurements
  • Advanced (*) - a new entry including:
    • Choose menu (*) - that allows to revert to the standard full menu.
    • Language
    • Console
  • About

(*) These are new entries, and so will not be localized; you may wish to edit them for your intended language.

You can get this custom menu here.