import pygame
import sys
import pyautogui
import pyperclip

pygame.init()

WIDTH, HEIGHT = 700, 420
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("全局取色器 | 颜色识别工具")

# ========== 修复字体部分 ==========
try:
    font = pygame.font.SysFont("simhei", 26)
    font_small = pygame.font.SysFont("simhei", 20)
except:
    try:
        font = pygame.font.SysFont("Arial", 26)
        font_small = pygame.font.SysFont("Arial", 20)
    except:
        font = pygame.font.Font(None, 26)
        font_small = pygame.font.Font(None, 20)
# =================================

preview_w, preview_h = 140, 140

def rgb_to_hex(r, g, b):
    return f"#{r:02X}{g:02X}"

def main():
    clock = pygame.time.Clock()
    running = True
    last_hex = "#000000"
    tip_text = "提示：鼠标移出窗口取色，左键复制HEX"

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    try:
                        pyperclip.copy(last_hex)
                        tip_text = "✅ 色号已复制剪贴板！"
                    except Exception:
                        tip_text = "❌ 剪贴板复制失败"

        try:
            mx, my = pyautogui.position()
            r, g, b = pyautogui.pixel(mx, my)
            last_hex = rgb_to_hex(r, g, b)
        except Exception as e:
            r, g, b = 100,100,100
            tip_text = f"取色异常:{str(e)[:20]}"

        screen.fill((25, 25, 25))

        color_rect = pygame.Rect(30, 30, preview_w, preview_h)
        pygame.draw.rect(screen, (r, g, b), color_rect)
        pygame.draw.rect(screen, (255,255,255), color_rect, 3)

        text_rgb = font.render(f"RGB: ({r}, {g}, {b})", True, (255,255,255))
        text_hex = font.render(f"HEX: {last_hex}", True, (255,255,255))
        text_pos = font_small.render(f"全局坐标: ({mx}, {my})", True, (220,220,220))
        tip_render = font_small.render(tip_text, True, (180, 220, 255))

        screen.blit(text_rgb, (190, 35))
        screen.blit(text_hex, (190, 75))
        screen.blit(text_pos, (190, 120))
        screen.blit(tip_render, (30, 200))

        lx, ly = pygame.mouse.get_pos()
        pygame.draw.line(screen, (255,255,255), (lx - 15, ly), (lx + 15, ly), 2)
        pygame.draw.line(screen, (255,255,255), (lx, ly - 15), (lx, ly + 15), 2)

        pygame.display.flip()
        clock.tick(30)

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()
