1
0
mirror of https://github.com/EDCD/EDMarketConnector.git synced 2025-05-03 00:41:32 +03:00

[2406] Refactor Non-Plugin Modules

This commit is contained in:
David Sangrey 2025-04-14 21:33:54 -04:00
parent e31de6a999
commit 08bfbe1582
No known key found for this signature in database
GPG Key ID: 3AEADBB0186884BC
6 changed files with 85 additions and 93 deletions

23
EDMC.py
View File

@ -10,12 +10,12 @@ from __future__ import annotations
import argparse
import json
import locale
import os
import queue
import sys
from time import sleep, time
from typing import TYPE_CHECKING, Any
from common_utils import log_locale, SERVER_RETRY
# isort: off
os.environ["EDMC_NO_UI"] = "1"
@ -52,31 +52,12 @@ import eddn # noqa: E402
# isort: on
def log_locale(prefix: str) -> None:
"""Log the current state of locale settings."""
logger.debug(f'''Locale: {prefix}
Locale LC_COLLATE: {locale.getlocale(locale.LC_COLLATE)}
Locale LC_CTYPE: {locale.getlocale(locale.LC_CTYPE)}
Locale LC_MONETARY: {locale.getlocale(locale.LC_MONETARY)}
Locale LC_NUMERIC: {locale.getlocale(locale.LC_NUMERIC)}
Locale LC_TIME: {locale.getlocale(locale.LC_TIME)}'''
)
tr.install_dummy()
SERVER_RETRY = 5 # retry pause for Companion servers [s]
EXIT_SUCCESS, EXIT_SERVER, EXIT_CREDENTIALS, EXIT_VERIFICATION, EXIT_LAGGING, EXIT_SYS_ERR, EXIT_ARGS, \
EXIT_JOURNAL_READ_ERR, EXIT_COMMANDER_UNKNOWN = range(9)
def versioncmp(versionstring) -> list:
"""Quick and dirty version comparison assuming "strict" numeric only version numbers."""
return list(map(int, versionstring.split('.')))
def deep_get(target: dict | companion.CAPIData, *args: str, default=None) -> Any:
"""
Walk into a dict and return the specified deep value.
@ -108,7 +89,7 @@ def deep_get(target: dict | companion.CAPIData, *args: str, default=None) -> Any
return current
def main(): # noqa: C901, CCR001
def main() -> None: # noqa: C901, CCR001
"""Run the main code of the program."""
try:
# arg parsing

View File

@ -68,6 +68,7 @@ from config import appversion, appversion_nobuild, config, copyright
from EDMCLogging import edmclogger, logger, logging
from journal_lock import JournalLock, JournalLockResult
from update import check_for_fdev_updates
from common_utils import log_locale, SERVER_RETRY
if __name__ == '__main__': # noqa: C901
# Command-line arguments
@ -416,8 +417,6 @@ from monitor import monitor
from theme import theme
from ttkHyperlinkLabel import HyperlinkLabel, SHIPYARD_HTML_TEMPLATE
SERVER_RETRY = 5 # retry pause for Companion servers [s]
class AppWindow:
"""Define the main application window."""
@ -1981,17 +1980,6 @@ def test_logging() -> None:
logger.debug('Test from EDMarketConnector.py top-level test_logging()')
def log_locale(prefix: str) -> None:
"""Log all of the current local settings."""
logger.debug(f'''Locale: {prefix}
Locale LC_COLLATE: {locale.getlocale(locale.LC_COLLATE)}
Locale LC_CTYPE: {locale.getlocale(locale.LC_CTYPE)}
Locale LC_MONETARY: {locale.getlocale(locale.LC_MONETARY)}
Locale LC_NUMERIC: {locale.getlocale(locale.LC_NUMERIC)}
Locale LC_TIME: {locale.getlocale(locale.LC_TIME)}'''
)
def setup_killswitches(filename: str | None):
"""Download and setup the main killswitch list."""
logger.debug('fetching killswitches...')

61
common_utils.py Normal file
View File

@ -0,0 +1,61 @@
"""
common_utils.py - Common functions and modules.
Copyright (c) EDCD, All Rights Reserved
Licensed under the GNU General Public License.
See LICENSE file.
"""
from __future__ import annotations
import sys
import locale
from typing import TYPE_CHECKING
from EDMCLogging import get_main_logger
if TYPE_CHECKING:
import tkinter as tk
logger = get_main_logger()
SERVER_RETRY = 5 # retry pause for Companion servers [s]
if sys.platform == 'win32':
import ctypes
from ctypes.wintypes import POINT, RECT, SIZE, UINT, BOOL
import win32gui
try:
CalculatePopupWindowPosition = ctypes.windll.user32.CalculatePopupWindowPosition
CalculatePopupWindowPosition.argtypes = [
ctypes.POINTER(POINT), ctypes.POINTER(SIZE), UINT, ctypes.POINTER(RECT), ctypes.POINTER(RECT)
]
CalculatePopupWindowPosition.restype = BOOL
except Exception: # Not supported under Wine 4.0
CalculatePopupWindowPosition = None # type: ignore
def ensure_on_screen(self, parent: tk.Tk):
"""
Ensure a pop-up window is on the printable screen area.
:param self: The calling class instance of tk.TopLevel
:param parent: The parent window
"""
# Ensure fully on-screen
if sys.platform == 'win32' and CalculatePopupWindowPosition:
position = RECT()
win32gui.GetWindowRect(win32gui.GetParent(self.winfo_id()))
if CalculatePopupWindowPosition(
POINT(parent.winfo_rootx(), parent.winfo_rooty()),
SIZE(position.right - position.left, position.bottom - position.top), # type: ignore
0x10000, None, position
):
self.geometry(f"+{position.left}+{position.top}")
def log_locale(prefix: str) -> None:
"""Log all of the current local settings."""
logger.debug(f'''Locale: {prefix}
Locale LC_COLLATE: {locale.getlocale(locale.LC_COLLATE)}
Locale LC_CTYPE: {locale.getlocale(locale.LC_CTYPE)}
Locale LC_MONETARY: {locale.getlocale(locale.LC_MONETARY)}
Locale LC_NUMERIC: {locale.getlocale(locale.LC_NUMERIC)}
Locale LC_TIME: {locale.getlocale(locale.LC_TIME)}'''
)

View File

@ -24,6 +24,7 @@ from l10n import translations as tr
from monitor import monitor
from theme import theme
from ttkHyperlinkLabel import HyperlinkLabel
from common_utils import ensure_on_screen
logger = get_main_logger()
@ -187,7 +188,6 @@ if sys.platform == 'win32':
import ctypes
import winreg
from ctypes.wintypes import LPCWSTR, LPWSTR, MAX_PATH, POINT, RECT, SIZE, UINT, BOOL
import win32gui
import win32api
is_wine = False
try:
@ -307,15 +307,7 @@ class PreferencesDialog(tk.Toplevel):
self.grab_set()
# Ensure fully on-screen
if sys.platform == 'win32' and CalculatePopupWindowPosition:
position = RECT()
win32gui.GetWindowRect(win32gui.GetParent(self.winfo_id()))
if CalculatePopupWindowPosition(
POINT(parent.winfo_rootx(), parent.winfo_rooty()),
SIZE(position.right - position.left, position.bottom - position.top), # type: ignore
0x10000, None, position
):
self.geometry(f"+{position.left}+{position.top}")
ensure_on_screen(self, parent)
# Set Log Directory
self.logfile_loc = Path(config.app_dir_path / 'logs')

View File

@ -64,9 +64,19 @@ COMMENT_SAME_LINE_RE = re.compile(r"^.*?(#.*)$")
COMMENT_OWN_LINE_RE = re.compile(r"^\s*?(#.*)$")
def extract_comments( # noqa: CCR001
call: ast.Call, lines: list[str], file: pathlib.Path
) -> str | None:
def _extract_lang_comment(line: str, pattern: re.Pattern, file: pathlib.Path,
lineno: int) -> tuple[str | None, str | None]:
"""Attempt to extract a LANG comment from a line using a given regex pattern."""
match = pattern.match(line)
if match:
comment = match.group(1).strip()
if comment.startswith("# LANG:"):
return comment.replace("# LANG:", "").strip(), None
return None, f"Unknown comment for {file}:{lineno} {line}"
return None, None
def extract_comments(call: ast.Call, lines: list[str], file: pathlib.Path) -> str | None:
"""
Extract comments from source code based on the given call.
@ -86,29 +96,13 @@ def extract_comments( # noqa: CCR001
above_comment: str | None = None
current_line = lines[current].strip()
current_comment: str | None = None
bad_comment: str | None = None
if above_line is not None:
match = COMMENT_OWN_LINE_RE.match(above_line)
if match:
above_comment = match.group(1).strip()
if not above_comment.startswith("# LANG:"):
bad_comment = f"Unknown comment for {file}:{call.lineno} {above_line}"
above_comment = None
else:
above_comment = above_comment.replace("# LANG:", "").strip()
if above_line:
above_comment, bad_comment = _extract_lang_comment(above_line, COMMENT_OWN_LINE_RE, file, call.lineno)
if current_line is not None:
match = COMMENT_SAME_LINE_RE.match(current_line)
if match:
current_comment = match.group(1).strip()
if not current_comment.startswith("# LANG:"):
bad_comment = f"Unknown comment for {file}:{call.lineno} {current_line}"
current_comment = None
else:
current_comment = current_comment.replace("# LANG:", "").strip()
if current_line:
current_comment, bad_comment = _extract_lang_comment(current_line, COMMENT_SAME_LINE_RE, file, call.lineno)
if current_comment is not None:
out = current_comment

View File

@ -20,25 +20,10 @@ from edmc_data import ship_name_map
from hotkey import hotkeymgr
from l10n import Locale, translations as tr
from monitor import monitor
from common_utils import ensure_on_screen
logger = EDMCLogging.get_main_logger()
if sys.platform == 'win32':
import ctypes
from ctypes.wintypes import POINT, RECT, SIZE, UINT, BOOL
import win32gui
try:
CalculatePopupWindowPosition = ctypes.windll.user32.CalculatePopupWindowPosition
CalculatePopupWindowPosition.argtypes = [
ctypes.POINTER(POINT), ctypes.POINTER(SIZE), UINT, ctypes.POINTER(RECT), ctypes.POINTER(RECT)
]
CalculatePopupWindowPosition.restype = BOOL
except Exception: # Not supported under Wine 4.0
CalculatePopupWindowPosition = None # type: ignore
CR_LINES_START = 1
CR_LINES_END = 3
RANK_LINES_START = 3
@ -418,16 +403,7 @@ class StatsResults(tk.Toplevel):
self.grab_set()
# Ensure fully on-screen
if sys.platform == 'win32' and CalculatePopupWindowPosition:
position = RECT()
win32gui.GetWindowRect(win32gui.GetParent(self.winfo_id()))
if CalculatePopupWindowPosition(
POINT(parent.winfo_rootx(), parent.winfo_rooty()),
# - is evidently supported on the C side
SIZE(position.right - position.left, position.bottom - position.top), # type: ignore
0x10000, None, position
):
self.geometry(f"+{position.left}+{position.top}")
ensure_on_screen(self, parent)
def addpage(
self, parent, header: list[str] | None = None, align: str | None = None