|
| 1 | +import os |
| 2 | +import mimetypes |
| 3 | +from typing import Optional |
| 4 | +from dataclasses import dataclass |
| 5 | +from webui import webui |
| 6 | + |
| 7 | + |
| 8 | +@dataclass |
| 9 | +class VirtualFile: |
| 10 | + path: str |
| 11 | + body: str |
| 12 | + |
| 13 | + |
| 14 | +virtual_files: list[VirtualFile] = [] |
| 15 | +# flat list: [dir_key, index_path, dir_key, index_path, …] |
| 16 | +index_files: list[str] = [] |
| 17 | + |
| 18 | + |
| 19 | +def build_vfs(directory: str): |
| 20 | + """ |
| 21 | + Scan a directory tree and populate the global virtual file lists. |
| 22 | +
|
| 23 | + Walks through every file under `directory`, reads its contents as raw bytes |
| 24 | + (decoded via Latin-1 to preserve 1:1 byte -> character mapping), and appends |
| 25 | + a `VirtualFile(path, body)` entry to `virtual_files`. Detects any files |
| 26 | + named `index.*`, recording them in `index_files`. |
| 27 | +
|
| 28 | + Args: |
| 29 | + directory: The root directory whose files will be loaded into memory. |
| 30 | +
|
| 31 | + Globals: |
| 32 | + virtual_files: Cleared and then extended with VirtualFile instances |
| 33 | + for each file found. |
| 34 | + index_files: Cleared and then populated with flat [dir_key, index_path] |
| 35 | + pairs corresponding to each directory’s index file. |
| 36 | + """ |
| 37 | + global virtual_files, index_files |
| 38 | + virtual_files.clear() |
| 39 | + index_files.clear() |
| 40 | + |
| 41 | + index_map: dict[str,str] = {} |
| 42 | + |
| 43 | + for root, _, filenames in os.walk(directory): |
| 44 | + rel_dir = os.path.relpath(root, directory).replace('\\','/') |
| 45 | + if rel_dir == '.': |
| 46 | + rel_dir = '' |
| 47 | + |
| 48 | + for fn in filenames: |
| 49 | + full = os.path.join(root, fn) |
| 50 | + vpath = f"/{rel_dir}/{fn}".replace('//','/') |
| 51 | + |
| 52 | + # read raw bytes → latin-1 so we preserve 1:1 in the str |
| 53 | + with open(full, 'rb') as f: |
| 54 | + body = f.read().decode('latin-1') |
| 55 | + |
| 56 | + virtual_files.append(VirtualFile(path=vpath, body=body)) |
| 57 | + |
| 58 | + if fn.startswith("index."): |
| 59 | + dir_key = f"/{rel_dir}/".replace('//','/') |
| 60 | + if dir_key not in index_map: |
| 61 | + index_map[dir_key] = vpath |
| 62 | + |
| 63 | + # flatten map into list |
| 64 | + for dk, ip in index_map.items(): |
| 65 | + index_files.extend([dk, ip]) |
| 66 | + |
| 67 | + |
| 68 | +def virtual_file_system(path: str) -> Optional[VirtualFile]: |
| 69 | + """ |
| 70 | + Returns the matching VirtualFile or None. |
| 71 | + """ |
| 72 | + global virtual_files |
| 73 | + |
| 74 | + for vf in virtual_files: |
| 75 | + if vf.path == path: |
| 76 | + return vf |
| 77 | + return None |
| 78 | + |
| 79 | + |
| 80 | +def vfs(path: str) -> Optional[str]: |
| 81 | + """ |
| 82 | + Handler function for set_file_handler(), |
| 83 | + Type needed: Callable[[str], Optional[str]] |
| 84 | + - If exact file found, return "200 OK" headers + body. |
| 85 | + - Else, check index_files for a 302 redirect. |
| 86 | + - Else, return None. |
| 87 | + """ |
| 88 | + global index_files |
| 89 | + |
| 90 | + # Try exact file |
| 91 | + vf = virtual_file_system(path) |
| 92 | + if vf is not None: |
| 93 | + length = len(vf.body) # latin-1 str length == byte length |
| 94 | + ctype = mimetypes.guess_type(path)[0] or "application/octet-stream" |
| 95 | + header = ( |
| 96 | + "HTTP/1.1 200 OK\r\n" |
| 97 | + f"Content-Type: {ctype}\r\n" |
| 98 | + f"Content-Length: {length}\r\n" |
| 99 | + "Cache-Control: no-cache\r\n\r\n" |
| 100 | + ) |
| 101 | + return header + vf.body |
| 102 | + |
| 103 | + # Not found; check for index redirect |
| 104 | + redirect_path = path |
| 105 | + if not redirect_path.endswith('/'): |
| 106 | + redirect_path += '/' |
| 107 | + |
| 108 | + for i in range(0, len(index_files), 2): |
| 109 | + if index_files[i] == redirect_path: |
| 110 | + location = index_files[i+1] |
| 111 | + header = ( |
| 112 | + "HTTP/1.1 302 Found\r\n" |
| 113 | + f"Location: {location}\r\n" |
| 114 | + "Cache-Control: no-cache\r\n\r\n" |
| 115 | + ) |
| 116 | + return header |
| 117 | + |
| 118 | + # No match; will default to normal WebUI file system behavior |
| 119 | + return None |
| 120 | + |
| 121 | + |
| 122 | +def exit_app(e: webui.Event): |
| 123 | + webui.exit() |
| 124 | + |
| 125 | + |
| 126 | +def main(): |
| 127 | + # Create new window |
| 128 | + react_window = webui.Window() |
| 129 | + |
| 130 | + # Set window size |
| 131 | + react_window.set_size(550, 450) |
| 132 | + |
| 133 | + # Set window position |
| 134 | + react_window.set_position(250, 250) |
| 135 | + |
| 136 | + # Allow multi-user connection to WebUI window |
| 137 | + webui.set_config(webui.Config.multi_client, True) |
| 138 | + |
| 139 | + # Disable WebUI's cookies |
| 140 | + webui.set_config(webui.Config.use_cookies, True) |
| 141 | + |
| 142 | + # Bind react HTML element IDs with a python function |
| 143 | + react_window.bind("Exit", exit_app) |
| 144 | + |
| 145 | + # VFS (Virtual File System) Example |
| 146 | + # |
| 147 | + # 1. Build your list of files |
| 148 | + |
| 149 | + # 2. Create a function with this type: |
| 150 | + # Callable[[str], Optional[str]] |
| 151 | + # |
| 152 | + # 3. The parameter should be for a file name |
| 153 | + # and the return string is the header + body. |
| 154 | + # Ex. |
| 155 | + # def my_handler(filename: str) -> Optional[str]: |
| 156 | + # response_body = "Hello, World!" |
| 157 | + # response_headers = ( |
| 158 | + # "HTTP/1.1 200 OK\r\n" |
| 159 | + # "Content-Type: text/plain\r\n" |
| 160 | + # f"Content-Length: {len(response_body)}\r\n" |
| 161 | + # "\r\n" |
| 162 | + # ) |
| 163 | + # return response_headers + response_body |
| 164 | + # |
| 165 | + # 4. pass that function into the set_file_handler(<handler>) |
| 166 | + |
| 167 | + # Build out the vfs and index list |
| 168 | + build_vfs("./webui-react-example/build") |
| 169 | + |
| 170 | + # Set a custom files handler |
| 171 | + react_window.set_file_handler(vfs) |
| 172 | + |
| 173 | + # Show the React window |
| 174 | + # react_window.show_browser("index.html", webui.Browser.Chrome) |
| 175 | + react_window.show("index.html") |
| 176 | + |
| 177 | + # Wait until all windows get closed |
| 178 | + webui.wait() |
| 179 | + |
| 180 | + # Free all memory resources (Optional) |
| 181 | + webui.clean() |
| 182 | + |
| 183 | + print('Thank you.') |
| 184 | + |
| 185 | + |
| 186 | +if __name__ == "__main__": |
| 187 | + main() |
0 commit comments