# -*- coding: utf-8 -*-
"""颜色识别工具 v2.0 — 含屏幕取色/渐变/配色/色盲模拟"""
import tkinter as tk
from tkinter import ttk, messagebox
import random, math, re, json, os, colorsys

# 尝试导入截图和鼠标库
try:
    from PIL import ImageGrab
    HAS_PIL = True
except ImportError:
    HAS_PIL = False
try:
    import pyautogui
    HAS_PYAUTOGUI = True
except ImportError:
    HAS_PYAUTOGUI = False

FT_TITLE = ("Microsoft YaHei", 16, "bold")
FT_BTN   = ("Microsoft YaHei", 11)
FT_BIG   = ("Microsoft YaHei", 20, "bold")
FT_MID   = ("Microsoft YaHei", 13)
FT_SMALL = ("Microsoft YaHei", 10)

# ============ 颜色数据库 ============
COLOR_NAMES = {
    "黑色":(0,0,0),"白色":(255,255,255),"红色":(255,0,0),"绿色":(0,128,0),"蓝色":(0,0,255),
    "黄色":(255,255,0),"青色":(0,255,255),"品红":(255,0,255),"橙色":(255,165,0),"紫色":(128,0,128),
    "粉色":(255,192,203),"棕色":(165,42,42),"灰色":(128,128,128),"银色":(192,192,192),"金色":(255,215,0),
    "深红":(139,0,0),"浅红":(255,102,102),"深绿":(0,100,0),"浅绿":(144,238,144),"深蓝":(0,0,139),
    "浅蓝":(173,216,230),"天蓝":(135,206,235),"珊瑚":(255,127,80),"玫红":(255,20,147),"翠绿":(46,139,87),
    "巧克力":(210,105,30),"番茄红":(255,99,71),"柠檬黄":(255,247,0),"薄荷":(189,252,201),"薰衣草":(230,230,250),
}

# ============ 核心转换函数 ============
def hex_to_rgb(hex_str):
    hex_str = hex_str.strip().lstrip('#')
    if len(hex_str) == 3: hex_str = ''.join(c+c for c in hex_str)
    if len(hex_str) != 6: return None
    try: return tuple(int(hex_str[i:i+2],16) for i in (0,2,4))
    except: return None

def rgb_to_hex(r,g,b):
    return "#{:02X}{:02X}{:02X}".format(max(0,min(255,int(r))),max(0,min(255,int(g))),max(0,min(255,int(b))))

def rgb_to_hsl(r,g,b):
    r,g,b = r/255,g/255,b/255
    mx,mn = max(r,g,b),min(r,g,b)
    h=s=l=(mx+mn)/2
    if mx==mn: h=s=0
    else:
        d=mx-mn
        s=d/(2-mx-mn) if l>0.5 else d/(mx+mn)
        if mx==r: h=(g-b)/d+(6 if g<b else 0)
        elif mx==g: h=(b-r)/d+2
        else: h=(r-g)/d+4
        h/=6
    return int(h*360),int(s*100),int(l*100)

def hsl_to_rgb(h,s,l):
    h,s,l = h/360,s/100,l/100
    if s==0: return int(l*255),int(l*255),int(l*255)
    def f(p,q,t):
        if t<0:t+=1
        if t>1:t-=1
        if t<1/6:return p+(q-p)*6*t
        if t<1/2:return q
        if t<2/3:return p+(q-p)*(2/3-t)*6
        return p
    q=l*(1+s) if l<0.5 else l+s-l*s
    p=2*l-q
    return int(f(p,q,h+1/3)*255),int(f(p,q,h)*255),int(f(p,q,h-1/3)*255)

def find_closest_name(r,g,b):
    return min(COLOR_NAMES.keys(), key=lambda k: sum((c-v)**2 for c,v in zip((r,g,b),COLOR_NAMES[k])))

# ============ 色盲模拟矩阵 ============
def simulate_colorblind(r,g,b, cb_type):
    """使用颜色变换矩阵模拟色盲"""
    rn,gn,bn = r/255,g/255,b/255
    if cb_type == "红色盲":
        # Protanopia
        R = 0.567*rn + 0.433*gn + 0*bn
        G = 0.558*rn + 0.442*gn + 0*bn
        B = 0*rn + 0.242*gn + 0.758*bn
    elif cb_type == "绿色盲":
        # Deuteranopia
        R = 0.625*rn + 0.375*gn + 0*bn
        G = 0.7*rn + 0.3*gn + 0*bn
        B = 0*rn + 0.3*gn + 0.7*bn
    elif cb_type == "蓝色盲":
        # Tritanopia
        R = 0.95*rn + 0.05*gn + 0*bn
        G = 0*rn + 0.433*gn + 0.567*bn
        B = 0*rn + 0.475*gn + 0.525*bn
    elif cb_type == "全色盲":
        # 灰度
        gray = 0.299*rn + 0.587*gn + 0.114*bn
        return int(gray*255),int(gray*255),int(gray*255)
    else:
        return r,g,b
    return int(max(0,min(255,R*255))), int(max(0,min(255,G*255))), int(max(0,min(255,B*255)))

# ============ 配色方案 ============
def get_palette(r,g,b):
    """生成互补色/三角/类似色"""
    h,s,l = rgb_to_hsl(r,g,b)
    h = h/360
    schemes = {}
    # 互补色
    schemes["互补色"] = [hsl_to_rgb((h+0.5)%1 * 360, s, l)]
    # 三角配色
    schemes["三角配色"] = [hsl_to_rgb((h+1/3)%1 * 360, s, l), hsl_to_rgb((h+2/3)%1 * 360, s, l)]
    # 类似色
    schemes["类似色"] = [hsl_to_rgb((h+0.083)%1 * 360, s, l), hsl_to_rgb((h-0.083)%1 * 360, s, l)]
    # 分裂互补
    schemes["分裂互补"] = [hsl_to_rgb((h+0.42)%1 * 360, s, l), hsl_to_rgb((h+0.58)%1 * 360, s, l)]
    # 四角色
    schemes["四角色"] = [hsl_to_rgb((h+0.25)%1 * 360, s, l), hsl_to_rgb((h+0.5)%1 * 360, s, l), hsl_to_rgb((h+0.75)%1 * 360, s, l)]
    return schemes

# ============ 主窗口 ============
class ColorApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("颜色识别工具 v2.0")
        self.geometry("720x620")
        self.config(bg="#1a1a2e")
        self.resizable(False, False)
        self.current_rgb = (255,255,255)
        self._menu()

    def _clear(self):
        for w in self.winfo_children(): w.destroy()

    # ==================== 主菜单 ====================
    def _menu(self):
        self._clear()
        tk.Label(self, text="颜色识别工具 v2.0", bg="#1a1a2e", fg="#FFD700", font=FT_TITLE).place(relx=0.5, y=30, anchor="center")

        cards = [
            ("🎨 颜色转换", "RGB / HEX / HSL / 中文名互转", self._page_convert),
            ("🔍 颜色识别", "输入颜色值，识别颜色信息", self._page_identify),
            ("📋 调色板", "内置常用颜色快速选择", self._page_palette),
            ("⚖ 对比度检测", "检测两种颜色对比度(WCAG)", self._page_contrast),
            ("🖱️ 屏幕取色器", "点击屏幕任意位置取色", self._page_picker),
            ("🌈 渐变生成器", "两个颜色之间生成渐变", self._page_gradient),
            ("📊 配色方案", "互补色/三角/类似色推荐", self._page_palette_gen),
            ("🔤 色盲模拟", "模拟色盲看到的颜色", self._page_cbsim),
        ]
        for i, (title, desc, cmd) in enumerate(cards):
            row = i // 2
            col = i % 2
            f = tk.Frame(self, bg="#16213e", relief=tk.RAISED, bd=1)
            f.place(x=60+col*320, y=80+row*90, width=290, height=75)
            tk.Label(f, text=title, bg="#16213e", fg="white", font=FT_MID).pack(pady=(8,2))
            tk.Label(f, text=desc, bg="#16213e", fg="#aaa", font=FT_SMALL).pack()
            f.bind("<Button-1>", lambda e,c=cmd: c())
            for w in f.winfo_children(): w.bind("<Button-1>", lambda e,c=cmd: c())

    # ==================== 屏幕取色器 ====================
    def _page_picker(self):
        self._clear()
        tk.Label(self, text="🖱️ 屏幕取色器", bg="#1a1a2e", fg="#FFD700", font=FT_TITLE).place(relx=0.5, y=25, anchor="center")

        if not HAS_PIL:
            tk.Label(self, text="需要安装 PIL 库：\npip install pillow pyautogui", bg="#1a1a2e", fg="#FF4444", font=FT_MID).place(relx=0.5, y=150, anchor="center")
            tk.Button(self, text="返回", bg="#666", fg="white", font=FT_BTN, command=self._menu, width=10).place(relx=0.5, y=250, anchor="center")
            return

        tk.Label(self, text="将鼠标移到目标位置，按 F2 取色", bg="#1a1a2e", fg="#aaa", font=FT_BTN).place(relx=0.5, y=80, anchor="center")

        # 放大预览（十字取景器效果）
        self.pick_canvas = tk.Canvas(self, width=200, height=200, bg="#000", relief=tk.RAISED, bd=2)
        self.pick_canvas.place(relx=0.5, y=220, anchor="center")
        self.pick_canvas.create_text(100,100,text="按 F2 取色\n或点击这里实时预览", fill="#666", font=FT_SMALL, justify="center")

        # 结果
        self.pick_result = tk.Label(self, text="", bg="#1a1a2e", fg="white", font=FT_BIG)
        self.pick_result.place(relx=0.5, y=360, anchor="center")

        # 详细信息
        self.pick_info = tk.Label(self, text="坐标: -  颜色: -", bg="#1a1a2e", fg="#aaa", font=FT_SMALL)
        self.pick_info.place(relx=0.5, y=410, anchor="center")

        # 颜色块
        self.pick_block = tk.Frame(self, bg="white", width=120, height=60, relief=tk.RAISED, bd=2)
        self.pick_block.place(relx=0.5, y=460, anchor="center")

        tk.Button(self, text="📋 复制HEX", bg="#2196F3", fg="white", font=FT_BTN,
                  command=lambda: self._copy(self._last_hex or ""), width=10).place(relx=0.35, y=530, anchor="center")
        tk.Button(self, text="返回", bg="#666", fg="white", font=FT_BTN, command=self._menu, width=10).place(relx=0.65, y=530, anchor="center")

        # 绑定F2
        self.bind("<F2>", lambda e: self._do_pick())
        self.bind("<f2>", lambda e: self._do_pick())
        tk.Label(self, text="快捷键: F2 取色", bg="#1a1a2e", fg="#FFD700", font=FT_SMALL).place(relx=0.5, y=570, anchor="center")

        self._last_hex = None

    def _do_pick(self):
        if not HAS_PIL:
            return
        try:
            x, y = pyautogui.position()
            # 截取鼠标周围区域（放大效果）
            screenshot = ImageGrab.grab(bbox=(x-10, y-10, x+10, y+10))
            # 获取中心像素颜色
            r, g, b = screenshot.getpixel((10, 10))[:3]
            # 显示放大图
            screenshot = screenshot.resize((200, 200))
            from PIL import ImageTk
            self._pick_img = ImageTk.PhotoImage(screenshot)
            self.pick_canvas.create_image(100, 100, image=self._pick_img)
            self.pick_canvas.create_line(0,100,200,100,fill="red",width=1)
            self.pick_canvas.create_line(100,0,100,200,fill="red",width=1)

            hex_color = rgb_to_hex(r,g,b)
            self._last_hex = hex_color
            self.pick_result.config(text=hex_color)
            self.pick_info.config(text="坐标: ({}, {})  RGB: ({}, {}, {})  名称: {}".format(x,y,r,g,b,find_closest_name(r,g,b)))
            self.pick_block.config(bg=hex_color)
            self.current_rgb = (r,g,b)
        except Exception as e:
            self.pick_result.config(text="取色失败: {}".format(e), fg="#FF4444")

    # ==================== 渐变生成器 ====================
    def _page_gradient(self):
        self._clear()
        tk.Label(self, text="🌈 渐变生成器", bg="#1a1a2e", fg="#FFD700", font=FT_TITLE).place(relx=0.5, y=25, anchor="center")

        # 颜色1
        tk.Label(self, text="颜色1:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=100, y=70)
        self.grad_c1 = tk.StringVar(value="#FF0000")
        tk.Entry(self, textvariable=self.grad_c1, bg="#16213e", fg="white", font=FT_BTN, width=10, justify="center", insertbackground="white").place(x=180, y=68)

        # 颜色2
        tk.Label(self, text="颜色2:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=100, y=110)
        self.grad_c2 = tk.StringVar(value="#0000FF")
        tk.Entry(self, textvariable=self.grad_c2, bg="#16213e", fg="white", font=FT_BTN, width=10, justify="center", insertbackground="white").place(x=180, y=108)

        # 步数
        tk.Label(self, text="色阶数:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=100, y=150)
        self.grad_steps = tk.IntVar(value=10)
        ttk.Spinbox(self, from_=3, to=30, textvariable=self.grad_steps, width=6, font=FT_BTN).place(x=180, y=148)

        # 方向
        tk.Label(self, text="方向:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=100, y=190)
        self.grad_dir = tk.StringVar(value="水平")
        ttk.Combobox(self, textvariable=self.grad_dir, values=["水平","垂直"], width=6, font=FT_BTN, state="readonly").place(x=180, y=188)

        tk.Button(self, text="生成", bg="#4CAF50", fg="white", font=FT_BTN, command=self._do_gradient, width=10).place(relx=0.5, y=240, anchor="center")

        # 渐变显示
        self.grad_canvas = tk.Canvas(self, width=500, height=80, bg="#000", relief=tk.RAISED, bd=1)
        self.grad_canvas.place(relx=0.5, y=310, anchor="center")

        # 色值列表
        self.grad_list = tk.Text(self, bg="#0f3460", fg="#ccc", font=("Courier", 9), height=6, width=65, relief=tk.FLAT)
        self.grad_list.place(relx=0.5, y=440, anchor="center")

        tk.Button(self, text="返回", bg="#666", fg="white", font=FT_BTN, command=self._menu, width=10).place(relx=0.5, y=570, anchor="center")

    def _do_gradient(self):
        c1 = hex_to_rgb(self.grad_c1.get()) or (255,0,0)
        c2 = hex_to_rgb(self.grad_c2.get()) or (0,0,255)
        steps = self.grad_steps.get()

        self.grad_canvas.delete("all")
        self.grad_list.delete(1.0, tk.END)

        w = 500
        h = 80
        step_w = w // steps

        for i in range(steps):
            t = i / (steps - 1) if steps > 1 else 0
            r = int(c1[0] + (c2[0] - c1[0]) * t)
            g = int(c1[1] + (c2[1] - c1[1]) * t)
            b = int(c1[2] + (c2[2] - c1[2]) * t)
            hex_c = rgb_to_hex(r,g,b)
            x1 = i * step_w
            x2 = (i+1) * step_w
            self.grad_canvas.create_rectangle(x1, 0, x2, h, fill=hex_c, outline=hex_c)
            self.grad_list.insert(tk.END, "{:<12}".format(hex_c))

        self.grad_list.insert(tk.END, "\n\n共 {} 个色阶".format(steps))

    # ==================== 配色方案 ====================
    def _page_palette_gen(self):
        self._clear()
        tk.Label(self, text="📊 配色方案推荐", bg="#1a1a2e", fg="#FFD700", font=FT_TITLE).place(relx=0.5, y=25, anchor="center")

        tk.Label(self, text="基准色:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=100, y=70)
        self.pal_base = tk.StringVar(value="#FF5733")
        tk.Entry(self, textvariable=self.pal_base, bg="#16213e", fg="white", font=FT_BTN, width=10, justify="center", insertbackground="white").place(x=190, y=68)

        tk.Label(self, text="方案:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=100, y=110)
        self.pal_scheme = tk.StringVar(value="互补色")
        ttk.Combobox(self, textvariable=self.pal_scheme, values=["互补色","三角配色","类似色","分裂互补","四角色"], width=10, font=FT_BTN, state="readonly").place(x=190, y=108)

        tk.Button(self, text="生成", bg="#4CAF50", fg="white", font=FT_BTN, command=self._do_palette, width=10).place(relx=0.5, y=160, anchor="center")

        # 配色显示区
        self.pal_canvas = tk.Canvas(self, width=550, height=100, bg="#1a1a2e", highlightthickness=0)
        self.pal_canvas.place(relx=0.5, y=250, anchor="center")

        # 详细信息
        self.pal_info = tk.Text(self, bg="#0f3460", fg="#ccc", font=FT_SMALL, height=10, width=65, relief=tk.FLAT)
        self.pal_info.place(relx=0.5, y=430, anchor="center")

        tk.Button(self, text="返回", bg="#666", fg="white", font=FT_BTN, command=self._menu, width=10).place(relx=0.5, y=570, anchor="center")

    def _do_palette(self):
        base = hex_to_rgb(self.pal_base.get()) or (255,87,51)
        schemes = get_palette(*base)
        scheme_name = self.pal_scheme.get()
        colors = [base] + schemes.get(scheme_name, [])

        self.pal_canvas.delete("all")
        self.pal_info.delete(1.0, tk.END)

        w = 550
        step_w = w // len(colors)

        self.pal_info.insert(tk.END, "方案：{}（基准色 {}）\n\n".format(scheme_name, rgb_to_hex(*base)))
        for i, (r,g,b) in enumerate(colors):
            hex_c = rgb_to_hex(r,g,b)
            x1 = i * step_w
            x2 = (i+1) * step_w
            self.pal_canvas.create_rectangle(x1, 0, x2, 100, fill=hex_c, outline=hex_c)
            label = "基准" if i == 0 else "配色{}".format(i)
            self.pal_canvas.create_text(x1+step_w//2, 50, text=hex_c, fill="white" if sum((r,g,b))<400 else "black", font=FT_SMALL)
            h,s,l = rgb_to_hsl(r,g,b)
            self.pal_info.insert(tk.END, "  {}: {}  RGB({},{},{})  HSL({},{},{})\n".format(label, hex_c, r,g,b,h,s,l))

    # ==================== 色盲模拟 ====================
    def _page_cbsim(self):
        self._clear()
        tk.Label(self, text="🔤 色盲模拟", bg="#1a1a2e", fg="#FFD700", font=FT_TITLE).place(relx=0.5, y=25, anchor="center")

        tk.Label(self, text="输入颜色:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=100, y=70)
        self.cb_input = tk.StringVar(value="#FF5733")
        tk.Entry(self, textvariable=self.cb_input, bg="#16213e", fg="white", font=FT_BTN, width=10, justify="center", insertbackground="white").place(x=200, y=68)

        tk.Label(self, text="色盲类型:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=100, y=110)
        self.cb_type = tk.StringVar(value="红色盲")
        ttk.Combobox(self, textvariable=self.cb_type, values=["红色盲(Protanopia)","绿色盲(Deuteranopia)","蓝色盲(Tritanopia)","全色盲(灰度)"], width=20, font=FT_BTN, state="readonly").place(x=200, y=108)

        tk.Button(self, text="模拟", bg="#4CAF50", fg="white", font=FT_BTN, command=self._do_cbsim, width=10).place(relx=0.5, y=160, anchor="center")

        # 原色 vs 模拟对比
        tk.Label(self, text="原色", bg="#1a1a2e", fg="#aaa", font=FT_SMALL).place(x=180, y=220)
        tk.Label(self, text="模拟", bg="#1a1a2e", fg="#aaa", font=FT_SMALL).place(x=420, y=220)

        self.cb_orig = tk.Frame(self, bg="#FF5733", width=120, height=120, relief=tk.RAISED, bd=2)
        self.cb_orig.place(x=120, y=240)
        self.cb_sim = tk.Frame(self, bg="#FF5733", width=120, height=120, relief=tk.RAISED, bd=2)
        self.cb_sim.place(x=360, y=240)

        # 箭头
        tk.Label(self, text="→", bg="#1a1a2e", fg="white", font=("Arial", 24)).place(x=275, y=290)

        # 详细信息
        self.cb_info = tk.Text(self, bg="#0f3460", fg="#ccc", font=FT_SMALL, height=8, width=65, relief=tk.FLAT)
        self.cb_info.place(relx=0.5, y=440, anchor="center")

        tk.Button(self, text="返回", bg="#666", fg="white", font=FT_BTN, command=self._menu, width=10).place(relx=0.5, y=570, anchor="center")

        # 初始化显示
        self._do_cbsim()

    def _do_cbsim(self):
        rgb = hex_to_rgb(self.cb_input.get()) or (255,87,51)
        cb_type = self.cb_type.get().split("(")[0]
        sim_rgb = simulate_colorblind(*rgb, cb_type)

        self.cb_orig.config(bg=rgb_to_hex(*rgb))
        self.cb_sim.config(bg=rgb_to_hex(*sim_rgb))

        self.cb_info.delete(1.0, tk.END)
        self.cb_info.insert(tk.END, "原色: {}  RGB({}, {}, {})\n".format(rgb_to_hex(*rgb), *rgb))
        self.cb_info.insert(tk.END, "模拟: {}  RGB({}, {}, {})\n\n".format(rgb_to_hex(*sim_rgb), *sim_rgb))
        self.cb_info.insert(tk.END, "色盲类型说明：\n")
        descs = {
            "红色盲": "Protanopia — 无法感知红色，红色调偏暗偏绿",
            "绿色盲": "Deuteranopia — 无法感知绿色，红绿色混淆（最常见）",
            "蓝色盲": "Tritanopia — 无法感知蓝色，蓝黄色混淆（罕见）",
            "全色盲": "Achromatopsia — 只能看到灰度，完全无色彩"
        }
        self.cb_info.insert(tk.END, "  {}：{}\n".format(cb_type, descs.get(cb_type, "")))

    # ==================== 颜色转换页（保留核心功能） ====================
    def _page_convert(self):
        self._clear()
        tk.Label(self, text="颜色转换", bg="#1a1a2e", fg="#FFD700", font=FT_TITLE).place(relx=0.5, y=25, anchor="center")

        self.cv_frame = tk.Frame(self, bg="white", width=200, height=80, relief=tk.RAISED, bd=2)
        self.cv_frame.place(relx=0.5, y=80, anchor="center")

        tk.Label(self, text="HEX:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=200, y=140)
        self.c_hex = tk.StringVar()
        tk.Entry(self, textvariable=self.c_hex, bg="#16213e", fg="white", font=FT_BTN, width=12, justify="center", insertbackground="white").place(x=260, y=138)

        tk.Label(self, text="R:", bg="#1a1a2e", fg="#ff6666", font=FT_BTN).place(x=200, y=180)
        self.c_r = tk.StringVar()
        tk.Entry(self, textvariable=self.c_r, bg="#16213e", fg="white", font=FT_BTN, width=5, justify="center", insertbackground="white").place(x=230, y=178)
        tk.Label(self, text="G:", bg="#1a1a2e", fg="#66ff66", font=FT_BTN).place(x=290, y=180)
        self.c_g = tk.StringVar()
        tk.Entry(self, textvariable=self.c_g, bg="#16213e", fg="white", font=FT_BTN, width=5, justify="center", insertbackground="white").place(x=320, y=178)
        tk.Label(self, text="B:", bg="#1a1a2e", fg="#6666ff", font=FT_BTN).place(x=380, y=180)
        self.c_b = tk.StringVar()
        tk.Entry(self, textvariable=self.c_b, bg="#16213e", fg="white", font=FT_BTN, width=5, justify="center", insertbackground="white").place(x=410, y=178)

        tk.Label(self, text="颜色名:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=200, y=220)
        self.c_name = tk.StringVar()
        tk.Entry(self, textvariable=self.c_name, bg="#16213e", fg="white", font=FT_BTN, width=12, justify="center", insertbackground="white").place(x=280, y=218)

        tk.Button(self, text="转换", bg="#4CAF50", fg="white", font=FT_BTN, command=self._do_convert, width=10).place(relx=0.35, y=270, anchor="center")
        tk.Button(self, text="随机", bg="#FF9800", fg="white", font=FT_BTN, command=self._random_color, width=10).place(relx=0.65, y=270, anchor="center")

        self.c_info = tk.Label(self, text="", bg="#1a1a2e", fg="#aaa", font=FT_SMALL)
        self.c_info.place(relx=0.5, y=330, anchor="center")

        tk.Button(self, text="复制HEX", bg="#2196F3", fg="white", font=FT_BTN, command=lambda: self._copy(self.c_hex.get()), width=8).place(relx=0.35, y=380, anchor="center")
        tk.Button(self, text="返回", bg="#666", fg="white", font=FT_BTN, command=self._menu, width=8).place(relx=0.65, y=380, anchor="center")

    def _do_convert(self):
        r,g,b = None,None,None
        hex_val = self.c_hex.get().strip()
        name_val = self.c_name.get().strip()
        if hex_val:
            result = hex_to_rgb(hex_val)
            if result: r,g,b = result
        elif name_val and name_val in COLOR_NAMES:
            r,g,b = COLOR_NAMES[name_val]
        else:
            try: r,g,b = int(self.c_r.get() or 0), int(self.c_g.get() or 0), int(self.c_b.get() or 0)
            except: return
        if r is None: return
        r,g,b = max(0,min(255,r)),max(0,min(255,g)),max(0,min(255,b))
        self.c_r.set(str(r)); self.c_g.set(str(g)); self.c_b.set(str(b))
        self.c_hex.set(rgb_to_hex(r,g,b))
        self.c_name.set(find_closest_name(r,g,b))
        self.cv_frame.config(bg=rgb_to_hex(r,g,b))
        self.c_info.config(text="{} | HSL: {}".format(find_closest_name(r,g,b), rgb_to_hsl(r,g,b)))

    def _random_color(self):
        r,g,b = random.randint(0,255),random.randint(0,255),random.randint(0,255)
        self.c_r.set(str(r)); self.c_g.set(str(g)); self.c_b.set(str(b))
        self.c_hex.set(""); self.c_name.set("")
        self._do_convert()

    # ==================== 识别/调色板/对比度（精简版） ====================
    def _page_identify(self):
        self._clear()
        tk.Label(self, text="颜色识别", bg="#1a1a2e", fg="#FFD700", font=FT_TITLE).place(relx=0.5, y=25, anchor="center")
        tk.Label(self, text="输入颜色值（HEX/RGB/颜色名）:", bg="#1a1a2e", fg="white", font=FT_BTN).place(relx=0.5, y=80, anchor="center")
        self.i_input = tk.StringVar()
        tk.Entry(self, textvariable=self.i_input, bg="#16213e", fg="white", font=FT_BIG, width=18, justify="center", insertbackground="white").place(relx=0.5, y=120, anchor="center")
        tk.Button(self, text="识别", bg="#4CAF50", fg="white", font=FT_BTN, command=self._do_identify, width=10).place(relx=0.5, y=170, anchor="center")
        self.i_preview = tk.Frame(self, bg="white", width=200, height=80, relief=tk.RAISED, bd=2)
        self.i_preview.place(relx=0.5, y=260, anchor="center")
        self.i_info = tk.Text(self, bg="#0f3460", fg="#ccc", font=FT_SMALL, height=8, width=60, relief=tk.FLAT)
        self.i_info.place(relx=0.5, y=420, anchor="center")
        self.i_info.config(state=tk.DISABLED)
        tk.Button(self, text="返回", bg="#666", fg="white", font=FT_BTN, command=self._menu, width=10).place(relx=0.5, y=560, anchor="center")
        self.bind("<Return>", lambda e: self._do_identify())

    def _do_identify(self):
        val = self.i_input.get().strip()
        r,g,b = None,None,None
        if hex_to_rgb(val): r,g,b = hex_to_rgb(val)
        elif re.match(r'^\d+[\s,]+?\d+[\s,]+?\d+$', val):
            p = re.split(r'[\s,]+', val)
            try: r,g,b = int(p[0]),int(p[1]),int(p[2])
            except: pass
        elif val in COLOR_NAMES: r,g,b = COLOR_NAMES[val]
        if r is None: return
        r,g,b = max(0,min(255,r)),max(0,min(255,g)),max(0,min(255,b))
        hex_c = rgb_to_hex(r,g,b)
        self.i_preview.config(bg=hex_c)
        self.i_info.config(state=tk.NORMAL)
        self.i_info.delete(1.0, tk.END)
        self.i_info.insert(tk.END, "  {}  |  RGB({},{},{})  |  HSL{}".format(find_closest_name(r,g,b),r,g,b,rgb_to_hsl(r,g,b)))
        self.i_info.config(state=tk.DISABLED)

    def _page_palette(self):
        self._clear()
        tk.Label(self, text="调色板", bg="#1a1a2e", fg="#FFD700", font=FT_TITLE).place(relx=0.5, y=25, anchor="center")
        row, col = 0, 0
        for name, rgb in COLOR_NAMES.items():
            f = tk.Frame(self, bg=rgb_to_hex(*rgb), width=50, height=35, relief=tk.RAISED, bd=1)
            f.place(x=40+col*58, y=70+row*42)
            f.bind("<Button-1>", lambda e, r=rgb[0],g=rgb[1],b=rgb[2]: self._pick_color(r,g,b))
            col += 1
            if col >= 11: col=0; row+=1
        tk.Button(self, text="返回", bg="#666", fg="white", font=FT_BTN, command=self._menu, width=10).place(relx=0.5, y=560, anchor="center")

    def _pick_color(self,r,g,b):
        self.current_rgb=(r,g,b)
        self._page_convert()
        self.c_r.set(str(r)); self.c_g.set(str(g)); self.c_b.set(str(b))
        self._do_convert()

    def _page_contrast(self):
        self._clear()
        tk.Label(self, text="对比度检测", bg="#1a1a2e", fg="#FFD700", font=FT_TITLE).place(relx=0.5, y=25, anchor="center")
        tk.Label(self, text="颜色1 HEX:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=150, y=80)
        self.ct_h1 = tk.StringVar(value="#FFFFFF")
        tk.Entry(self, textvariable=self.ct_h1, bg="#16213e", fg="white", font=FT_BTN, width=10, justify="center", insertbackground="white").place(x=260, y=78)
        tk.Label(self, text="颜色2 HEX:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=150, y=120)
        self.ct_h2 = tk.StringVar(value="#000000")
        tk.Entry(self, textvariable=self.ct_h2, bg="#16213e", fg="white", font=FT_BTN, width=10, justify="center", insertbackground="white").place(x=260, y=118)
        tk.Button(self, text="检测", bg="#4CAF50", fg="white", font=FT_BTN, command=self._do_contrast_simple, width=10).place(relx=0.5, y=170, anchor="center")
        self.ct_rl = tk.Label(self, text="", bg="#1a1a2e", fg="white", font=FT_BIG)
        self.ct_rl.place(relx=0.5, y=250, anchor="center")
        tk.Button(self, text="返回", bg="#666", fg="white", font=FT_BTN, command=self._menu, width=10).place(relx=0.5, y=320, anchor="center")

    def _do_contrast_simple(self):
        def lum(r,g,b):
            def lin(c): c=c/255; return c/12.92 if c<=0.03928 else ((c+0.055)/1.055)**2.4
            return 0.2126*lin(r)+0.7152*lin(g)+0.0722*lin(b)
        c1 = hex_to_rgb(self.ct_h1.get()) or (255,255,255)
        c2 = hex_to_rgb(self.ct_h2.get()) or (0,0,0)
        l1,l2 = lum(*c1),lum(*c2)
        ratio = round((max(l1,l2)+0.05)/(min(l1,l2)+0.05),2)
        self.ct_rl.config(text="对比度: {}:1".format(ratio))

    def _copy(self, text):
        self.clipboard_clear()
        self.clipboard_append(text)
        messagebox.showinfo("复制", "已复制: {}".format(text))

# ============ 入口 ============
if __name__ == "__main__":
    app = ColorApp()
    app.mainloop()