1
1
mirror of https://github.com/KenanZhu/AutoLibrary.git synced 2026-08-02 06:09:36 +08:00

style: 统一代码格式与导入优化

This commit is contained in:
2026-06-26 09:16:23 +08:00
parent 05ad9ba0b3
commit 92c5fa0dfb
7 changed files with 36 additions and 42 deletions
+2 -2
View File
@@ -11,7 +11,7 @@ import logging
import queue import queue
import datetime import datetime
import managers.log.LogManager as LogManager from managers.log.LogManager import getLogger
class MsgBase: class MsgBase:
@@ -54,7 +54,7 @@ class MsgBase:
self._input_queue = input_queue self._input_queue = input_queue
self._output_queue = output_queue self._output_queue = output_queue
try: try:
self._logger = LogManager.getLogger(self._class_name) self._logger = getLogger(self._class_name)
except RuntimeError: except RuntimeError:
self._logger = None self._logger = None
+2 -1
View File
@@ -73,6 +73,8 @@ def _initializeWebDriverManager(
def _initializeAppearance( def _initializeAppearance(
): ):
logger = logInstance().getLogger("AppInitializer")
app = QApplication.instance() app = QApplication.instance()
if not app: if not app:
return return
@@ -82,7 +84,6 @@ def _initializeAppearance(
saved_custom_theme = cfg.get(CfgKey.GLOBAL.APPEARANCE.CUSTOM_THEME, "") saved_custom_theme = cfg.get(CfgKey.GLOBAL.APPEARANCE.CUSTOM_THEME, "")
app.setStyle(saved_style) app.setStyle(saved_style)
setActiveStyle(saved_style) setActiveStyle(saved_style)
logger = logInstance().getLogger("AppInitializer")
if saved_custom_theme: if saved_custom_theme:
try: try:
themeInstance().applyTheme(saved_custom_theme) themeInstance().applyTheme(saved_custom_theme)
+3 -7
View File
@@ -77,11 +77,9 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
self.connectSignals() self.connectSignals()
self.startMsgPolling() self.startMsgPolling()
self.startTimerTaskPolling() self.startTimerTaskPolling()
self.__bulletin_poller.start() self.__bulletin_poller.start()
if bulletinInstance().autoFetch(): if bulletinInstance().autoFetch():
QTimer.singleShot(1000, self.__bulletin_poller.fetchNow) QTimer.singleShot(1000, self.__bulletin_poller.fetchNow)
self._showLog("主窗口初始化完成") self._showLog("主窗口初始化完成")
def modifyUi( def modifyUi(
@@ -182,9 +180,7 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
self.StopButton.clicked.connect(self.onStopButtonClicked) self.StopButton.clicked.connect(self.onStopButtonClicked)
self.SendButton.clicked.connect(self.onSendButtonClicked) self.SendButton.clicked.connect(self.onSendButtonClicked)
self.MessageEdit.returnPressed.connect(self.onSendButtonClicked) self.MessageEdit.returnPressed.connect(self.onSendButtonClicked)
self.__bulletin_poller.newBulletinsDetected.connect( self.__bulletin_poller.newBulletinsDetected.connect(self.onBulletinPollerNewBulletins)
self._onBulletinPollerNewBulletins
)
def closeEvent( def closeEvent(
self, self,
@@ -365,12 +361,12 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
self.__bulletin_poller.setDialogOpen(False) self.__bulletin_poller.setDialogOpen(False)
@Slot(int) @Slot(int)
def _onBulletinPollerNewBulletins( def onBulletinPollerNewBulletins(
self, self,
count: int count: int
): ):
if not hasattr(self, 'TrayIcon'): if not hasattr(self, "TrayIcon"):
return return
self.TrayIcon.showMessage( self.TrayIcon.showMessage(
"公告栏 - AutoLibrary", "公告栏 - AutoLibrary",
+8 -10
View File
@@ -223,24 +223,24 @@ class BulletinManager:
try: try:
if self.isFirstSync(): if self.isFirstSync():
start_date = now - timedelta(days=7) start_date = now - timedelta(days=7)
range_hour = str(24 * 8) range_hour = str(24*8)
elif self.shouldFullSync(): elif self.shouldFullSync():
with self.__lock: with self.__lock:
bulletins = self.bulletins() bulletins = self.bulletins()
earliest = min(bulletins, key=self._parseBulletinDateTime) earliest = min(bulletins, key=self._parseBulletinDateTime)
start_date = self._parseBulletinDateTime(earliest) start_date = self._parseBulletinDateTime(earliest)
diff = now - start_date diff = now - start_date
range_hour = str(int(diff.total_seconds() / 3600) + 1) range_hour = str(int(diff.total_seconds()/3600) + 1)
else: else:
with self.__lock: with self.__lock:
bulletins = self.bulletins() bulletins = self.bulletins()
latest = max(bulletins, key=self._parseBulletinDateTime) latest = max(bulletins, key=self._parseBulletinDateTime)
start_date = self._parseBulletinDateTime(latest) start_date = self._parseBulletinDateTime(latest)
diff = now - start_date diff = now - start_date
range_hour = str(int(diff.total_seconds() / 3600) + 1) range_hour = str(int(diff.total_seconds()/3600) + 1)
except (ValueError, TypeError, KeyError): except (ValueError, TypeError, KeyError):
start_date = now - timedelta(days=7) start_date = now - timedelta(days=7)
range_hour = str(24 * 8) range_hour = str(24*8)
return { return {
"date": start_date.strftime("%Y-%m-%d"), "date": start_date.strftime("%Y-%m-%d"),
@@ -256,9 +256,10 @@ class BulletinManager:
""" """
Merge incoming bulletins into the cache. Merge incoming bulletins into the cache.
New bulletins are added with isNew=True. Existing bulletins - New bulletins are added with isNew=True.
keep their current isNew state. Entries listed in delete_ids - Existing bulletins keep their current isNew state.
are removed. Bulletins missing an "id" field are skipped. - Entries listed in delete_ids are removed.
- Bulletins missing an "id" field are skipped.
Args: Args:
new_bulletins (list[dict]): Incoming bulletin list. new_bulletins (list[dict]): Incoming bulletin list.
@@ -275,7 +276,6 @@ class BulletinManager:
bid = b.get("id") bid = b.get("id")
if bid is not None: if bid is not None:
bulletins_dict[str(bid)] = b bulletins_dict[str(bid)] = b
for bulletin in new_bulletins: for bulletin in new_bulletins:
bid = bulletin.get("id") bid = bulletin.get("id")
if bid is None: if bid is None:
@@ -290,10 +290,8 @@ class BulletinManager:
else bulletins_dict[bid].get("isNew", True) else bulletins_dict[bid].get("isNew", True)
) )
bulletins_dict[bid] = bulletin bulletins_dict[bid] = bulletin
for bid in delete_set: for bid in delete_set:
bulletins_dict.pop(bid, None) bulletins_dict.pop(bid, None)
result = list(bulletins_dict.values()) result = list(bulletins_dict.values())
result.sort(key=lambda x: str(x.get("id", ""))) result.sort(key=lambda x: str(x.get("id", "")))
self.setBulletins(result) self.setBulletins(result)
+4 -4
View File
@@ -18,7 +18,7 @@ from interfaces.ConfigProvider import ConfigType, ConfigPath
# This config manager class only responsible for global and other # This config manager class only responsible for global and other
# unconfigurable config files. # config files. NOT include run and user config files.
class ConfigTemplate: class ConfigTemplate:
@@ -87,8 +87,8 @@ class ConfigManager:
): ):
self.__config_dir = os.path.abspath(config_dir) self.__config_dir = os.path.abspath(config_dir)
self.__config_lock = threading.Lock()
self.__config_data = {} self.__config_data = {}
self.__lock = threading.Lock()
self.initialize() self.initialize()
@@ -121,7 +121,7 @@ class ConfigManager:
default: Optional[Any] = None default: Optional[Any] = None
) -> Any: ) -> Any:
with self.__config_lock: with self.__lock:
config_data = self.__config_data[key.config_type.value] config_data = self.__config_data[key.config_type.value]
if key.key == "": if key.key == "":
return config_data return config_data
@@ -138,7 +138,7 @@ class ConfigManager:
value: Any = None value: Any = None
): ):
with self.__config_lock: with self.__lock:
root_data = self.__config_data[key.config_type.value] root_data = self.__config_data[key.config_type.value]
if key.key == "": if key.key == "":
self.__config_data[key.config_type.value] = value self.__config_data[key.config_type.value] = value
-5
View File
@@ -99,17 +99,14 @@ class LogManager:
self.__logger = logging.getLogger("AutoLibrary") self.__logger = logging.getLogger("AutoLibrary")
self.__logger.setLevel(logging.DEBUG) self.__logger.setLevel(logging.DEBUG)
self.__logger.handlers.clear() self.__logger.handlers.clear()
formatter = CallerInfoFormatter( formatter = CallerInfoFormatter(
'[%(asctime)s] - [%(name)s] - [%(levelname)s] - [%(filename)s:%(lineno)s] - %(message)s', '[%(asctime)s] - [%(name)s] - [%(levelname)s] - [%(filename)s:%(lineno)s] - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S' datefmt='%Y-%m-%d %H:%M:%S'
) )
console_handler = logging.StreamHandler() console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO) console_handler.setLevel(logging.INFO)
console_handler.setFormatter(formatter) console_handler.setFormatter(formatter)
self.__logger.addHandler(console_handler) self.__logger.addHandler(console_handler)
all_log_file = os.path.join(self.__log_dir, "all.log") all_log_file = os.path.join(self.__log_dir, "all.log")
file_handler_all = TimedRotatingFileHandler( file_handler_all = TimedRotatingFileHandler(
all_log_file, all_log_file,
@@ -122,7 +119,6 @@ class LogManager:
file_handler_all.setLevel(logging.DEBUG) file_handler_all.setLevel(logging.DEBUG)
file_handler_all.setFormatter(formatter) file_handler_all.setFormatter(formatter)
self.__logger.addHandler(file_handler_all) self.__logger.addHandler(file_handler_all)
error_log_file = os.path.join(self.__log_dir, "error.log") error_log_file = os.path.join(self.__log_dir, "error.log")
file_handler_error = TimedRotatingFileHandler( file_handler_error = TimedRotatingFileHandler(
error_log_file, error_log_file,
@@ -135,7 +131,6 @@ class LogManager:
file_handler_error.setLevel(logging.ERROR) file_handler_error.setLevel(logging.ERROR)
file_handler_error.setFormatter(formatter) file_handler_error.setFormatter(formatter)
self.__logger.addHandler(file_handler_error) self.__logger.addHandler(file_handler_error)
self.__initialized = True self.__initialized = True
def getLogger( def getLogger(
+17 -13
View File
@@ -28,6 +28,8 @@ from utils.ThemeUtils import (
) )
# we use Fusion as the default active style name
# because it's cross-platform.
_active_style_name = "Fusion" _active_style_name = "Fusion"
@@ -61,8 +63,10 @@ class ThemeManager:
): ):
self.__themes_dir = os.path.abspath(themes_dir) self.__themes_dir = os.path.abspath(themes_dir)
self.__lock = threading.Lock()
self.__current_theme_name = "" self.__current_theme_name = ""
self.__lock = threading.Lock()
# directory must exist
os.makedirs(self.__themes_dir, exist_ok=True) os.makedirs(self.__themes_dir, exist_ok=True)
@staticmethod @staticmethod
@@ -144,18 +148,6 @@ class ThemeManager:
) )
return alt_path return alt_path
def themesDir(
self
) -> str:
"""
Get the themes directory path.
Returns:
str: The absolute path to the themes storage directory.
"""
return self.__themes_dir
def importTheme( def importTheme(
self, self,
source_path: str source_path: str
@@ -321,6 +313,18 @@ class ThemeManager:
) )
app.setStyle(QStyleFactory.create(_active_style_name)) app.setStyle(QStyleFactory.create(_active_style_name))
def themesDir(
self
) -> str:
"""
Get the themes directory path.
Returns:
str: The absolute path to the themes storage directory.
"""
return self.__themes_dir
# ThemeManager singleton instance. # ThemeManager singleton instance.
_theme_manager_instance = None _theme_manager_instance = None