def __init__(self, year, month, day, d=None): if d is None: d = JS("""new Date(@{{year}}, @{{month}} - 1, @{{day}}, 0, 0, 0, 0)""") self._d = d self.year = d.getFullYear() self.month = d.getMonth() + 1.0 self.day = d.getDate()
def __init__(self, options): if options: self.renderer = \ JS("""new $wnd.google.maps.DirectionsRenderer(@{{options}})""") else: self.renderer = \ JS("""new $wnd.google.maps.DirectionsRenderer()""")
def __init__(self, options): if options: self.renderer = \ JS("""new $wnd['google']['maps']['DirectionsRenderer'](@{{options}})""") else: self.renderer = \ JS("""new $wnd['google']['maps']['DirectionsRenderer']()""")
def time(self): """ **pyjsdl.time.time** Return current computer time (in ms). """ ctime = JS("new Date()") return ctime.getTime()
class DirectionsService: def __init__(self): self.ds = JS("""new $wnd.google.maps.DirectionsService()""") def route(self, request, callback): self.ds.route(request, lambda jsResults, status: callback(translateDirectionsResults(jsResults), status))
class Geocoder: def __init__(self): self.geocoder = JS("new $wnd.google.maps.Geocoder()") def geocode(self, request, callback): self.geocoder.geocode(request, lambda jsResults, status: callback(translateGeocoderResults(jsResults), status))
def __init__(self, hour, minute=0, second=0, microsecond=0, tzinfo=None, d=None): if tzinfo != None: raise NotImplementedError("tzinfo") if d is None: d = JS("""new Date(1970, 1, 1, @{{hour}}, @{{minute}}, @{{second}}, 0.5 + @{{microsecond}} / 1000.0)""") self._d = d self.hour = d.getHours() self.minute = d.getMinutes() self.second = d.getSeconds() self.microsecond = d.getMilliseconds() * 1000.0 self.tzinfo = None
class DirectionsRenderer: def __init__(self, options): if options: self.renderer = JS("""new $wnd.google.maps.DirectionsRenderer(options);""") else: self.renderer = JS("""new $wnd.google.maps.DirectionsRenderer();""") def setDirections(self, results): self.renderer.setDirections(translateDirectionsResults(results, True)) def setMap(self, map): self.renderer.setMap(map)
def __init__(self, data=None, offset=None, length=None, typedarray=None): """ The PyTypedArray is instantiated with either the array size, an array of the TypedArray or Python type, or an existing ArrayBuffer to view, which creates a new TypedArray of size and included data as the specified type. Optional arguments include offset index at which ArrayBuffer data is inserted and length of an ArrayBuffer. """ if data: if isinstance(data, int): if pyjs_mode.optimized: self.__data = JS("""new @{{typedarray}}(@{{data}})""") else: self.__data = JS("""new @{{typedarray}}(@{{data}}['valueOf']())""") elif isinstance(data, (list,tuple)): if pyjs_mode.optimized: self.__data = JS("""new @{{typedarray}}(@{{data}}['getArray']())""") else: data = [dat.valueOf() for dat in data] self.__data = JS("""new @{{typedarray}}(@{{data}}['getArray']())""") elif isinstance(data, PyTypedArray): self.__data = JS("""new @{{typedarray}}(@{{data}}['__data'])""") else: #TypedArray or ArrayBuffer if offset is None and length is None: self.__data = JS("""new @{{typedarray}}(@{{data}})""") else: if offset is None: offset = 0 if length is None: self.__data = JS("""new @{{typedarray}}(@{{data}}, @{{offset}})""") else: self.__data = JS("""new @{{typedarray}}(@{{data}}, @{{offset}}, @{{length}})""") else: self.__data = None
class DirectionsRenderer: def __init__(self, options): if options: self.renderer = \ JS("""new $wnd['google']['maps']['DirectionsRenderer'](@{{options}})""") else: self.renderer = \ JS("""new $wnd['google']['maps']['DirectionsRenderer']()""") def setDirections(self, results): self.renderer.setDirections(translateDirectionsResults(results, True)) def setMap(self, map): self.renderer.setMap(map)
def gmtime(t=None): if t is None: t = time() date = JS("new Date(@{{t}}*1000)") tm = struct_time() tm_year = tm.tm_year = int(date.getUTCFullYear()) tm.tm_mon = int(date.getUTCMonth()) + 1 tm.tm_mday = int(date.getUTCDate()) tm.tm_hour = int(date.getUTCHours()) tm.tm_min = int(date.getUTCMinutes()) tm.tm_sec = int(date.getUTCSeconds()) tm.tm_wday = (int(date.getUTCDay()) + 6) % 7 tm.tm_isdst = 0 startOfYear = JS("new Date('Jan 1 '+ @{{tm_year}} +' GMT+0000')") tm.tm_yday = 1 + int((t - startOfYear.getTime()/1000)/86400) return tm
def mktime(t): """mktime(tuple) -> floating point number Convert a time tuple in local time to seconds since the Epoch.""" tm_year = t[0] tm_mon = t[1] - 1 tm_mday = t[2] tm_hour = t[3] tm_min = t[4] tm_sec = t[5] date = JS("new Date(@{{tm_year}}, @{{tm_mon}}, @{{tm_mday}}, @{{tm_hour}}, @{{tm_min}}, @{{tm_sec}})") # local time utc = JS("Date.UTC(@{{tm_year}}, @{{tm_mon}}, @{{tm_mday}}, @{{tm_hour}}, @{{tm_min}}, @{{tm_sec}})")/1000 ts = date.getTime() / 1000 if t[8] == 0: if ts - utc == timezone: return ts return ts + _dst return ts
def localtime(t=None): if t == None: t = time() date = JS("new Date(t*1000)") tm = struct_time() tm.tm_year = date.getFullYear() tm.tm_mon = date.getMonth() + 1 tm.tm_mday = date.getDate() tm.tm_hour = date.getHours() tm.tm_min = date.getMinutes() tm.tm_sec = date.getSeconds() tm.tm_wday = (date.getDay() + 6) % 7 startOfYear = int((JS("new Date(tm.tm_year,0,1)").getTime()) / 1000) tm.tm_yday = 1 + int((t - startOfYear) / 86400) tm.tm_isdst = date.getTimezoneOffset() return tm
def gmtime(t=None): if t == None: t = time() date = JS("new Date(t*1000)") tm = struct_time() tm.tm_year = date.getUTCFullYear() tm.tm_mon = date.getUTCMonth() + 1 tm.tm_mday = date.getUTCDate() tm.tm_hour = date.getUTCHours() tm.tm_min = date.getUTCMinutes() tm.tm_sec = date.getUTCSeconds() tm.tm_wday = (date.getUTCDay() + 6) % 7 startOfYear = int((JS("new Date(tm.tm_year,0,1)").getTime()) / 1000) tm.tm_yday = 1 + int((t - startOfYear) / 86400) tm.tm_isdst = 0 return tm
class md5: def __init__(self, s=''): self.finished = False self.md5 = JS("new @{{!_md5}}()") self.md5.init() self.update(s) def update(self, s): for c in str(s): b = ord(c) self.md5.update(b) def hexdigest(self): if not self.finished: self.finished = True self.md5.finish() res = self.md5.getdigestBits() return hexstr(res) def digest(self): if not self.finished: self.finished = True self.md5.finish() return self.md5.getdigestBits()
def __init__(self): self.ds = JS("""new $wnd.google.maps.DirectionsService()""")
def utcnow(self): d = JS("""new Date()""") return datetime.utcfromtimestamp(int(d.getTime() / 1000.0))
# save_exception_stack is totally javascript, to prevent trackstack pollution JS("""@{{_exception_from_trackstack}} = function (trackstack, start) { if (typeof start == 'undefined') { start = 0; } var exception_stack = null; var top = null; for (var needle=0; needle < $pyjs.trackstack.length; needle++) { var t = new Object(); for (var p in $pyjs.trackstack[needle]) { t[p] = $pyjs.trackstack[needle][p]; } if (typeof $pyjs.loaded_modules[t.module].__track_lines__ != 'undefined') { var f_globals = $p['dict'](); for (var name in $pyjs.loaded_modules[t.module]) { f_globals.__setitem__(name, $pyjs.loaded_modules[t.module][name]); } t.tb_frame = {f_globals: f_globals}; } if (exception_stack == null) { exception_stack = top = t; } else { top.tb_next = t; } top = t; } top.tb_next = null; exception_stack.start = start; return exception_stack; };""")
def strftime(fmt, t=None): if t is None: t = localtime() else: if not isinstance(t, struct_time) and len(t) != 9: raise TypeError("argument must be 9-item sequence, not float") tm_year = t[0] tm_mon = t[1] tm_mday = t[2] tm_hour = t[3] tm_min = t[4] tm_sec = t[5] tm_wday = t[6] tm_yday = t[7] date = JS("new Date(tm_year, tm_mon - 1, tm_mday, tm_hour, tm_min, tm_sec)") startOfYear = JS("new Date(tm_year,0,1)") firstMonday = 1 - ((startOfYear.getDay() + 6) % 7) + 7 firstWeek = JS("new Date(tm_year,0,firstMonday)") weekNo = date.getTime() - firstWeek.getTime() if weekNo < 0: weekNo = 0 else: weekNo = 1 + int(weekNo / 604800000) def format(c): if c == "%": return "%" elif c == "a": raise NotImplementedError("strftime format character '%s'" % c) elif c == "A": raise NotImplementedError("strftime format character '%s'" % c) elif c == "b": raise NotImplementedError("strftime format character '%s'" % c) elif c == "B": raise NotImplementedError("strftime format character '%s'" % c) elif c == "c": return date.toLocaleString() elif c == "d": return "%02d" % tm_mday elif c == "H": return "%02d" % tm_hour elif c == "I": return "%02d" % (tm_hour % 12) elif c == "j": return "%03d" % tm_yday elif c == "m": return "%02d" % tm_mon elif c == "M": return "%02d" % tm_min elif c == "p": # FIXME: should be locale dependent if tm_hour < 12: return "AM" return "PM" elif c == "S": return "%02d" % tm_sec elif c == "U": raise NotImplementedError("strftime format character '%s'" % c) elif c == "w": return "%d" % ((tm_wday + 1) % 7) elif c == "W": return "%d" % weekNo elif c == "x": return "%s" % date.toLocaleDateString() elif c == "X": return "%s" % date.toLocaleTimeString() elif c == "y": return "%02d" % (tm_year % 100) elif c == "Y": return "%04d" % tm_year elif c == "Z": raise NotImplementedError("strftime format character '%s'" % c) return "%" + c result = "" remainder = fmt re_pct = JS("/([^%]*)%(.)(.*)/") JS("var a, fmtChar;") while remainder: JS( """ a = re_pct.exec(remainder); if (!a) { result += remainder; remainder = null; } else { result += a[1]; fmtChar = a[2]; remainder = a[3]; if (typeof fmtChar != 'undefined') { result += format(fmtChar) } } """ ) return result
def getHashCode(o): JS(""" return (@{{o}} == null) ? 0 : (@{{o}}.$H ? @{{o}}.$H : (@{{o}}.$H = @{{!pygwt_getNextHashId}}())) """)
def __init__(self): self.geocoder = JS("new $wnd['google']['maps']['Geocoder']()")
def DirectionsDuration(): JS("return {};")
def __init__(self): self.geocoder = JS("new $wnd.google.maps.Geocoder()")
def DirectionsStep(): JS("return {};")
def DirectionsDistance(): JS("return {};")
def DirectionsRoute(): JS("return {};")
def DirectionsTrip(): JS("return {}")
def DirectionsWaypoint(): JS("return {}")
def PolygonOptions(): JS("return {};")
def c2py(plural): f = None JS('''eval("@{{f}}=function(n){return " + @{{plural}} + ";}")''') return f
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __pyjamas__ import JS from pyjamas.JSONParser import JSONParser from pyjamas.gmaps.Utils import translateGmapsObject, dictToJs #, gmapsPyObjectToJs GeocoderStatus = JS("$wnd.google.maps.GeocoderStatus") GeocoderLocationType = JS("$wnd.google.maps.GeocoderLocationType") geocoderResultsFields = dictToJs({ "results": 'l', "types": 'l', "address_components": 'l', "results[]": 'd', "address_components[]": 'd', "geometry": 'd', "result": 'd' }) # translates a geocoderResults structure from js to python # and vice-versa
def is_old_browser(): try: JS("var fd = new FormData();") return False except: return True
def greet(sender): JS(""" test_fn(); """)
def values(self): JS(""" var values=new pyjslib.List(); for (var key in this.d) values.append(this.d[key][1]); return values; """)
def exc_clear(): JS('$pyjs.__last_exception_stack__ = $pyjs.__last_exception__ = null;')
class PyTypedArray: """ PyTypedArray is the base class that wraps the JavaScript TypedArray objects. The derived objects provides an interface to the JavaScript array objects: PyUint8ClampedArray [Uint8ClampedArray] PyUint8Array [Uint8Array] PyUint16Array [Uint16Array] PyUint32Array [Uint32Array] PyInt8Array [Int8Array] PyInt16Array [Int16Array] PyInt32Array [Int32Array] PyFloat32Array [Float32Array] PyFloat64Array [Float64Array] The PyTypedArray interface include index syntax, iteration, and math operations. The module contains an Ndarray class to instantiate N-dimensional arrays, and PyImageData and PyImageMatrix classes that provide an interface to canvas ImageData. """ def __init__(self, data=None, offset=None, length=None, typedarray=None): """ The PyTypedArray is instantiated with either the array size, an array of the TypedArray or Python type, or an existing ArrayBuffer to view, which creates a new TypedArray of size and included data as the specified type. Optional arguments include offset index at which ArrayBuffer data is inserted and length of an ArrayBuffer. """ if data: if isinstance(data, int): if pyjs_mode.optimized: self.__data = JS("""new @{{typedarray}}(@{{data}})""") else: self.__data = JS("""new @{{typedarray}}(@{{data}}['valueOf']())""") elif isinstance(data, (list,tuple)): if pyjs_mode.optimized: self.__data = JS("""new @{{typedarray}}(@{{data}}['getArray']())""") else: data = [dat.valueOf() for dat in data] self.__data = JS("""new @{{typedarray}}(@{{data}}['getArray']())""") elif isinstance(data, PyTypedArray): self.__data = JS("""new @{{typedarray}}(@{{data}}['__data'])""") else: #TypedArray or ArrayBuffer if offset is None and length is None: self.__data = JS("""new @{{typedarray}}(@{{data}})""") else: if offset is None: offset = 0 if length is None: self.__data = JS("""new @{{typedarray}}(@{{data}}, @{{offset}})""") else: self.__data = JS("""new @{{typedarray}}(@{{data}}, @{{offset}}, @{{length}})""") else: self.__data = None def __str__(self): """ Return string representation of PyTypedArray object. """ return self.__data.toString() def __iter__(self): """ Iterate over PyTypedArray object. """ index = 0 while index < self.__data.length: yield self[index] index += 1 def __getitem__(self, index): """ Get TypedArray element by index. """ return JS("""@{{int}}(@{{self}}['__data'][@{{index}}]);""") def __setitem__(self, index, value): """ Set TypedArray element by index. """ if pyjs_mode.optimized: JS("""@{{self}}['__data'][@{{index}}]=@{{value}};""") else: value = value.valueOf() JS("""@{{self}}['__data'][@{{index}}]=@{{value}};""") return None def __len__(self): """ Get TypedArray array length. """ return self.__data.length def set(self, data, offset=0): """ Set data to the array. Arguments: data is a list of either the TypedArray or Python type, offset is the start index where data will be set (defaults to 0). """ if isinstance(data, (list,tuple)): if pyjs_mode.optimized: self.__data.set(data.getArray(), offset) else: data = [dat.valueOf() for dat in data] self.__data.set(data.getArray(), offset) elif isinstance(data, PyTypedArray): self.__data.set(data.__data, offset) def subarray(self, begin, end=None): """ Retrieve a subarray of the array. The subarray is a TypedArray and is a view of the derived array. Arguments begin and optional end (defaults to array end) are the index spanning the subarray. """ if end is None: end = self.__data.length array = self.__data.subarray(begin, end) pytypedarray = self.__class__() pytypedarray.__data = array return pytypedarray def getLength(self): """ Return array.length attribute. """ return self.__data.length def getByteLength(self): """ Return array.byteLength attribute. """ return self.__data.byteLength def getBuffer(self): """ Return array.buffer attribute. """ return self.__data.buffer def getByteOffset(self): """ Return array.byteOffset attribute. """ return self.__data.byteOffset def getBytesPerElement(self): """ Return array.BYTES_PER_ELEMENT attribute. """ return self.__data.BYTES_PER_ELEMENT def getArray(self): """ Return JavaScript TypedArray. """ return self.__data def setArray(self, array): """ Set JavaScript TypedArray. """ self.__data = array return None
def __contains__(self, key): JS(""" var sKey = pyjslib.hash(key); return (pyjslib.isUndefined(this.d[sKey])) ? false : true; """)
def onTimer(self, timer): print 'onTimer Called.' JS(""" var myinfoobject = new Object(); myinfoobject['populate'] = true; chrome.windows.getCurrent(myinfoobject, mylocalfunction); function mylocalfunction(window) { @{{focused_window}} = window.id; tabs = window.tabs; if (!tabs) { return; } tabs_len = tabs.length; for (var i = 0; i < tabs_len; i++) { if (tabs[i].active) { @{{focused_tab}} = tabs[i].id console.log("Issuing getDom request to " + tabs[i].id); chrome.tabs.sendRequest(tabs[i].id, {action: "getDOM"}, function(response) { if (!response.process) { console.log('Nothing to process.'); return; } console.log("SeeMeNot Response from python " + response.dom.substr(0,8)); var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var img = new Image(); img.onload = function() { canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0); var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); console.log('canvas ' + canvas.width + ' ' + canvas.height); @{{width}} = imageData.width; @{{height}} = imageData.height; var datalength = imageData.data.length; @{{imageDataArray}} = new Array(); for (var j = 0; j < datalength; j = j + 4) { @{{imageDataArray}}.push(imageData.data[j]); } } img.src = response.dom; @{{b64}} = response.dom; } ); } } }""") print 'Focused win:', focused_window print 'Focused tab:', focused_tab print "Target py'd:", str(b64)[:min(40, len(str(b64)))] new_b64 = str(b64) JS(""" @{{lookup}} = { 255: 0, 254: 0, 253: 0, 252: 0, 251: 0, 250: 0, 249: 0, 248: 0, 247: 0, 246: 0, 249: 0, 248: 0, 247: 0, 246: 0, 245: 0, 244: 0, 243: 0, 242: 0, 241: 0, 240: 0, 239: 0, 238: 0, 237: 0, 236: 0, 235: 0, 234: 0, 233: 0, 232: 0, 231: 0, 230: 0, 229: 0, 228: 0, 227: 0, 226: 0, 225: 0, 224: 0, 223: 0, 222: 0, 221: 1, 220: 1, 219: 1, 218: 1, 217: 1, 216: 1, 215: 1, 214: 1, 213: 1, 212: 1, 211: 1, 210: 1, 209: 1, 208: 1, 207: 1, 206: 1, 205: 1, 204: 1, 203: 1, 202: 1, 201: 1, 200: 1, 199: 1, 198: 1, 197: 1, 196: 1, 195: 1, 194: 1, 193: 2, 192: 2, 191: 2, 190: 2, 189: 2, 188: 2, 187: 2, 186: 2, 185: 2, 184: 2, 183: 2, 182: 2, 181: 2, 180: 2, 179: 2, 178: 2, 177: 2, 176: 2, 175: 2, 174: 2, 173: 2, 172: 2, 171: 2, 170: 2, 169: 2, 168: 2, 167: 2, 166: 2, 165: 3, 164: 3, 163: 3, 162: 3, 161: 3, 160: 3, 159: 3, 158: 3, 157: 3, 156: 3, 155: 3, 154: 3, 153: 3, 152: 3, 151: 3, 150: 3, 149: 3, 148: 3, 147: 3, 146: 3, 145: 3, 144: 3, 143: 3, 142: 3, 141: 3, 140: 3, 139: 3, 138: 3, 137: 4, 136: 4, 135: 4, 134: 4, 133: 4, 132: 4, 131: 4, 130: 4, 129: 4, 128: 4, 127: 4, 126: 4, 125: 4, 124: 4, 123: 4, 122: 4, 121: 4, 120: 4, 119: 4, 118: 4, 117: 4, 116: 4, 115: 4, 114: 4, 113: 4, 112: 4, 111: 4, 110: 4, 109: 5, 108: 5, 107: 5, 106: 5, 105: 5, 104: 5, 103: 5, 102: 5, 101: 5, 100: 5, 99: 5, 98: 5, 97: 5, 96: 5, 95: 5, 94: 5, 93: 5, 92: 5, 91: 5, 90: 5, 89: 5, 88: 5, 87: 5, 86: 5, 85: 5, 84: 5, 83: 5, 82: 5, 81: 6, 80: 6, 79: 6, 78: 6, 77: 6, 76: 6, 75: 6, 74: 6, 73: 6, 72: 6, 71: 6, 70: 6, 69: 6, 68: 6, 67: 6, 66: 6, 65: 6, 64: 6, 63: 6, 62: 6, 61: 6, 60: 6, 59: 6, 58: 6, 57: 6, 56: 6, 55: 6, 54: 6, 53: 7, 52: 7, 51: 7, 50: 7, 49: 7, 48: 7, 47: 7, 46: 7, 45: 7, 44: 7, 43: 7, 42: 7, 41: 7, 40: 7, 39: 7, 38: 7, 37: 7, 36: 7, 35: 7, 34: 7, 33: 7, 32: 7, 31: 7, 30: 7, 29: 7, 28: 7, 27: 7, 26: 7, 25: 8, 24: 8, 23: 8, 22: 8, 21: 8, 20: 8, 19: 8, 18: 8, 17: 8, 16: 8, 15: 8, 14: 8, 13: 8, 12: 8, 11: 8, 10: 8, 9: 8, 8: 8, 7: 8, 6: 8, 5: 8, 4: 8, 3: 8, 2: 8, 1: 8, 0: 8 } """) symbol_signal_coder = Base64SymbolSignalCoder() if str(focused_tab) and str(new_b64) and str(width): print 'Dimensions', width, height _data_len = len(imageDataArray) imageDataArray.reverse() pixels = [] for _h in range(height): pixels.append([]) for _w in range(width): red = imageDataArray.pop() pixels[_h].append(red) print 'Pixel matrix set.' shape_width, shape_height = self.symbol_shape.get_shape_size() extracted_data = '' values = {} for y_coord in range(0, height, shape_height): for x_coord in range(0, width, shape_width): values.clear() _symbol = [] for symbol_val in range( self.symbol_shape.get_num_symbol_shapes()): coords = self.symbol_shape.get_symbol_shape_coords( symbol_val + 1) _vals = 0 _num_vals = 0 for x, y in coords: _vals += pixels[y_coord + y][x_coord + x] _num_vals += 1 _avg = int(_vals / float(_num_vals)) JS("@{{_symbol_val}} = @{{lookup}}[@{{_avg}}]") _symbol.append(int(_symbol_val)) extracted_datum = self.message_symbol_coder.symbol_to_message( _symbol) extracted_data += extracted_datum extracted_data = _base64_pad(extracted_data) print 'Submitting extracted_data.' if not extracted_data in self.decoded: self.decoded[extracted_data] = True JS(""" chrome.tabs.sendRequest(@{{focused_tab}}, {action: "decrypted", data: @{{extracted_data}}}, function(response) { console.log("Success"); } ); """) else: print 'Already sent for decoding.' self.timer.schedule(1000)
def fromtimestamp(self, timestamp, tz=None): if tz != None: raise NotImplementedError("tz") d = JS("""new Date()""") d.setTime(timestamp * 1000.0) return datetime(0, 0, 0, d=d)
def __delitem__(self, key): JS(""" var sKey = pyjslib.hash(key); delete this.d[sKey]; """)
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __pyjamas__ import JS from pyjamas.gmaps.Utils import translateGmapsObject, dictToJs from pyjamas.gmaps.Geocoder import translateGeocoderResult DirectionsStatus = JS("$wnd.google.maps.DirectionsStatus") DirectionsTravelMode = JS("$wnd.google.maps.DirectionsTravelMode") DirectionsUnitSystem = JS("$wnd.google.maps.DirectionsUnitSystem") directionsResultsFields = dictToJs({ "trips": 'l', "warnings": 'l', "routes": 'l', "steps": 'l', "results": 'd', "trips[]": 'd', "routes[]": 'd', "steps[]": 'd', "start_geocode": translateGeocoderResult,
def localtime(t=None): if t is None: t = time() date = JS("new Date(@{{t}}*1000)") dateOffset = date.getTimezoneOffset() tm = struct_time() tm_year = tm.tm_year = int(date.getFullYear()) tm_mon = tm.tm_mon = int(date.getMonth()) + 1 tm_mday = tm.tm_mday = int(date.getDate()) tm.tm_hour = int(date.getHours()) tm.tm_min = int(date.getMinutes()) tm.tm_sec = int(date.getSeconds()) tm.tm_wday = (int(date.getDay()) + 6) % 7 tm.tm_isdst = 0 if timezone == 60*date.getTimezoneOffset() else 1 startOfYear = JS("new Date(@{{tm_year}},0,1)") # local time startOfYearOffset = startOfYear.getTimezoneOffset() startOfDay = JS("new Date(@{{tm_year}},@{{tm_mon}}-1,@{{tm_mday}})") dt = float(startOfDay.getTime() - startOfYear.getTime())/1000 dt = dt + 60 * (startOfYearOffset - dateOffset) tm.tm_yday = 1 + int(dt/86400.0) return tm
def flush(self): content = self.content JS("$p._print_to_console(@{{content}})") self.content = ''
def fromordinal(self, ordinal): d = JS("""new Date()""") d.setTime((ordinal - 719163.0) * 86400000.0) return datetime(0, 0, 0, d=d)
def __len__(self): JS(""" var size=0; for (var i in this.d) size++; return size; """)
def fromtimestamp(self, timestamp): d = JS("""new Date()""") d.setTime(timestamp * 1000.0) return date(0, 0, 0, d=d)
def Polygon(options): JS("return new $wnd.google.maps.Polygon(options);")
from pyjamas.ui.Widget import Widget from __pyjamas__ import JS log = logging.getAppendLogger(__name__, logging.DEBUG, logging.PLAIN_FORMAT) def createFCK(name): JS(""" return new @{{!FCKeditor}}(@{{name}}); """) JS(""" $wnd.FCKeditor_OnComplete = function(editorInstance ) { var pyjsObject = $doc.getElementById(editorInstance.Name.substr(3)).__listener; if(pyjsObject) pyjsObject.onFCKLoaded(editorInstance); } """) class RichTextEditor(Widget): def __init__(self, initialValue="", target="", method="POST", basePath=None, **kwargs): self.id = "rte" + str(hash(self))
def strftime(fmt, t=None): if t is None: t = localtime() else: if not isinstance(t, struct_time) and len(t) != 9: raise TypeError('argument must be 9-item sequence, not float') tm_year = t[0] tm_mon = t[1] tm_mday = t[2] tm_hour = t[3] tm_min = t[4] tm_sec = t[5] tm_wday = t[6] tm_yday = t[7] date = JS("new Date(@{{tm_year}}, @{{tm_mon}} - 1, @{{tm_mday}}, @{{tm_hour}}, @{{tm_min}}, @{{tm_sec}})") startOfYear = JS("new Date(@{{tm_year}},0,1)") firstMonday = 1 - ((startOfYear.getDay() + 6) % 7) + 7 firstWeek = JS("new Date(@{{tm_year}},0,@{{firstMonday}})") weekNo = date.getTime() - firstWeek.getTime() if weekNo < 0: weekNo = 0 else: weekNo = 1 + int(weekNo/604800000) def format(c): if c == '%': return '%' elif c == 'a': return format('A')[:3] elif c == 'A': return __c__days[format('w')] elif c == 'b': return format('B')[:3] elif c == 'B': return __c__months[tm_mon-1] elif c == 'c': return date.toLocaleString() elif c == 'd': return "%02d" % tm_mday elif c == 'H': return "%02d" % tm_hour elif c == 'I': return "%02d" % (tm_hour % 12) elif c == 'j': return "%03d" % tm_yday elif c == 'm': return "%02d" % tm_mon elif c == 'M': return "%02d" % tm_min elif c == 'p': # FIXME: should be locale dependent if tm_hour < 12: return "AM" return "PM" elif c == 'S': return "%02d" % tm_sec elif c == 'U': raise NotImplementedError("strftime format character '%s'" % c) elif c == 'w': return "%d" % ((tm_wday+1) % 7) elif c == 'W': return "%d" % weekNo elif c == 'x': return "%s" % date.toLocaleDateString() elif c == 'X': return "%s" % date.toLocaleTimeString() elif c == 'y': return "%02d" % (tm_year % 100) elif c == 'Y': return "%04d" % tm_year elif c == 'Z': raise NotImplementedError("strftime format character '%s'" % c) return "%" + c result = '' remainder = fmt re_pct = JS("/([^%]*)%(.)(.*)/") JS("var a, fmtChar;") while remainder: JS(""" @{{!a}} = @{{re_pct}}.exec(@{{remainder}}); if (!@{{!a}}) { @{{result}} += @{{remainder}}; @{{remainder}} = false; } else { @{{result}} += @{{!a}}[1]; @{{!fmtChar}} = @{{!a}}[2]; @{{remainder}} = @{{!a}}[3]; if (typeof @{{!fmtChar}} != 'undefined') { @{{result}} += @{{format}}(@{{!fmtChar}}); } } """) return str(result)
def listToJs(list): obj = JS("[]") for i in list: obj.push(i) return obj
def createFCK(name): JS(""" return new @{{!FCKeditor}}(@{{name}}); """)
def __init__(self, options): if options: self.renderer = JS("""new $wnd.google.maps.DirectionsRenderer(options);""") else: self.renderer = JS("""new $wnd.google.maps.DirectionsRenderer();""")
def toJSONString(self, obj): JS(r""" var m = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, s = { 'array': function (x) { var a = ['['], b, f, i, l = x['length'], v; for (i = 0; i < l; i += 1) { v = x[i]; f = s[typeof v]; if (f) { v = f(v); if (typeof v == 'string') { if (b) { a[a['length']] = ','; } a[a['length']] = v; b = true; } } } a[a['length']] = ']'; return a['join'](''); }, 'boolean': function (x) { return String(x); }, 'undefined':function (x) { return "null"; }, 'null': function (x) { return "null"; }, 'number': function (x) { return isFinite(x) ? String(x) : 'null'; }, 'object': function (x) { if (x) { if (x['__number__']) { return String(x); } if (x instanceof Array) { return s['array'](x); } if (x instanceof pyjslib['list']) { return s['array'](x['__array']); } if (x instanceof pyjslib['tuple']) { return s['array'](x['__array']); } if (x instanceof pyjslib['dict']) { return s['object'](pyjslib['toJSObjects'](x)); } var a = ['{'], b, f, i, v; for (i in x) { v = x[i]; f = s[typeof v]; if (f) { v = f(v); if (typeof v == 'string') { if (b) { a[a['length']] = ','; } a['push'](s['string'](i), ':', v); b = true; } } } a[a['length']] = '}'; return a['join'](''); } return 'null'; }, 'string': function (x) { if (/["\\\x00-\x1f]/.test(x)) { x = x['replace'](/([\x00-\x1f\\"])/g, function(a, b) { var c = m[b]; if (c) { return c; } c = b['charCodeAt'](); return '\\u00' + Math['floor'](c / 16)['toString'](16) + (c % 16)['toString'](16); }); } return '"' + x + '"'; } }; var typ = typeof @{{obj}}; f=s[typ]; return f(@{{obj}}); """)
JS(""" // Copyright 2007 Google Inc. All Rights Reserved. // // Sets up google['gears'].*, which is *the only* supported way to access Gears. // // Circumvent this file at your own risk! // // In the future, Gears may automatically define google['gears'].* without this // file. Gears may use these objects to transparently fix bugs and compatibility // issues. Applications that use the code below will continue to work seamlessly // when that happens. @{{!init_gears}} = function() { // We are already defined. Hooray! if ($wnd['google'] && $wnd['google']['gears']) { return; } var factory = null; // Firefox if (typeof @{{!GearsFactory}} != 'undefined') { factory = new @{{!GearsFactory}}(); } else { // IE try { factory = new ActiveXObject('Gears['Factory']'); } catch (e) { // Safari if (navigator['mimeTypes']["application/x-googlegears"]) { factory = $doc['createElement']("object"); factory['style']['display'] = "none"; factory['width'] = 0; factory['height'] = 0; factory['type'] = "application/x-googlegears"; $doc['documentElement']['appendChild'](factory); } } } // *Do not* define any objects if Gears is not installed. This mimics the // behavior of Gears defining the objects in the future. if (!factory) { return; } // Now set up the objects, being careful not to overwrite anything. if (!$wnd['google']) { $wnd['google'] = {}; } if (!$wnd['google']['gears']) { $wnd['google']['gears'] = {factory: factory}; } } """)
def getInstance(): JS(""" @{{!init_gears}}(); return $wnd['google'] && $wnd['google']['gears'] && $wnd['google']['gears']['factory']; """)
def __init__(self): self.ds = JS("""new $wnd['google']['maps']['DirectionsService']()""")
def __init__(self, s=''): self.finished = False self.md5 = JS("new @{{!_md5}}()") self.md5.init() self.update(s)
def __setitem__(self, key, value): JS(""" var sKey = pyjslib.hash(key); this.d[sKey]=[key, value]; """)