image_generator.py 46.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
#!/usr/bin/env python3
"""
Gemini Image Generator App
Simple GUI application for generating images using Google's Gemini API
"""

import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
from PIL import Image, ImageTk
import base64
import io
import json
import os
import sys
import tempfile
import subprocess
import platform
from pathlib import Path
from google import genai
from google.genai import types
import threading
import hashlib
import pymysql
from datetime import datetime


def hash_password(password: str) -> str:
    """使用 SHA256 哈希密码"""
    return hashlib.sha256(password.encode('utf-8')).hexdigest()


class DatabaseManager:
    """数据库连接管理类"""
    def __init__(self, db_config):
        self.config = db_config

    def authenticate(self, username, password):
        """
        验证用户凭证
        返回: (success: bool, message: str)
        """
        try:
            # 计算密码哈希
            password_hash = hash_password(password)

            # 连接数据库
            conn = pymysql.connect(
                host=self.config['host'],
                port=self.config.get('port', 3306),
                user=self.config['user'],
                password=self.config['password'],
                database=self.config['database'],
                connect_timeout=5
            )

            try:
                with conn.cursor() as cursor:
                    # 使用参数化查询防止 SQL 注入
                    sql = f"SELECT * FROM {self.config['table']} WHERE user_name=%s AND passwd=%s AND status='active'"
                    cursor.execute(sql, (username, password_hash))
                    result = cursor.fetchone()

                    if result:
                        return True, "认证成功"
                    else:
                        return False, "用户名或密码错误"
            finally:
                conn.close()

        except pymysql.OperationalError as e:
            return False, "无法连接到服务器,请检查网络连接"
        except Exception as e:
            return False, f"认证失败: {str(e)}"


class LoginWindow:
    """登录窗口类"""
    def __init__(self, db_config, last_user="", saved_password_hash=""):
        self.db_config = db_config
        self.last_user = last_user
        self.saved_password_hash = saved_password_hash
        self.success = False
        self.authenticated_user = ""
        self.password_changed = False  # 标记密码是否被修改

        # 创建登录窗口
        self.root = tk.Tk()
        self.root.title("登录 - AI 图像生成器")
        self.root.geometry("400x400")
        self.root.resizable(False, False)

        # 创建 BooleanVar (必须在 Tk 根窗口创建之后)
        self.remember_user = tk.BooleanVar(value=bool(last_user))
        self.remember_password = tk.BooleanVar(value=bool(saved_password_hash))

        # 设置窗口居中
        self.center_window()

        # 设置样式
        self.setup_styles()

        # 创建UI
        self.setup_ui()

        # 绑定回车键
        self.root.bind('<Return>', lambda e: self.on_login())

        # 处理窗口关闭
        self.root.protocol("WM_DELETE_WINDOW", self.on_close)

    def center_window(self):
        """窗口居中显示"""
        self.root.update_idletasks()
        width = self.root.winfo_width()
        height = self.root.winfo_height()
        x = (self.root.winfo_screenwidth() // 2) - (width // 2)
        y = (self.root.winfo_screenheight() // 2) - (height // 2)
        self.root.geometry(f'{width}x{height}+{x}+{y}')

    def setup_styles(self):
        """设置样式"""
        style = ttk.Style()
        style.theme_use('clam')

        bg_color = '#ffffff'
        accent_color = '#007AFF'

        self.root.configure(bg=bg_color)

        style.configure('Login.TButton',
                       background=accent_color,
                       foreground='white',
                       borderwidth=0,
                       focuscolor='none',
                       font=('Segoe UI', 10, 'bold'),
                       padding=(20, 10))

        style.map('Login.TButton',
                 background=[('active', '#0051D5'), ('pressed', '#0051D5')])

    def setup_ui(self):
        """创建登录界面"""
        # 主容器
        main_frame = ttk.Frame(self.root, padding=40)
        main_frame.pack(fill="both", expand=True)

        # 标题
        title_label = tk.Label(main_frame, text="登录",
                              font=('Segoe UI', 20, 'bold'),
                              bg='white', fg='#1d1d1f')
        title_label.pack(pady=(0, 30))

        # 用户名
        username_frame = ttk.Frame(main_frame)
        username_frame.pack(fill="x", pady=(0, 15))

        username_label = tk.Label(username_frame, text="用户名",
                                 font=('Segoe UI', 10),
                                 bg='white', fg='#666666')
        username_label.pack(anchor="w")

        self.username_entry = tk.Entry(username_frame,
                                       font=('Segoe UI', 11),
                                       relief='solid',
                                       borderwidth=1)
        self.username_entry.pack(fill="x", ipady=8, pady=(5, 0))
        self.username_entry.insert(0, self.last_user)

        # 密码
        password_frame = ttk.Frame(main_frame)
        password_frame.pack(fill="x", pady=(0, 15))

        password_label = tk.Label(password_frame, text="密码",
                                 font=('Segoe UI', 10),
                                 bg='white', fg='#666666')
        password_label.pack(anchor="w")

        self.password_entry = tk.Entry(password_frame,
                                       font=('Segoe UI', 11),
                                       relief='solid',
                                       borderwidth=1,
                                       show='*')
        self.password_entry.pack(fill="x", ipady=8, pady=(5, 0))

        # 如果有保存的密码,显示占位符
        if self.saved_password_hash:
            self.password_entry.insert(0, "••••••••")
            self.password_entry.config(fg='#999999')

        # 监听密码框变化
        self.password_entry.bind('<KeyPress>', self.on_password_change)
        self.password_entry.bind('<Return>', lambda e: self.on_login())

        # 复选框容器
        checkbox_frame = ttk.Frame(main_frame)
        checkbox_frame.pack(fill="x", pady=(0, 20))

        # 记住用户名复选框
        remember_user_check = tk.Checkbutton(checkbox_frame,
                                       text="记住用户名",
                                       variable=self.remember_user,
                                       font=('Segoe UI', 9),
                                       bg='white',
                                       activebackground='white')
        remember_user_check.pack(side="left")

        # 记住密码复选框
        remember_password_check = tk.Checkbutton(checkbox_frame,
                                       text="记住密码",
                                       variable=self.remember_password,
                                       font=('Segoe UI', 9),
                                       bg='white',
                                       activebackground='white')
        remember_password_check.pack(side="left", padx=(20, 0))

        # 登录按钮
        self.login_button = ttk.Button(main_frame,
                                       text="登录",
                                       style='Login.TButton',
                                       command=self.on_login)
        self.login_button.pack(fill="x")

        # 错误提示标签
        self.error_label = tk.Label(main_frame,
                                   text="",
                                   font=('Segoe UI', 9),
                                   bg='white',
                                   fg='#ff3b30')
        self.error_label.pack(pady=(15, 0))

        # 焦点设置
        if self.last_user:
            self.password_entry.focus()
        else:
            self.username_entry.focus()

    def on_password_change(self, event):
        """监听密码框变化"""
        if not self.password_changed and self.saved_password_hash:
            # 首次修改密码,清空占位符
            self.password_entry.delete(0, tk.END)
            self.password_entry.config(fg='#000000')
            self.password_changed = True

    def on_login(self):
        """处理登录"""
        print("[DEBUG] 登录按钮被点击")
        username = self.username_entry.get().strip()
        password_input = self.password_entry.get()

        print(f"[DEBUG] 用户名: {username}")
        print(f"[DEBUG] 密码输入长度: {len(password_input)}")
        print(f"[DEBUG] 密码已修改: {self.password_changed}")
        print(f"[DEBUG] 有保存的哈希: {bool(self.saved_password_hash)}")

        # 验证输入
        if not username:
            print("[DEBUG] 用户名为空")
            self.show_error("请输入用户名")
            return

        if not password_input:
            print("[DEBUG] 密码为空")
            self.show_error("请输入密码")
            return

        # 禁用按钮,防止重复点击
        self.login_button.config(state='disabled')
        self.error_label.config(text="正在验证...", fg='#666666')
        self.root.update()

        # 判断使用保存的密码还是新输入的密码
        if not self.password_changed and self.saved_password_hash:
            # 使用保存的密码哈希
            print("[DEBUG] 使用保存的密码哈希")
            password_hash = self.saved_password_hash
        else:
            # 计算新密码的哈希
            print("[DEBUG] 计算新密码的哈希")
            password_hash = hash_password(password_input)

        # 直接使用哈希值进行数据库验证
        try:
            print(f"[DEBUG] 开始连接数据库: {self.db_config['host']}")
            conn = pymysql.connect(
                host=self.db_config['host'],
                port=self.db_config.get('port', 3306),
                user=self.db_config['user'],
                password=self.db_config['password'],
                database=self.db_config['database'],
                connect_timeout=5
            )
            print("[DEBUG] 数据库连接成功")

            try:
                with conn.cursor() as cursor:
                    sql = f"SELECT * FROM {self.db_config['table']} WHERE user_name=%s AND passwd=%s AND status='active'"
                    print(f"[DEBUG] 执行查询,用户名: {username}, 哈希前8位: {password_hash[:8]}...")
                    cursor.execute(sql, (username, password_hash))
                    result = cursor.fetchone()
                    print(f"[DEBUG] 查询结果: {'找到用户' if result else '未找到匹配'}")

                    if result:
                        print("[DEBUG] 登录成功")
                        self.success = True
                        self.authenticated_user = username
                        # 保存密码哈希用于下次登录
                        self.current_password_hash = password_hash
                        self.root.quit()
                        self.root.destroy()
                    else:
                        print("[DEBUG] 用户名或密码错误")
                        self.show_error("用户名或密码错误")
                        self.password_entry.delete(0, tk.END)
                        self.password_changed = False
                        self.login_button.config(state='normal')
            finally:
                conn.close()
                print("[DEBUG] 数据库连接已关闭")

        except pymysql.OperationalError as e:
            print(f"[DEBUG] 数据库连接失败: {e}")
            self.show_error("无法连接到服务器,请检查网络连接")
            self.login_button.config(state='normal')
        except Exception as e:
            print(f"[DEBUG] 认证异常: {e}")
            self.show_error(f"认证失败: {str(e)}")
            self.login_button.config(state='normal')

    def show_error(self, message):
        """显示错误信息"""
        self.error_label.config(text=message, fg='#ff3b30')

    def on_close(self):
        """处理窗口关闭"""
        self.success = False
        self.root.quit()
        self.root.destroy()

    def run(self):
        """运行登录窗口"""
        self.root.mainloop()
        return (self.success,
                self.authenticated_user,
                self.remember_user.get(),
                self.remember_password.get(),
                getattr(self, 'current_password_hash', ''))


class ImageGeneratorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("AI 图像生成器")
        self.root.geometry("1200x850")
        self.root.minsize(1000, 700)

        # Configure modern styling
        self.setup_styles()

        self.api_key = ""
        self.uploaded_images = []  # List of (file_path, PhotoImage) tuples
        self.generated_image_data = None
        self.generated_image_bytes = None
        self.saved_prompts = []  # Store favorite prompts

        self.load_config()
        self.setup_ui()

    def setup_styles(self):
        """Setup modern macOS-inspired UI styles"""
        style = ttk.Style()
        style.theme_use('clam')
        
        # macOS-inspired color palette
        bg_color = '#ffffff'
        secondary_bg = '#f6f6f6'
        accent_color = '#007AFF'
        hover_color = '#0051D5'
        border_color = '#e5e5e5'
        text_color = '#1d1d1f'
        
        self.root.configure(bg=bg_color)
        
        # Primary button style
        style.configure('Accent.TButton',
                       background=accent_color,
                       foreground='white',
                       borderwidth=1,
                       relief='solid',
                       focuscolor='none',
                       font=('Segoe UI', 10),
                       padding=(18, 8))

        style.map('Accent.TButton',
                 background=[('active', hover_color), ('pressed', '#003D99')],
                 foreground=[('disabled', '#999999')])
        
        # Secondary button style
        style.configure('Secondary.TButton',
                       background=secondary_bg,
                       foreground=text_color,
                       borderwidth=1,
                       relief='solid',
                       font=('Segoe UI', 9),
                       padding=(12, 6))

        style.map('Secondary.TButton',
                 background=[('active', '#e8e8e8'), ('pressed', '#c8c8c8')])
        
        # Icon button style (small, subtle)
        style.configure('Icon.TButton',
                       background=bg_color,
                       foreground='#666666',
                       borderwidth=1,
                       relief='solid',
                       font=('Segoe UI', 9),
                       padding=(4, 4))

        style.map('Icon.TButton',
                 background=[('active', secondary_bg), ('pressed', '#d8d8d8')],
                 foreground=[('active', accent_color)])
        
        # Delete button style (visible with red hover)
        style.configure('Delete.TButton',
                       background='#ff4444',
                       foreground='#ffffff',
                       borderwidth=1,
                       relief='solid',
                       font=('Segoe UI', 9, 'bold'),
                       padding=(3, 1))
        
        style.map('Delete.TButton',
                 background=[('active', '#FF3B30'), ('pressed', '#cc0000')],
                 foreground=[('active', 'white'), ('pressed', 'white')],
                 borderwidth=[('active', 1)],
                 relief=[('active', 'solid')])
        
        style.configure('TLabelframe', background=bg_color, borderwidth=0, relief='flat')
        style.configure('TLabelframe.Label', background=bg_color, font=('Segoe UI', 10, 'bold'), foreground=text_color)
        style.configure('TLabel', background=bg_color, font=('Segoe UI', 9), foreground=text_color)
        style.configure('TFrame', background=bg_color)
        style.configure('Card.TFrame', background=secondary_bg, relief='flat')
        style.configure('TCombobox', font=('Segoe UI', 9))

    def get_config_dir(self):
        """Get the appropriate directory for config files based on platform and mode"""
        # Check if running as a bundled app (PyInstaller)
        if getattr(sys, 'frozen', False):
            # Running as bundled app - use user data directory
            system = platform.system()
            if system == 'Darwin':  # macOS
                config_dir = Path.home() / 'Library' / 'Application Support' / 'ZB100ImageGenerator'
            elif system == 'Windows':
                config_dir = Path(os.getenv('APPDATA', Path.home())) / 'ZB100ImageGenerator'
            else:  # Linux and others
                config_dir = Path.home() / '.config' / 'zb100imagegenerator'
        else:
            # Running in development mode - use current directory
            config_dir = Path('.')

        # Create directory if it doesn't exist
        config_dir.mkdir(parents=True, exist_ok=True)
        return config_dir

    def get_config_path(self):
        """Get the full path to config.json"""
        return self.get_config_dir() / 'config.json'

    def load_config(self):
        """Load API key, saved prompts, and db config from config file"""
        config_path = self.get_config_path()

        # 初始化默认值
        self.db_config = None
        self.last_user = ""
        self.saved_password_hash = ""

        # Try to load from user config first
        if config_path.exists():
            try:
                with open(config_path, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    self.api_key = config.get("api_key", "")
                    self.saved_prompts = config.get("saved_prompts", [])
                    self.db_config = config.get("db_config")
                    self.last_user = config.get("last_user", "")
                    self.saved_password_hash = config.get("saved_password_hash", "")
            except Exception as e:
                print(f"Failed to load config from {config_path}: {e}")

        # If no config found and we're in bundled mode, try to load from bundled resources
        if not self.api_key and getattr(sys, 'frozen', False):
            try:
                # PyInstaller creates a temp folder and stores path in _MEIPASS
                bundle_dir = Path(sys._MEIPASS)
                bundled_config = bundle_dir / 'config.json'
                if bundled_config.exists():
                    with open(bundled_config, 'r', encoding='utf-8') as f:
                        config = json.load(f)
                        self.api_key = config.get("api_key", "")
                        self.db_config = config.get("db_config")
                        # Don't load saved_prompts from bundle, only API key
                    # Save to user config for future use
                    self.save_config()
            except Exception as e:
                print(f"Failed to load bundled config: {e}")

        if not self.api_key:
            messagebox.showwarning("警告", f"未找到API密钥\n配置文件位置: {config_path}\n\n请在应用中输入API密钥或手动编辑配置文件")

    def save_config(self, last_user=None):
        """Save configuration to file"""
        config_path = self.get_config_path()

        try:
            config = {
                "api_key": self.api_key,
                "saved_prompts": self.saved_prompts
            }

            # 添加数据库配置(如果存在)
            if self.db_config:
                config["db_config"] = self.db_config

            # 添加最后登录用户
            if last_user is not None:
                config["last_user"] = last_user
            elif hasattr(self, 'last_user'):
                config["last_user"] = self.last_user
            else:
                config["last_user"] = ""

            # 添加保存的密码哈希
            if hasattr(self, 'saved_password_hash'):
                config["saved_password_hash"] = self.saved_password_hash
            else:
                config["saved_password_hash"] = ""

            # Ensure directory exists
            config_path.parent.mkdir(parents=True, exist_ok=True)

            with open(config_path, 'w', encoding='utf-8') as f:
                json.dump(config, f, indent=2, ensure_ascii=False)
        except Exception as e:
            messagebox.showerror("错误", f"保存配置失败: {str(e)}\n路径: {config_path}")

    def setup_ui(self):
        """Setup the user interface with macOS-inspired design"""
        # Main container
        main_container = ttk.Frame(self.root, padding=20)
        main_container.pack(fill="both", expand=True)
        
        # Reference Images Section with preview
        ref_frame = ttk.LabelFrame(main_container, text="参考图片", padding=12)
        ref_frame.pack(fill="x", pady=(0, 15))
        
        # Upload button and info
        upload_header = ttk.Frame(ref_frame)
        upload_header.pack(fill="x", pady=(0, 8))
        
        upload_btn = ttk.Button(upload_header, text="+ 添加图片", 
                               command=self.upload_images, 
                               style='Secondary.TButton')
        upload_btn.pack(side="left")
        self.bind_hover_effect(upload_btn)
        
        self.image_count_label = ttk.Label(upload_header, text="已选择 0 张", foreground='#666666')
        self.image_count_label.pack(side="left", padx=12)
        
        # Image preview container (horizontal scrollable)
        preview_container = ttk.Frame(ref_frame, style='Card.TFrame', height=140)
        preview_container.pack(fill="x", pady=(0, 0))
        preview_container.pack_propagate(False)
        
        # Canvas for horizontal scrolling (without visible scrollbar)
        self.img_canvas = tk.Canvas(preview_container, height=110, bg='#f6f6f6', 
                                    highlightthickness=0, bd=0)
        self.img_preview_frame = ttk.Frame(self.img_canvas, style='Card.TFrame')
        
        self.img_preview_frame.bind("<Configure>", 
                                    lambda e: self.img_canvas.configure(scrollregion=self.img_canvas.bbox("all")))
        
        self.img_canvas.create_window((0, 0), window=self.img_preview_frame, anchor="nw")
        
        # Enable mouse wheel scrolling
        self.img_canvas.bind('<MouseWheel>', self._on_mousewheel)
        self.img_canvas.bind('<Shift-MouseWheel>', self._on_mousewheel)
        
        self.img_canvas.pack(fill="both", expand=True)
        
        # Content area: Prompt (left) + Settings (right)
        content_row = ttk.Frame(main_container)
        content_row.pack(fill="x", pady=(0, 15))
        
        # Left: Prompt Section
        prompt_container = ttk.LabelFrame(content_row, text="提示词", padding=12)
        prompt_container.pack(side="left", fill="both", expand=True, padx=(0, 10))
        
        # Prompt toolbar
        prompt_toolbar = ttk.Frame(prompt_container)
        prompt_toolbar.pack(fill="x", pady=(0, 8))
        
        self.save_prompt_btn = ttk.Button(prompt_toolbar, text="⭐ 收藏",
                                     command=self.toggle_favorite,
                                     style='Icon.TButton')
        self.save_prompt_btn.pack(side="left", padx=(0, 5))
        self.bind_hover_effect(self.save_prompt_btn)
        
        # Saved prompts dropdown
        ttk.Label(prompt_toolbar, text="快速选择:", foreground='#666666').pack(side="left", padx=(10, 5))
        self.saved_prompts_combo = ttk.Combobox(prompt_toolbar, width=30, state="readonly")
        self.saved_prompts_combo.pack(side="left")
        self.saved_prompts_combo.bind('<<ComboboxSelected>>', self.load_saved_prompt)
        self.update_saved_prompts_list()
        
        # Delete saved prompt button
        delete_prompt_btn = ttk.Button(prompt_toolbar, text="🗑️ 删除", 
                                      command=self.delete_saved_prompt, 
                                      style='Icon.TButton')
        delete_prompt_btn.pack(side="left", padx=(5, 0))
        self.bind_hover_effect(delete_prompt_btn)
        
        # Prompt text area
        self.prompt_text = scrolledtext.ScrolledText(prompt_container, height=8, wrap=tk.WORD,
                                                     font=('Segoe UI', 10),
                                                     borderwidth=1, relief='solid',
                                                     bg='#fafafa')
        self.prompt_text.pack(fill="both", expand=True)
        self.prompt_text.insert("1.0", "一幅美丽的风景画,有山有湖,日落时分")

        # Bind text change event to check favorite status
        self.prompt_text.bind('<<Modified>>', self.on_prompt_change)

        # Right: Settings Section
        settings_container = ttk.LabelFrame(content_row, text="生成设置", padding=12)
        settings_container.pack(side="right", fill="y")
        
        # Aspect Ratio
        ttk.Label(settings_container, text="宽高比", foreground='#666666').pack(anchor="w", pady=(0, 4))
        self.aspect_ratio = ttk.Combobox(settings_container, width=18, state="readonly")
        self.aspect_ratio['values'] = ("1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9")
        self.aspect_ratio.current(0)
        self.aspect_ratio.pack(fill="x", pady=(0, 12))
        
        # Image Size
        ttk.Label(settings_container, text="图片尺寸", foreground='#666666').pack(anchor="w", pady=(0, 4))
        self.image_size = ttk.Combobox(settings_container, width=18, state="readonly")
        self.image_size['values'] = ("1K", "2K", "4K")
        self.image_size.current(1)
        self.image_size.pack(fill="x", pady=(0, 0))
        
        # Action buttons
        action_frame = ttk.Frame(main_container)
        action_frame.pack(fill="x", pady=(0, 15))
        
        self.generate_btn = ttk.Button(action_frame, text="生成图片", 
                                       command=self.generate_image_async, 
                                       style='Accent.TButton')
        self.generate_btn.pack(side="left", padx=(0, 10))
        self.bind_hover_effect(self.generate_btn, scale=True)
        
        self.download_btn = ttk.Button(action_frame, text="下载图片", 
                                       command=self.download_image, 
                                       state="disabled",
                                       style='Secondary.TButton')
        self.download_btn.pack(side="left", padx=(0, 10))
        self.bind_hover_effect(self.download_btn)
        
        self.status_label = ttk.Label(action_frame, text="● 就绪", 
                                      font=('Segoe UI', 9),
                                      foreground='#007AFF')
        self.status_label.pack(side="left", padx=15)
        
        # Preview Section (expands to fill remaining space)
        preview_frame = ttk.LabelFrame(main_container, text="预览", padding=12)
        preview_frame.pack(fill="both", expand=True)
        
        # Create a frame to center the image
        preview_inner = ttk.Frame(preview_frame)
        preview_inner.pack(fill="both", expand=True)
        
        self.preview_label = ttk.Label(preview_inner, text="生成的图片将在这里显示\n双击用系统查看器打开", 
                                      anchor="center",
                                      font=('Segoe UI', 10),
                                      foreground='#999999')
        self.preview_label.place(relx=0.5, rely=0.5, anchor="center")
        
        # Bind double-click to open with system viewer
        self.preview_label.bind('<Double-Button-1>', self.open_fullsize_view)
    
    def _on_mousewheel(self, event):
        """Handle horizontal scrolling with mouse wheel"""
        # Shift+Wheel or just Wheel for horizontal scroll
        self.img_canvas.xview_scroll(int(-1 * (event.delta / 120)), "units")
    
    def bind_hover_effect(self, widget, scale=False):
        """Add smooth macOS-style hover effect"""
        original_cursor = widget['cursor']
        
        def on_enter(e):
            widget['cursor'] = 'hand2'
            # Subtle scale effect for primary buttons
            if scale and hasattr(widget, 'configure'):
                try:
                    widget.configure(padding=(19, 9))
                except:
                    pass
        
        def on_leave(e):
            widget['cursor'] = original_cursor
            if scale and hasattr(widget, 'configure'):
                try:
                    widget.configure(padding=(18, 8))
                except:
                    pass
        
        widget.bind('<Enter>', on_enter)
        widget.bind('<Leave>', on_leave)
    
    def update_saved_prompts_list(self):
        """Update the saved prompts dropdown"""
        if self.saved_prompts:
            # Show first 50 chars of each prompt
            display_prompts = [p[:50] + "..." if len(p) > 50 else p for p in self.saved_prompts]
            self.saved_prompts_combo['values'] = display_prompts
        else:
            self.saved_prompts_combo['values'] = []

    def check_favorite_status(self):
        """Check if current prompt is favorited and update button state"""
        prompt = self.prompt_text.get("1.0", tk.END).strip()
        if prompt in self.saved_prompts:
            self.save_prompt_btn.config(text="✓ 已收藏")
        else:
            self.save_prompt_btn.config(text="⭐ 收藏")

    def on_prompt_change(self, event=None):
        """Callback when prompt text changes"""
        # Clear the modified flag to avoid repeated triggers
        self.prompt_text.edit_modified(False)
        self.check_favorite_status()

    def toggle_favorite(self):
        """Toggle favorite status of current prompt"""
        prompt = self.prompt_text.get("1.0", tk.END).strip()
        if not prompt:
            self.status_label.config(text="● 提示词不能为空", foreground='#FF3B30')
            return

        if prompt in self.saved_prompts:
            # Remove from favorites
            self.saved_prompts.remove(prompt)
            self.save_config()
            self.update_saved_prompts_list()
            self.status_label.config(text="● 该提示词已取消收藏", foreground='#34C759')
        else:
            # Add to favorites
            self.saved_prompts.append(prompt)
            self.save_config()
            self.update_saved_prompts_list()
            self.status_label.config(text="● 该提示词已收藏", foreground='#34C759')

        # Update button state
        self.check_favorite_status()
    
    def load_saved_prompt(self, event):
        """Load a saved prompt"""
        index = self.saved_prompts_combo.current()
        if index >= 0 and index < len(self.saved_prompts):
            self.prompt_text.delete("1.0", tk.END)
            self.prompt_text.insert("1.0", self.saved_prompts[index])
            self.status_label.config(text="● 已加载提示词", foreground='#007AFF')
            self.check_favorite_status()
    
    def delete_saved_prompt(self):
        """Delete the currently selected saved prompt"""
        index = self.saved_prompts_combo.current()

        if index < 0 or index >= len(self.saved_prompts):
            self.status_label.config(text="● 请先选择要删除的提示词", foreground='#FF9500')
            return

        # Delete without confirmation - just do it
        self.saved_prompts.pop(index)
        self.save_config()
        self.update_saved_prompts_list()
        self.saved_prompts_combo.set('')  # Clear selection
        self.status_label.config(text="● 已删除提示词", foreground='#34C759')

    def upload_images(self):
        """Upload reference images with preview"""
        files = filedialog.askopenfilenames(
            title="选择参考图片",
            filetypes=[("图片文件", "*.png *.jpg *.jpeg *.gif *.bmp"), ("所有文件", "*.*")]
        )

        if files:
            for file_path in files:
                try:
                    # Load and create thumbnail with uniform size
                    img = Image.open(file_path)
                    
                    # Create 100x100 square thumbnail with center crop
                    thumb_size = 100
                    img_copy = img.copy()
                    
                    # Calculate crop box for center crop
                    width, height = img_copy.size
                    aspect = width / height
                    
                    if aspect > 1:  # Landscape
                        new_width = int(height * 1)
                        left = (width - new_width) // 2
                        crop_box = (left, 0, left + new_width, height)
                    elif aspect < 1:  # Portrait
                        new_height = int(width * 1)
                        top = (height - new_height) // 2
                        crop_box = (0, top, width, top + new_height)
                    else:  # Square
                        crop_box = (0, 0, width, height)
                    
                    # Crop to square and resize
                    img_square = img_copy.crop(crop_box)
                    img_square = img_square.resize((thumb_size, thumb_size), Image.Resampling.LANCZOS)
                    photo = ImageTk.PhotoImage(img_square)
                    
                    # Add to list maintaining order
                    self.uploaded_images.append((file_path, photo))
                except Exception as e:
                    messagebox.showerror("错误", f"无法加载图片: {file_path}\n{str(e)}")
            
            self.update_image_preview()
            self.image_count_label.config(text=f"已选择 {len(self.uploaded_images)} 张")
            self.status_label.config(text=f"● 已添加 {len(files)} 张参考图片", foreground='#34C759')
    
    def update_image_preview(self):
        """Update the image preview panel"""
        # Clear existing previews
        for widget in self.img_preview_frame.winfo_children():
            widget.destroy()
        
        # Nothing to show if no images
        if not self.uploaded_images:
            return
        
        # Add each image with delete button
        for idx, (file_path, photo) in enumerate(self.uploaded_images):
            # Container for each image
            img_container = ttk.Frame(self.img_preview_frame, style='Card.TFrame')
            img_container.pack(side="left", padx=5, pady=5)
            
            # Store reference in container to prevent garbage collection
            img_container._photo_ref = photo
            
            # Image label
            img_label = ttk.Label(img_container, image=photo, relief='solid', borderwidth=1)
            img_label.image = photo  # Keep reference
            img_label.pack()
            
            # Info frame (index + delete button)
            info_frame = ttk.Frame(img_container, style='Card.TFrame')
            info_frame.pack(fill="x", pady=(2, 0))
            
            # Image index
            index_label = ttk.Label(info_frame, text=f"图 {idx + 1}", 
                                   font=('Segoe UI', 8), foreground='#666666')
            index_label.pack(side="left", padx=2)
            
            # Delete button with enhanced visibility
            del_btn = ttk.Button(info_frame, text="✕", width=3,
                               command=lambda i=idx: self.delete_image(i),
                               style='Delete.TButton')
            del_btn.pack(side="right")
            
            # Enhanced hover effect for delete button
            def on_delete_hover(e, btn=del_btn):
                btn['cursor'] = 'hand2'
            
            def on_delete_leave(e, btn=del_btn):
                btn['cursor'] = ''
            
            del_btn.bind('<Enter>', on_delete_hover)
            del_btn.bind('<Leave>', on_delete_leave)
        
        # Force canvas to update scrollregion
        self.img_canvas.update_idletasks()
    
    def delete_image(self, index):
        """Delete a specific image by index"""
        if 0 <= index < len(self.uploaded_images):
            self.uploaded_images.pop(index)
            self.update_image_preview()
            self.image_count_label.config(text=f"已选择 {len(self.uploaded_images)} 张")
            self.status_label.config(text="● 已删除图片", foreground='#FF9500')



    def image_to_base64(self, image_path):
        """Convert image file to base64 string"""
        with open(image_path, 'rb') as f:
            return base64.b64encode(f.read()).decode('utf-8')
    
    def generate_image_async(self):
        """Start image generation in a separate thread"""
        thread = threading.Thread(target=self.generate_image, daemon=True)
        thread.start()

    def generate_image(self):
        """Generate image using Gemini API"""
        prompt = self.prompt_text.get("1.0", tk.END).strip()

        if not prompt:
            self.root.after(0, lambda: messagebox.showerror("错误", "请输入图片描述!"))
            return

        if not self.api_key:
            self.root.after(0, lambda: messagebox.showerror("错误", "未找到API密钥,请在config.json中配置!"))
            return

        self.root.after(0, lambda: self.status_label.config(text="● 正在生成图片...", foreground='#FF9500'))
        self.root.after(0, lambda: self.generate_btn.config(state="disabled"))
        self.root.after(0, lambda: self.download_btn.config(state="disabled"))

        try:
            client = genai.Client(api_key=self.api_key)

            # Build content parts
            content_parts = [prompt]

            # Add reference images if uploaded
            for img_path, _ in self.uploaded_images:
                img_data = self.image_to_base64(img_path)
                mime_type = "image/png"
                if img_path.lower().endswith('.jpg') or img_path.lower().endswith('.jpeg'):
                    mime_type = "image/jpeg"

                content_parts.append(
                    types.Part.from_bytes(
                        data=base64.b64decode(img_data),
                        mime_type=mime_type
                    )
                )

            # Generation config - using snake_case field names
            config = types.GenerateContentConfig(
                response_modalities=["IMAGE"],
                image_config=types.ImageConfig(
                    aspect_ratio=self.aspect_ratio.get(),
                    image_size=self.image_size.get()
                )
            )

            # Generate
            response = client.models.generate_content(
                model="gemini-3-pro-image-preview",
                contents=content_parts,
                config=config
            )

            # Extract image - Fixed for proper data handling
            for part in response.parts:
                if hasattr(part, 'inline_data') and part.inline_data:
                    # Store both base64 string and raw bytes
                    if isinstance(part.inline_data.data, bytes):
                        self.generated_image_bytes = part.inline_data.data
                        self.generated_image_data = base64.b64encode(part.inline_data.data).decode('utf-8')
                    else:
                        self.generated_image_data = part.inline_data.data
                        self.generated_image_bytes = base64.b64decode(part.inline_data.data)

                    self.root.after(0, self.display_image)
                    self.root.after(0, lambda: self.download_btn.config(state="normal"))
                    self.root.after(0, lambda: self.status_label.config(text="● 图片生成成功", foreground='#34C759'))
                    return

            raise Exception("响应中没有图片数据")

        except Exception as e:
            error_msg = str(e)
            self.root.after(0, lambda: messagebox.showerror("错误", f"生成失败: {error_msg}"))
            self.root.after(0, lambda: self.status_label.config(text="● 生成失败", foreground='#FF3B30'))
        finally:
            self.root.after(0, lambda: self.generate_btn.config(state="normal"))

    def display_image(self):
        """Display generated image in preview with proper scaling"""
        if not self.generated_image_bytes:
            return

        try:
            # Use raw bytes directly for display
            image = Image.open(io.BytesIO(self.generated_image_bytes))
            
            # Get available space (account for padding and labels)
            preview_frame = self.preview_label.master
            self.root.update_idletasks()
            available_width = preview_frame.winfo_width() - 40
            available_height = preview_frame.winfo_height() - 40
            
            # Ensure minimum size
            available_width = max(available_width, 400)
            available_height = max(available_height, 300)

            # Calculate scale to fit while maintaining aspect ratio
            img_width, img_height = image.size
            scale_w = available_width / img_width
            scale_h = available_height / img_height
            scale = min(scale_w, scale_h, 1.0)  # Don't upscale
            
            new_width = int(img_width * scale)
            new_height = int(img_height * scale)
            
            # Resize image
            image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)

            photo = ImageTk.PhotoImage(image)
            self.preview_label.config(image=photo, text="", cursor="hand2")
            self.preview_label.image = photo
        except Exception as e:
            error_msg = str(e)
            messagebox.showerror("错误", f"图片显示失败: {error_msg}")

    def open_fullsize_view(self, event=None):
        """Open generated image with system default viewer"""
        if not self.generated_image_bytes:
            return
        
        try:
            # Create temporary file
            with tempfile.NamedTemporaryFile(delete=False, suffix='.png', mode='wb') as tmp_file:
                tmp_file.write(self.generated_image_bytes)
                tmp_path = tmp_file.name
            
            # Open with system default viewer
            system = platform.system()
            if system == 'Windows':
                os.startfile(tmp_path)
            elif system == 'Darwin':  # macOS
                subprocess.run(['open', tmp_path], check=True)
            else:  # Linux and others
                subprocess.run(['xdg-open', tmp_path], check=True)
            
            self.status_label.config(text="● 已用系统查看器打开", foreground='#007AFF')
            
        except Exception as e:
            messagebox.showerror("错误", f"无法打开系统图片查看器: {str(e)}")
    
    def download_image(self):
        """Download generated image"""
        if not self.generated_image_bytes:
            messagebox.showerror("错误", "没有可下载的图片!")
            return

        # 生成默认文件名: 时间戳格式 YYYYMMDDHHMMSS.png
        default_filename = datetime.now().strftime("%Y%m%d%H%M%S.png")

        file_path = filedialog.asksaveasfilename(
            defaultextension=".png",
            initialfile=default_filename,
            filetypes=[("PNG 文件", "*.png"), ("JPEG 文件", "*.jpg"), ("所有文件", "*.*")],
            title="保存图片"
        )

        if file_path:
            try:
                # Use raw bytes directly for saving
                with open(file_path, 'wb') as f:
                    f.write(self.generated_image_bytes)
                
                file_size = len(self.generated_image_bytes)
                messagebox.showinfo("成功", f"图片已保存到:\n{file_path}\n\n文件大小: {file_size:,} 字节")
                self.status_label.config(text="● 图片已保存", foreground='#34C759')
            except Exception as e:
                messagebox.showerror("错误", f"保存失败: {str(e)}")


def main():
    # 首先加载配置以获取数据库信息
    config_dir = Path('.')
    if getattr(sys, 'frozen', False):
        system = platform.system()
        if system == 'Darwin':
            config_dir = Path.home() / 'Library' / 'Application Support' / 'ZB100ImageGenerator'
        elif system == 'Windows':
            config_dir = Path(os.getenv('APPDATA', Path.home())) / 'ZB100ImageGenerator'
        else:
            config_dir = Path.home() / '.config' / 'zb100imagegenerator'

    config_dir.mkdir(parents=True, exist_ok=True)
    config_path = config_dir / 'config.json'

    db_config = None
    last_user = ""
    saved_password_hash = ""

    if config_path.exists():
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                config = json.load(f)
                db_config = config.get("db_config")
                last_user = config.get("last_user", "")
                saved_password_hash = config.get("saved_password_hash", "")
        except Exception as e:
            print(f"Failed to load config: {e}")

    # 如果没有数据库配置,显示错误并退出
    if not db_config:
        root = tk.Tk()
        root.withdraw()
        messagebox.showerror("配置错误",
                           f"未找到数据库配置\n配置文件: {config_path}\n\n"
                           "请确保 config.json 包含 db_config 字段")
        return

    # 显示登录窗口
    login_window = LoginWindow(db_config, last_user, saved_password_hash)
    success, authenticated_user, remember_user, remember_password, password_hash = login_window.run()

    # 如果登录失败,退出应用
    if not success:
        return

    # 保存/清除 last_user 和密码哈希
    if config_path.exists():
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                config = json.load(f)

            if remember_user:
                config["last_user"] = authenticated_user
            else:
                config["last_user"] = ""

            if remember_password:
                config["saved_password_hash"] = password_hash
            else:
                config["saved_password_hash"] = ""

            with open(config_path, 'w', encoding='utf-8') as f:
                json.dump(config, f, indent=2, ensure_ascii=False)
        except Exception as e:
            print(f"Failed to save config: {e}")

    # 登录成功,启动主应用
    root = tk.Tk()
    app = ImageGeneratorApp(root)
    root.mainloop()


if __name__ == "__main__":
    main()