[sagenb] 19/157: Tweaks to Jmol/JSmol

felix salfelder felix-guest at moszumanska.debian.org
Mon Dec 22 16:51:44 UTC 2014


This is an automated email from the git hooks/post-receive script.

felix-guest pushed a commit to branch master
in repository sagenb.

commit 7ce561653aa3ffbb28eb36f487be381227018958
Author: gutow <gutow at uwosh.edu>
Date:   Sun Mar 23 17:56:20 2014 -0500

    Tweaks to Jmol/JSmol
    
    Tweaks to Jmol/JSmol in notebook.  Pure javascript 3-D interactive plots
    with option to load live or static. Have removed user interface bells
    and whistles temporarily.
---
 flask_version/worksheet.py               |  9 ++++
 sagenb/data/sage/html/notebook/base.html |  3 ++
 sagenb/data/sage/js/jmol_lib.js          | 90 +++++++++++++++++++++++++-------
 sagenb/notebook/cell.py                  |  9 +++-
 sagenb/notebook/worksheet.py             | 72 ++++++++++++++++++++++++-
 5 files changed, 160 insertions(+), 23 deletions(-)

diff --git a/flask_version/worksheet.py b/flask_version/worksheet.py
index 573b16c..bfe60bc 100644
--- a/flask_version/worksheet.py
+++ b/flask_version/worksheet.py
@@ -166,6 +166,15 @@ def worksheet_pretty_print(worksheet, enable):
     worksheet.set_pretty_print(enable)
     return 'success'
 
+ at worksheet_command('live_3D/<enable>')
+def worksheet_live_3D(worksheet, enable):
+    if enable == 'true':
+        worksheet.set_live_3D(True)
+    else:
+        worksheet.set_live_3D(False)
+    return 'success'
+
+
 @worksheet_command('conf')
 def worksheet_conf(worksheet):
     return str(worksheet.conf())
diff --git a/sagenb/data/sage/html/notebook/base.html b/sagenb/data/sage/html/notebook/base.html
index 0d32fbd..820e06e 100644
--- a/sagenb/data/sage/html/notebook/base.html
+++ b/sagenb/data/sage/html/notebook/base.html
@@ -143,6 +143,9 @@ jmolSetCallback("menuFile","/java/jmol/appletweb/SageMenu.mnu");
         <input type="checkbox" title="{{ gettext('Enable/disable pretty_printing') }}"
                onchange="pretty_print_check(this.checked);"
                class="worksheet" value="pretty_print" {{ "checked" if worksheet.pretty_print() else "" }} /> Typeset
+        <input id="3D_check", type="checkbox" title="{{ gettext('Load 3-D Live. Not recommended for worksheets with > 2 3-D Plots.') }}"
+               onchange="live_3D_check(this.checked);"
+               class="worksheet" value="live_3D" {{ "checked" if worksheet.live_3D() else "" }} /> {{ gettext('Load 3-D Live') }}
         {% endif %}
     {% endif %} 
     </div>
diff --git a/sagenb/data/sage/js/jmol_lib.js b/sagenb/data/sage/js/jmol_lib.js
index 4219f4d..050a270 100644
--- a/sagenb/data/sage/js/jmol_lib.js
+++ b/sagenb/data/sage/js/jmol_lib.js
@@ -9,6 +9,8 @@
 
 var jmolApplet; //our generic viewer.
 
+var live_3D_state = false;
+
 var jmolInfo = { //default values
     width: "100%",
     height: "100%",
@@ -65,6 +67,11 @@ var small = 250;
 var medium = 400;
 var large = 600;
 
+//Check whether to load 3-D live
+live_3D_state = $('#3D_check').prop('checked');
+//start the watch function
+jmolWatcher = setInterval('jmolActivator();',500);
+
 function jmol_applet(size, image, url, cell_num, functionnames) { //makes a new applet. 
     var appletID = jmol_count;
     jmol_count = jmol_count + 1;
@@ -74,37 +81,80 @@ function jmol_applet(size, image, url, cell_num, functionnames) { //makes a new
         }
     Jmol.setDocument(document);
     //Where am I?  Need to know in cases where I need to write directly to this cell.
-    cell_ID = 'cell_output_html_'+cell_num;
-    //however, I might be inside something else like an interact as well...so
-    parent = get_element('jmol_static'+cell_num).parentNode;
+    cell_ID = 'sage_jmol'+cell_num;
     jmolStatus.jmolInfo[appletID] = jmolInfo; //set default values
     jmolStatus.jmolInfo[appletID].coverImage = image; //this should be the image url
     jmolStatus.jmolInfo[appletID].script = "script "+url; //this should be the script url
-    parentStr = parent.innerHTML;
-    //str = parentStr + newJmolTableStr(appletID, size, size, url, wakeMessage, sleepMessage, captionStr, controlStr);
-    //str = parentStr + '<script>Jmol.getAppletHtml("jmolApplet'+appletID+'",jmolStatus.jmolInfo['+appletID+']))</script>';
+    //Check whether to load 3-D live
+    live_3D_state = $('#3D_check').prop('checked');    
+    if (live_3D_state){
+       jmolStatus.jmolInfo[appletID].deferApplet=false;
+       }
     jmolDivStr = "jmol"+appletID;
     jmolStatus.widths[appletID] = size;
     jmolStatus.heights[appletID]= size;
-   $(parent).append('<div id="'+jmolDivStr+'" style="height:'+size+'px; width:'+size+'px;" >JSmol here</div>');
+    //appending to cell_ID
+    $('#'+cell_ID).append('<div id="'+jmolDivStr+'" style="height:'+size+'px; width:'+size+'px;" >JSmol here</div>');
+    //launching JSmol/Jmol applet
     $('#'+jmolDivStr).html(Jmol.getAppletHtml("jmolApplet"+appletID,jmolStatus.jmolInfo[appletID])); 
-    //add debugging div
-    //str += '<div id="JmolDebug">Jmol Debugging goes here</div>';
-    //now we can start the new one
-    //cell_writer.write(str);
-    parent.innerHTML = str;
-    //jmolSetAppletColor("white");
-    //if (appletID==0){
-    //    jmol_checkbrowserOS();
-     //   }
     //we will still set all the data for this applet so that other asynchronously created applets do not grab its ID.
     jmolStatus.signed[appletID]=jmolStatus.loadSigned;
     jmolStatus.urls[appletID]=url;
     //    jmolStatus.numLive = jmolStatus.numLive+1;
-    jmolStatus.controlStrs[appletID] = controlStr;
-    jmolStatus.captionStrs[appletID] = captionStr;
-    jmolStatus.cntrls[appletID]=cntrlPanels;
+    //jmolStatus.controlStrs[appletID] = controlStr;
+    //jmolStatus.captionStrs[appletID] = captionStr;
+    //jmolStatus.cntrls[appletID]=cntrlPanels;
 //Now we wait for the server by calling a function that waits if the div is not yet written.
 //    launchNewJmol(size,scriptStr,appletID);
-    return str;
+    return jmolDivStr;//for historical compatibility
+    }
+
+function jmolActivator(){
+    if (document.getElementById("loadJmol")){
+        parentdiv = $("#loadJmol").parent();
+        //parentid = $(parentdiv).attr("id");
+        //alert("The parent id is:"+parentid);
+        cell_num = $(parentdiv).children("#loadJmol").html();//this div must have the ID number
+        //alert("Trying to launch JSmol #"+cell_num);
+        $(parentdiv).children("#loadJmol").remove();
+        size = $(parentdiv).children("#sage_jmol_size"+cell_num).html();
+        img = $(parentdiv).children("#sage_jmol_img"+cell_num).html();
+        script = $(parentdiv).children("#sage_jmol_script"+cell_num).html();
+        tmpdiv = jmol_applet(size, img, script, cell_num);
+        $(parentdiv).children("#sage_jmol_status"+cell_num).html() = "Activated";
     }
+}
+
+function live_3D_check(s) {
+    /*
+    Send a message back to the server either turn live_3D on of off.
+    INPUT:
+        s -- boolean; whether the pretty print box is checked.
+    */
+    live_3D_state =s;
+    //alert ('live_3D_state:'+live_3D_state);
+    async_request(worksheet_command('live_3D/' + s));
+}
+
+//The following two delete functions do not do anything in this truncated jmol_lib.
+//They are for compatibility with the notebook_lib.js
+function jmol_delete_all_output() {
+    //called by the delete_all_output function of the notebook to get jmol parameters cleaned up.
+    jmol_count=0;
+    jmolStatus.numLive=0;
+    jmolStatus.jmolArray=new Array();
+}
+
+function jmol_delete_check() {
+    //called when cells are evaluated to see if any jmols have been deleted.  If so update their status.
+    liveCount = jmolStatus.jmolArray.length;
+    for ( k = 0; k< liveCount; k++) {
+        testId= 'Jmol_Table_Jmol'+k; //looking for the whole table Jmol is in, since if the table is there it is sleeping.
+        if (!get_element(testId)) { //we need to set this as deleted and maybe free up the ID?
+            jmolStatus.jmolArray[k] = -1;
+            //for the time being old IDs will not be reused.  Shouldn't be real big problem as completely resets
+            //each time a page is opened.
+        }
+    }
+    //jmol_numLiveUpdate();
+}
diff --git a/sagenb/notebook/cell.py b/sagenb/notebook/cell.py
index 4b36d60..f50ec10 100755
--- a/sagenb/notebook/cell.py
+++ b/sagenb/notebook/cell.py
@@ -2376,7 +2376,14 @@ class Cell(Cell_generic):
                     jmol_file.close()
 
                 image_name = os.path.join(self.url_to_self(),'.jmol_images',F)
-                script = '<div id = "jmol_static%s"><script>jmol_applet(%s, "%s.png?%d", "%s?%d",%s);</script></div>' % (self._id,size, image_name, time.time(), url, time.time(), self._id)
+                #script = '<div id = "jmol_static%s"><script>jmol_applet(%s, "%s.png?%d", "%s?%d",%s);</script></div>' % (self._id,size, image_name, time.time(), url, time.time(), self._id)
+                script = '\n<div id="sage_jmol%s" class="3DPlotDiv">'%(self._id)
+                script += '\n  <div id = "loadJmol" style="display:none;">%s</div>'%(self._id)
+                script += '\n  <div id="sage_jmol_size%s" class="JmolSize" style="display:none;">%s</div>'%(self._id,size)
+                script += '\n  <div id="sage_jmol_img%s" class="JmolImg" style="display:none;">%s.png?%d </div>'%(self._id, image_name, time.time())
+                script += '\n  <div id="sage_jmol_script%s" class="JmolScript" style="display:none;">%s?%d</div>'%(self._id, url, time.time())
+                script += '\n  <div id="sage_jmol_status%s" class="JmolStatus" style="display:none;">notActivated</div>'%(self._id)
+                script += '\n</div>'
                 #script = '<div id = "jmol_static%s">Sleeping...<button onClick="javascript:void(jmol_launch(%s, \'%s?%d\', %s))">Make Interactive</button>'  % (self._id, size, url, time.time(), self._id)
                 #script += '<br><img src="%s.png?%d" alt="If no image appears re-execute the cell. 3-D viewer has been updated."></div>' % (image_name, time.time())
                 images.append(script)
diff --git a/sagenb/notebook/worksheet.py b/sagenb/notebook/worksheet.py
index b03d4f2..3d9c3f3 100644
--- a/sagenb/notebook/worksheet.py
+++ b/sagenb/notebook/worksheet.py
@@ -160,7 +160,7 @@ class Worksheet(object):
     def __init__(self, name=None, id_number=None,
                  notebook_worksheet_directory=None, system=None,
                  owner=None, pretty_print=False,
-                 auto_publish=False, create_directories=True):
+                 auto_publish=False, create_directories=True, live_3D=False):
         ur"""
         Create and initialize a new worksheet.
 
@@ -189,6 +189,9 @@ class Worksheet(object):
           creates various files and directories where data will be
           stored.  This option is here only for the
           migrate_old_notebook method in notebook.py
+        -  ``live_3D`` - bool (default: False); whether 3-D plots should
+           be loaded live (interactive). To many live plots may make a
+           worksheet unresponsive because of the javascript load.
 
         EXAMPLES: We test the constructor via an indirect doctest::
 
@@ -213,6 +216,7 @@ class Worksheet(object):
         self.__collaborators = []
         self.__autopublish = auto_publish
         self.__saved_by_info = {}
+        self.__live_3D = live_3D
 
         # state sequence number, used for sync
         self.__state_number = 0
@@ -341,6 +345,12 @@ class Worksheet(object):
              # worksheet by default
              'pretty_print': self.pretty_print(),
 
+             # Whether to load 3-D live.  Should only be set to
+             # true by the user as worksheets with more than 1 or 2
+             # live (interactive) 3-D plots may bog down because of
+             # javascript overload.
+             'live_3D': self.live_3D(),
+
              # what other users think of this worksheet: list of
              # triples
              #       (username, rating, comment)
@@ -407,7 +417,7 @@ class Worksheet(object):
                     self.__filename = filename
                     self.__dir = os.path.join(notebook_worksheet_directory, str(value))
             elif key in ['system', 'owner', 'viewers', 'collaborators',
-                         'pretty_print', 'ratings']:
+                         'pretty_print', 'ratings', 'live_3D']:
                 # ugly
                 setattr(self, '_Worksheet__' + key, value)
             elif key == 'auto_publish':
@@ -1056,6 +1066,59 @@ class Worksheet(object):
             check = True
         self.__pretty_print = check
         self.eval_asap_no_output("pretty_print_default(%r)" % check)
+    ##########################################################
+    # 3-D plots
+    ##########################################################
+    def live_3D(self):
+        """
+        Return True if the 3-D plots should be loaded live (interactive) by default.
+
+        OUTPUT:
+
+        -  ``bool`` - True of False
+
+        EXAMPLES::
+
+            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
+            sage: nb.create_default_users('password')
+            sage: W = nb.create_new_worksheet('A Test Worksheet', 'admin')
+            sage: W.live_3D()
+            False
+            sage: W.quit()
+            sage: nb.delete()
+        """
+        try:
+            return self.__live_3D
+        except AttributeError:
+            self.__live_3D = False
+            return self.__live_3D
+
+    def set_live_3D(self, check=False):
+        """
+        Set whether or not 3-D plots should be live by default.  Not a good idea for
+        worksheets with more than 1 or 2 3-D plots.
+
+        INPUT:
+
+        -  ``check`` - boolean
+
+        EXAMPLES::
+
+            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
+            sage: nb.create_default_users('password')
+            sage: W = nb.create_new_worksheet('A Test Worksheet', 'admin')
+            sage: W.set_live_3D(False)
+            sage: W.live_3D()
+            False
+            sage: W.set_live_3D(True)
+            sage: W.live_3D()
+            True
+            sage: W.quit()
+            sage: nb.delete()
+        """
+        self.__live_3D = check
+        self.eval_asap_no_output("live_3D_default(%r)" % check)
+        #not sure the line above does anything as I cannot trace the equivalent for pretty_print!
 
     ##########################################################
     # Publication
@@ -3009,6 +3072,11 @@ except (KeyError, IOError):
         # right pretty printing mode.
         if self.pretty_print():
             S.execute('pretty_print_default(True);')
+        # Check to see if the live_3D button is checked.  If so,
+        # send code to initialize the worksheet to have the right
+        # setting.
+        if self.live_3D():
+            S.execute('live_3D_default(True);')
             
         if not self.is_published():
             self._enqueue_auto_cells()

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-science/packages/sagenb.git



More information about the debian-science-commits mailing list