import pygame
import os
import sys
from . import image_scrolling
import math
import subprocess
from tkinter import messagebox, filedialog, simpledialog
import tkinter as tk
import json
from rgb import RGB
from data import (
    ae_images_position_x, 
    ae_images_position_y, 
    ae_images_path, 
    ae_images_direction, 
    ae_images_size_x, 
    ae_images_size_y, 
    ae_next_id, 
    ae_images_id, 
    ae_images_type, 
    ae_every_frame_position_x, 
    ae_every_frame_position_y, 
    ae_every_frame_path, 
    ae_every_frame_direction, 
    ae_every_frame_size_x, 
    ae_every_frame_size_y, 
    ae_every_frame_type
)

_is_tk = False
_data = {"animation_name":"untitled word", "frame":int(1)}

def _display_button(screen : pygame.Surface, font_path, x, y, w, h, text, color, text_color, font_size=20):
    font = pygame.font.Font(font_path, font_size)
    pygame.draw.rect(
        screen, 
        color, 
        (
           x, y, w, h 
        )
    )
    text_surface = font.render(text, True, text_color)
    screen.blit(text_surface, text_surface.get_rect(center=(x + w // 2, y + h // 2)))
    
def _display_text(screen : pygame.Surface, font_path, x, y, text, color):
    font = pygame.font.Font(font_path, 20)
    text_surface = font.render(text, True, color)
    screen.blit(text_surface, text_surface.get_rect(center=(x, y)))

def _get_value(string, index, default="0"):
    """从分号分隔的字符串中获取第index个值"""
    if not string:
        return default
    parts = string.split(";")
    if index < len(parts):
        return parts[index]
    return default



# 按钮按下后的事件处理函数
def _import_button(grid : image_scrolling.InfiniteImageGrid):
    image_path = filedialog.askopenfilename(
        title="选择图片", 
        filetypes=[("图片文件", "*.jpg *.png *.jpeg")]
    )
    if image_path:
        grid.add_image(image_path)


def _settings_button():
    global _is_tk
    def _set_animation_name():
        name = simpledialog.askstring("设置动画名称", "请输入动画名称：")
        if name:
            _data["animation_name"] = name
        else:
            messagebox.showerror("Error", "请输入动画名称！")


    _is_tk = True
    loop = tk.Tk()
    loop.title("settings")

    icon = tk.PhotoImage(file=os.path.join(os.path.dirname(__file__), "Image/tk_icon.gif"))
    loop.iconphoto(False, icon)

    loop.geometry("600x800")
    loop.resizable(False, False)
    loop.configure(bg=RGB(16, 16, 16).of())

    # Text
    notice_text = tk.Label(loop, 
                           text="⚠所有设置关闭窗口后会生效！", 
                           font=(os.path.join(os.path.dirname(__file__), "font", "MSYHBD.TTC"), 16, "bold"), 
                           bg=RGB(16, 16, 16).of(), 
                           fg=RGB(255, 0, 0).of()
    )
    notice_text.pack()
    

    # Botton
    set_name_button = tk.Button(loop, 
                                text="设置动画名称", 
                                font=(os.path.join(os.path.dirname(__file__), "font", "MSYHBD.TTC"), 16), 
                                command=_set_animation_name, 
                                bg=RGB(50, 50, 50).of(), 
                                fg=RGB(255, 255, 255).of()
    )
    set_name_button.pack()

    loop.mainloop()
    _is_tk = False





def _collisions(x, y, w, h, x_2, y_2, w_2, h_2):
    if x < x_2 + w_2 and x + w > x_2 and y < y_2 + h_2 and y + h > y_2:
        return True
    else:
        return False




class AnimationEngine:
    def __init__(self):
        pygame.init()
        pygame.font.init()

        self.YELLOW = (255, 255, 0)

        self.dirpath = os.path.dirname(__file__)
        self.font_path = os.path.join(self.dirpath, "font", "MSYHBD.TTC")
        self.font = pygame.font.Font(self.font_path)
        self.FPS = 60
        self.animation_engine_window = pygame.display.set_mode((1600, 850), pygame.DOUBLEBUF)
        self.editor_images_cache = {}  # 缓存编辑器中的图片
        self.is_has_image_drag = {}  # 是否有图片被拖动dict
        self.is_has_image_display_attribution = {}  # 是否有图片显示属性dict
        self.is_rotateing = {}  # 是否正在旋转dict
        self.is_sizing = {}  # 是否正在缩放dict
        self.current_dragging_key = None  # 当前正在拖动的图片key
        self.is_dragging = False  # 是否正在拖动中
        self._dirty_caches = set()

        self.end_x = 0
        self.end_y = 0



        # import button
        self.import_button_rect_x, self.import_button_rect_y = 5, 3
        self.import_button_rect_width, self.import_button_rect_height = 80, 30
        self.import_button_text = "导入图片"
        self.import_button_color, self.import_button_text_color = (50, 50, 50), (255, 255, 255)

        # settings button
        self.settings_button_rect_x, self.settings_button_rect_y = 90, 3
        self.settings_button_rect_width, self.settings_button_rect_height = 80, 30
        self.settings_button_text = "设置"
        self.settings_button_color, self.settings_button_text_color = (50, 50, 50), (255, 255, 255)

        # save button
        self.save_button_rect_x, self.save_button_rect_y = 175, 3
        self.save_button_rect_width, self.save_button_rect_height = 80, 30
        self.save_button_text = "保存"
        self.save_button_color, self.save_button_text_color = (50, 50, 50), (255, 255, 255)

        # open button
        self.open_button_rect_x, self.open_button_rect_y = 260, 3
        self.open_button_rect_width, self.open_button_rect_height = 80, 30
        self.open_button_text = "打开"
        self.open_button_color, self.open_button_text_color = (50, 50, 50), (255, 255, 255)

        # frame add button
        self.frame_add_button_rect_x, self.frame_add_button_rect_y = self.animation_engine_window.get_width() - 50, self.animation_engine_window.get_height() - 25
        self.frame_add_button_rect_width, self.frame_add_button_rect_height = 20, 20
        self.frame_add_button_text = "+"
        self.frame_add_button_color, self.frame_add_button_text_color = (50, 50, 50), (255, 255, 255)

        # frame remove button
        self.frame_remove_button_rect_x, self.frame_remove_button_rect_y = self.animation_engine_window.get_width() - 25, self.animation_engine_window.get_height() - 25
        self.frame_remove_button_rect_width, self.frame_remove_button_rect_height = 20, 20
        self.frame_remove_button_text = "-"
        self.frame_remove_button_color, self.frame_remove_button_text_color = (50, 50, 50), (255, 255, 255)

        # frame set button
        self.frame_set_button_rect_x, self.frame_set_button_rect_y = self.animation_engine_window.get_width() - 100, self.animation_engine_window.get_height() - 25
        self.frame_set_button_rect_width, self.frame_set_button_rect_height = 40, 20
        self.frame_set_button_text = "set"
        self.frame_set_button_color, self.frame_set_button_text_color = (50, 50, 50), (255, 255, 255)




        self.WINDOW_WIDTH, self.WINDOW_HEIGHT = self.animation_engine_window.get_size()
        # 设置：显示区域在右下角
        self.grid_width = 320  # 宽度
        self.grid_height = 500  # 高度
        # 位置：右下角，留出边距
        self.margin = 20
        self.x = self.WINDOW_WIDTH - self.grid_width - self.margin
        self.y = self.WINDOW_HEIGHT - self.grid_height - self.margin - 15
        # 创建网格（2列显示）
        self.grid = image_scrolling.InfiniteImageGrid(
            x=self.x, 
            y=self.y, 
            width=self.grid_width, 
            height=self.grid_height,
            columns=2,          # 2列
            thumbnail_size=130, # 缩略图大小
            spacing=12          # 间距
        )

        self.icon_path = os.path.join(self.dirpath, "Image", "icon.ico")
        self.icon = pygame.image.load(self.icon_path)
        self.clock = pygame.time.Clock()
        pygame.display.set_icon(self.icon)
        self.running : bool = True
        while self.running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False

                if event.type == pygame.DROPFILE:
                    file_path = event.file  # 直接获取路径字符串
                    
                    if file_path.lower().endswith((".jpg", ".png", ".jpeg")):
                        self.grid.add_image(file_path)
                    else:
                        messagebox.showerror("Error", "Only support image files.(.jpg .png .jpeg)")


                self.mouse_pos = pygame.mouse.get_pos()
                
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        # 只有点击空白区域才退出模式
                        if not self._is_clicking_on_control_point():
                            for key in list(self.is_rotateing.keys()):
                                self.is_rotateing[key] = False
                            for key in list(self.is_sizing.keys()):
                                self.is_sizing[key] = False


                    # Button click
                    if event.button == 1:
                        if _collisions(self.mouse_pos[0], self.mouse_pos[1], 10, 10, 
                                    self.import_button_rect_x, self.import_button_rect_y, self.import_button_rect_width, self.import_button_rect_height):
                            _import_button(self.grid)

                        if _collisions(self.mouse_pos[0], self.mouse_pos[1], 10, 10, 
                                    self.settings_button_rect_x, self.settings_button_rect_y, self.settings_button_rect_width, self.settings_button_rect_height):
                            if not _is_tk:
                                _settings_button()
                        if _collisions(self.mouse_pos[0], self.mouse_pos[1], 10, 10, 
                                        self.save_button_rect_x, self.save_button_rect_y, self.save_button_rect_width, self.save_button_rect_height):
                            self._save_to_file()
                        if _collisions(self.mouse_pos[0], self.mouse_pos[1], 10, 10, 
                                        self.open_button_rect_x, self.open_button_rect_y, self.open_button_rect_width, self.open_button_rect_height):
                            self._open_from_file()

                        if _collisions(self.mouse_pos[0], self.mouse_pos[1], 10, 10, 
                                    self.frame_add_button_rect_x, self.frame_add_button_rect_y, self.frame_add_button_rect_width, self.frame_add_button_rect_height):
                            self._update_every_about_frame_data()
                            _data["frame"] += 1
                            self._load_frame_data(_data["frame"], clear_first=True, copy_from_previous=True)

                        if _collisions(self.mouse_pos[0], self.mouse_pos[1], 10, 10, 
                                    self.frame_remove_button_rect_x, self.frame_remove_button_rect_y, self.frame_remove_button_rect_width, self.frame_remove_button_rect_height):
                            if _data["frame"] > 1:
                                self._update_every_about_frame_data()
                                _data["frame"] -= 1
                                self._load_frame_data(_data["frame"], clear_first=True, copy_from_previous=False)
                                
                        if _collisions(self.mouse_pos[0], self.mouse_pos[1], 10, 10, 
                                        self.frame_set_button_rect_x, self.frame_set_button_rect_y, self.frame_set_button_rect_width, self.frame_set_button_rect_height):
                            self._frame_set_button()
                    if event.button == 3:  # 右键
                        hover_index = self.grid.get_hover_image_index(self.mouse_pos[0], self.mouse_pos[1])
                        if hover_index != -1:
                            self._attribute_window(hover_index)
                    

                if event.type == pygame.MOUSEWHEEL:
                    if _collisions(self.mouse_pos[0], self.mouse_pos[1], 10, 10, 
                                   0, self.animation_engine_window.get_height()-35, self.animation_engine_window.get_width(), 35):
                        if event.y > 0:
                            self._update_every_about_frame_data()
                            _data["frame"] += 1
                            self._load_frame_data(_data["frame"], clear_first=True, copy_from_previous=True)
                        elif event.y < 0:
                            if _data["frame"] > 1:
                                self._update_every_about_frame_data()
                                _data["frame"] -= 1
                                self._load_frame_data(_data["frame"], clear_first=True, copy_from_previous=False)

                if event.type == pygame.MOUSEBUTTONUP:
                    # 重置缩放状态（只重置状态标志，不删除整个state）
                    if hasattr(self, 'size_state'):
                        for state in self.size_state.values():
                            state['resizing_x'] = False
                            state['resizing_y'] = False



                    # add image
                    if self.grid.dragging and event.button == 1:
                        drag_index = self.grid.drag_index
                        if drag_index != -1:
                            global ae_next_id
                            # 检查是否在编辑器区域内（左侧）
                            editor_rect = pygame.Rect(0, self.settings_rect_height, 
                                                    self.animation_engine_window.get_width() - self.grid_width - 19, 
                                                    780)
                            if editor_rect.collidepoint(self.mouse_pos):
                                # 生成新的唯一ID
                                new_id = ae_next_id
                                ae_next_id += 1
                                
                                # 保存新实例
                                ae_images_position_x[new_id] = self.grid.get_drag_image_rect(drag_index).x
                                ae_images_position_y[new_id] = self.grid.get_drag_image_rect(drag_index).y
                                self.is_has_image_drag[new_id] = False
                                self.is_has_image_display_attribution[new_id] = False
                                self.is_rotateing[new_id] = False
                                self.is_sizing[new_id] = False
                                ae_images_path[new_id] = self.grid.get_image_path(drag_index)
                                ae_images_direction[new_id] = 0
                                ae_images_size_x[new_id] = self.grid.original_images_size[drag_index][0]
                                ae_images_size_y[new_id] = self.grid.original_images_size[drag_index][1]
                                ae_images_id[drag_index] = new_id
                                ae_images_type[new_id] = "Image"
                                #self.grid.add_image_name(self.grid.get_image_path(drag_index))
                                

                self.grid.handle_event(event)
            


            pygame.display.set_caption(f"Animation Engine - {_data["animation_name"]}")

            self.animation_engine_window.fill((16, 16, 16))

            self.settings_rect_width, self.settings_rect_height = self.animation_engine_window.get_width(), 35
            self.frame_rect_height = 35

            # 编辑器区域
            self.editor_rect_x, self.editor_rect_y = 0, self.settings_rect_height
            self.editor_rect_width = self.animation_engine_window.get_width() - self.grid_width - 19
            self.editor_rect_height = self.animation_engine_window.get_height() - self.frame_rect_height
            pygame.draw.rect(
                self.animation_engine_window, 
                (8, 8, 8), 
                (
                self.editor_rect_x, 
                self.editor_rect_y, 
                self.editor_rect_width, 
                self.editor_rect_height
                )
            )

            self._update_editor()
            self._interactive_images()
            self._update_every_about_frame_data()

            # 设置栏
            pygame.draw.rect(
                self.animation_engine_window, 
                (100, 100, 100), 
                (
                    self.animation_engine_window.get_width() // 2 - self.settings_rect_width // 2,  # 矩形左上角的 x 坐标
                    0,  # 矩形左上角的 y 坐标，即窗口顶部
                    self.settings_rect_width,  # 矩形的宽度
                    self.settings_rect_height  # 矩形的高度
                )
            )

            # 帧栏
            pygame.draw.rect(
                self.animation_engine_window, 
                (100, 100, 100), 
                (
                    0,  # x
                    self.animation_engine_window.get_height()-self.frame_rect_height,  # y
                    self.animation_engine_window.get_width(),  # w
                    self.frame_rect_height # h
                )
            )





            # display import button
            _display_button(
                self.animation_engine_window, 
                self.font_path, 
                self.import_button_rect_x, 
                self.import_button_rect_y, 
                self.import_button_rect_width, 
                self.import_button_rect_height, 
                self.import_button_text, 
                self.import_button_color, 
                self.import_button_text_color
            )
            # display settings button
            _display_button(
                self.animation_engine_window, 
                self.font_path, 
                self.settings_button_rect_x, 
                self.settings_button_rect_y, 
                self.settings_button_rect_width, 
                self.settings_button_rect_height, 
                self.settings_button_text, 
                self.settings_button_color, 
                self.settings_button_text_color
            )
            # display frame add button
            _display_button(
                self.animation_engine_window, 
                self.font_path, 
                self.frame_add_button_rect_x, 
                self.frame_add_button_rect_y, 
                self.frame_add_button_rect_width, 
                self.frame_add_button_rect_height, 
                self.frame_add_button_text, 
                self.frame_add_button_color, 
                self.frame_add_button_text_color
            )
            # display save button
            _display_button(
                self.animation_engine_window, 
                self.font_path, 
                self.save_button_rect_x, 
                self.save_button_rect_y, 
                self.save_button_rect_width, 
                self.save_button_rect_height, 
                self.save_button_text, 
                self.save_button_color, 
                self.save_button_text_color, 
            )
            # display open button
            _display_button(
                self.animation_engine_window, 
                self.font_path, 
                self.open_button_rect_x, 
                self.open_button_rect_y, 
                self.open_button_rect_width, 
                self.open_button_rect_height, 
                self.open_button_text, 
                self.open_button_color, 
                self.open_button_text_color
            )


            #display frame remove button
            _display_button(
                self.animation_engine_window, 
                self.font_path, 
                self.frame_remove_button_rect_x, 
                self.frame_remove_button_rect_y, 
                self.frame_remove_button_rect_width, 
                self.frame_remove_button_rect_height, 
                self.frame_remove_button_text, 
                self.frame_remove_button_color, 
                self.frame_remove_button_text_color
            )
            #display frame set button
            _display_button(
                self.animation_engine_window, 
                self.font_path, 
                self.frame_set_button_rect_x, 
                self.frame_set_button_rect_y, 
                self.frame_set_button_rect_width, 
                self.frame_set_button_rect_height, 
                self.frame_set_button_text, 
                self.frame_set_button_color, 
                self.frame_set_button_text_color
            )


            # display frame value
            _display_text(
                self.animation_engine_window, 
                self.font_path, 
                70, 
                self.animation_engine_window.get_height() - 20, 
                f"Frame: {_data["frame"]}", 
                (255, 255, 255)
            )
            
            self.grid.draw(self.animation_engine_window, self.font_path)
            
            pygame.display.flip()
            self.clock.tick(self.FPS)


    def _save_to_file(self):
        """保存当前动画数据到文件"""
        file_path = filedialog.asksaveasfilename(
            title="保存动画",
            defaultextension=".animationdata",
            filetypes=[("动画数据文件", "*.animationdata"), ("所有文件", "*.*")], 
            initialfile=_data["animation_name"]
        )
        
        if not file_path:
            return
        
        # 编辑器区域尺寸（用于坐标缩放）
        editor_width = self.editor_rect_width
        editor_height = self.editor_rect_height
        
        # 构建 frame 数据
        frame_data = {}
        frame_data["1;" + str(_data["frame"])] = {"sprite_number": len(ae_images_path)}
        
        # 收集所有对象
        objects = {}
        obj_index = 1
        
        for key in ae_images_path:
            path = ae_images_path.get(key, "")
            if not path:
                continue
            
            # 找到这个图片ID对应的网格索引
            grid_index = None
            for idx, img_id in ae_images_id.items():
                if img_id == key:
                    grid_index = idx
                    break
            
            if grid_index is None:
                continue
            
            # 构建每个帧的数据
            frame_detail = {}
            show_frames = []
            
            for frame in range(1, _data["frame"] + 1):
                frame_path_str = ae_every_frame_path.get(frame, "")
                if not frame_path_str:
                    continue
                
                frame_path_list = frame_path_str.split(";")
                
                if grid_index < len(frame_path_list) and frame_path_list[grid_index]:
                    # 获取原始坐标
                    x = float(_get_value(ae_every_frame_position_x.get(frame, ""), grid_index, "0"))
                    y = float(_get_value(ae_every_frame_position_y.get(frame, ""), grid_index, "0"))
                    
                    # 转换为相对坐标（0-1范围），便于在不同分辨率下还原
                    rel_x = x / editor_width if editor_width > 0 else 0
                    rel_y = y / editor_height if editor_height > 0 else 0
                    
                    direction = float(_get_value(ae_every_frame_direction.get(frame, ""), grid_index, "0"))
                    size_x = float(_get_value(ae_every_frame_size_x.get(frame, ""), grid_index, "100"))
                    size_y = float(_get_value(ae_every_frame_size_y.get(frame, ""), grid_index, "100"))
                    
                    frame_detail[str(frame)] = {
                        "position": {"rel_x": rel_x, "rel_y": rel_y},
                        "direction": direction,
                        "size": {"size_x": size_x, "size_y": size_y}
                    }
                    show_frames.append(str(frame))
            
            if frame_detail:
                objects[f"Object{obj_index}"] = {
                    "name": f"{os.path.basename(path).split('.')[0]}",
                    "type": ae_images_type.get(key, "Image"),
                    "path": path,
                    "show_frame": ";".join(show_frames),
                    "frame": frame_detail
                }
                obj_index += 1
        
        # 构建完整JSON
        output = {
            "name": _data["animation_name"],
            "total_frame": _data["frame"],
            "editor_width": editor_width,
            "editor_height": editor_height,
            "frame": frame_data,
            **objects
        }
        
        with open(file_path, "w", encoding="utf-8") as f:
            json.dump(output, f, indent=2, ensure_ascii=False)
        
        messagebox.showinfo("成功", f"动画已保存到:\n{file_path}")


    def _open_from_file(self):
        """从文件打开动画"""
        file_path = filedialog.askopenfilename(
            title="打开动画",
            filetypes=[("动画数据文件", "*.animationdata"), ("所有文件", "*.*")]
        )
        
        if not file_path:
            return
        
        with open(file_path, "r", encoding="utf-8") as f:
            data = json.load(f)
        
        # 设置动画名称
        _data["animation_name"] = data.get("name", "untitled")
        
        # 获取总帧数（从frame的key中解析）
        frame_keys = list(data.get("frame", {}).keys())
        if frame_keys:
            # 解析 "1;2" 格式，取最后一个数字
            last_frame = frame_keys[0].split(";")[-1]
            _data["frame"] = int(last_frame)
        
        # 清空当前所有图片
        for key in list(ae_images_path.keys()):
            self._delete_image(key, ask_confirm=False)
        
        # 加载对象
        global ae_next_id
        for obj_name, obj_data in data.items():
            if obj_name.startswith("Object"):
                new_id = ae_next_id
                ae_next_id += 1
                
                path = obj_data.get("path", "")
                ae_images_path[new_id] = path
                ae_images_type[new_id] = obj_data.get("type", "Image")
                
                # 获取show_frame，解析该对象出现在哪些帧
                show_frame_str = obj_data.get("show_frame", "")
                show_frames = show_frame_str.split(";") if show_frame_str else []
                
                # 加载每一帧的数据
                frame_detail = obj_data.get("frame", {})
                
                for frame_str, frame_info in frame_detail.items():
                    frame = int(frame_str)
                    pos = frame_info.get("position", {})
                    
                    # 兼容两种格式
                    if "rel_x" in pos and "rel_y" in pos:
                        # 相对坐标格式，转换为绝对坐标
                        editor_w = data.get("editor_width", 1261)
                        editor_h = data.get("editor_height", 780)
                        x = pos["rel_x"] * editor_w
                        y = pos["rel_y"] * editor_h
                    elif "x" in pos and "y" in pos:
                        x = pos["x"]
                        y = pos["y"]
                    else:
                        x, y = 0, 0
                    
                    direction = frame_info.get("direction", 0)
                    size = frame_info.get("size", {"size_x": 100, "size_y": 100})
                    
                    # 确保该帧的数据字典存在
                    if frame not in ae_every_frame_position_x:
                        ae_every_frame_position_x[frame] = ""
                        ae_every_frame_position_y[frame] = ""
                        ae_every_frame_path[frame] = ""
                        ae_every_frame_direction[frame] = ""
                        ae_every_frame_size_x[frame] = ""
                        ae_every_frame_size_y[frame] = ""
                        ae_every_frame_type[frame] = ""
                    
                    # 获取现有的字符串
                    pos_x_str = ae_every_frame_position_x[frame]
                    pos_y_str = ae_every_frame_position_y[frame]
                    path_str = ae_every_frame_path[frame]
                    dir_str = ae_every_frame_direction[frame]
                    size_x_str = ae_every_frame_size_x[frame]
                    size_y_str = ae_every_frame_size_y[frame]
                    type_str = ae_every_frame_type[frame]
                    
                    # 追加新数据
                    # 追加新数据
                    if pos_x_str:
                        ae_every_frame_position_x[frame] = pos_x_str + ";" + str(x)
                        ae_every_frame_position_y[frame] = pos_y_str + ";" + str(y)
                        ae_every_frame_path[frame] = path_str + ";" + path
                        ae_every_frame_direction[frame] = dir_str + ";" + str(direction)
                        ae_every_frame_size_x[frame] = size_x_str + ";" + str(size["size_x"])
                        ae_every_frame_size_y[frame] = size_y_str + ";" + str(size["size_y"])
                        ae_every_frame_type[frame] = type_str + ";" + obj_data.get("type", "Image")
                    else:
                        ae_every_frame_position_x[frame] = str(x)
                        ae_every_frame_position_y[frame] = str(y)
                        ae_every_frame_path[frame] = path
                        ae_every_frame_direction[frame] = str(direction)
                        ae_every_frame_size_x[frame] = str(size["size_x"])
                        ae_every_frame_size_y[frame] = str(size["size_y"])
                        ae_every_frame_type[frame] = obj_data.get("type", "Image")
                
                # 初始化状态
                self.is_has_image_drag[new_id] = False
                self.is_has_image_display_attribution[new_id] = False
                self.is_rotateing[new_id] = False
                self.is_sizing[new_id] = False
        
        # 重新加载当前帧
        self._load_frame_data(_data["frame"])
        
        messagebox.showinfo("成功", f"已打开动画:\n{file_path}")

    def _frame_set_button(self):
        frame = simpledialog.askstring("设置帧数", "请输入帧数：")
        if frame:
            try:
                frame = int(frame)
                if frame > 0:
                    _data["frame"] = frame
                    self._load_frame_data(frame)
                    return
                else:
                    messagebox.showerror("Error", "帧数必须大于0！")
            except ValueError:
                messagebox.showerror("Error", "请输入正确的数字！")
            except TypeError:
                messagebox.showerror("Error", "请输入数字！")
            self._frame_set_button()

    def _is_clicking_on_control_point(self):
        """检查鼠标是否点击在任何图片的控制点上"""
        for key in ae_images_path:
            x = ae_images_position_x.get(key, 0)
            y = ae_images_position_y.get(key, 0)
            w = ae_images_size_x.get(key, self.grid.thumbnail_size)
            h = ae_images_size_y.get(key, self.grid.thumbnail_size)
            
            center_x = x + w // 2
            center_y = y + h // 2
            control_distance = 100
            x_control_x = center_x + control_distance
            y_control_y = center_y + control_distance
            
            # 检查X控制点
            if _collisions(self.mouse_pos[0], self.mouse_pos[1], 1, 1,
                        x_control_x - 5, center_y - 5, 10, 10):
                return True
            # 检查Y控制点
            if _collisions(self.mouse_pos[0], self.mouse_pos[1], 1, 1,
                        center_x - 5, y_control_y - 5, 10, 10):
                return True
        return False
    

    def _add_attribute_choose(self, x, y, choose_height, choose_width, *texts):
        """添加属性选择"""
        pygame.draw.rect(
            self.animation_engine_window, 
            (100, 100, 100), 
            (
                x, y, 
                choose_width, 30 * len(texts)
            )
        )
        for i, text in enumerate(texts):
            _display_button(
                self.animation_engine_window, 
                self.font_path, 
                x + 5, y + 5 + choose_height * i, 
                choose_width - 5, choose_height - 5, 
                text, 
                (80, 80, 80), 
                (255, 255, 255), 
                16
            )
            if _collisions(self.mouse_pos[0], self.mouse_pos[1], 10, 10, 
                        x+5, y+5 + choose_height * i, choose_width-5,  choose_height-5):
                if pygame.mouse.get_pressed()[0]:
                    return text

    def _rebuild_dirty_caches(self):
        """重建所有脏缓存"""
        for image_index in list(self._dirty_caches):
            path = ae_images_path.get(image_index, "")
            w = ae_images_size_x.get(image_index, self.grid.thumbnail_size)
            h = ae_images_size_y.get(image_index, self.grid.thumbnail_size)
            direction = ae_images_direction.get(image_index, 0)
            
            # 删除旧缓存
            cache_key = (path, w, h, direction)
            if cache_key in self.editor_images_cache:
                del self.editor_images_cache[cache_key]
            
            # 新缓存会在 _update_editor 中自动生成
        self._dirty_caches.clear()


    def _update_editor(self):
        """绘制编辑器中的图片"""
        self._rebuild_dirty_caches()
        
        for key in ae_images_path:
            x = ae_images_position_x.get(key, 0)
            y = ae_images_position_y.get(key, 0)
            w = ae_images_size_x.get(key, self.grid.thumbnail_size)
            h = ae_images_size_y.get(key, self.grid.thumbnail_size)
            direction = ae_images_direction.get(key, 0)
            path = ae_images_path.get(key, "")
            
            if not path or not os.path.exists(path):
                continue
            
            # 计算缩放比例
            original_image = pygame.image.load(path)
            orig_w, orig_h = original_image.get_size()
            scale_x = w / orig_w
            scale_y = h / orig_h
            
            # 使用 rotozoom 一次性处理旋转和缩放
            cache_key = (path, direction, w, h)
            if cache_key not in self.editor_images_cache:
                # pygame.transform.rotozoom(image, angle, scale)
                # 注意：rotozoom 的 scale 是等比例缩放
                # 如果需要非等比例，需要特殊处理
                scale = min(scale_x, scale_y)  # 等比例缩放，保持宽高比
                rotated_scaled = pygame.transform.rotozoom(original_image, direction, scale)
                self.editor_images_cache[cache_key] = rotated_scaled
            
            image_to_draw = self.editor_images_cache[cache_key]
            rect = image_to_draw.get_rect(center=(x + w//2, y + h//2))
            self.animation_engine_window.blit(image_to_draw, rect)

    def _update_every_about_frame_data(self):
        """更新当前帧的所有图片数据到每帧数据字典"""
        current_frame = _data["frame"]
        
        # 收集当前所有图片的数据
        positions_x = []
        positions_y = []
        paths = []
        directions = []
        sizes_x = []
        sizes_y = []
        types = []
        
        for key in ae_images_path:
            positions_x.append(str(ae_images_position_x.get(key, 0)))
            positions_y.append(str(ae_images_position_y.get(key, 0)))
            paths.append(ae_images_path.get(key, ""))
            directions.append(str(ae_images_direction.get(key, 0)))
            sizes_x.append(str(ae_images_size_x.get(key, 100)))
            sizes_y.append(str(ae_images_size_y.get(key, 100)))
            types.append(ae_images_type.get(key, "Image"))
        
        # 用分号连接所有数据
        ae_every_frame_position_x[current_frame] = ";".join(positions_x) if positions_x else ""
        ae_every_frame_position_y[current_frame] = ";".join(positions_y) if positions_y else ""
        ae_every_frame_path[current_frame] = ";".join(paths) if paths else ""
        ae_every_frame_direction[current_frame] = ";".join(directions) if directions else ""
        ae_every_frame_size_x[current_frame] = ";".join(sizes_x) if sizes_x else ""
        ae_every_frame_size_y[current_frame] = ";".join(sizes_y) if sizes_y else ""
        ae_every_frame_type[current_frame] = ";".join(types) if types else ""
        

    def _load_frame_data(self, frame, clear_first=True, copy_from_previous=False):
        """加载指定帧的数据"""
        global ae_next_id
        
        # 如果需要从上一帧复制数据，且当前帧没有数据
        if copy_from_previous and frame > 1:
            # 检查当前帧是否已有数据
            current_path_str = ae_every_frame_path.get(frame, "")
            if not current_path_str:
                prev_frame = frame - 1
                prev_path_str = ae_every_frame_path.get(prev_frame, "")
                if prev_path_str:
                    # 复制上一帧的数据到当前帧
                    ae_every_frame_position_x[frame] = ae_every_frame_position_x.get(prev_frame, "")
                    ae_every_frame_position_y[frame] = ae_every_frame_position_y.get(prev_frame, "")
                    ae_every_frame_path[frame] = prev_path_str
                    ae_every_frame_direction[frame] = ae_every_frame_direction.get(prev_frame, "")
                    ae_every_frame_size_x[frame] = ae_every_frame_size_x.get(prev_frame, "")
                    ae_every_frame_size_y[frame] = ae_every_frame_size_y.get(prev_frame, "")
                    ae_every_frame_type[frame] = ae_every_frame_type.get(prev_frame, "")
        
        # 获取该帧的数据字符串
        pos_x_str = ae_every_frame_position_x.get(frame, "")
        pos_y_str = ae_every_frame_position_y.get(frame, "")
        path_str = ae_every_frame_path.get(frame, "")
        dir_str = ae_every_frame_direction.get(frame, "")
        size_x_str = ae_every_frame_size_x.get(frame, "")
        size_y_str = ae_every_frame_size_y.get(frame, "")
        
        if not path_str:
            if clear_first:
                for key in list(ae_images_path.keys()):
                    self._delete_image(key, ask_confirm=False)
            return
        
        if clear_first:
            # 清空当前所有图片
            for key in list(ae_images_path.keys()):
                self._delete_image(key, ask_confirm=False)
            
            # 清空 ae_images_id
            ae_images_id.clear()
            
            # 分割字符串
            pos_x_list = pos_x_str.split(";")
            pos_y_list = pos_y_str.split(";")
            path_list = path_str.split(";")
            dir_list = dir_str.split(";")
            size_x_list = size_x_str.split(";")
            size_y_list = size_y_str.split(";")
            
            # 重新创建图片数据
            for i in range(len(path_list)):
                if i >= len(path_list) or not path_list[i]:
                    continue
                
                new_id = ae_next_id
                ae_next_id += 1
                
                ae_images_path[new_id] = path_list[i]
                ae_images_position_x[new_id] = float(pos_x_list[i]) if i < len(pos_x_list) else 0
                ae_images_position_y[new_id] = float(pos_y_list[i]) if i < len(pos_y_list) else 0
                ae_images_direction[new_id] = float(dir_list[i]) if i < len(dir_list) else 0
                ae_images_size_x[new_id] = float(size_x_list[i]) if i < len(size_x_list) else 100
                ae_images_size_y[new_id] = float(size_y_list[i]) if i < len(size_y_list) else 100
                ae_images_type[new_id] = "Image"
                
                # 关键：设置 ae_images_id，使用索引 i 作为网格索引
                ae_images_id[i] = new_id
                
                # 初始化状态
                self.is_has_image_drag[new_id] = False
                self.is_has_image_display_attribution[new_id] = False
                self.is_rotateing[new_id] = False
                self.is_sizing[new_id] = False

    def _delete_image(self, image_key, ask_confirm=True):
        """删除图片及其所有相关数据"""
        image_path = ae_images_path.get(image_key, "")
        if ask_confirm:
            image_name = os.path.basename(image_path) if image_path else f"图片{image_key}"
            result = messagebox.askyesno(
                "确认删除",
                f"确定要删除图片「{image_name}」吗？\n\n删除后无法恢复！",
                icon='warning'
            )
            if not result:
                return
        
        # 1. 清除缓存中的该图片
        keys_to_delete = []
        for cache_key in self.editor_images_cache:
            if cache_key[0] == image_path:
                keys_to_delete.append(cache_key)
        for key in keys_to_delete:
            del self.editor_images_cache[key]
        
        # 2. 清除状态字典
        self.is_has_image_drag.pop(image_key, None)
        self.is_has_image_display_attribution.pop(image_key, None)
        self.is_rotateing.pop(image_key, None)
        self.is_sizing.pop(image_key, None)
        
        # 3. 清除缩放状态
        if hasattr(self, 'size_state') and image_key in self.size_state:
            del self.size_state[image_key]
        
        # 4. 清除全局数据字典
        ae_images_position_x.pop(image_key, None)
        ae_images_position_y.pop(image_key, None)
        ae_images_path.pop(image_key, None)
        ae_images_direction.pop(image_key, None)
        ae_images_size_x.pop(image_key, None)
        ae_images_size_y.pop(image_key, None)
        ae_images_type.pop(image_key, None)


    def _interactive_images(self):
        """交互式图片编辑"""
        for key in list(ae_images_path.keys()):
            x = ae_images_position_x.get(key, 0)
            y = ae_images_position_y.get(key, 0)
            w = ae_images_size_x.get(key, self.grid.thumbnail_size)
            h = ae_images_size_y.get(key, self.grid.thumbnail_size)
            
            # 检查鼠标是否在图片上或正在拖动
            is_hover = _collisions(self.mouse_pos[0], self.mouse_pos[1], 1, 1, x, y, w, h)
            
            # 如果正在拖动其他图片，跳过当前图片的拖动逻辑
            if self.is_dragging and self.current_dragging_key != key:
                # 但仍然需要处理旋转和缩放模式
                if self.is_rotateing.get(key, False):
                    self._rotate_direction(key)
                if self.is_sizing.get(key, False):
                    self._size(key)
                continue
            
            if is_hover or self.is_has_image_drag.get(key, False) or self.is_has_image_display_attribution.get(key, False):
                if not self.is_rotateing.get(key, False) and not self.is_sizing.get(key, False):
                    # 绘制高亮边框
                    pygame.draw.rect(self.animation_engine_window, self.YELLOW, (x, y, w, h), 2)
                    
                    # 右键弹出属性选择
                    if pygame.mouse.get_pressed()[2] or self.is_has_image_display_attribution.get(key, False):
                        global old_mouse_pos
                        if not self.is_has_image_display_attribution.get(key, False):
                            old_mouse_pos = self.mouse_pos
                        self.is_has_image_display_attribution[key] = True

                        choose = self._add_attribute_choose(old_mouse_pos[0], old_mouse_pos[1], 30, 200, "属性", "打开图片所在路径", "旋转", "大小", "删除")
                        if choose == "属性":
                            # 方法1：反向查找 - 从 ae_images_id 中找对应的键
                            grid_index = None
                            for idx, img_id in ae_images_id.items():
                                if img_id == key:
                                    grid_index = idx
                                    break
                            
                            # 方法2：如果方法1找不到，直接从网格的原始数据中查找
                            if grid_index is None:
                                # 尝试直接从网格中找
                                for idx in range(len(self.grid.image_paths)):
                                    if self.grid.image_paths[idx] == ae_images_path.get(key, ""):
                                        grid_index = idx
                                        break
                            
                            if grid_index is not None:
                                self._attribute_window(grid_index)
                            else:
                                # 如果还是找不到，直接用 key 作为 grid_index 试试
                                if key < len(self.grid.image_paths):
                                    self._attribute_window(key)
                                else:
                                    messagebox.showerror("错误", f"找不到图片索引，图片ID: {key}")
                        elif choose == "打开图片所在路径":
                            dirpath = os.path.dirname(ae_images_path.get(key, ""))
                            if dirpath:
                                if sys.platform == "win32":
                                    os.startfile(dirpath)
                                elif sys.platform == "darwin":
                                    subprocess.run(["open", dirpath])
                                else:
                                    subprocess.run(["xdg-open", dirpath])
                        elif choose == "旋转":
                            self.is_rotateing[key] = True
                            # 退出缩放模式
                            self.is_sizing[key] = False
                        elif choose == "大小":
                            self.is_sizing[key] = True
                            # 退出旋转模式
                            self.is_rotateing[key] = False
                        elif choose == "删除":
                            self._delete_image(key)
                            return  # 删除后立即返回，避免继续处理已删除的图片
                    
                    # 左键拖动
                    if pygame.mouse.get_pressed()[0]:
                        if self.is_has_image_display_attribution.get(key, False):
                            self.is_has_image_display_attribution[key] = False
                            continue
                        
                        # 开始拖动
                        if not self.is_has_image_drag.get(key, False) and not self.is_dragging:
                            self.is_has_image_drag[key] = True
                            self.is_dragging = True
                            self.current_dragging_key = key
                        
                        # 只有当前拖动的图片才能移动
                        if self.is_dragging and self.current_dragging_key == key:
                            # 编辑器区域边界
                            editor_left = 0
                            editor_top = self.settings_rect_height
                            editor_right = self.animation_engine_window.get_width() - self.grid_width - 19
                            editor_bottom = self.animation_engine_window.get_height() - self.frame_rect_height
                            
                            # 计算新位置（图片中心跟随鼠标）
                            new_x = self.mouse_pos[0] - w // 2
                            new_y = self.mouse_pos[1] - h // 2
                            
                            # 限制在编辑器区域内
                            new_x = max(editor_left, min(new_x, editor_right - w))
                            new_y = max(editor_top, min(new_y, editor_bottom - h))
                            
                            ae_images_position_x[key] = new_x
                            ae_images_position_y[key] = new_y
                    else:
                        # 鼠标松开，结束拖动
                        if self.is_has_image_drag.get(key, False):
                            self.is_has_image_drag[key] = False
                            self.is_dragging = False
                            self.current_dragging_key = None
            
            # 处理旋转和缩放模式（即使不在hover状态也要处理）
            if self.is_rotateing.get(key, False):
                self._rotate_direction(key)
            if self.is_sizing.get(key, False):
                self._size(key)

    def _rotate_direction(self, image_index):
        """旋转图片方向 - 只更新角度，不实时重建缓存"""
        actual_size_x = ae_images_size_x.get(image_index, 100)
        actual_size_y = ae_images_size_y.get(image_index, 100)
        radius = min(actual_size_x, actual_size_y) + 100
        
        center_x = ae_images_position_x.get(image_index, 0) + actual_size_x // 2
        center_y = ae_images_position_y.get(image_index, 0) + actual_size_y // 2
        
        pygame.draw.circle(
            self.animation_engine_window, 
            "green", 
            (center_x, center_y), 
            radius=radius, 
            width=3
        )
        
        dx = self.mouse_pos[0] - center_x
        dy = self.mouse_pos[1] - center_y
        distance = math.hypot(dx, dy)
        
        if distance <= radius:
            if distance > 0:
                line_length = min(distance, radius * 0.8)
                direction_x = dx / distance
                direction_y = dy / distance
                end_x = center_x + direction_x * line_length
                end_y = center_y + direction_y * line_length
            else:
                end_x, end_y = center_x, center_y
            
            pygame.draw.line(
                self.animation_engine_window, 
                "red", 
                (center_x, center_y), 
                (end_x, end_y), 
                3
            )
            
            pygame.draw.circle(
                self.animation_engine_window, 
                "yellow", 
                (int(end_x), int(end_y)), 
                8
            )
            
            if distance > 0:
                angle = math.degrees(math.atan2(dy, dx))
                final_angle = -angle
                ae_images_direction[image_index] = final_angle
                # 标记缓存为脏
                self._dirty_caches.add(image_index)
        else:
            if distance > 0:
                direction_x = dx / distance
                direction_y = dy / distance
                end_x = center_x + direction_x * radius * 0.8
                end_y = center_y + direction_y * radius * 0.8
                
                pygame.draw.line(
                    self.animation_engine_window, 
                    (100, 100, 100),
                    (center_x, center_y), 
                    (end_x, end_y), 
                    2
                )
                
                pygame.draw.circle(
                    self.animation_engine_window, 
                    (100, 100, 100),
                    (int(end_x), int(end_y)), 
                    6
                )


    def _size(self, image_index):
        """调整图片大小"""
        x = ae_images_position_x.get(image_index, 0)
        y = ae_images_position_y.get(image_index, 0)
        w = ae_images_size_x.get(image_index, self.grid.thumbnail_size)
        h = ae_images_size_y.get(image_index, self.grid.thumbnail_size)
        
        center_x = x + w // 2
        center_y = y + h // 2
        
        pygame.draw.rect(self.animation_engine_window, self.YELLOW, (x, y, w, h), 2)
        
        control_distance = 100
        x_control_x = center_x + control_distance
        y_control_y = center_y + control_distance
        
        if not hasattr(self, 'size_state'):
            self.size_state = {}
        
        if image_index not in self.size_state:
            self.size_state[image_index] = {
                'resizing_x': False,
                'resizing_y': False,
                'start_mouse_x': 0,
                'start_mouse_y': 0,
                'start_w': w,
                'start_h': h
            }
        
        state = self.size_state[image_index]
        
        pygame.draw.line(
            self.animation_engine_window, 
            (255, 0, 0), 
            (center_x, center_y), 
            (x_control_x, center_y), 
            2
        )
        pygame.draw.rect(
            self.animation_engine_window, 
            "red", 
            (x_control_x - 5, center_y - 5, 10, 10)
        )
        
        pygame.draw.line(
            self.animation_engine_window, 
            (0, 255, 0), 
            (center_x, center_y), 
            (center_x, y_control_y), 
            2
        )
        pygame.draw.rect(
            self.animation_engine_window, 
            "green", 
            (center_x - 5, y_control_y - 5, 10, 10)
        )
        
        if not state['resizing_x'] and not state['resizing_y']:
            mouse_on_x = _collisions(
                self.mouse_pos[0], self.mouse_pos[1], 1, 1,
                x_control_x - 5, center_y - 5, 10, 10
            )
            mouse_on_y = _collisions(
                self.mouse_pos[0], self.mouse_pos[1], 1, 1,
                center_x - 5, y_control_y - 5, 10, 10
            )
            
            if mouse_on_x and pygame.mouse.get_pressed()[0]:
                state['resizing_x'] = True
                state['start_mouse_x'] = self.mouse_pos[0]
                state['start_w'] = w
            
            if mouse_on_y and pygame.mouse.get_pressed()[0]:
                state['resizing_y'] = True
                state['start_mouse_y'] = self.mouse_pos[1]
                state['start_h'] = h
        
        if state['resizing_x']:
            delta_x = self.mouse_pos[0] - state['start_mouse_x']
            new_w = max(10, state['start_w'] + delta_x)
            ae_images_size_x[image_index] = new_w
            
            # 清除缩放缓存（只清除这个图片的缩放缓存）
            scale_cache_key = (ae_images_path.get(image_index, ""), w, h)
            if scale_cache_key in self.editor_images_cache:
                del self.editor_images_cache[scale_cache_key]
        
        if state['resizing_y']:
            delta_y = self.mouse_pos[1] - state['start_mouse_y']
            new_h = max(10, state['start_h'] + delta_y)
            ae_images_size_y[image_index] = new_h
            
            # 清除缩放缓存
            scale_cache_key = (ae_images_path.get(image_index, ""), w, h)
            if scale_cache_key in self.editor_images_cache:
                del self.editor_images_cache[scale_cache_key]




    # Window
    def _attribute_window(self, image_index : int):
        global _is_tk

        _is_tk = True

        loop = tk.Tk()
        loop.title(f"属性 - {self.grid.image_names[image_index]}")
        loop.geometry("800x600")
        loop.resizable(False, False)
        icon = tk.PhotoImage(file=os.path.join(os.path.dirname(__file__), "Image/tk_icon.gif"))
        loop.iconphoto(False, icon)
        loop.config(bg=RGB(16, 16, 16).of())

        # Text
        notice_text = tk.Label(loop, 
                            text="⚠所有设置关闭后生效！", 
                            font=(self.font_path, 16, "bold"), 
                            bg=RGB(16, 16, 16).of(), 
                            fg=RGB(255, 0, 0).of()
        )
        notice_text.pack(pady=10)
        name_text = tk.Label(loop, 
                            text=f"名称：{self.grid.image_names[image_index]}", 
                            font=(self.font_path, 16), 
                            bg=RGB(50, 50, 50).of(), 
                            fg=RGB(255, 255, 255).of()
        )
        name_text.pack(pady=10)
        path_text = tk.Label(loop, 
                            text=f"路径：{self.grid.image_paths[image_index]}", 
                            font=(self.font_path, 16), 
                            bg=RGB(50, 50, 50).of(), 
                            fg=RGB(255, 255, 255).of()
        )


        # Button
        def name_button():
            name = simpledialog.askstring("重命名", "请输入新的名称：", parent=loop)
            if name:
                self.grid.image_names[image_index] = name
                name_text.config(text=f"名称：{self.grid.image_names[image_index]}")
            
        name_button = tk.Button(loop, 
                                text="重命名", 
                                font=(self.font_path, 16), 
                                command=name_button, 
                                bg=RGB(50, 50, 50).of(), 
                                fg=RGB(255, 255, 255).of()
        )
        name_button.pack()

        
        path_text.pack(pady=10)

        loop.mainloop()
        _is_tk = False

    def _image_interactive_window(self, global_id : int):
        global _is_tk

        _is_tk = True

        loop = tk.Tk()
        # 从全局字典获取图片路径来显示名称
        image_path = ae_images_path.get(global_id, "")
        image_name = os.path.basename(image_path) if image_path else "未知"
        loop.title(f"属性 - {image_name}")
        loop.geometry("800x600")
        loop.resizable(False, False)
        icon = tk.PhotoImage(file=os.path.join(os.path.dirname(__file__), "Image/tk_icon.gif"))
        loop.iconphoto(False, icon)
        loop.config(bg=RGB(16, 16, 16).of())

        # 使用 global_id 访问字典
        name_text = tk.Label(loop, 
            text=f"名称：{image_name}", 
            font=(self.font_path, 16), 
            bg=RGB(16, 16, 16).of(), 
            fg=RGB(255, 255, 255).of()
        )
        name_text.pack()
        
        path_text = tk.Label(loop, 
            text=f"路径：{ae_images_path.get(global_id, '')}", 
            font=(self.font_path, 16), 
            bg=RGB(16, 16, 16).of(), 
            fg=RGB(255, 255, 255).of()
        )
        path_text.pack()
        
        position_text = tk.Label(loop, 
            text=f"对于窗口的坐标：({ae_images_position_x.get(global_id, 0)}, {ae_images_position_y.get(global_id, 0)})", 
            font=(self.font_path, 16), 
            bg=RGB(16, 16, 16).of(), 
            fg=RGB(255, 255, 255).of()
        )
        position_text.pack()
        
        size_text = tk.Label(loop, 
            text=f"大小：({ae_images_size_x.get(global_id, 100)}, {ae_images_size_y.get(global_id, 100)})", 
            font=(self.font_path, 16), 
            bg=RGB(16, 16, 16).of(), 
            fg=RGB(255, 255, 255).of()
        )
        size_text.pack()
        
        direction_text = tk.Label(loop, 
            text=f"方向：{ae_images_direction.get(global_id, 0)}", 
            font=(self.font_path, 16), 
            bg=RGB(16, 16, 16).of(), 
            fg=RGB(255, 255, 255).of()
        )
        direction_text.pack()

        loop.mainloop()
        _is_tk = False

        

if __name__ == '__main__':
    animation_engine = AnimationEngine()
    pygame.quit()