Skip to content

Commit

Permalink
修复bug 增加日志管理
Browse files Browse the repository at this point in the history
修复bug 增加日志管理
  • Loading branch information
DoiiarX committed Feb 5, 2024
1 parent 03ce568 commit 1a0bc4e
Show file tree
Hide file tree
Showing 6 changed files with 175 additions and 40 deletions.
2 changes: 1 addition & 1 deletion cddagl/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.8.2
1.8.3
39 changes: 39 additions & 0 deletions cddagl/launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,46 @@
from cddagl.ui.views.tabbed import TabbedWindow
from cddagl.win32 import get_ui_locale, SingleInstance, write_named_pipe

import logging
import os
import time
from glob import glob

# 创建日志器
logger = logging.getLogger('cddagl')
logger.setLevel(logging.DEBUG) # 设置日志级别

# 确保 /log 文件夹存在
log_dir = os.path.join(os.getcwd(),'log')
if not os.path.exists(log_dir):
os.makedirs(log_dir)

# 删除旧的日志文件,如果超过三个
log_files = sorted(glob(os.path.join(log_dir, '*.log')))
while len(log_files) > 3:
os.remove(log_files.pop(0))

# 使用当前时间创建日志文件名
log_filename = time.strftime("%Y%m%d%H%M%S") + '.log'
log_filepath = os.path.join(log_dir, log_filename)

# 创建文件处理器
file_handler = logging.FileHandler(log_filepath, encoding='utf-8')
file_handler.setLevel(logging.DEBUG) # 设置文件日志级别

# 创建控制台处理器
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG) # 设置控制台日志级别

# 创建日志格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)

# 添加处理器到日志器
logger.addHandler(file_handler)
logger.addHandler(console_handler)



def init_single_instance():
Expand Down
131 changes: 104 additions & 27 deletions cddagl/ui/views/fonts.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
#
# SPDX-License-Identifier: MIT
import logging
import os
import json

from PyQt5.QtCore import Qt, QStringListModel
from PyQt5.QtGui import QFontDatabase, QFont
Expand Down Expand Up @@ -127,24 +129,24 @@ def __init__(self):
self.large_map_font_size = None
self.font_mixture_enabled = False
self.selected_font = None

self.game_dir = None
self.load_font_settings()

def load_font_settings(self):
# 从fontjson中加载字体设置
self.fontjson = {
"typeface": ["data/font/Terminus.ttf", "data/font/unifont.ttf"],
"map_typeface": ["data/font/Terminus.ttf", "data/font/unifont.ttf"],
"over_map_typeface": ["data/font/Terminus.ttf", "data/font/unifont.ttf"]
# 从fontsjson中加载字体设置
self.fontsjson = {
"typeface": ["userdata/font/Terminus.ttf", "userdata/font/unifont.ttf"],
"map_typeface": ["userdata/font/Terminus.ttf", "userdata/font/unifont.ttf"],
"over_map_typeface": ["userdata/font/Terminus.ttf", "userdata/font/unifont.ttf"]
}

# 更新current_font_text_edit的文本
self.update_current_font_text_edit()

def update_current_font_text_edit(self):
typeface = self.fontjson.get("typeface", [])
map_typeface = self.fontjson.get("map_typeface", [])
over_map_typeface = self.fontjson.get("over_map_typeface", [])
typeface = self.fontsjson.get("typeface", [])
map_typeface = self.fontsjson.get("map_typeface", [])
over_map_typeface = self.fontsjson.get("over_map_typeface", [])

current_font_text = f"""UI: {typeface[0]} => {typeface[1] if len(typeface) > 1 else ''}
地图: {map_typeface[0]} => {map_typeface[1] if len(map_typeface) > 1 else ''}
Expand All @@ -160,23 +162,30 @@ def load_fonts(self):

def set_ui_font(self):
logger.debug("触发设为UI字体事件")
print(self.game_dir)
if self.selected_font is not None:
# 更新fontjson的UI字体部分
self.fontjson["typeface"][0] = self.selected_font
# 更新fontsjson的UI字体部分
self.fontsjson["typeface"][0] = self.selected_font
write_fontsjson_to_path(self.fontsjson)
copy_font_to_directory_by_name(self.selected_font)
self.update_current_font_text_edit()

def set_map_font(self):
logger.debug("触发设为地图字体事件")
if self.selected_font is not None:
# 更新fontjson的地图字体部分
self.fontjson["map_typeface"][0] = self.selected_font
# 更新fontsjson的地图字体部分
self.fontsjson["map_typeface"][0] = self.selected_font
write_fontsjson_to_path(self.fontsjson)
copy_font_to_directory_by_name(self.selected_font)
self.update_current_font_text_edit()

def set_large_map_font(self):
logger.debug("触发设为大地图字体事件")
if self.selected_font is not None:
# 更新fontjson的大地图字体部分
self.fontjson["over_map_typeface"][0] = self.selected_font
# 更新fontsjson的大地图字体部分
self.fontsjson["over_map_typeface"][0] = self.selected_font
write_fontsjson_to_path(self.fontsjson)
copy_font_to_directory_by_name(self.selected_font)
self.update_current_font_text_edit()

def set_all_font(self):
Expand All @@ -185,10 +194,11 @@ def set_all_font(self):
selected_font = self.selected_font

# 更新字体设置字典中的所有字体
self.fontjson["typeface"] = [selected_font, selected_font]
self.fontjson["map_typeface"] = [selected_font, selected_font]
self.fontjson["over_map_typeface"] = [selected_font, selected_font]

self.fontsjson["typeface"] = [selected_font, selected_font]
self.fontsjson["map_typeface"] = [selected_font, selected_font]
self.fontsjson["over_map_typeface"] = [selected_font, selected_font]
write_fontsjson_to_path(self.fontsjson)
copy_font_to_directory_by_name(self.selected_font)
# 更新UI界面
self.update_current_font_text_edit()

Expand Down Expand Up @@ -217,19 +227,86 @@ def font_selected(self, index):
self.test_text_edit.setFont(font)
pass

def game_dir_changed(self, new_dir):
# todo
# 设置游戏目录为新的目录
self.game_dir = new_dir
# 清空现有的模组列表

# 构建游戏的模组目录和用户模组目录的路径
fonts_dir = os.path.join(new_dir, 'data', 'font')
user_fonts_dir = os.path.join(new_dir, 'font')

self.load_fonts()

def get_main_window(self):
return self.parentWidget().parentWidget().parentWidget()

def get_main_tab(self):
return self.parentWidget().parentWidget().main_tab












def write_fontsjson_to_path(data, subpath='userdata\config'):
try:
# 检查路径是否存在,如果不存在则创建它
if not os.path.exists(subpath):
os.makedirs(subpath)

# 构建JSON文件的完整路径
json_path = os.path.join(os.getcwd(), subpath, 'fonts.json')

# 写入JSON数据到文件
with open(json_path, 'w') as json_file:
json.dump(data, json_file, indent=4)

print(f"JSON数据已成功写入到路径: {json_path}")
except Exception as e:
print(f"写入JSON数据时出错: {str(e)}")

def copy_font_to_directory_by_name(font_name, subpath='data/fonts', font_size=14):
target_directory = os.path.join(os.getcwd(), subpath)

# 使用 QFontDatabase 来获取字体文件路径
font_database = QFontDatabase()
font_id = font_database.addApplicationFont(QFont(font_name, font_size).toString())

if font_id == -1:
print(f"无法找到字体文件: {font_name}")
return

font_file_paths = font_database.applicationFontPaths(font_id)
font_file_name = os.path.basename(font_file_paths[0])

# 检查目标目录是否存在字体文件
target_font_path = os.path.join(target_directory, font_file_name)
if os.path.exists(target_font_path):
print(f"字体 '{font_name}' 已存在于目标目录中.")
return

try:
# 复制字体文件到目标目录
shutil.copy(font_file_paths[0], target_directory)
print(f"字体 '{font_name}' 已成功复制到目标目录.")
except Exception as e:
print(f"复制字体 '{font_name}' 到目标目录时发生错误: {str(e)}")

def get_windows_fonts_directory():
# 获取系统文件夹路径
windir = os.environ.get('WINDIR', 'C:\\Windows')

# 检查系统位数(32位或64位)
is_64bit = ctypes.windll.kernel32.IsWow64Process()

if is_64bit:
# 64位系统
fonts_directory = os.path.join(windir, 'SysNative', 'fonts')
else:
# 32位系统
fonts_directory = os.path.join(windir, 'fonts')

return fonts_directory



Expand Down
14 changes: 13 additions & 1 deletion cddagl/ui/views/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -423,13 +423,15 @@ def launch_game_process(self):
params = get_config_value('command.params', '').strip()
if params != '':
params = ' ' + params

userdatadir = os.path.join(os.getcwd(),'userdata')
params += f' --userdir "{userdatadir}"'
cmd = '"{exe_path}"{params}'.format(exe_path=self.exe_path,
params=params)

try:
game_process = subprocess.Popen(cmd, cwd=exe_dir,
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
logger.debug(f"cmd:{cmd}")
except OSError as e:
main_window = self.get_main_window()
status_bar = main_window.statusBar()
Expand Down Expand Up @@ -582,6 +584,14 @@ def update_mods(self):

directory = self.dir_combo.currentText()
mods_tab.game_dir_changed(directory)

# def update_fonts(self):
# main_window = self.get_main_window()
# central_widget = main_window.central_widget
# fonts_tab = central_widget.fonts_tab

# directory = self.dir_combo.currentText()
# fonts_tab.game_dir_changed(directory)

def update_backups(self):
main_window = self.get_main_window()
Expand Down Expand Up @@ -695,6 +705,7 @@ def game_directory_changed(self):
self.update_version()
self.update_saves()
self.update_soundpacks()
# self.update_fonts()
self.update_mods()
self.update_backups()

Expand Down Expand Up @@ -2869,6 +2880,7 @@ def finish_updating(self):

game_dir_group_box.update_soundpacks()
game_dir_group_box.update_mods()
# game_dir_group_box.update_fonts()
game_dir_group_box.update_backups()

soundpacks_tab = main_tab.get_soundpacks_tab()
Expand Down
13 changes: 10 additions & 3 deletions cddagl/ui/views/mods.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
rarfile.UNRAR_TOOL = get_cddagl_path('UnRAR.exe')


class ModsTab(QTabWidget):
class ModsTab(QWidget):
def __init__(self):
super(ModsTab, self).__init__()

Expand Down Expand Up @@ -826,6 +826,7 @@ def download_dl_progress(self, bytes_read, total_bytes):
self.download_last_read = datetime.utcnow()

def extract_new_mod(self):
logger.debug(f'extract_new_mod:{self.game_dir}')
self.extracting_new_mod = True

if self.downloaded_file.lower().endswith('.7z'):
Expand All @@ -844,7 +845,10 @@ def extract_new_mod(self):

self.extracting_infolist = z.infolist()

self.extract_dir = os.path.join(self.game_dir, 'newmod')
modname = os.path.basename(self.downloaded_file)
modname, temp = os.path.splitext(modname)

self.extract_dir = os.path.join(self.game_dir, modname)
while os.path.exists(self.extract_dir):
self.extract_dir = os.path.join(self.game_dir,
'newmod-{0}'.format('%08x' % random.randrange(16**8)))
Expand Down Expand Up @@ -1295,9 +1299,12 @@ def clear_mods(self):

def game_dir_changed(self, new_dir):
self.game_dir = new_dir
# 清空现有的模组列表
self.mods = []
# 更新用户界面元素
self.update_ui_elements()

# 构建游戏的模组目录和用户模组目录的路径
mods_dir = os.path.join(new_dir, 'data', 'mods')
user_mods_dir = os.path.join(new_dir, 'mods')

Expand Down Expand Up @@ -1342,7 +1349,7 @@ def process_mod_directory(self, mod_path):

def process_mod_config_file(self, config_file, mod_path, enabled):
info = self.config_info(config_file)
if 'ident' in info:
if ('ident' in info) or ('id' in info):
mod_info = {
'path': mod_path,
'enabled': enabled
Expand Down
16 changes: 8 additions & 8 deletions cddagl/ui/views/tabbed.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
from cddagl.sql.functions import get_config_value, set_config_value, config_true
from cddagl.ui.views.backups import BackupsTab
from cddagl.ui.views.dialogs import AboutDialog, FaqDialog
from cddagl.ui.views.fonts import FontsTab
# from cddagl.ui.views.fonts import FontsTab
from cddagl.ui.views.main import MainTab
from cddagl.ui.views.mods import ModsTab
from cddagl.ui.views.settings import SettingsTab
Expand Down Expand Up @@ -429,7 +429,7 @@ def __init__(self):
self.create_mods_tab()
#self.create_tilesets_tab()
self.create_soundpacks_tab()
self.create_fonts_tab()
# self.create_fonts_tab()
self.create_settings_tab()
self.create_statistics_tab()
self.create_cddaguide_tab()
Expand All @@ -440,7 +440,7 @@ def set_text(self):
self.setTabText(self.indexOf(self.mods_tab), _('Mods'))
#self.setTabText(self.indexOf(self.tilesets_tab), _('Tilesets'))
self.setTabText(self.indexOf(self.soundpacks_tab), _('Soundpacks'))
self.setTabText(self.indexOf(self.fonts_tab), _('Fonts'))
# self.setTabText(self.indexOf(self.fonts_tab), _('Fonts'))
self.setTabText(self.indexOf(self.settings_tab), _('Settings'))
self.setTabText(self.indexOf(self.statistics_tab), _('Statistics'))
self.setTabText(self.indexOf(self.cddaguide_tab), _('CDDA Guide'))
Expand All @@ -450,7 +450,7 @@ def set_text(self):
self.mods_tab.set_text()
#self.tilesets_tab.set_text()
self.soundpacks_tab.set_text()
self.fonts_tab.set_text()
# self.fonts_tab.set_text()
self.settings_tab.set_text()
self.statistics_tab.set_text()
self.cddaguide_tab.set_text()
Expand Down Expand Up @@ -480,10 +480,10 @@ def create_soundpacks_tab(self):
self.addTab(soundpacks_tab, _('Soundpacks'))
self.soundpacks_tab = soundpacks_tab

def create_fonts_tab(self):
fonts_tab = FontsTab()
self.addTab(fonts_tab, _('Fonts'))
self.fonts_tab = fonts_tab
# def create_fonts_tab(self):
# fonts_tab = FontsTab()
# self.addTab(fonts_tab, _('Fonts'))
# self.fonts_tab = fonts_tab

def create_settings_tab(self):
settings_tab = SettingsTab()
Expand Down

0 comments on commit 1a0bc4e

Please sign in to comment.