Пример #1
0
	def Make(self):
		self.UpdateRPL()
		romfile = self.romsec.get()
		try: os.unlink(romfile)
		except OSError as err:
			if err.errno == 2: pass
			else:
				helper.err('Could not delete "%s": %s' % (romfile, err.strerror))
				return 1
			#endif
		#endtry
		start = time()
		try: self.rpl.importData(romfile, self.dirsec.get(), self.what, self.args.blank)
		except (rpl.RPLError, helper.RPLInternal) as err:
			self.ielbl.config(text=unicode(err))
		else:
			self.ielbl.config(text="Finished %s. Time taken: %.3fs" % (
				"test build" if self.args.blank else "building",
				time() - start
			))
Пример #2
0
def main():
	parser = argparse.ArgumentParser(
		description  = "CRC32 by Wa (logicplace.com)\n"
		"Allows you to retrieve CRC32s of sections of a file. Prints"
		" checksums to stdout in RPL format.\n"
		"Part of Imperial Exchange.",

		#usage        = "Usage: %(prog)s File Range...",

		formatter_class=argparse.RawTextHelpFormatter,
		add_help     = False,
		prefix_chars = "-"
	)
	parser.add_argument("--help", "-h", "-?",
		help    = argparse.SUPPRESS,
		action  = "store_true"
	)
	parser.add_argument("file",
		help  = "Binary file to perform checksums on.",
		nargs = "?"
	)
	parser.add_argument("ranges",
		help  = "RPL range types to interpret and use as address scopes for checksums.\n"
		"If omitted, checksum entire file.",
		nargs = "*"
	)
	if len(sys.argv) == 1:
		parser.print_help
		return 0
	#endif
	args = parser.parse_args(sys.argv[1:])

	if args.help:
		parser.print_help()
		return 0
	elif not args.file:
		parser.error("File argument required.")
	#endif

	f = open(args.file, "rb")

	# Checksum entire file
	if not args.ranges:
		print u"crc32: %s" % unicode(HexNum(crc32(f.read()) & 0xFFFFFFFF))
		return 0
	#endif

	rpl = RPL()
	check = RPLTypeCheck(rpl, "check", "range")
	out = []
	# Checksum all ranges
	for x in args.ranges:
		try: data = check.verify(rpl.parseData(x))
		except RPLError:
			err("Ranges should be RPL range type.")
			return 1
		#endtry

		# Since nothing's going to process this list, we can leave x as is
		out.append(List([x, HexNum(ROM.getCRC(f, data))]))
	#endfor

	if len(out) == 1: print u"crc32: %s" % unicode(out[0])
	else: print u"crc32: %s" % unicode(List(out))
	return 0
Пример #3
0
	def run(self, args):
		if Tk is None:
			print("Please install python-tk!")
			return 1
		#endif
		self.args, self.what, self.defs, self.rpl = args, [], dict(args.define), rpl.RPL()
		romfile, rplfile, folder = "", "", ""
		romnote, rplnote = u"", u""

		startup = self.config("StartupMode", "cli,smart,session").replace(" ", "").split(",")
		for x in startup:
			try:
				romfile, rplfile, folder, romnote, rplnote = {
					"cli": self.cliFiles,
					"smart": self.guessFiles,
					"session": self.sessionFiles
				}[x](romfile, rplfile, folder)
			except KeyError: helper.err("Unknown startup mode %s." % x)
		#endfor

		####### Create GUI. #######
		root = Tk.Tk()
		root.title(TITLE)

		# Add menu.
		menubar = Tk.Menu(root)
		filemenu = Tk.Menu(menubar, tearoff=0)
		filemenu.add_command(label="Run", command=self.Run)
		filemenu.add_command(label="Make", command=self.Make)
		#filemenu.add_separator()
		#filemenu.add_command(label="New ROM", command=self.)
		#filemenu.add_command(label="New RPL", command=self.)
		filemenu.add_separator()
		filemenu.add_command(label="Exit", command=root.quit)
		menubar.add_cascade(label="File", menu=filemenu)
		editmenu = Tk.Menu(menubar, tearoff=0)
		editmenu.add_command(label="Defs struct", command=self.Defines)
		#editmenu.add_command(label="Edit mode", command=self.)
		editmenu.add_separator()
		editmenu.add_command(label="Edit ROM externally", command=self.EditROM)
		editmenu.add_command(label="Edit RPL externally", command=self.EditRPL)
		editmenu.add_separator()
		editmenu.add_command(label="Preferences", command=self.Preferences)
		menubar.add_cascade(label="Edit", menu=editmenu)
		helpmenu = Tk.Menu(menubar, tearoff=0)
		helpmenu.add_command(label="Help", command=self.Help)
		helpmenu.add_command(label="About", command=self.About)
		menubar.add_cascade(label="Help", menu=helpmenu)
		root.config(menu=menubar)

		# Add sections.
		romfile = StringVar(text=romfile)
		self.romsec = Section(self.rpl, root, text="ROM", entryvar=romfile, note=romnote)
		self.romsec.pack(fill=Tk.X)
		rplfile = StringVar(text=rplfile)
		self.rplsec = Section(
			self.rpl, root, text="RPL", entryvar=rplfile, note=rplnote,
			filetypes=[("RPL Files", "*.rpl")],
		)
		self.rplsec.pack(fill=Tk.X)
		folder = StringVar(text=folder)
		self.dirsec = Section(self.rpl, root, text="Resource Directory", entryvar=folder, isdir=True)
		self.dirsec.pack(fill=Tk.X)

		# Setup session saving.
		def updateSession(name, index, mode):
			self.saveconfig({
				"SessionROM":    romfile,
				"SessionRPL":    rplfile,
				"SessionFolder": folder
			})
		#enddef
		romfile.trace("w", updateSession)
		rplfile.trace("w", updateSession)
		folder.trace("w", updateSession)

		# Import/Export buttons.
		self.ieframe = ieframe = Tk.Frame(root)
		impbut = Tk.Button(ieframe, text="Import", command=self.Import)
		impbut.grid(row=0, column=0, sticky="news")
		expbut = Tk.Button(ieframe, text="Export", command=self.Export)
		expbut.grid(row=0, column=1, sticky="news")
		self.ielbl = Note(ieframe)
		self.ielbl.grid(row=1, columnspan=2, sticky=Tk.N)
		ieframe.grid_columnconfigure(0, weight=1)
		ieframe.grid_columnconfigure(1, weight=1)
		ieframe.grid_rowconfigure(0, weight=1)
		ieframe.pack(fill=Tk.BOTH, expand=1)

		# Contine/Cancel buttons.
		self.ccframe = ccframe = Tk.Frame(root)
		contbut = Tk.Button(ccframe, text="Continue", command=self.Continue)
		contbut.grid(row=0, column=0, sticky="news")
		cnclbut = Tk.Button(ccframe, text="Cancel", command=self.Cancel)
		cnclbut.grid(row=0, column=0, sticky="news")
		ccframe.grid_columnconfigure(0, weight=1)
		ccframe.grid_columnconfigure(1, weight=1)
		ccframe.grid_rowconfigure(0, weight=1)

		# All done, show it.
		root.mainloop()
Пример #4
0
def main():
	global debug
	parser = argparse.ArgumentParser(
		description  = TITLE + " by Wa (logicplace.com)\n"
		"Easily replace resources in ROMs (or other binary formats) by use of"
		" a standard descriptor format.",

		usage        = "Usage: %(prog)s [options] {-x | -i | -m} ROM RPL [Struct names...]\n"
		"       %(prog)s -h [RPL | lib]\n"
		"       %(prog)s -t [RPL] [-l libs] [-s Struct types...]",

		formatter_class=argparse.RawDescriptionHelpFormatter,
		add_help     = False,
	)
	action = parser.add_mutually_exclusive_group()
	action.add_argument("--help", "-h", "-?", #"/?", "/h",
		help    = argparse.SUPPRESS,
		action  = "store_true"
	)
	action.add_argument("--version", #"/v",
		help    = "Show version number and exit.",
		action  = "store_true"
	)
	action.add_argument("--import", "-i", #"/i",
		dest    = "importing",
		help    = "Import resources in the ROM via the descriptor.",
		nargs   = 2,
		metavar = ("ROM", "RPL")
	)
	action.add_argument("--export", "-x", #"/x",
		help    = "Export resources from the ROM via the descriptor.",
		nargs   = 2,
		metavar = ("ROM", "RPL")
	)
	action.add_argument("--makefile", "-m", "--binary", "-b", #"/m", "/b",
		help    = "Create a new file. This will overwrite an existing file.\n"
		"Implies -r",
		nargs   = 2,
		metavar = ("ROM", "RPL")
	)
	action.add_argument("--template", "-t", #"/t",
		help    = "Generate a descriptor skeleton for the given module.\n"
		'Use "rpl" to generate the basic one.\n'
		"If no destination is given, result is printed to stdout.",
		action  = "store_true"
	)
	action.add_argument("--run",
		help    = "Run a RPL without involving a ROM. Implies --romless",
		nargs   = 1,
		metavar = ("RPL")
	)
	action.add_argument("--gui",
		help    = "Open the GUI.",
		action  = "store_true"
	)
	parser.add_argument("--libs", "-l", #"/l",
		help    = "What libs to load for template creation.",
		nargs   = "*"
	)
	parser.add_argument("--structs", "-s", #"/s",
		help    = "What structs to include in the template.",
		nargs   = "*"
	)
	parser.add_argument("--romless", "-r", #"/r",
		help    = "Do not perform validations in ROM struct, and"
		" do not warn if there isn't a ROM struct.",
		action  = "store_true"
	)
	parser.add_argument("--blank",
		help    = "Run action without creating or modifying a ROM file.",
		action  = "store_true"
	)
	parser.add_argument("--define", "-d", #"/d",
		help    = "Define a value that can be referenced by @Defs.name\n"
		"Values are interpreted as RPL data, be aware of this in regards to"
		" strings vs. literals.",
		action  = "append",
		nargs   = 2,
		metavar = ("name", "value"),
		default = []
	)
	parser.add_argument("--folder", "-f", #"/f",
		help    = "Folder to export to, or import from. By default this is the"
		" current folder.",
		default = "."
	)
	parser.add_argument("--debug",
		help    = argparse.SUPPRESS,
		action  = "store_true"
	)
	parser.add_argument("args", nargs="*", help=argparse.SUPPRESS)

	args = parser.parse_args(sys.argv[1:])

	debug = args.debug

	# Windows help flag.
	if args.args and args.args[0] == "/?":
		args.help = True
		args.args.pop(0)
	#endif

	if args.help:
		if len(args.args) >= 1:
			if args.args[0][-3:] == "rpl":
				# Load a RPL file's help.
				thing = rpl.RPL()
				thing.parse(args.args[0], ["RPL"])
				rplStruct = thing.childrenByType("RPL")
				if not rplStruct: return 0
				help = rplStruct[0]["help"].get()

				# Abuse argparse's help generator.
				filehelp = argparse.ArgumentParser(
					description = help[0].get(),
					usage       = argparse.SUPPRESS
				)
				for x in help[1:]:
					defkey, defhelp = tuple([y.get() for y in x.get()])
					filehelp.add_argument("-d" + defkey, help=defhelp)
				#endfor
				filehelp.print_help()
			else:
				# Load a lib's help.
				tmp = getattr(__import__("rpl." + args.args[0], globals(), locals()), args.args[0])
				tmp.printHelp(args.args[1:])
			#endif
		else: parser.print_help()
	elif args.version:
		print(TITLE + " - v" + VERSION)
	elif args.template:
		thing = rpl.RPL()
		# Load requested libs.
		if args.libs:
			rplStruct = rpl.StructRPL()
			rplStruct["lib"] = rpl.List(map(rpl.String, args.libs))
			thing.load(rplStruct)
		#endif
		structs = args.structs
		if structs and not args.romless: structs = ["ROM"] + structs
		print(thing.template(structs))
	elif args.run:
		thing = rpl.RPL()

		thing.parse(args.run[0])

		# Do defines.
		for x in args.define: thing.addDef(*x)

		# Run RPL.
		start = time()
		thing.run(args.folder, args.args)
		print("Finished executing. Time taken: %.3fs" % (time() - start))
	elif args.importing or args.export or args.makefile:
		# Regular form.
		thing = rpl.RPL()

		# Grab filenames.
		if args.importing:  romfile, rplfile = tuple(args.importing)
		elif args.export:   romfile, rplfile = tuple(args.export)
		elif args.makefile: romfile, rplfile = tuple(args.makefile)

		thing.parse(rplfile)

		if not args.romless and not args.makefile:
			romstream = helper.stream(romfile)
			roms = thing.childrenByType("ROM")
			for x in roms:
				successes, fails = x.validate(romstream)
				if fails:
					print("Failed the following checks: %s" % helper.list2english([
						("%s[%i]" % fail
						if type(fail) is tuple else
						fail) for fail in fails
					]))
					answer = "."
					while answer not in "yYnN": answer = raw_input("Continue anyway (y/n)? ")
					if answer in "nN": return 1
				#endif
			#endfor
		#endif

		# Do defines.
		for x in args.define: thing.addDef(*x)

		# Run imports.
		start = time()
		if args.importing:
			thing.importData(romstream, args.folder, args.args, args.blank)
			helper.prntc("Finished %s." % ("blank import" if args.blank else "importing"))
			romstream.close()
		elif args.export:
			thing.exportData(romstream, args.folder, args.args, args.blank)
			helper.prntc("Finished %s." % ("blank export" if args.blank else "exporting"))
			romstream.close()
		elif args.makefile:
			try: os.unlink(romfile)
			except OSError as err:
				if err.errno == 2: pass
				else:
					helper.err('Could not delete "%s": %s' % (romfile, err.strerror))
					return 1
				#endif
			#endtry
			thing.importData(romfile, args.folder, args.args, args.blank)
			helper.prntc("Finished %s." % ("build test" if args.blank else "building"))
		#endif
		print("Time taken: %.3fs" % (time() - start))
	else:
		return GUI().run(args)
	#endif
	return 0
Пример #5
0
				if row[0].get() == key: return row[1].get()
			#endfor
		#endif
		return None
	#enddef

	def set(self, key, value=""):
		for row in self.rows:
			if row[0].get() == key:
				row[1].delete(0, Tk.END)
				row[1].insert(0, value)
				return True
			#endif
		#endfor
		return False
	#enddef
#endclass

if __name__ == "__main__":
	try: sys.exit(main())
	except (EOFError, KeyboardInterrupt):
		if debug: raise
		print("\nOperations terminated by user.")
		sys.exit(0)
	except (rpl.RPLError, helper.RPLInternal) as err:
		if debug: raise
		helper.err(err)
		sys.exit(1)
	#endtry
#endif