svgui/pyjs/lib/pyjslib.py
changeset 1736 7e61baa047f0
parent 1730 64d8f52bc8c8
child 1740 b789b695b5c6
equal deleted inserted replaced
1735:c02818d7e29f 1736:7e61baa047f0
    17 
    17 
    18 from __pyjamas__ import JS
    18 from __pyjamas__ import JS
    19 
    19 
    20 # must declare import _before_ importing sys
    20 # must declare import _before_ importing sys
    21 
    21 
       
    22 
    22 def import_module(path, parent_module, module_name, dynamic=1, async=False):
    23 def import_module(path, parent_module, module_name, dynamic=1, async=False):
    23     """
    24     """
    24     """
    25     """
    25 
    26 
    26     JS("""
    27     JS("""
   182 
   183 
   183     wait();
   184     wait();
   184 }
   185 }
   185 """)
   186 """)
   186 
   187 
       
   188 
   187 class Object:
   189 class Object:
   188     pass
   190     pass
   189 
   191 
   190 object = Object
   192 object = Object
       
   193 
   191 
   194 
   192 class Modload:
   195 class Modload:
   193 
   196 
   194     def __init__(self, path, app_modlist, app_imported_fn, dynamic,
   197     def __init__(self, path, app_modlist, app_imported_fn, dynamic,
   195                  parent_mod):
   198                  parent_mod):
   210         if self.idx >= len(self.app_modlist):
   213         if self.idx >= len(self.app_modlist):
   211             import_wait(self.app_imported_fn, self.parent_mod, self.dynamic)
   214             import_wait(self.app_imported_fn, self.parent_mod, self.dynamic)
   212         else:
   215         else:
   213             import_wait(getattr(self, "next"), self.parent_mod, self.dynamic)
   216             import_wait(getattr(self, "next"), self.parent_mod, self.dynamic)
   214 
   217 
       
   218 
   215 def get_module(module_name):
   219 def get_module(module_name):
   216     ev = "__mod = %s;" % module_name
   220     ev = "__mod = %s;" % module_name
   217     JS("pyjs_eval(ev);")
   221     JS("pyjs_eval(ev);")
   218     return __mod
   222     return __mod
   219 
   223 
       
   224 
   220 def preload_app_modules(path, app_modnames, app_imported_fn, dynamic,
   225 def preload_app_modules(path, app_modnames, app_imported_fn, dynamic,
   221                         parent_mod=None):
   226                         parent_mod=None):
   222 
   227 
   223     loader = Modload(path, app_modnames, app_imported_fn, dynamic, parent_mod)
   228     loader = Modload(path, app_modnames, app_imported_fn, dynamic, parent_mod)
   224     loader.next()
   229     loader.next()
   225 
   230 
   226 import sys
   231 import sys
       
   232 
   227 
   233 
   228 class BaseException:
   234 class BaseException:
   229 
   235 
   230     name = "BaseException"
   236     name = "BaseException"
   231 
   237 
   240         return repr(self.args)
   246         return repr(self.args)
   241 
   247 
   242     def toString(self):
   248     def toString(self):
   243         return str(self)
   249         return str(self)
   244 
   250 
       
   251 
   245 class Exception(BaseException):
   252 class Exception(BaseException):
   246 
       
   247     name = "Exception"
   253     name = "Exception"
       
   254 
   248 
   255 
   249 class TypeError(BaseException):
   256 class TypeError(BaseException):
   250     name = "TypeError"
   257     name = "TypeError"
   251 
   258 
       
   259 
   252 class StandardError(Exception):
   260 class StandardError(Exception):
   253     name = "StandardError"
   261     name = "StandardError"
   254 
   262 
       
   263 
   255 class LookupError(StandardError):
   264 class LookupError(StandardError):
   256     name = "LookupError"
   265     name = "LookupError"
   257 
   266 
   258     def toString(self):
   267     def toString(self):
   259         return self.name + ": " + self.args[0]
   268         return self.name + ": " + self.args[0]
   260 
   269 
       
   270 
   261 class KeyError(LookupError):
   271 class KeyError(LookupError):
   262     name = "KeyError"
   272     name = "KeyError"
   263 
   273 
       
   274 
   264 class AttributeError(StandardError):
   275 class AttributeError(StandardError):
   265 
       
   266     name = "AttributeError"
   276     name = "AttributeError"
   267 
   277 
   268     def toString(self):
   278     def toString(self):
   269         return "AttributeError: %s of %s" % (self.args[1], self.args[0])
   279         return "AttributeError: %s of %s" % (self.args[1], self.args[0])
   270 
   280 
   405 
   415 
   406 pyjslib.abs = Math.abs;
   416 pyjslib.abs = Math.abs;
   407 
   417 
   408 """)
   418 """)
   409 
   419 
       
   420 
   410 class Class:
   421 class Class:
   411     def __init__(self, name):
   422     def __init__(self, name):
   412         self.name = name
   423         self.name = name
   413 
   424 
   414     def __str___(self):
   425     def __str___(self):
   415         return self.name
   426         return self.name
       
   427 
   416 
   428 
   417 def eq(a,b):
   429 def eq(a,b):
   418     JS("""
   430     JS("""
   419     if (pyjslib.hasattr(a, "__cmp__")) {
   431     if (pyjslib.hasattr(a, "__cmp__")) {
   420         return a.__cmp__(b) == 0;
   432         return a.__cmp__(b) == 0;
   421     } else if (pyjslib.hasattr(b, "__cmp__")) {
   433     } else if (pyjslib.hasattr(b, "__cmp__")) {
   422         return b.__cmp__(a) == 0;
   434         return b.__cmp__(a) == 0;
   423     }
   435     }
   424     return a == b;
   436     return a == b;
   425     """)
   437     """)
       
   438 
   426 
   439 
   427 def cmp(a,b):
   440 def cmp(a,b):
   428     if hasattr(a, "__cmp__"):
   441     if hasattr(a, "__cmp__"):
   429         return a.__cmp__(b)
   442         return a.__cmp__(b)
   430     elif hasattr(b, "__cmp__"):
   443     elif hasattr(b, "__cmp__"):
   434     elif b > a:
   447     elif b > a:
   435         return -1
   448         return -1
   436     else:
   449     else:
   437         return 0
   450         return 0
   438 
   451 
       
   452 
   439 def bool(v):
   453 def bool(v):
   440     # this needs to stay in native code without any dependencies here,
   454     # this needs to stay in native code without any dependencies here,
   441     # because this is used by if and while, we need to prevent
   455     # because this is used by if and while, we need to prevent
   442     # recursion
   456     # recursion
   443     JS("""
   457     JS("""
   453         }
   467         }
   454         return true;
   468         return true;
   455     }
   469     }
   456     return Boolean(v);
   470     return Boolean(v);
   457     """)
   471     """)
       
   472 
   458 
   473 
   459 class List:
   474 class List:
   460     def __init__(self, data=None):
   475     def __init__(self, data=None):
   461         JS("""
   476         JS("""
   462         this.l = [];
   477         this.l = [];
   603     def __str__(self):
   618     def __str__(self):
   604         return repr(self)
   619         return repr(self)
   605 
   620 
   606 list = List
   621 list = List
   607 
   622 
       
   623 
   608 class Tuple:
   624 class Tuple:
   609     def __init__(self, data=None):
   625     def __init__(self, data=None):
   610         JS("""
   626         JS("""
   611         this.l = [];
   627         this.l = [];
   612         this.extend(data);
   628         this.extend(data);
   898         return repr(self)
   914         return repr(self)
   899 
   915 
   900 dict = Dict
   916 dict = Dict
   901 
   917 
   902 # taken from mochikit: range( [start,] stop[, step] )
   918 # taken from mochikit: range( [start,] stop[, step] )
       
   919 
       
   920 
   903 def range():
   921 def range():
   904     JS("""
   922     JS("""
   905     var start = 0;
   923     var start = 0;
   906     var stop = 0;
   924     var stop = 0;
   907     var step = 1;
   925     var step = 1;
   928             return this;
   946             return this;
   929             }
   947             }
   930         }
   948         }
   931     """)
   949     """)
   932 
   950 
       
   951 
   933 def slice(object, lower, upper):
   952 def slice(object, lower, upper):
   934     JS("""
   953     JS("""
   935     if (pyjslib.isString(object)) {
   954     if (pyjslib.isString(object)) {
   936         if (lower < 0) {
   955         if (lower < 0) {
   937            lower = object.length + lower;
   956            lower = object.length + lower;
   946         return object.slice(lower, upper);
   965         return object.slice(lower, upper);
   947 
   966 
   948     return null;
   967     return null;
   949     """)
   968     """)
   950 
   969 
       
   970 
   951 def str(text):
   971 def str(text):
   952     JS("""
   972     JS("""
   953     if (pyjslib.hasattr(text,"__str__")) {
   973     if (pyjslib.hasattr(text,"__str__")) {
   954         return text.__str__();
   974         return text.__str__();
   955     }
   975     }
   956     return String(text);
   976     return String(text);
   957     """)
   977     """)
   958 
   978 
       
   979 
   959 def ord(x):
   980 def ord(x):
   960     if(isString(x) and len(x) is 1):
   981     if(isString(x) and len(x) is 1):
   961         JS("""
   982         JS("""
   962             return x.charCodeAt(0);
   983             return x.charCodeAt(0);
   963         """)
   984         """)
   965         JS("""
   986         JS("""
   966             throw pyjslib.TypeError();
   987             throw pyjslib.TypeError();
   967         """)
   988         """)
   968     return None
   989     return None
   969 
   990 
       
   991 
   970 def chr(x):
   992 def chr(x):
   971     JS("""
   993     JS("""
   972         return String.fromCharCode(x)
   994         return String.fromCharCode(x)
   973     """)
   995     """)
       
   996 
   974 
   997 
   975 def is_basetype(x):
   998 def is_basetype(x):
   976     JS("""
   999     JS("""
   977        var t = typeof(x);
  1000        var t = typeof(x);
   978        return t == 'boolean' ||
  1001        return t == 'boolean' ||
   981        t == 'string' ||
  1004        t == 'string' ||
   982        t == 'undefined'
  1005        t == 'undefined'
   983        ;
  1006        ;
   984     """)
  1007     """)
   985 
  1008 
       
  1009 
   986 def get_pyjs_classtype(x):
  1010 def get_pyjs_classtype(x):
   987     JS("""
  1011     JS("""
   988        if (pyjslib.hasattr(x, "__class__"))
  1012        if (pyjslib.hasattr(x, "__class__"))
   989            if (pyjslib.hasattr(x.__class__, "__new__"))
  1013            if (pyjslib.hasattr(x.__class__, "__new__"))
   990                var src = x.__class__.__name__;
  1014                var src = x.__class__.__name__;
   991                return src;
  1015                return src;
   992        return null;
  1016        return null;
   993     """)
  1017     """)
       
  1018 
   994 
  1019 
   995 def repr(x):
  1020 def repr(x):
   996     """ Return the string representation of 'x'.
  1021     """ Return the string representation of 'x'.
   997     """
  1022     """
   998     JS("""
  1023     JS("""
  1086 
  1111 
  1087        //var s = constructor.replace(new RegExp('_', "g"), '.');
  1112        //var s = constructor.replace(new RegExp('_', "g"), '.');
  1088        return "<" + constructor + " object>";
  1113        return "<" + constructor + " object>";
  1089     """)
  1114     """)
  1090 
  1115 
       
  1116 
  1091 def float(text):
  1117 def float(text):
  1092     JS("""
  1118     JS("""
  1093     return parseFloat(text);
  1119     return parseFloat(text);
  1094     """)
  1120     """)
  1095 
  1121 
       
  1122 
  1096 def int(text, radix=0):
  1123 def int(text, radix=0):
  1097     JS("""
  1124     JS("""
  1098     return parseInt(text, radix);
  1125     return parseInt(text, radix);
  1099     """)
  1126     """)
       
  1127 
  1100 
  1128 
  1101 def len(object):
  1129 def len(object):
  1102     JS("""
  1130     JS("""
  1103     if (object==null) return 0;
  1131     if (object==null) return 0;
  1104     if (pyjslib.isObject(object) && object.__len__) return object.__len__();
  1132     if (pyjslib.isObject(object) && object.__len__) return object.__len__();
  1105     return object.length;
  1133     return object.length;
  1106     """)
  1134     """)
       
  1135 
  1107 
  1136 
  1108 def isinstance(object_, classinfo):
  1137 def isinstance(object_, classinfo):
  1109     if pyjslib.isUndefined(object_):
  1138     if pyjslib.isUndefined(object_):
  1110         return False
  1139         return False
  1111     if not pyjslib.isObject(object_):
  1140     if not pyjslib.isObject(object_):
  1117                 return True
  1146                 return True
  1118         return False
  1147         return False
  1119     else:
  1148     else:
  1120         return _isinstance(object_, classinfo)
  1149         return _isinstance(object_, classinfo)
  1121 
  1150 
       
  1151 
  1122 def _isinstance(object_, classinfo):
  1152 def _isinstance(object_, classinfo):
  1123     if not pyjslib.isObject(object_):
  1153     if not pyjslib.isObject(object_):
  1124         return False
  1154         return False
  1125     JS("""
  1155     JS("""
  1126     if (object_.__class__){
  1156     if (object_.__class__){
  1127         var res =  object_ instanceof classinfo.constructor;
  1157         var res =  object_ instanceof classinfo.constructor;
  1128         return res;
  1158         return res;
  1129     }
  1159     }
  1130     return false;
  1160     return false;
  1131     """)
  1161     """)
       
  1162 
  1132 
  1163 
  1133 def getattr(obj, name, default_):
  1164 def getattr(obj, name, default_):
  1134     JS("""
  1165     JS("""
  1135     if ((!pyjslib.isObject(obj))||(pyjslib.isUndefined(obj[name]))){
  1166     if ((!pyjslib.isObject(obj))||(pyjslib.isUndefined(obj[name]))){
  1136         if (pyjslib.isUndefined(default_)){
  1167         if (pyjslib.isUndefined(default_)){
  1149         }
  1180         }
  1150     fnwrap.__name__ = name;
  1181     fnwrap.__name__ = name;
  1151     return fnwrap;
  1182     return fnwrap;
  1152     """)
  1183     """)
  1153 
  1184 
       
  1185 
  1154 def setattr(obj, name, value):
  1186 def setattr(obj, name, value):
  1155     JS("""
  1187     JS("""
  1156     if (!pyjslib.isObject(obj)) return null;
  1188     if (!pyjslib.isObject(obj)) return null;
  1157 
  1189 
  1158     obj[name] = value;
  1190     obj[name] = value;
  1159 
  1191 
  1160     """)
  1192     """)
       
  1193 
  1161 
  1194 
  1162 def hasattr(obj, name):
  1195 def hasattr(obj, name):
  1163     JS("""
  1196     JS("""
  1164     if (!pyjslib.isObject(obj)) return false;
  1197     if (!pyjslib.isObject(obj)) return false;
  1165     if (pyjslib.isUndefined(obj[name])) return false;
  1198     if (pyjslib.isUndefined(obj[name])) return false;
  1166 
  1199 
  1167     return true;
  1200     return true;
  1168     """)
  1201     """)
       
  1202 
  1169 
  1203 
  1170 def dir(obj):
  1204 def dir(obj):
  1171     JS("""
  1205     JS("""
  1172     var properties=new pyjslib.List();
  1206     var properties=new pyjslib.List();
  1173     for (property in obj) properties.append(property);
  1207     for (property in obj) properties.append(property);
  1174     return properties;
  1208     return properties;
  1175     """)
  1209     """)
       
  1210 
  1176 
  1211 
  1177 def filter(obj, method, sequence=None):
  1212 def filter(obj, method, sequence=None):
  1178     # object context is LOST when a method is passed, hence object must be passed separately
  1213     # object context is LOST when a method is passed, hence object must be passed separately
  1179     # to emulate python behaviour, should generate this code inline rather than as a function call
  1214     # to emulate python behaviour, should generate this code inline rather than as a function call
  1180     items = []
  1215     items = []
  1238     return maxValue
  1273     return maxValue
  1239 
  1274 
  1240 
  1275 
  1241 next_hash_id = 0
  1276 next_hash_id = 0
  1242 
  1277 
       
  1278 
  1243 def hash(obj):
  1279 def hash(obj):
  1244     JS("""
  1280     JS("""
  1245     if (obj == null) return null;
  1281     if (obj == null) return null;
  1246 
  1282 
  1247     if (obj.$H) return obj.$H;
  1283     if (obj.$H) return obj.$H;
  1257 def isObject(a):
  1293 def isObject(a):
  1258     JS("""
  1294     JS("""
  1259     return (a != null && (typeof a == 'object')) || pyjslib.isFunction(a);
  1295     return (a != null && (typeof a == 'object')) || pyjslib.isFunction(a);
  1260     """)
  1296     """)
  1261 
  1297 
       
  1298 
  1262 def isFunction(a):
  1299 def isFunction(a):
  1263     JS("""
  1300     JS("""
  1264     return typeof a == 'function';
  1301     return typeof a == 'function';
  1265     """)
  1302     """)
  1266 
  1303 
       
  1304 
  1267 def isString(a):
  1305 def isString(a):
  1268     JS("""
  1306     JS("""
  1269     return typeof a == 'string';
  1307     return typeof a == 'string';
  1270     """)
  1308     """)
  1271 
  1309 
       
  1310 
  1272 def isNull(a):
  1311 def isNull(a):
  1273     JS("""
  1312     JS("""
  1274     return typeof a == 'object' && !a;
  1313     return typeof a == 'object' && !a;
  1275     """)
  1314     """)
  1276 
  1315 
       
  1316 
  1277 def isArray(a):
  1317 def isArray(a):
  1278     JS("""
  1318     JS("""
  1279     return pyjslib.isObject(a) && a.constructor == Array;
  1319     return pyjslib.isObject(a) && a.constructor == Array;
  1280     """)
  1320     """)
  1281 
  1321 
       
  1322 
  1282 def isUndefined(a):
  1323 def isUndefined(a):
  1283     JS("""
  1324     JS("""
  1284     return typeof a == 'undefined';
  1325     return typeof a == 'undefined';
  1285     """)
  1326     """)
  1286 
  1327 
       
  1328 
  1287 def isIteratable(a):
  1329 def isIteratable(a):
  1288     JS("""
  1330     JS("""
  1289     return pyjslib.isString(a) || (pyjslib.isObject(a) && a.__iter__);
  1331     return pyjslib.isString(a) || (pyjslib.isObject(a) && a.__iter__);
  1290     """)
  1332     """)
  1291 
  1333 
       
  1334 
  1292 def isNumber(a):
  1335 def isNumber(a):
  1293     JS("""
  1336     JS("""
  1294     return typeof a == 'number' && isFinite(a);
  1337     return typeof a == 'number' && isFinite(a);
  1295     """)
  1338     """)
       
  1339 
  1296 
  1340 
  1297 def toJSObjects(x):
  1341 def toJSObjects(x):
  1298     """
  1342     """
  1299        Convert the pyjs pythonic List and Dict objects into javascript Object and Array
  1343        Convert the pyjs pythonic List and Dict objects into javascript Object and Array
  1300        objects, recursively.
  1344        objects, recursively.
  1335             }
  1379             }
  1336             return result;
  1380             return result;
  1337          """)
  1381          """)
  1338     return x
  1382     return x
  1339 
  1383 
       
  1384 
  1340 def printFunc(objs):
  1385 def printFunc(objs):
  1341     JS("""
  1386     JS("""
  1342     if ($wnd.console==undefined)  return;
  1387     if ($wnd.console==undefined)  return;
  1343     var s = "";
  1388     var s = "";
  1344     for(var i=0; i < objs.length; i++) {
  1389     for(var i=0; i < objs.length; i++) {
  1346         s += objs[i];
  1391         s += objs[i];
  1347     }
  1392     }
  1348     console.debug(s)
  1393     console.debug(s)
  1349     """)
  1394     """)
  1350 
  1395 
       
  1396 
  1351 def type(clsname, bases=None, methods=None):
  1397 def type(clsname, bases=None, methods=None):
  1352     """ creates a class, derived from bases, with methods and variables
  1398     """ creates a class, derived from bases, with methods and variables
  1353     """
  1399     """
  1354 
  1400 
  1355     JS(" var mths = {}; ")
  1401     JS(" var mths = {}; ")