def generate(): for root, subdirs, files in os.walk(os.getcwd()): importedLibs = [] neededPath = os.path.join("docs", os.path.relpath(root)) if not os.path.exists(neededPath): os.makedirs(neededPath) for i in range(0, len(files)): if os.path.isfile(os.path.join(root, files[i])): infile = open(os.path.join(root, files[i]), "rb") infileData = infile.read() infile.close() outfile = open( os.path.join(neededPath, ".".join( files[i].split(".")[:-1])) + ".json", "w") if files[i].endswith(".js"): output.action(_("genDocs", [files[i]])) json.dump(scan(infileData.decode("utf-8")), outfile) outfile.close() output.returns(_("genDocsSuccessful"))
def installLib(name, description): global requiredInstalls requiredInstalls = True output.action(_("installRequiredLibs", [description])) returns = subprocess.call([sys.executable, "-m", "pip", "install", name], stdout = subprocess.PIPE, stderr = subprocess.PIPE) if returns != 0: output.error(_("installRequiredLibsError")) sys.exit(1)
def get(item): if storage.read("useCache") != "false": itemName = item.replace("/", "-").replace(":", "-").replace(".", "-") try: if os.path.exists(os.path.join(cacheDirectory, itemName + ".gzc")): file = open(os.path.join(cacheDirectory, itemName + ".gzc"), "rb") fileData = file.read() file.close() output.action(_("takenFromCache", [item])) return fileData else: site = urllib.request.urlopen(item) siteData = site.read() site.close() file = open(os.path.join(cacheDirectory, itemName + ".gzc"), "wb") file.write(siteData) file.close() return siteData except: return False else: site = urllib.request.urlopen(item) siteData = site.read() site.close() return siteData
def run(filename, size=6144, debugging=False): registers = [0] * 20 memory = [0] * size fileDirectory = "" file = open(filename, "rb") directoryPath = "/" directoryPosition = 0 position = 0 while True: c = file.read(1) if not c: break memory[position] = ord(c) position += 1 file.close() if debugging: output.action( _("startMemoryDump", [" ".join(hex(i)[2:].zfill(2) for i in memory)])) running = True while running: instruction = memory[registers[0]] parameters = [] for i in range(5, 8): parameters.append(registers[i]) if debugging: output.action(_("instructionHex", [hex(instruction)[2:].zfill(2)])) print(" " + _("instructionParameters", [ hex(parameters[0])[2:].zfill(2) + ", " + hex(parameters[1])[2:].zfill(2) + ", " + hex(parameters[2])[2:].zfill(2) ])) if instruction == 0x00: # halt running = False elif instruction == 0x01: # allocate for i in range(0, parameters[1]): memory[parameters[0] + i] = 0 elif instruction == 0x02: # copy for i in range(0, parameters[1]): memory[parameters[2] + i] = memory[parameters[0] + i] elif instruction == 0x03: # jump registers[0] = parameters[0] elif instruction == 0x04: # write affectedValue = parameters[0] while affectedValue >= 256: affectedValue = affectedValue - 256 memory[parameters[1]] = affectedValue elif instruction == 0x05: # read registers[1] = memory[parameters[0]] elif instruction == 0x06: # add registers[2] = parameters[0] + parameters[1] registers[3] = 0 elif instruction == 0x07: # sub registers[2] = parameters[0] - parameters[1] if registers[2] < 0: registers[2] = 65536 + registers[2] registers[3] = 0 elif instruction == 0x08: # mul registers[2] = parameters[0] * parameters[1] registers[3] = 0 elif instruction == 0x09: # div if parameters[1] == 0: registers[3] = 1 else: registers[2] = parameters[0] // parameters[1] registers[3] = 0 elif instruction == 0x0A: # mod if parameters[1] == 0: registers[3] = 1 else: registers[2] = parameters[0] % parameters[1] registers[3] = 0 elif instruction == 0x0B: # equ if parameters[0] == parameters[1]: registers[0] = parameters[2] else: registers[0] += 1 elif instruction == 0x0C: # neq if parameters[0] != parameters[1]: registers[0] = parameters[2] else: registers[0] += 1 elif instruction == 0x0D: # ltn if parameters[0] < parameters[1]: registers[0] = parameters[2] else: registers[0] += 1 elif instruction == 0x0E: # gtn if parameters[0] > parameters[1]: registers[0] = parameters[2] else: registers[0] += 1 elif instruction == 0x0F: # func registers[4] = registers[0] registers[0] = parameters[0] elif instruction == 0x10: # ret registers[0] = registers[4] registers[4] = 0 elif instruction == 0x11: # sreg registers[parameters[0]] = parameters[1] elif instruction == 0x12: # sgp registers[parameters[0] + 11] = parameters[1] elif instruction == 0x13: # cgp for i in range(12, 20): registers[i] = 0 elif instruction == 0x14: # dwrite byteA = (parameters[0] >> 8) & 0xFF byteB = parameters[0] & 0xFF memory[parameters[1]] = byteA memory[parameters[1] + 1] = byteB elif instruction == 0x15: # dread registers[1] = (memory[parameters[0]] * 256) + memory[parameters[0] + 1] elif instruction == 0x16: # bsl registers[2] = (parameters[0] << parameters[1]) & 0xFFFF elif instruction == 0x17: # bsr registers[2] = (parameters[0] >> parameters[1]) & 0xFFFF elif instruction == 0x18: # and registers[2] = parameters[0] & parameters[1] elif instruction == 0x19: # or registers[2] = parameters[0] | parameters[1] elif instruction == 0x1A: # xor registers[2] = parameters[0] ^ parameters[1] elif instruction == 0x1B: # onec registers[2] = (~parameters[0]) & 0xFFFF elif instruction == 0xA0: # outbin for i in range(0, parameters[1]): print("{0:b}".format(memory[parameters[0] + i]), end="", flush=True) elif instruction == 0xA1: # outdec result = 0 for i in range(0, parameters[1]): result = (result * 256) + memory[parameters[0] + i] print(result, end="", flush=True) elif instruction == 0xA2: # outhex for i in range(0, parameters[1]): if len(hex(memory[parameters[0] + i])[2:]) < 2: print("0" + hex(memory[parameters[0] + i])[2:], end="", flush=True) else: print(hex(memory[parameters[0] + i])[2:], end="", flush=True) elif instruction == 0xA3: # outasc for i in range(0, parameters[1]): print(chr(memory[parameters[0] + i]), end="", flush=True) elif instruction == 0xA4: # in entered = input("") for i in range(0, parameters[1]): if i < len(entered): memory[parameters[0] + i] = ord(entered[i]) elif instruction == 0xA5: # len currentChar = 0 while memory[parameters[0] + currentChar] != parameters[1]: currentChar += 1 registers[1] = currentChar elif instruction == 0xA6: # strnum number = 0 error = False for i in range(0, parameters[1]): if chr(memory[parameters[0] + i]) in "0123456789": number = (number * 10) + int(chr( memory[parameters[0] + i])) else: error = True registers[1] = number registers[3] = error * 2 elif instruction == 0xA7: # numstr number = str(parameters[2]) padCount = 0 for i in range(0, parameters[1]): if parameters[1] - i > len(number): memory[parameters[0] + i] = 0 padCount += 1 else: memory[parameters[0] + i] = ord(number[i - padCount]) elif instruction == 0xB0: # fopen fileDirectory = "" for i in range(0, parameters[1]): fileDirectory += chr(memory[parameters[0] + i]) registers[3] = 0 elif instruction == 0xB1: # fclose fileDirectory = "" elif instruction == 0xB2: # fwrite if fileDirectory != "": try: os.remove(fileDirectory) except: pass file = open(fileDirectory, "wb") for i in range(0, parameters[1]): file.write(bytes([memory[parameters[0] + i]])) file.close() registers[3] = 3 else: registers[3] = 0 elif instruction == 0xB3: # fwriter if fileDirectory != "": file = open(fileDirectory, "rb+") file.seek(parameters[2]) for i in range(0, parameters[1]): file.write(bytes([memory[parameters[0] + i]])) file.close() registers[3] = 3 else: registers[3] = 0 elif instruction == 0xB4: # fappend if fileDirectory != "": file = open(fileDirectory, "ab") for i in range(0, parameters[1]): file.write(bytes([memory[parameters[0] + i]])) file.close() registers[3] = 3 else: registers[3] = 0 elif instruction == 0xB5: # fread if fileDirectory != "": file = open(fileDirectory, "rb") if parameters[0] + parameters[1] <= size: for i in range(0, parameters[1]): nextChar = file.read(1) if nextChar: memory[parameters[0] + i] = ord(nextChar) else: registers[3] = 4 else: registers[3] = 5 file.close() registers[3] = 3 else: registers[3] = 0 elif instruction == 0xB6: # freadr if fileDirectory != "": file = open(fileDirectory, "rb") file.seek(parameters[2]) if parameters[0] + parameters[1] <= size: for i in range(0, parameters[1]): nextChar = file.read(1) if nextChar: memory[parameters[0] + i] = ord(nextChar) else: registers[3] = 4 else: registers[3] = 5 file.close() registers[3] = 3 else: registers[3] = 0 elif instruction == 0xB7: # fsize if fileDirectory != "": registers[1] = os.path.getsize( os.path.join(os.getcwd(), fileDirectory)) registers[3] = 0 else: registers[3] = 3 elif instruction == 0xB8: # fdel if fileDirectory != "": try: os.remove(os.path.join(os.getcwd(), fileDirectory)) except: pass registers[3] = 0 else: registers[3] = 3 elif instruction == 0xB9: # fmd directoryName = "" for i in range(0, parameters[1]): directoryName += chr(memory[parameters[0] + i]) try: if not os.path.exists(os.path.join(os.getcwd(), directoryName)): os.makedirs(os.path.join(os.getcwd(), directoryName)) except: pass elif instruction == 0xBA: # frd directoryName = "" for i in range(0, parameters[1]): directoryName += chr(memory[parameters[0] + i]) try: shutil.rmtree(os.path.join(os.getcwd(), directoryName)) except: pass elif instruction == 0xBB: # fstart directoryName = "" for i in range(0, parameters[1]): directoryName += chr(memory[parameters[0] + i]) directoryPath = directoryName directoryPosition = 0 elif instruction == 0xBC: # fnext directoryListing = os.listdir( os.path.join(os.getcwd(), directoryPath)) for i in range(0, 12): memory[parameters[0] + i] = 0 if directoryPosition < len(directoryListing): filename = directoryListing[directoryPosition] for i in range(0, min(len(filename), 12)): memory[parameters[0] + i] = ord(filename[i].upper()) directoryPosition += 1 elif instruction == 0xBD: # fex if fileDirectory != "": registers[1] = Path(os.path.join(os.getcwd(), fileDirectory)).exists() registers[3] = 0 else: registers[3] = 3 elif instruction == 0xBE: # fdir directoryListing = os.listdir( os.path.join(os.getcwd(), directoryPath)) if directoryPosition < len(directoryListing): registers[1] = os.path.isdir( os.path.join(os.getcwd(), directoryPath, directoryListing[directoryPosition])) else: registers[1] = 0 directoryPosition += 1 elif instruction == 0xC0: # gpos registers[8] = parameters[0] registers[9] = parameters[1] elif instruction == 0xC1: # gsize registers[10] = parameters[0] registers[11] = parameters[1] elif instruction == 0xC2: # ginit drawtools.ginit(registers[10], registers[11]) elif instruction == 0xC3: # gfill registers[3] = 6 - int(drawtools.gfill(parameters[0])) * 6 elif instruction == 0xC4: # gpixel registers[3] = 6 - int( drawtools.gpixel(registers[8], registers[9], parameters[0])) * 6 elif instruction == 0xC5: # gline registers[3] = 6 - int( drawtools.gline(registers[8], registers[9], registers[10], registers[11], parameters[0])) * 6 elif instruction == 0xC6: # gfline registers[3] = 6 - int( drawtools.gfline(registers[8], registers[9], registers[10], registers[11], parameters[1], parameters[0])) * 6 elif instruction == 0xC7: # grect if parameters[1] > 0: registers[3] = 6 - int( drawtools.grect(registers[8], registers[9], registers[10], registers[11], parameters[0], 0)) * 6 else: registers[3] = 6 - int( drawtools.grect(registers[8], registers[9], registers[10], registers[11], parameters[0], 1)) * 6 elif instruction == 0xC8: # gcircle if parameters[1] > 0: registers[3] = 6 - int( drawtools.gcircle(registers[8], registers[9], registers[10], parameters[0], 0)) * 6 else: registers[3] = 6 - int( drawtools.gcircle(registers[8], registers[9], registers[10], parameters[0], 1)) * 6 elif instruction == 0xC9: # gbin for i in range(0, parameters[2]): for j in range(0, len("{0:b}".format(memory[parameters[1] + i]))): registers[3] = 6 - int( drawtools.gchar( "{0:b}".format(memory[parameters[1] + i])[j], registers[8] + registers[8] + (j * registers[11] * 6), registers[9], registers[11], parameters[0])) * 6 elif instruction == 0xCA: # gdec result = 0 for i in range(0, parameters[2]): result = (result * 256) + memory[parameters[1] + i] for i in range(0, len(str(result))): registers[3] = 6 - int( drawtools.gchar( str(result)[i], registers[8] + (i * registers[11] * 6), registers[9], registers[11], parameters[0])) * 6 elif instruction == 0xCB: # ghex for i in range(0, parameters[2]): if len(hex(memory[parameters[1] + i])[2:]) < 2: registers[3] = 6 - int( drawtools.gchar( "0", registers[8] + ((i * 2) * registers[11] * 6), registers[9], registers[11], parameters[0])) * 6 registers[3] = 6 - int( drawtools.gchar( hex(memory[parameters[1] + i])[2:], registers[8] + (((i * 2) + 1) * registers[11] * 6), registers[9], registers[11], parameters[0])) * 6 else: registers[3] = 6 - int( drawtools.gchar( hex(memory[parameters[1] + i])[2:][0], registers[8] + ((i * 2) * registers[11] * 6), registers[9], registers[11], parameters[0])) * 6 registers[3] = 6 - int( drawtools.gchar( hex(memory[parameters[1] + i])[2:][1], registers[8] + (((i * 2) + 1) * registers[11] * 6), registers[9], registers[11], parameters[0])) * 6 elif instruction == 0xCC: # gasc for i in range(0, parameters[2]): registers[3] = 6 - int( drawtools.gchar(chr( memory[parameters[1] + i]), registers[8] + (i * registers[11] * 6), registers[9], registers[11], parameters[0])) * 6 elif instruction == 0xCD: # gbmp fileDirectory = "" for i in range(0, parameters[1]): fileDirectory += chr(memory[parameters[0] + i]) registers[3] = 6 - int( drawtools.gbmp(registers[8], registers[9], fileDirectory)) * 6 elif instruction == 0xCE: # gtouch values = drawtools.gtouch(parameters[0] > 0) if values == False: registers[3] = 6 else: registers[8] = values[0][0] registers[9] = values[0][1] registers[1] = values[1] registers[3] = 0 elif instruction == 0xD0: # sleep time.sleep(parameters[0] / 1000) elif instruction == 0xD1: # gyear registers[1] = datetime.datetime.now().year elif instruction == 0xD2: # gmonth registers[1] = datetime.datetime.now().month elif instruction == 0xD3: # gdate registers[1] = datetime.datetime.now().day elif instruction == 0xD4: # gday registers[1] = datetime.datetime.now().weekday() elif instruction == 0xD5: # ghour registers[1] = datetime.datetime.now().hour elif instruction == 0xD6: # gminute registers[1] = datetime.datetime.now().minute elif instruction == 0xD7: # gsecond registers[1] = datetime.datetime.now().second elif instruction == 0xD8: # sdate # Skipping, system time shouldn't be easily set by programs pass elif instruction == 0xD9: # stime # Skipping, system time shouldn't be easily set by programs pass elif instruction == 0xFD: # (setpar) # Uses raw parameters only. Registers can't be used! registers[memory[registers[0] + 1] + 5] = (memory[registers[0] + 2] * 256) + memory[registers[0] + 3] elif instruction == 0xFE: # (regpar) # Uses raw parameters only. Registers can't be used! registers[memory[registers[0] + 1] + 5] = registers[memory[registers[0] + 3]] elif instruction == 0xFF: # (loadpar) # Uses raw parameters only. Registers can't be used! registers[memory[registers[0] + 1] + 5] = memory[(memory[registers[0] + 2] * 256) + memory[registers[0] + 3]] if instruction != 0x03 and instruction != 0x0B and instruction != 0x0C and instruction != 0x0D and instruction != 0x0E and instruction != 0x0F: # Only increase PC if jump instruction isn't used if instruction == 0xFD or instruction == 0xFE or instruction == 0xFF: # Jump by 4 in parameter instructions registers[0] += 4 else: # Just jump by 1 registers[0] += 1 if debugging: output.returns( _("haltedEndMemoryDump", [" ".join(hex(i)[2:].zfill(2) for i in memory)])) else: output.returns(_("halted"))
def static(urlFormat, defaultLocale, staticFiles, localeFiles, rootFiles, workingDir, manifest, manifestAll): global importedLibs locales = {} output.action(_("buildRootFiles")) for root, subdirs, files in os.walk(rootFiles): importedLibs = [] neededPath = os.path.join("build", os.path.relpath(root, manifest["rootFiles"])) if not os.path.exists(neededPath): os.makedirs(neededPath) for i in range(0, len(files)): infile = open(os.path.join(root, files[i]), "rb") infileData = infile.read() infile.close() outfile = open(os.path.join(neededPath, files[i]), "wb") if files[i].endswith(".js"): outfile.write( js( infileData.decode("utf-8"), os.getcwd().replace("\\", "/") + "/" + root.replace("\\", "/")).encode("utf-8")) elif files[i].endswith(".html"): outfile.write( html( "<script>var _manifest = " + json.dumps(manifestAll).replace( "</script>", "<\/script>") + ";</script>" + infileData.decode("utf-8"), os.getcwd().replace("\\", "/") + "/" + root.replace("\\", "/")).encode( "utf-8", root.replace("\\", "/"))) elif files[i].endswith(".css"): outfile.write(css(infileData.decode("utf-8")).encode("utf-8")) else: outfile.write(infileData) outfile.close() for root, subdirs, files in os.walk(localeFiles): for i in range(0, len(files)): if not (files[i] in locales.keys()): locales[files[i].split(".")[0]] = os.path.join(root, files[i]) else: output.warning( _("doubleLanguageFile", [root.replace("\\", "/") + files[i]])) supportedLocales = list(locales.keys()) for i in range(0, len(supportedLocales)): output.action(_("buildLocale", [supportedLocales[i]])) openLocaleFile = open(locales[supportedLocales[i]], "r") openLocaleFileData = json.load(openLocaleFile) openLocaleFile.close() openDefaultLocaleFile = open(locales[manifest["defaultLocale"]], "r") openDefaultLocaleFileData = json.load(openDefaultLocaleFile) openDefaultLocaleFile.close() for root, subdirs, files in os.walk(staticFiles): importedLibs = [] splittablePath = ("build/" + manifest["urlFormat"].replace( "<locale>", supportedLocales[i]).replace( "<path>", os.path.relpath( root, manifest["staticFiles"]))).split("/") neededPath = os.path.join(*splittablePath) if not os.path.exists(neededPath): os.makedirs(neededPath) for j in range(0, len(files)): infile = open(os.path.join(root, files[j]), "rb") infileData = infile.read() infile.close() outfile = open(os.path.join(neededPath, files[j]), "wb") if files[j].endswith(".js"): outfile.write( js( infileData.decode("utf-8"), os.getcwd().replace("\\", "/") + "/" + root.replace("\\", "/")).encode("utf-8")) elif files[j].endswith(".html"): outfile.write( translate( html( "<script>var _manifest = " + json.dumps(manifestAll).replace( "</script>", "<\/script>") + ";</script>" + "<script>var _locale = " + json.dumps(openLocaleFileData) + ";</script>" + infileData.decode("utf-8"), os.getcwd().replace("\\", "/") + "/" + root.replace("\\", "/")), openLocaleFileData, openDefaultLocaleFileData, supportedLocales[i]).encode("utf-8")) elif files[j].endswith(".css"): outfile.write( css(infileData.decode("utf-8")).encode("utf-8")) else: outfile.write(infileData) outfile.close()
def js(content, location): initialContentLines = content.split("\n") finalContentLines = [] firstLocation = location finalContentLines.append("var _assets = {};") while len(initialContentLines) > 0: location = firstLocation initialContentLines[0] = initialContentLines[0].strip() if initialContentLines[0].startswith("// @import"): try: library = initialContentLines[0][11:] libraryName = "" if not ((location + "/" + library) in importedLibs): importedLibs.append(location + "/" + library) if location.startswith("http://") or location.startswith( "https://"): if not (library.startswith("http://") or library.startswith("https://")): library = location + "/" + library libraryName = library.split("/")[-1].split(".")[0] finalURL = urllib.parse.urljoin( library, ".") + library.split("/")[-1] if not finalURL.endswith(".js"): finalURL += ".js" output.action( _("importLibrary", [libraryName, finalURL])) location = urllib.parse.urljoin( "/".join( _replaceExceptFirst(library, "//", "/").split("/")), ".").rstrip("/") try: siteData = cache.get(finalURL) if siteData != False: finalContentLines.append( js(siteData.decode("utf-8"), location)) else: output.warning( _("unknownImport", [initialContentLines[0][3:]])) except: output.warning( _("unknownImport", [initialContentLines[0][3:]])) elif library.startswith("http://") or library.startswith( "https://"): libraryName = library.split("/")[-1].split(".")[0] output.action( _("importLibrary", [libraryName, library])) if not (location.startswith("http://") or location.startswith("https://")): location = urllib.parse.urljoin( "/".join( _replaceExceptFirst(library, "//", "/").split("/")), ".").rstrip("/") if not library.endswith(".js"): library += ".js" try: siteData = cache.get(library) if siteData != False: finalContentLines.append( js(siteData.decode("utf-8"), location)) else: output.warning( _("unknownImport", [initialContentLines[0][3:]])) except: output.warning( _("unknownImport", [initialContentLines[0][3:]])) else: oldLibrary = library library = location + "/" + library libraryName = library.split("/")[-1] if "/" in oldLibrary: location += "/" + "/".join( oldLibrary.split("/")[:-1]) output.action( _("importLibrary", [libraryName, library + ".js"])) try: libPath = library.split("/") libPath[-1] += ".js" file = open( os.path.join(*[os.sep, *libPath]).replace( ":", ":\\"), "r") fileData = file.read() file.close() finalContentLines.append(js(fileData, location)) except: output.warning( _("unknownImport", [initialContentLines[0][3:]])) else: output.action(_("circularImport", [library])) except: output.warning(_("illegalImport", [initialContentLines[0][3:]])) elif initialContentLines[0].startswith("// @import!"): try: library = initialContentLines[0][12:] libraryName = "" if location.startswith("http://") or location.startswith( "https://"): if not (library.startswith("http://") or library.startswith("https://")): library = location + "/" + library libraryName = library.split("/")[-1].split(".")[0] finalURL = urllib.parse.urljoin( library, ".") + library.split("/")[-1] if not finalURL.endswith(".js"): finalURL += ".js" output.action(_("importLibrary", [libraryName, finalURL])) location = urllib.parse.urljoin( "/".join( _replaceExceptFirst(library, "//", "/").split("/")), ".").rstrip("/") try: siteData = cache.get(finalURL) if siteData != False: finalContentLines.append( js(siteData.decode("utf-8"), location)) else: output.warning( _("unknownImport", [initialContentLines[0][3:]])) except: output.warning( _("unknownImport", [initialContentLines[0][3:]])) elif library.startswith("http://") or library.startswith( "https://"): libraryName = library.split("/")[-1].split(".")[0] output.action(_("importLibrary", [libraryName, library])) if not (location.startswith("http://") or location.startswith("https://")): location = urllib.parse.urljoin( "/".join( _replaceExceptFirst(library, "//", "/").split("/")), ".").rstrip("/") if not library.endswith(".js"): library += ".js" try: siteData = cache.get(library) if siteData != False: finalContentLines.append( js(siteData.decode("utf-8"), location)) else: output.warning( _("unknownImport", [initialContentLines[0][3:]])) except: output.warning( _("unknownImport", [initialContentLines[0][3:]])) else: oldLibrary = library library = location + "/" + library libraryName = library.split("/")[-1] if "/" in oldLibrary: location += "/" + "/".join(oldLibrary.split("/")[:-1]) output.action( _("importLibrary", [libraryName, library + ".js"])) try: libPath = library.split("/") libPath[-1] += ".js" file = open( os.path.join(*["/", *libPath]).replace(":", ":\\"), "r") fileData = file.read() file.close() finalContentLines.append(js(fileData, location)) except: output.warning( _("unknownImport", [initialContentLines[0][3:]])) except: output.warning(_("illegalImport", [initialContentLines[0][3:]])) elif initialContentLines[0].startswith("// @asset"): try: asset = initialContentLines[0][10:] assetName = "" initPath = asset.split("/")[:-1] if os.name == "nt": fullPath = os.path.join(location.replace("/", "\\"), asset) else: fullPath = urllib.parse.urljoin(location + "/", ".") + asset if not (fullPath in importedAssets): importedAssets.append(fullPath) if location.startswith("http://") or location.startswith( "https://"): originalAsset = asset if not (asset.startswith("http://") or asset.startswith("https://")): asset = location + "/" + asset assetName = asset.split("/")[-1].split(".")[0] output.action(_("importAsset", [assetName, asset])) location = urllib.parse.urljoin( "/".join( _replaceExceptFirst(library, "//", "/").split("/")), ".").rstrip("/") try: siteData = cache.get(asset) if siteData != False: finalContentLines.append( "_assets[\"" + originalAsset.replace("\"", "-") + "\"] = \"" + base64.b64encode( siteData).decode("utf-8") + "\";") else: output.warning( _("unknownAsset", [initialContentLines[0][3:]])) except: output.warning( _("unknownAsset", [initialContentLines[0][3:]])) elif asset.startswith("http://") or asset.startswith( "https://"): assetName = asset.split("/")[-1] output.action(_("importAsset", [assetName, asset])) try: siteData = cache.get(asset) if siteData != False: finalContentLines.append( "_assets[\"" + asset.replace("\"", "-") + "\"] = \"" + base64.b64encode( siteData).decode("utf-8") + "\";") else: output.warning( _("unknownAsset", [initialContentLines[0][3:]])) except: output.warning( _("unknownAsset", [initialContentLines[0][3:]])) else: oldAsset = asset assetName = asset.split("/")[-1] if "/" in asset: location += "/" + "/".join(asset.split("/")[:-1]) output.action(_("importAsset", [assetName, asset])) try: asset = asset.split("/")[-1] file = open(fullPath, "rb") fileData = file.read() file.close() finalContentLines.append( "_assets[\"" + assetName.replace("\"", "-") + "\"] = \"" + base64.b64encode(fileData).decode("utf-8") + "\";") except: output.warning( _("unknownAsset", [initialContentLines[0][3:]])) except: output.warning(_("illegalAsset", [initialContentLines[0][3:]])) else: finalContentLines.append(initialContentLines[0]) initialContentLines.pop(0) return jsmin.jsmin("\n".join(finalContentLines))
def html(content, location): minified = htmlmin.minify(content) imports = re.findall(r"\{\{ @import (.*?) \}\}", minified) for i in range(0, len(imports)): importStatement = "{{ @import " + imports[i] + " }}" library = imports[i] libraryName = "" if location.startswith("http://") or location.startswith("https://"): library = location + "/" + library libraryName = library.split("/")[-1].split(".")[0] finalURL = urllib.parse.urljoin(library, ".") + library.split("/")[-1] if not finalURL.endswith(".html"): finalURL += ".html" output.action(_("importLibrary", [libraryName, finalURL])) location = urllib.parse.urljoin( "/".join(_replaceExceptFirst(library, "//", "/").split("/")), ".").rstrip("/") try: siteData = cache.get(finalURL) if siteData != False: finalContentLines.append( js(siteData.decode("utf-8"), location)) else: output.warning( _("unknownImport", [initialContentLines[0][3:]])) except: output.warning(_("unknownImport", [initialContentLines[0][3:]])) elif library.startswith("http://") or library.startswith("https://"): libraryName = library.split("/")[-1].split(".")[0] output.action(_("importLibrary", [libraryName, library])) if not (location.startswith("http://") or location.startswith("https://")): location = urllib.parse.urljoin( "/".join( _replaceExceptFirst(library, "//", "/").split("/")), ".").rstrip("/") if not library.endswith(".html"): library += ".html" try: siteData = cache.get(library) if siteData != False: minified = minified.replace( importStatement, html(siteData.decode("utf-8"), location)) else: output.warning( _("unknownImport", ["@import " + imports[i]])) except: output.warning(_("unknownImport", [imports[i]])) else: library = location + "/" + library libraryName = library.split("/")[-1] output.action(_("importLibrary", [libraryName, library + ".html"])) try: libPath = library.split("/") libPath[-1] += ".html" file = open( os.path.join(*["/", *libPath]).replace(":", ":\\"), "r") fileData = file.read() file.close() minified = minified.replace(importStatement, html(fileData, location)) except: output.warning(_("unknownImport", [imports[i]])) return minified
def compile(infile, outfile, size=6144, definitions={}): file = open(infile, "r") code = file.read() file.close() sequence = code.split("\n") assembled = [0] * size position = 0 print("") for i in range(0, len(sequence)): currentLine = sequence[i].strip() currentLineSplit = currentLine.split(";")[0].replace( " ", "").replace(" ", "").split(" ") output.action(currentLine) for j in range(0, len(currentLineSplit)): if len(currentLineSplit[j]) > 1 and ( currentLineSplit[j][0] == "." or (currentLineSplit[j][0] == "@" and currentLineSplit[j][1] == ".")): # Data from definition if len(currentLineSplit[j] [1]) > 0 and currentLineSplit[j][0] == "@": if currentLineSplit[j][2:] in definitions: currentLineSplit[j] = "@" + definitions[ currentLineSplit[j][2:]] else: output.warning(" " + _("definitionDoesNotExist", [i + 1])) elif len(currentLineSplit[j][1]) > 0: if currentLineSplit[j][1:] in definitions: currentLineSplit[j] = definitions[currentLineSplit[j] [1:]] else: output.warning(" " + _("definitionDoesNotExist", [i + 1])) if currentLineSplit[0] == "#define": print(" " + _("definition")) original = currentLineSplit[1] replacement = " ".join(currentLineSplit[2:]) print(" " + _("definitionOriginal", [original])) print(" " + _("definitionReplacement", [original])) definitions[original] = replacement elif currentLineSplit[0] == "#data": print(" " + _("data")) startingAddress = int(currentLineSplit[1], 16) print(" " + _("dataAddress", [hex(startingAddress)[2:].zfill(2)])) if currentLineSplit[2][0] == "\"": # string print(" " + _("dataTypeString")) allocation = "" inString = False for j in range(0, len(currentLine)): if currentLine[j] == "\"": if inString: break else: inString = True elif inString: allocation += currentLine[j] allocation = allocation.replace("\\n", "\n") for j in range(0, len(allocation)): assembled[startingAddress + j] = ord(allocation[j]) elif len(currentLineSplit[2]) == 2: # byte print(" " + _("dataTypeByte")) assembled[startingAddress] = int(currentLineSplit[2], 16) elif len(currentLineSplit[2]) == 4: # int/uint print(" " + _("dataTypeIntUint")) assembled[startingAddress] = int(currentLineSplit[2][0:2], 16) assembled[startingAddress + 1] = int(currentLineSplit[2][2:4], 16) else: output.error(_("invalidDataStructure", [i + 1])) return elif currentLineSplit[0] == "#at": position = int(currentLineSplit[1], 16) elif currentLine != "" and currentLine[0] != ";": print(" " + _("instruction")) instructions = { "halt": 0x00, "allocate": 0x01, "copy": 0x02, "jump": 0x03, "write": 0x04, "read": 0x05, "add": 0x06, "sub": 0x07, "mul": 0x08, "div": 0x09, "mod": 0x0A, "equ": 0x0B, "neq": 0x0C, "ltn": 0x0D, "gtn": 0x0E, "func": 0x0F, "ret": 0x10, "sreg": 0x11, "sgp": 0x12, "cgp": 0x13, "dwrite": 0x14, "dread": 0x15, "bsl": 0x16, "bsr": 0x17, "and": 0x18, "or": 0x19, "xor": 0x1A, "onec": 0x1B, "outbin": 0xA0, "outdec": 0xA1, "outhex": 0xA2, "outasc": 0xA3, "in": 0xA4, "len": 0xA5, "strnum": 0xA6, "numstr": 0xA7, "dnumstr": 0xA8, "fopen": 0xB0, "fclose": 0xB1, "fwrite": 0xB2, "fwriter": 0xB3, "fappend": 0xB4, "fread": 0xB5, "freadr": 0xB6, "fsize": 0xB7, "fdel": 0xB8, "fmd": 0xB9, "frd": 0xBA, "fstart": 0xBB, "fnext": 0xBC, "fex": 0xBD, "fdir": 0xBE, "gpos": 0xC0, "gsize": 0xC1, "ginit": 0xC2, "gfill": 0xC3, "gpixel": 0xC4, "gline": 0xC5, "gfline": 0xC6, "grect": 0xC7, "gcircle": 0xC8, "gbin": 0xC9, "gdec": 0xCA, "ghex": 0xCB, "gasc": 0xCC, "gbmp": 0xCD, "gtouch": 0xCE, "sleep": 0xD0, "gyear": 0xD1, "gmonth": 0xD2, "gdate": 0xD3, "gday": 0xD4, "ghour": 0xD5, "gmin": 0xD6, "gsec": 0xD7, "sdate": 0xD8, "stime": 0xD9 } if currentLineSplit[0] in instructions: instruction = instructions[currentLineSplit[0]] params = [] print(" " + _("instructionInstruction", [currentLineSplit[0], hex(instruction)[2:].zfill(2)])) for i in range(0, len(currentLineSplit) - 1): params.append(currentLineSplit[i + 1]) print(" " + _("instructionParameters", [" ".join(str(k) for k in params)])) for i in range(0, len(params)): if params[i].strip() != "": if params[i][0] == "@": assembled[position] = 0xFF assembled[position + 1] = i if len(params[i]) == 3: assembled[position + 2] = 0 assembled[position + 3] = int( params[i][1:], 16) else: assembled[position + 2] = int( params[i][1:3], 16) assembled[position + 3] = int( params[i][3:5], 16) elif params[i][0] == "$": registerConversions = { "PC": 0, "RM": 1, "AR": 2, "ER": 3, "FR": 4, "PM1": 5, "PM2": 6, "PM3": 7, "GX": 8, "GY": 9, "GW": 10, "GH": 11, "GP1": 12, "GP2": 13, "GP3": 14, "GP4": 15, "GP5": 16, "GP6": 17, "GP7": 18, "GP8": 19 } assembled[position] = 0xFE assembled[position + 1] = i assembled[position + 2] = 0 assembled[position + 3] = registerConversions[params[i][1:]] else: assembled[position] = 0xFD assembled[position + 1] = i if len(params[i].strip()) == 2: assembled[position + 2] = 0 assembled[position + 3] = int( params[i].strip(), 16) else: assembled[position + 2] = int( params[i].strip()[0:2], 16) assembled[position + 3] = int( params[i].strip()[2:4], 16) position += 4 assembled[position] = instruction position += 1 else: output.error(_("invalidInstruction", [str(i + 1)])) sys.exit(1) while assembled[len(assembled) - 1] == 0: assembled.pop() file = open(outfile, "wb") file.write(bytearray(assembled)) file.close() return { "definitions": definitions, "stats": [len(assembled), size, (len(assembled) / size) * 100] }
if len(args) > 3: outfile = args[3] else: outfile = "".join(infile.split("/")[-1].split(".")[:-1]) + ".gbn" output.returns(_("programUsage", compiler.compile(infile, outfile, size)["stats"])) else: output.error(_("invalidCommandStructure")) sys.exit(1) elif args[1] == "build": size = useIntOrDefault(storage.read("size"), 6144) filesCompiled = 0 librariesCompiled = 0 output.action(_("cleanUpBuildDir")) try: shutil.rmtree("build") except: pass definitions = {} for compilePass in range(0, 2): if compilePass == 0: output.action(_("buildLibraries")) else: output.action(_("buildFiles")) for root, subdirs, files in os.walk(".", topdown = True):
storage.write(name, data) output.returns(_("varWriteReturn", [name, data])) else: output.error(_("invalidCommandStructure")) sys.exit(1) else: output.error(_("invalidCommandStructure")) sys.exit(1) except: output.error(_("varError")) sys.exit(1) elif args[1] == "build": if len(args) > 2: if args[2] == "app": output.action(_("buildDir", [os.getcwd()])) manifest = {} manifestLoads = {} try: manifestFile = open( os.path.join(os.getcwd(), "manifest.json"), "r") manifest = json.load(manifestFile) except: output.error(_("invalidManifest")) sys.exit(1) try: manifestLoads["package"] = manifest["package"] manifestLoads["version"] = manifest["version"]