82 lines
2.8 KiB
Python
82 lines
2.8 KiB
Python
# ==========================================
|
||
# 2. 字体工具函数 (Font Utilities)
|
||
# ==========================================
|
||
import os
|
||
import platform
|
||
import shutil
|
||
import time
|
||
from pathlib import Path
|
||
|
||
from loguru import logger
|
||
|
||
from config.config import load_config
|
||
|
||
config = load_config("config.toml")
|
||
|
||
|
||
def get_system_fonts():
|
||
"""获取系统中可用的字体列表"""
|
||
fonts = set()
|
||
if platform.system() == "Windows":
|
||
try:
|
||
system_fonts_dir = Path(os.environ['WINDIR']) / 'Fonts'
|
||
user_fonts_dir = Path.home() / 'AppData' / 'Local' / 'Microsoft' / 'Windows' / 'Fonts'
|
||
|
||
for folder in [system_fonts_dir, user_fonts_dir]:
|
||
if folder.exists():
|
||
for ext in ['*.ttf', '*.ttc', '*.otf']:
|
||
for font_file in folder.glob(ext):
|
||
fonts.add(font_file.stem)
|
||
except Exception as e:
|
||
logger.error(f"读取系统字体时出错: {e}")
|
||
fonts = {"微软雅黑", "宋体", "黑体", "Arial", "Microsoft YaHei"}
|
||
return fonts
|
||
|
||
|
||
def is_font_available(font_name):
|
||
"""检查字体是否在系统中可用"""
|
||
system_fonts = get_system_fonts()
|
||
check_names = [font_name, font_name.replace(" ", ""), font_name.replace("-", ""),
|
||
font_name.lower(), font_name.upper()]
|
||
for name in check_names:
|
||
if name in system_fonts:
|
||
return True
|
||
return False
|
||
|
||
|
||
def install_fonts_from_directory(fonts_dir="fonts"):
|
||
"""从指定目录安装字体到系统"""
|
||
if platform.system() != "Windows":
|
||
logger.success("字体安装功能目前仅支持Windows系统")
|
||
return False
|
||
|
||
target_font_dir = Path.home() / 'AppData' / 'Local' / 'Microsoft' / 'Windows' / 'Fonts'
|
||
target_font_dir.mkdir(parents=True, exist_ok=True)
|
||
|
||
if not os.path.exists(fonts_dir):
|
||
logger.error(f"字体目录 {fonts_dir} 不存在,请创建该目录并将字体文件放入")
|
||
return False
|
||
|
||
font_files = []
|
||
for ext in ['.ttf', '.ttc', '.otf', '.fon']:
|
||
font_files.extend(Path(fonts_dir).glob(f'*{ext}'))
|
||
|
||
if not font_files:
|
||
logger.error(f"在 {fonts_dir} 目录中未找到字体文件")
|
||
return False
|
||
|
||
installed_count = 0
|
||
for font_file in font_files:
|
||
try:
|
||
target_path = target_font_dir / font_file.name
|
||
if not target_path.exists():
|
||
shutil.copy2(font_file, target_path)
|
||
logger.success(f"已安装字体: {font_file.name}")
|
||
installed_count += 1
|
||
except Exception as e:
|
||
logger.error(f"安装字体 {font_file.name} 时出错: {str(e)}")
|
||
|
||
if installed_count > 0:
|
||
logger.success(f"共安装了 {installed_count} 个新字体文件,建议重启Python环境")
|
||
return True
|
||
return False |