Friday, December 5, 2014

Some CodeSkulptor Tricks

Since Skulpt's python interpreter switches back and forth between Javascript objects and Python objects, some pieces of python code have slightly different effects when run within the Codeskulptor enviromnent than they would if run in Python, and these differences can be used to create useful effects.

Reading the Console

One such useful effect comes from using the open keyword. This keyword uses the ids of the page's DOM elements as filenames, but these "files" are currently read-only.

Everytime you use the print keyword, the string is shown in the console (on the right-hand column of the screen).
This function will read the contents of the console and return it as a string.

def readConsole():
a = open("console")
return a.read()

Browser type detection

Another useful effect comes from using the file keyword. The open keyword uses file to find and return the contents of the DOM element whose id matches the "filename" being opened. However, if you call file directly, it returns an inmutable object of unknown type, which is actually a referrence to the Javascript window variable. Although this object is inmutable, dir is able to read its list of properties and methods.

This function is a moddified version of the browser-detection code used in Codeskulptor's simplegui module.

Session cookies

This class uses file to set up a reference to the Javascript window variable. Then creates a simplegui Control class object with this reference to window. In combining these, the Control class is able to read and write to window.textContent. Since the window variable doesn't change when you re-run or reset the python code, window.textContent can be used to simulate session cookies.

Set an Unload Handler for a simplegui Frame

By default, when the user closes the simplegui popup window, the code is not notified of this event. This sometimes results in background audio that continues to play until the "reset" button is clicked.
This function appends a set_unload_hander method to simplegui's Frame class. Any frames created after this automatically include this method. In this way, you can define a function to be called when the user closes the popup window.