|
| 1 | +import xml.etree.ElementTree as ET |
| 2 | +import sys, os |
| 3 | +import remi.gui as widget_list |
| 4 | + |
| 5 | +try: |
| 6 | + import lxml.etree as lxml_ET |
| 7 | + |
| 8 | + USE_LXML = True |
| 9 | +except ImportError: |
| 10 | + USE_LXML = False |
| 11 | + |
| 12 | + |
| 13 | +class RemiXMLTranslator: |
| 14 | + def __init__(self): |
| 15 | + # No longer need widget_map - we'll use dynamic class resolution |
| 16 | + pass |
| 17 | + |
| 18 | + def translate_xml_to_code_from_root(self, root, file_path=None): |
| 19 | + """Translate XML root element to Remi Python code.""" |
| 20 | + code_lines = [] |
| 21 | + code_lines.append("from remi import server, gui") |
| 22 | + code_lines.append("") |
| 23 | + |
| 24 | + # Generate code for root widget |
| 25 | + root_var = self._generate_widget_code(root, code_lines, "root", file_path) |
| 26 | + code_lines.append("") # Add empty line after root initialization |
| 27 | + |
| 28 | + # Add return statement |
| 29 | + code_lines.append(f"return {root_var}") |
| 30 | + |
| 31 | + return "\n".join(code_lines) |
| 32 | + |
| 33 | + def _generate_widget_code( |
| 34 | + self, element, code_lines: list[str], var_name: str, file_path: str = None |
| 35 | + ): |
| 36 | + """Recursively generate code for a widget and its children.""" |
| 37 | + tag = element.tag |
| 38 | + if not hasattr(widget_list, tag): |
| 39 | + line_info = "" |
| 40 | + if USE_LXML and hasattr(element, "sourceline"): |
| 41 | + line_info = ( |
| 42 | + f" at {os.path.abspath(file_path)}, line {element.sourceline}" |
| 43 | + ) |
| 44 | + elif file_path: |
| 45 | + line_info = f" in {os.path.abspath(file_path)}" |
| 46 | + raise ValueError(f'Unknown widget type: "{tag}"{line_info}') |
| 47 | + widget_class = tag |
| 48 | + |
| 49 | + # Collect attributes |
| 50 | + kwargs = {} |
| 51 | + for attr, value in element.attrib.items(): |
| 52 | + match attr: |
| 53 | + case "width" | "height": |
| 54 | + kwargs[attr] = value |
| 55 | + case _: |
| 56 | + kwargs[attr] = f'"{value}"' |
| 57 | + |
| 58 | + # Generate instantiation |
| 59 | + args_str = ", ".join([f"{k}={v}" for k, v in kwargs.items()]) |
| 60 | + code_lines.append(f"{var_name} = gui.{widget_class}({args_str})") |
| 61 | + |
| 62 | + # Generate code for children |
| 63 | + child_vars = [] |
| 64 | + for i, child in enumerate(element): |
| 65 | + child_var = f"{var_name}_{child.tag}_{i}" |
| 66 | + child_vars.append(child_var) |
| 67 | + self._generate_widget_code(child, code_lines, child_var, file_path) |
| 68 | + key = child.attrib.get("key", "") |
| 69 | + if key: |
| 70 | + code_lines.append(f"{var_name}.append({child_var}, '{key}')") |
| 71 | + else: |
| 72 | + code_lines.append(f"{var_name}.append({child_var})") |
| 73 | + # Add empty line after append/add_tab, except for the last child |
| 74 | + if i < len(element) - 1: |
| 75 | + code_lines.append( |
| 76 | + "" |
| 77 | + ) # Add empty line for readability after append/add_tab |
| 78 | + |
| 79 | + return var_name |
| 80 | + |
| 81 | + def translate_xml_file_to_code(self, xml_file_path: str): |
| 82 | + """Translate XML file to Remi Python code.""" |
| 83 | + if USE_LXML: |
| 84 | + tree = lxml_ET.parse(xml_file_path) |
| 85 | + root = tree.getroot() |
| 86 | + else: |
| 87 | + with open(xml_file_path, "r", encoding="utf-8") as f: |
| 88 | + xml_string = f.read() |
| 89 | + root = ET.fromstring(xml_string) |
| 90 | + return self.translate_xml_to_code_from_root(root, xml_file_path) |
| 91 | + |
| 92 | + |
| 93 | +# Command line usage |
| 94 | +def main(): |
| 95 | + if len(sys.argv) != 2: |
| 96 | + print("Usage: python translator.py <xml_file>") |
| 97 | + sys.exit(1) |
| 98 | + |
| 99 | + xml_file = sys.argv[1] |
| 100 | + translator = RemiXMLTranslator() |
| 101 | + code = translator.translate_xml_file_to_code(xml_file) |
| 102 | + |
| 103 | + # Parse the generated code |
| 104 | + lines = code.split("\n") |
| 105 | + import_line = lines[0] |
| 106 | + code_lines = lines[2:-1] # Remove import, empty line, and return statement |
| 107 | + ui_code = "\n".join( |
| 108 | + " " + line if line.strip() else "" for line in code_lines |
| 109 | + ) |
| 110 | + |
| 111 | + base_name = os.path.splitext(xml_file)[0] |
| 112 | + py_file = base_name + ".py" |
| 113 | + |
| 114 | + full_code = f"""{import_line} |
| 115 | +
|
| 116 | +class MyApp(server.App): |
| 117 | + def __init__(self, *args): |
| 118 | + super(MyApp, self).__init__(*args) |
| 119 | + |
| 120 | + def main(self): |
| 121 | +{ui_code} |
| 122 | + # add your code here |
| 123 | + |
| 124 | + return root |
| 125 | +
|
| 126 | +if __name__ == "__main__": |
| 127 | + server.start(MyApp) |
| 128 | +""" |
| 129 | + |
| 130 | + with open(py_file, "w", encoding="utf-8") as f: |
| 131 | + f.write(full_code) |
| 132 | + |
| 133 | + print(f"Generated {py_file}") |
| 134 | + |
| 135 | + |
| 136 | +if __name__ == "__main__": |
| 137 | + main() |
0 commit comments