import os import sys import json import ctypes import logging LOG_FORMAT = "%(asctime)s [%(levelname)s] %(name)s: %(message)s" LOG_DATE_FORMAT = "%Y-%m-%d %H:%M:%S" MUTEX_NAME = r"Global\WallpaperChanger_SingleInstance" ERROR_ALREADY_EXISTS = 183 def _bootstrap(): import config app_dir = config._get_app_dir() for d in ["assets", "cache", "logs"]: os.makedirs(os.path.join(app_dir, d), exist_ok=True) config_path = config._get_config_path() if not os.path.exists(config_path): with open(config_path, "w", encoding="utf-8") as f: json.dump(config.DEFAULT_CONFIG, f, indent=4, ensure_ascii=False) def _do_refresh(): logging.basicConfig( level=logging.INFO, format=LOG_FORMAT, datefmt=LOG_DATE_FORMAT, ) logger = logging.getLogger("refresh") import config import fetcher import wallpaper try: image_path = fetcher.fetch_wallpaper() fill_style = config.get("wallpaper.fill_style", "fill") wallpaper.set_wallpaper(image_path, fill_style) logger.info("Wallpaper updated successfully") except Exception as e: logger.error("Refresh failed: %s", e) sys.exit(1) def _setup_logging(): import config log_dir = os.path.join(config._get_app_dir(), "logs") os.makedirs(log_dir, exist_ok=True) log_file = os.path.join(log_dir, "app.log") logging.basicConfig( level=logging.INFO, format=LOG_FORMAT, datefmt=LOG_DATE_FORMAT, handlers=[ logging.FileHandler(log_file, encoding="utf-8"), logging.StreamHandler(sys.stdout), ], ) def _ensure_icon(): import config icon_path = os.path.join(config._get_app_dir(), "assets", "icon.ico") if os.path.exists(icon_path): return from PIL import Image img = Image.new("RGB", (64, 64), color=(66, 133, 244)) sizes = [(16, 16), (32, 32), (48, 48), (64, 64)] img.save(icon_path, format="ICO", sizes=sizes) def _check_single_instance(): handle = ctypes.windll.kernel32.CreateMutexW(None, False, MUTEX_NAME) if ctypes.windll.kernel32.GetLastError() == ERROR_ALREADY_EXISTS: ctypes.windll.user32.MessageBoxW(0, "程序已运行", "壁纸更换器", 0x40) return False return True def main(): _bootstrap() if "--refresh" in sys.argv: _do_refresh() return if not _check_single_instance(): return _setup_logging() logger = logging.getLogger("main") try: _ensure_icon() except Exception as e: logger.warning("Failed to generate icon: %s", e) from tray_app import TrayApp app = TrayApp() logger.info("Starting Wallpaper Changer...") app.run() if __name__ == "__main__": main()