|
| 1 | +import json |
| 2 | +from .utils import ( |
| 3 | + extract_text, extract_label, extract_property, |
| 4 | + validate_tpl_header, move_to_tool_data_section |
| 5 | +) |
| 6 | + |
| 7 | + |
| 8 | +class TPLReader: |
| 9 | + """Class for reading and parsing Photoshop TPL files.""" |
| 10 | + |
| 11 | + def __init__(self, file_path): |
| 12 | + self.file_path = file_path |
| 13 | + self.tpl_data = {} |
| 14 | + |
| 15 | + def read_tool(self, file): |
| 16 | + """ |
| 17 | + Reads tool data from the TPL file and extracts relevant properties. |
| 18 | +
|
| 19 | + Parameters: |
| 20 | + file (BinaryIO): The file object of the TPL file to be read. |
| 21 | +
|
| 22 | + Returns: |
| 23 | + dict: A dictionary containing the tool data extracted from the file. |
| 24 | + """ |
| 25 | + tpl = {} |
| 26 | + |
| 27 | + while True: |
| 28 | + # Extract the tool name |
| 29 | + tool_name = extract_text(file) |
| 30 | + # Skip 10 bytes (typically padding or non-essential data) |
| 31 | + file.read(10) |
| 32 | + |
| 33 | + # Extract the tool type |
| 34 | + tool_type = extract_label(file).decode('ascii', errors='ignore') |
| 35 | + |
| 36 | + # Initialize the tool type in the dictionary if not already present |
| 37 | + if tool_type not in tpl: |
| 38 | + tpl[tool_type] = [] |
| 39 | + |
| 40 | + # Extract the number of properties and their values |
| 41 | + count = int(file.read(4).hex(), 16) |
| 42 | + properties = [extract_property(file) for _ in range(count)] |
| 43 | + |
| 44 | + # Append the tool data to the dictionary |
| 45 | + tpl[tool_type].append({ |
| 46 | + "name": tool_name.split("=")[-1], |
| 47 | + "properties": properties |
| 48 | + }) |
| 49 | + |
| 50 | + # Check if there are more tools to read |
| 51 | + if len(file.read(4)) != 4: |
| 52 | + break |
| 53 | + file.seek(-4, 1) |
| 54 | + |
| 55 | + return tpl |
| 56 | + |
| 57 | + def read_tpl(self): |
| 58 | + """ |
| 59 | + Reads and parses the TPL file. |
| 60 | +
|
| 61 | + Returns: |
| 62 | + dict: A dictionary containing the parsed TPL data. |
| 63 | + """ |
| 64 | + with open(self.file_path, 'rb') as file: |
| 65 | + # Validate the TPL file header and move the cursor to the tool data section |
| 66 | + if not validate_tpl_header(file) or not move_to_tool_data_section(file): |
| 67 | + return {} |
| 68 | + |
| 69 | + # Extract the tool data |
| 70 | + self.tpl_data = self.read_tool(file) |
| 71 | + return self.tpl_data |
| 72 | + |
| 73 | + def save_to_json(self, output_file): |
| 74 | + """ |
| 75 | + Saves the parsed TPL data to a JSON file. |
| 76 | +
|
| 77 | + Parameters: |
| 78 | + output_file (str): The path to the JSON file where the data will be saved. |
| 79 | + """ |
| 80 | + with open(output_file, "w+", encoding="utf-8") as f: |
| 81 | + json.dump(self.tpl_data, f, indent=2) |
0 commit comments