#!/usr/bin/env python """ Script to parse GtkBuilder XML file for signal handler references and generate code to add them to GtkBuilder. This prevents having to add them to the global namespace. """ import optparse import os import re import sys from xml.etree import ElementTree as ET def find_handlers(xml_filename, excludes=[]): def is_excluded(name, excludes): for exclude in excludes: m = re.match(exclude, name) if m: return True return False tree = ET.parse(xml_filename) root = tree.getroot() handlers = set() signals = root.findall(".//signal") for signal in signals: handler = signal.attrib["handler"] if not is_excluded(handler, excludes): handlers.add(handler) return sorted(handlers) def render_handlers(handlers): text = '' for handler in handlers: text += '\tg_hash_table_insert(hash, "%s", G_CALLBACK(%s));\n' % ( handler, handler) return text.rstrip() def main(args): p = optparse.OptionParser(usage="%prog [-o FILE] XMLFILE") p.add_option("-o", "--output", metavar="FILE", dest="output_file", default="-", help="write the output to this file (default `-' for stdin)") p.add_option("-t", "--template", metavar="FILE", dest="template_file", default=None, help="the template file to perform replacements in") opts, args = p.parse_args(args) output_file = None try: if opts.template_file is None: p.error("invalid template file, use -t argument to specify") template = '' with open(opts.template_file) as tmpl_file: template = tmpl_file.read() if opts.output_file == "-": output_file = sys.stdout else: output_file = open(opts.output_file, 'w') args = args[1:] if len(args) == 0: p.error("invalid XMLFILE argument, expecting a filename, got none") elif len(args) > 1: p.error("too many XMLFILE arguments, expecting a single filename") #handlers = find_handlers(args[0], ["gtk_.+"]) handlers = find_handlers(args[0]) handlers = render_handlers(handlers) replacement = template.replace('@callback_map@', handlers) output_file.write(replacement) finally: if output_file is not None and output_file is not sys.stdout: output_file.close() return 0 if __name__ == "__main__": sys.exit(main(sys.argv))