From f18f724a7f74e178469dfed814dce412e3ea1f97 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 16 Feb 2025 20:03:51 -0500 Subject: [PATCH 01/62] [Minor] Because Typing Changelogs is Hard --- ChangeLog.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ChangeLog.md b/ChangeLog.md index 2d7c9423..f591940f 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -9,7 +9,7 @@ This is the master changelog for Elite Dangerous Market Connector. Entries are Release 5.12.2 === -This is a pre-release to test a number of bugfixes and security improvements in EDMC. +This is a release to test a number of bugfixes and security improvements in EDMC. **Changes and Enhancements** * Adds a guard against workflow shell execution vulnerabilities in GitHub Actions From cfcae63b232af83191465091a6401c0e5a80e2f6 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 16 Feb 2025 20:14:52 -0500 Subject: [PATCH 02/62] [Minor] Update Winsparkle Version in Autobuilds --- .github/workflows/windows-build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/windows-build.yml b/.github/workflows/windows-build.yml index 8a4d115a..6e681f54 100644 --- a/.github/workflows/windows-build.yml +++ b/.github/workflows/windows-build.yml @@ -113,9 +113,9 @@ jobs: - name: Download winsparkle run: | - Invoke-Webrequest -UseBasicParsing https://github.com/vslavik/winsparkle/releases/download/v0.8.1/WinSparkle-0.8.1.zip -OutFile out.zip + Invoke-Webrequest -UseBasicParsing https://github.com/vslavik/winsparkle/releases/download/v0.8.3/WinSparkle-0.8.3.zip -OutFile out.zip Expand-Archive out.zip - Move-Item 'out\WinSparkle-0.8.1\Release\*' '.\' + Move-Item 'out\WinSparkle-0.8.3\Release\*' '.\' - name: Build EDMC run: | From f18ead9efabe09065039c993409d7bb4f6f3a576 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 16 Feb 2025 20:49:03 -0500 Subject: [PATCH 03/62] [#1428] Implement Timestamp Checker --- EDMarketConnector.py | 9 +++++++++ config/__init__.py | 14 ++++++++++++++ plug.py | 9 +++++++++ 3 files changed, 32 insertions(+) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 80a958e1..28e83686 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -187,6 +187,12 @@ if __name__ == '__main__': # noqa: C901 '--killswitches-file', help='Specify a custom killswitches file', ) + + parser.add_argument( + '--skip-timecheck', + help='Skips the Time Delta check for processed events', + action='store_true' + ) ########################################################################### args: argparse.Namespace = parser.parse_args() @@ -250,6 +256,9 @@ if __name__ == '__main__': # noqa: C901 for d in conf_module.trace_on: logger.info(f'marked {d} for TRACE') + if args.skip_timecheck: + config.set_skip_timecheck() + def handle_edmc_callback_or_foregrounding() -> None: # noqa: CCR001 """Handle any edmc:// auth callback, else foreground an existing window.""" logger.trace_if('frontier-auth.windows', 'Begin...') diff --git a/config/__init__.py b/config/__init__.py index adf3e47f..05eb3f5b 100644 --- a/config/__init__.py +++ b/config/__init__.py @@ -201,6 +201,7 @@ class AbstractConfig(abc.ABC): __auth_force_edmc_protocol = False # Should we force edmc:// protocol ? __eddn_url = None # Non-default EDDN URL __eddn_tracking_ui = False # Show EDDN tracking UI ? + __skip_timecheck = False # Skip checking event timestamps? def __init__(self) -> None: self.home_path = pathlib.Path.home() @@ -270,6 +271,19 @@ class AbstractConfig(abc.ABC): """ return self.__eddn_tracking_ui + def set_skip_timecheck(self): + """Set the Event Timecheck bool.""" + self.__skip_timecheck = True + + @property + def skip_timecheck(self) -> bool: + """ + Determine if the Event Timecheck bool is enabled. + + :return: bool - Should EDMC check event timechecks? + """ + return self.__skip_timecheck + @property def app_dir(self) -> str: """Return a string version of app_dir.""" diff --git a/plug.py b/plug.py index ee53e76b..acaa006a 100644 --- a/plug.py +++ b/plug.py @@ -14,6 +14,7 @@ import operator import os import sys import tkinter as tk +from datetime import datetime, timedelta from pathlib import Path from tkinter import ttk from typing import Any, Mapping, MutableMapping @@ -331,6 +332,14 @@ def notify_journal_entry( logger.trace_if('journal.locations', 'Notifying plugins of "Location" event') error = None + + if "timestamp" in entry and not config.skip_timecheck: + # Check that timestamp is recent enough + dt = datetime.strptime(entry["timestamp"], "%Y-%m-%dT%H:%M:%SZ") + if dt > datetime.utcnow() - timedelta(minutes=60): + error = f"Event at {entry['timestamp']} beyond Time Delta of 60 minutes. Skipping." + return error + for plugin in PLUGINS: journal_entry = plugin._get_func('journal_entry') if journal_entry: From 2b95a3eece3a93ed26960c1cdd5d0fa8b34861fa Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 16 Feb 2025 20:49:27 -0500 Subject: [PATCH 04/62] [Minor] Fallback to Latest 3.11 Version Why pin the specific build? Just use the lastest GitHub available 3.11 version. --- .python-version | 2 +- ChangeLog.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.python-version b/.python-version index 2419ad5b..2c073331 100644 --- a/.python-version +++ b/.python-version @@ -1 +1 @@ -3.11.9 +3.11 diff --git a/ChangeLog.md b/ChangeLog.md index f591940f..e65181d1 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,6 +1,6 @@ This is the master changelog for Elite Dangerous Market Connector. Entries are in reverse chronological order (latest first). --- -* We currently test against, and package with, Python 3.11.9, 32-bit. +* We currently test against, and package with, Python 3.11, 32-bit. * As a result, we do not support Windows 7, 8, or 8.1. * Developers can check the contents of the `.python-version` file in the source (not distributed with the Windows installer) for the From 1a93396047c1de8b9bfe5027bb6ee0928dae5ac2 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 16 Feb 2025 21:12:19 -0500 Subject: [PATCH 05/62] [Security] Remove ExecutionPolicy Command This command isn't needed and opens EDMC to a potential security bug. --- resources/EDMC_Installer_Config_template.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/EDMC_Installer_Config_template.txt b/resources/EDMC_Installer_Config_template.txt index de40630c..1a31eeca 100644 --- a/resources/EDMC_Installer_Config_template.txt +++ b/resources/EDMC_Installer_Config_template.txt @@ -80,7 +80,7 @@ begin begin PowerShellOutputFile := ExpandConstant('{tmp}\PowershellOutput.txt'); // Construct the PowerShell command and capture output to a file - Exec('powershell.exe', '-NoProfile -ExecutionPolicy Bypass -Command "Get-WmiObject -Class Win32_Product | where Name -eq ''Elite Dangerous Market Connector'' | select-object -expandproperty IdentifyingNumber" | Out-File -Encoding ASCII "' + PowerShellOutputFile + '"', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); + Exec('powershell.exe', '-NoProfile -Command "Get-WmiObject -Class Win32_Product | where Name -eq ''Elite Dangerous Market Connector'' | select-object -expandproperty IdentifyingNumber" | Out-File -Encoding ASCII "' + PowerShellOutputFile + '"', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); begin if LoadStringFromFile(PowerShellOutputFile, S) then S:= Trim(S); From 92a752cee0f089241f00e9b3d8bc46fa303efa6c Mon Sep 17 00:00:00 2001 From: Florian Probst Date: Mon, 24 Feb 2025 23:31:28 +0100 Subject: [PATCH 06/62] Update plug.py --- plug.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/plug.py b/plug.py index acaa006a..e11cf743 100644 --- a/plug.py +++ b/plug.py @@ -14,7 +14,7 @@ import operator import os import sys import tkinter as tk -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from pathlib import Path from tkinter import ttk from typing import Any, Mapping, MutableMapping @@ -335,8 +335,8 @@ def notify_journal_entry( if "timestamp" in entry and not config.skip_timecheck: # Check that timestamp is recent enough - dt = datetime.strptime(entry["timestamp"], "%Y-%m-%dT%H:%M:%SZ") - if dt > datetime.utcnow() - timedelta(minutes=60): + dt = datetime.strptime(entry["timestamp"], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc) + if dt < datetime.now(timezone.utc) - timedelta(minutes=60): error = f"Event at {entry['timestamp']} beyond Time Delta of 60 minutes. Skipping." return error From 3fc8251fa4bfbe7bd0a442a069c195a8a4faced4 Mon Sep 17 00:00:00 2001 From: David Muckle Date: Thu, 27 Feb 2025 11:50:56 -0500 Subject: [PATCH 07/62] Squashed commit of the following: commit 39b0aec5f2830b9b0fe9ca3c40aa0eaa52a45ba1 Merge: 9c600bf8 2f3f7262 Author: David Muckle Date: Thu Feb 27 09:29:09 2025 -0500 Merge branch 'main' into expanduser-journal-path commit 9c600bf84755c0d9c25c60007d816384862abf33 Author: David Muckle Date: Thu Feb 27 09:24:04 2025 -0500 Expanduser journal path --- journal_lock.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/journal_lock.py b/journal_lock.py index 2aae20a6..3e16b309 100644 --- a/journal_lock.py +++ b/journal_lock.py @@ -51,7 +51,7 @@ class JournalLock: else: try: - self.journal_dir_path = pathlib.Path(self.journal_dir) + self.journal_dir_path = pathlib.Path.expanduser(pathlib.Path(self.journal_dir)) except Exception: # pragma: no cover logger.exception("Couldn't make pathlib.Path from journal_dir") From 8962c3a24105b6af4d458773c9ee07e8d988e0c7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 1 Mar 2025 17:40:49 +0000 Subject: [PATCH 08/62] Bump flake8-comprehensions from 3.15.0 to 3.16.0 Bumps [flake8-comprehensions](https://github.com/adamchainz/flake8-comprehensions) from 3.15.0 to 3.16.0. - [Changelog](https://github.com/adamchainz/flake8-comprehensions/blob/main/CHANGELOG.rst) - [Commits](https://github.com/adamchainz/flake8-comprehensions/compare/3.15.0...3.16.0) --- updated-dependencies: - dependency-name: flake8-comprehensions dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 81e36d88..d8004dcc 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -7,7 +7,7 @@ setuptools==75.8.0 flake8==7.1.1 flake8-annotations-coverage==0.0.6 flake8-cognitive-complexity==0.1.0 -flake8-comprehensions==3.15.0 +flake8-comprehensions==3.16.0 flake8-docstrings==1.7.0 flake8-json==24.4.0 flake8-noqa==1.4.0 From fd4084dc37884ca779e1a884ea7bb26499f1be0b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 1 Mar 2025 17:40:54 +0000 Subject: [PATCH 09/62] Bump mypy from 1.14.1 to 1.15.0 Bumps [mypy](https://github.com/python/mypy) from 1.14.1 to 1.15.0. - [Changelog](https://github.com/python/mypy/blob/master/CHANGELOG.md) - [Commits](https://github.com/python/mypy/compare/v1.14.1...v1.15.0) --- updated-dependencies: - dependency-name: mypy dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 81e36d88..19eadf3f 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -14,7 +14,7 @@ flake8-noqa==1.4.0 flake8-polyfill==1.0.2 flake8-use-fstring==1.4 -mypy==1.14.1 +mypy==1.15.0 pep8-naming==0.14.1 safety==3.2.14 types-requests==2.32.0.20241016 From 0d27c8923bf8ecaf2655b6eae568f4bab689f678 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 1 Mar 2025 17:40:58 +0000 Subject: [PATCH 10/62] Bump pytest from 8.3.2 to 8.3.4 Bumps [pytest](https://github.com/pytest-dev/pytest) from 8.3.2 to 8.3.4. - [Release notes](https://github.com/pytest-dev/pytest/releases) - [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst) - [Commits](https://github.com/pytest-dev/pytest/compare/8.3.2...8.3.4) --- updated-dependencies: - dependency-name: pytest dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 81e36d88..7b1094ce 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -34,7 +34,7 @@ mistune==3.1.1 py2exe==0.13.0.2; sys_platform == 'win32' # Testing -pytest==8.3.2 +pytest==8.3.4 pytest-cov==6.0.0 # Pytest code coverage support coverage[toml]==7.6.1 # pytest-cov dep. This is here to ensure that it includes TOML support for pyproject.toml configs coverage-conditional-plugin==0.9.0 From d9b70b59be54b670e8a9ebe202d9a5ded3733cb7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 1 Mar 2025 17:41:04 +0000 Subject: [PATCH 11/62] Bump pre-commit from 3.8.0 to 4.1.0 Bumps [pre-commit](https://github.com/pre-commit/pre-commit) from 3.8.0 to 4.1.0. - [Release notes](https://github.com/pre-commit/pre-commit/releases) - [Changelog](https://github.com/pre-commit/pre-commit/blob/main/CHANGELOG.md) - [Commits](https://github.com/pre-commit/pre-commit/compare/v3.8.0...v4.1.0) --- updated-dependencies: - dependency-name: pre-commit dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 81e36d88..fc482b5b 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -24,7 +24,7 @@ types-setuptools==75.8.0.20250210 autopep8==2.3.2 # Git pre-commit checking -pre-commit==3.8.0 +pre-commit==4.1.0 # HTML changelogs mistune==3.1.1 From 9bb8d5976b199a7af14f675d686a26902ce1d221 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 5 Mar 2025 23:58:10 +0000 Subject: [PATCH 12/62] Bump flake8 from 7.1.1 to 7.1.2 Bumps [flake8](https://github.com/pycqa/flake8) from 7.1.1 to 7.1.2. - [Commits](https://github.com/pycqa/flake8/compare/7.1.1...7.1.2) --- updated-dependencies: - dependency-name: flake8 dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index ae6bf584..1d836835 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -4,7 +4,7 @@ setuptools==75.8.0 # Static analysis tools -flake8==7.1.1 +flake8==7.1.2 flake8-annotations-coverage==0.0.6 flake8-cognitive-complexity==0.1.0 flake8-comprehensions==3.16.0 From 3197f019f2db6540069ee15417967b9ce61b2d2d Mon Sep 17 00:00:00 2001 From: INeedMana Date: Wed, 12 Mar 2025 22:53:32 +0100 Subject: [PATCH 13/62] Fixes #2360: Translate Elements MaterialReward as Raw --- monitor.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/monitor.py b/monitor.py index e37e77c1..45652530 100644 --- a/monitor.py +++ b/monitor.py @@ -1688,6 +1688,8 @@ class EDLogs(FileSystemEventHandler): if 'Category' in reward: # Category not present in E:D 3.0 category = self.category(reward['Category']) material = self.canonicalise(reward['Name']) + if category == 'Elements': + category = 'Raw' self.state[category][material] += reward.get('Count', 1) elif event_type == 'engineercontribution': From 2b4c8280c3d786138e4383f1b1627ff50eeb941f Mon Sep 17 00:00:00 2001 From: David Muckle Date: Mon, 24 Mar 2025 20:08:50 -0400 Subject: [PATCH 14/62] Update powerplay tracking to account for new journal events --- monitor.py | 6 ++++++ plugins/inara.py | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/monitor.py b/monitor.py index e37e77c1..e821c317 100644 --- a/monitor.py +++ b/monitor.py @@ -1852,6 +1852,12 @@ class EDLogs(FileSystemEventHandler): self.state['Powerplay']['Merits'] = entry.get('Merits', 0) self.state['Powerplay']['Votes'] = entry.get('Votes', 0) self.state['Powerplay']['TimePledged'] = entry.get('TimePledged', 0) + + elif event_type == 'powerplaymerits': + self.state['Powerplay']['Merits'] = entry.get('TotalMerits', 0) + + elif event_type == 'powerplayrank': + self.state['Powerplay']['Rank'] = entry.get('Rank', 0) return entry diff --git a/plugins/inara.py b/plugins/inara.py index b48609f0..dbbefb98 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -552,6 +552,14 @@ def journal_entry( # noqa: C901, CCR001 power_data = {'powerName': entry["Power"], 'rankValue': entry["Rank"], 'meritsValue': entry["Merits"]} new_add_event('setCommanderRankPower', entry['timestamp'], power_data) + elif event_name == 'PowerplayMerits': + power_data = {'powerName': state["Powerplay"]["Power"], 'rankValue': state["Powerplay"]["Rank"], 'meritsValue': entry["TotalMerits"]} + new_add_event('setCommanderRankPower', entry['timestamp'], power_data) + + elif event_name == 'PowerplayRank': + power_data = {'powerName': entry["Power"], 'rankValue': entry["Rank"]} + new_add_event('setCommanderRankPower', entry['timestamp'], power_data) + # Ship change if event_name == 'Loadout' and this.shipswap: this.loadout = make_loadout(state) From 749ae939b5059f05f3b6e3f92cf03cdf57c1e92a Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Mon, 31 Mar 2025 20:31:23 -0400 Subject: [PATCH 15/62] [Minor] Flake8 Linter Run --- monitor.py | 2 +- plugins/inara.py | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/monitor.py b/monitor.py index e821c317..4a554217 100644 --- a/monitor.py +++ b/monitor.py @@ -1852,7 +1852,7 @@ class EDLogs(FileSystemEventHandler): self.state['Powerplay']['Merits'] = entry.get('Merits', 0) self.state['Powerplay']['Votes'] = entry.get('Votes', 0) self.state['Powerplay']['TimePledged'] = entry.get('TimePledged', 0) - + elif event_type == 'powerplaymerits': self.state['Powerplay']['Merits'] = entry.get('TotalMerits', 0) diff --git a/plugins/inara.py b/plugins/inara.py index dbbefb98..6c243172 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -553,7 +553,8 @@ def journal_entry( # noqa: C901, CCR001 new_add_event('setCommanderRankPower', entry['timestamp'], power_data) elif event_name == 'PowerplayMerits': - power_data = {'powerName': state["Powerplay"]["Power"], 'rankValue': state["Powerplay"]["Rank"], 'meritsValue': entry["TotalMerits"]} + power_data = {'powerName': state["Powerplay"]["Power"], 'rankValue': state["Powerplay"]["Rank"], + 'meritsValue': entry["TotalMerits"]} new_add_event('setCommanderRankPower', entry['timestamp'], power_data) elif event_name == 'PowerplayRank': From 931cc57fa8dc746baba55ff5fefcdfafd17b5eed Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 1 Apr 2025 17:15:17 +0000 Subject: [PATCH 16/62] Bump pytest from 8.3.4 to 8.3.5 Bumps [pytest](https://github.com/pytest-dev/pytest) from 8.3.4 to 8.3.5. - [Release notes](https://github.com/pytest-dev/pytest/releases) - [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst) - [Commits](https://github.com/pytest-dev/pytest/compare/8.3.4...8.3.5) --- updated-dependencies: - dependency-name: pytest dependency-version: 8.3.5 dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index e00633c5..d9c88447 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -34,7 +34,7 @@ mistune==3.1.1 py2exe==0.13.0.2; sys_platform == 'win32' # Testing -pytest==8.3.4 +pytest==8.3.5 pytest-cov==6.0.0 # Pytest code coverage support coverage[toml]==7.6.1 # pytest-cov dep. This is here to ensure that it includes TOML support for pyproject.toml configs coverage-conditional-plugin==0.9.0 From a47615acaf2f848d060078597590e2721bea7054 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 1 Apr 2025 17:15:24 +0000 Subject: [PATCH 17/62] Bump types-requests from 2.32.0.20241016 to 2.32.0.20250328 Bumps [types-requests](https://github.com/python/typeshed) from 2.32.0.20241016 to 2.32.0.20250328. - [Commits](https://github.com/python/typeshed/commits) --- updated-dependencies: - dependency-name: types-requests dependency-version: 2.32.0.20250328 dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index e00633c5..eb6e306a 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -17,7 +17,7 @@ flake8-use-fstring==1.4 mypy==1.15.0 pep8-naming==0.14.1 safety==3.2.14 -types-requests==2.32.0.20241016 +types-requests==2.32.0.20250328 types-setuptools==75.8.0.20250210 # Code formatting tools From 689717971fb455983e5de79616d884424d3b3818 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 1 Apr 2025 20:47:59 +0000 Subject: [PATCH 18/62] Bump pytest-cov from 6.0.0 to 6.1.0 Bumps [pytest-cov](https://github.com/pytest-dev/pytest-cov) from 6.0.0 to 6.1.0. - [Changelog](https://github.com/pytest-dev/pytest-cov/blob/master/CHANGELOG.rst) - [Commits](https://github.com/pytest-dev/pytest-cov/compare/v6.0.0...v6.1.0) --- updated-dependencies: - dependency-name: pytest-cov dependency-version: 6.1.0 dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 48c0c843..a351d133 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -35,7 +35,7 @@ py2exe==0.13.0.2; sys_platform == 'win32' # Testing pytest==8.3.5 -pytest-cov==6.0.0 # Pytest code coverage support +pytest-cov==6.1.0 # Pytest code coverage support coverage[toml]==7.6.1 # pytest-cov dep. This is here to ensure that it includes TOML support for pyproject.toml configs coverage-conditional-plugin==0.9.0 From 0521fb8eb96c02a9bfaeccec370b2a1cc00021ba Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 1 Apr 2025 20:48:03 +0000 Subject: [PATCH 19/62] Bump types-setuptools from 75.8.0.20250210 to 78.1.0.20250329 Bumps [types-setuptools](https://github.com/python/typeshed) from 75.8.0.20250210 to 78.1.0.20250329. - [Commits](https://github.com/python/typeshed/commits) --- updated-dependencies: - dependency-name: types-setuptools dependency-version: 78.1.0.20250329 dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 48c0c843..bacfc92a 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -18,7 +18,7 @@ mypy==1.15.0 pep8-naming==0.14.1 safety==3.2.14 types-requests==2.32.0.20250328 -types-setuptools==75.8.0.20250210 +types-setuptools==78.1.0.20250329 # Code formatting tools autopep8==2.3.2 From 09b98d172e624c3a395b5dede1721034c31f84b1 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Tue, 1 Apr 2025 16:55:40 -0400 Subject: [PATCH 20/62] [Minor] Update Safety Dev Requirement --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 305117a4..a36ee506 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -16,7 +16,7 @@ flake8-use-fstring==1.4 mypy==1.15.0 pep8-naming==0.14.1 -safety==3.2.14 +safety==3.3.1 types-requests==2.32.0.20250328 types-setuptools==78.1.0.20250329 From 29e4bc715b9379a2f94e1e7491e9c6f5576b1d5e Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Tue, 1 Apr 2025 17:03:43 -0400 Subject: [PATCH 21/62] [Minor] Update Pre-Commit Hooks --- .pre-commit-config.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 51702e14..c2b520d3 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -36,7 +36,7 @@ repos: types: [ python ] - repo: https://github.com/pre-commit/pygrep-hooks - rev: 'v1.9.0' + rev: 'v1.10.0' hooks: - id: python-no-eval - id: python-no-log-warn @@ -46,7 +46,7 @@ repos: # mypy - static type checking # mypy --follow-imports skip - repo: https://github.com/pre-commit/mirrors-mypy - rev: 'v0.991' + rev: 'v1.15.0' hooks: - id: mypy # verbose: true @@ -68,7 +68,7 @@ repos: # safety.exe check -r requirements.txt - repo: https://github.com/Lucas-C/pre-commit-hooks-safety - rev: 'v1.2.3' + rev: 'v1.4.0' hooks: - id: python-safety-dependencies-check entry: safety From 336c627c070d6d75e25bb9f2e44e2931fcc828de Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 11 Apr 2025 19:55:01 -0400 Subject: [PATCH 22/62] [#1822] Better Update Checks Also simplifies some if-else checks and sets up cleaner handling of the requests response --- update.py | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/update.py b/update.py index adef9a80..e9d17abb 100644 --- a/update.py +++ b/update.py @@ -11,6 +11,8 @@ import pathlib import shutil import sys import threading +import os +from tkinter import messagebox from traceback import print_exc from typing import TYPE_CHECKING from xml.etree import ElementTree @@ -29,10 +31,7 @@ logger = get_main_logger() def check_for_fdev_updates(silent: bool = False, local: bool = False) -> None: # noqa: CCR001 """Check for and download FDEV ID file updates.""" - if local: - pathway = config.respath_path - else: - pathway = config.app_dir_path + pathway = config.respath_path if local else config.app_dir_path files_urls = [ ('commodity.csv', 'https://raw.githubusercontent.com/EDCD/FDevIDs/master/commodity.csv'), @@ -60,8 +59,10 @@ def check_for_fdev_updates(silent: bool = False, local: bool = False) -> None: except FileNotFoundError: local_content = None - response = requests.get(url, timeout=20) - if response.status_code != 200: + try: + response = requests.get(url, timeout=20) + response.raise_for_status() + except requests.RequestException: if not silent: logger.error(f'Failed to download {file}! Unable to continue.') continue @@ -161,6 +162,13 @@ class Updater: except Exception: print_exc() self.updater = None + if not os.getenv("EDMC_NO_UI"): + messagebox.showerror( + title=appname, + message="Updater Failed to Initialize. Please file a bug report!" + ) + else: + logger.error("Updater Failed to Initialize. Please file a bug report!") return @@ -277,4 +285,3 @@ class Updater: and *it* might have asked this whole application to quit, in which case we don't want to ask *it* to quit """ - pass From 4c334835f2330b9387386b41a0a2e175193c08d3 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 11 Apr 2025 19:57:18 -0400 Subject: [PATCH 23/62] [Minor] Simplify if-else statements --- EDMCLogging.py | 10 ++-------- EDMarketConnector.py | 5 +---- collate.py | 18 +++--------------- companion.py | 17 +++++++---------- plug.py | 6 +----- prefs.py | 8 +++----- 6 files changed, 17 insertions(+), 47 deletions(-) diff --git a/EDMCLogging.py b/EDMCLogging.py index 49b1aa40..b6612570 100644 --- a/EDMCLogging.py +++ b/EDMCLogging.py @@ -258,10 +258,7 @@ def get_plugin_logger(plugin_name: str, loglevel: int = _default_loglevel) -> 'L :param loglevel: Optional logLevel for this Logger. :return: logging.Logger instance, all set up. """ - if not os.getenv('EDMC_NO_UI'): - base_logger_name = appname - else: - base_logger_name = appcmdname + base_logger_name = appcmdname if os.getenv('EDMC_NO_UI') else appname plugin_logger = logging.getLogger(f'{base_logger_name}.{plugin_name}') plugin_logger.setLevel(loglevel) @@ -537,10 +534,7 @@ loglevel: str | int = config.get_str('loglevel') if not loglevel: loglevel = logging.INFO -if not os.getenv('EDMC_NO_UI'): - base_logger_name = appname -else: - base_logger_name = appcmdname +base_logger_name = appcmdname if os.getenv('EDMC_NO_UI') else appname edmclogger = Logger(base_logger_name, loglevel=loglevel) logger: 'LoggerMixin' = edmclogger.get_logger() diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 28e83686..498872c5 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -748,10 +748,7 @@ class AppWindow: self.toggle_suit_row(visible=False) if args.start_min: logger.warning("Trying to start minimized") - if root.overrideredirect(): - self.oniconify() - else: - self.w.wm_iconify() + self.oniconify() if root.overrideredirect() else self.w.wm_iconify() def update_suit_text(self) -> None: """Update the suit text for current type and loadout.""" diff --git a/collate.py b/collate.py index bba94df1..191f2580 100755 --- a/collate.py +++ b/collate.py @@ -234,20 +234,8 @@ if __name__ == "__main__": print('No starport!') continue - if data['lastStarport'].get('commodities'): - addcommodities(data) + addcommodities(data) if data['lastStarport'].get('commodities') else print('No market') - else: - print('No market') + addmodules(data) if data['lastStarport'].get('modules') else print('No outfitting') - if data['lastStarport'].get('modules'): - addmodules(data) - - else: - print('No outfitting') - - if data['lastStarport'].get('ships'): - addships(data) - - else: - print('No shipyard') + addships(data) if data['lastStarport'].get('ships') else print('No shipyard') diff --git a/companion.py b/companion.py index 9d655bc6..82db868d 100644 --- a/companion.py +++ b/companion.py @@ -110,11 +110,8 @@ class CAPIData(UserDict): logger.debug('modules was None. FC or Damaged Station?') elif isinstance(modules, list): - if not modules: - logger.debug('modules is empty list. Damaged Station?') - - else: - logger.error(f'modules is non-empty list: {modules!r}') + logger.debug('modules is empty list. Damaged Station?') if not modules \ + else logger.error(f'modules is non-empty list: {modules!r}') else: logger.error(f'modules was not None, a list, or a dict! type: {type(modules)}, content: {modules}') @@ -543,11 +540,11 @@ class Auth: # noinspection PyMethodMayBeStatic def dump(self, r: requests.Response) -> None: """Dump details of HTTP failure from oAuth attempt.""" - if r: - logger.debug(f'Frontier CAPI Auth: {r.url} {r.status_code} {r.reason if r.reason else "None"} {r.text}') - - else: - logger.debug(f'Frontier CAPI Auth: failed with `r` False: {r!r}') + logger.debug( + f'Frontier CAPI Auth: {r.url} {r.status_code} {r.reason or "None"} {r.text}' + if r else + f'Frontier CAPI Auth: failed with `r` False: {r!r}' + ) # noinspection PyMethodMayBeStatic def base64_url_encode(self, text: bytes) -> str: diff --git a/plug.py b/plug.py index 75f9eaf4..9841ee0a 100644 --- a/plug.py +++ b/plug.py @@ -414,11 +414,7 @@ def notify_capidata(data: companion.CAPIData, is_beta: bool) -> str | None: error = None for plugin in PLUGINS: # TODO: Handle it being Legacy data - if data.source_host == companion.SERVER_LEGACY: - cmdr_data = plugin._get_func('cmdr_data_legacy') - - else: - cmdr_data = plugin._get_func('cmdr_data') + cmdr_data = plugin._get_func('cmdr_data_legacy' if data.source_host == companion.SERVER_LEGACY else 'cmdr_data') if cmdr_data: try: diff --git a/prefs.py b/prefs.py index 95f29e7f..436decb1 100644 --- a/prefs.py +++ b/prefs.py @@ -965,11 +965,9 @@ class PreferencesDialog(tk.Toplevel): ).grid(padx=self.PADX, pady=self.PADY, sticky=tk.W, row=row.get()) for plugin in enabled_plugins: - if plugin.name == plugin.folder: - label = nb.Label(plugins_frame, text=plugin.name) - - else: - label = nb.Label(plugins_frame, text=f'{plugin.folder} ({plugin.name})') + label = nb.Label(plugins_frame, + text=plugin.name if plugin.name == plugin.folder + else f'{plugin.folder} ({plugin.name})') label.grid(columnspan=2, padx=self.LISTX, pady=self.PADY, sticky=tk.W, row=row.get()) From de503e39fc2850159d51281790efee638584c4f0 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 11 Apr 2025 20:49:13 -0400 Subject: [PATCH 24/62] [#2348] Remove WiX Check --- resources/EDMC_Installer_Config_template.txt | 44 -------------------- 1 file changed, 44 deletions(-) diff --git a/resources/EDMC_Installer_Config_template.txt b/resources/EDMC_Installer_Config_template.txt index 1a31eeca..06ad4ea6 100644 --- a/resources/EDMC_Installer_Config_template.txt +++ b/resources/EDMC_Installer_Config_template.txt @@ -54,50 +54,6 @@ Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: de [Run] Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent -;Check if a WiX-based installation exists. If so, kill it with fire. -[Code] -function EndsWith(SubText, Text: AnsiString): Boolean; -var - EndStr: string; -begin - Log('Starting'); - EndStr := Copy(Text, Length(Text) - Length(SubText) + 1, Length(SubText)); - Log(EndStr); - { Use SameStr, if you need a case-sensitive comparison } - Result := SameText(SubText, EndStr); -end; - -// EDMC didn't keep a consistant GUID during previous history. Due to that, we have to do this tomfoolery. -procedure CurStepChanged(CurStep: TSetupStep); -var - ResultCode: Integer; - Uninstall: String; - OldWiX: Boolean; - S: AnsiString; - PowerShellOutputFile: String; -begin - if (CurStep = ssInstall) then - begin - PowerShellOutputFile := ExpandConstant('{tmp}\PowershellOutput.txt'); - // Construct the PowerShell command and capture output to a file - Exec('powershell.exe', '-NoProfile -Command "Get-WmiObject -Class Win32_Product | where Name -eq ''Elite Dangerous Market Connector'' | select-object -expandproperty IdentifyingNumber" | Out-File -Encoding ASCII "' + PowerShellOutputFile + '"', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); - begin - if LoadStringFromFile(PowerShellOutputFile, S) then - S:= Trim(S); - Log(S); - begin - OldWiX:=EndsWith('}', S); - if (OldWiX = True) then - begin - MsgBox('Warning: an old version of EDMC is installed! Please close EDMC while we remove the old version!', mbInformation, MB_OK); - Uninstall := '/x ' + S; - Exec('MsiExec.exe', Uninstall, '', SW_SHOW, ewWaitUntilTerminated, ResultCode); - end; - end; - end; - end; -end; - [Registry] ; Create the main registry key under HKCR Root: HKCR; Subkey: "edmc"; Flags: uninsdeletekey From aeed31acd12e7f4c8a22b1d3da5edbfa7e642f29 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sat, 12 Apr 2025 12:23:18 -0400 Subject: [PATCH 25/62] [Minor] Add Back Pass Stylistic choice after discussion in Discord Signed-off-by: David Sangrey --- update.py | 1 + 1 file changed, 1 insertion(+) diff --git a/update.py b/update.py index e9d17abb..f9574242 100644 --- a/update.py +++ b/update.py @@ -285,3 +285,4 @@ class Updater: and *it* might have asked this whole application to quit, in which case we don't want to ask *it* to quit """ + pass From 26f06b7bf0cbfa24301b4e289c15cbcf354467e8 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 13 Apr 2025 13:42:06 -0400 Subject: [PATCH 26/62] [#2406] Consolidate Modules --- build.py | 1 + plugins/common_coreutils.py | 190 ++++++++++++++++++++++++++++++++++++ plugins/coriolis.py | 33 +++---- plugins/eddn.py | 12 +-- plugins/edsm.py | 62 ++---------- plugins/edsy.py | 19 +--- plugins/inara.py | 71 +++----------- plugins/spansh_core.py | 38 ++------ 8 files changed, 244 insertions(+), 182 deletions(-) create mode 100644 plugins/common_coreutils.py diff --git a/build.py b/build.py index d14b4f62..e17c0979 100644 --- a/build.py +++ b/build.py @@ -121,6 +121,7 @@ def build() -> None: "plugins/edsy.py", "plugins/inara.py", "plugins/spansh_core.py", + "plugins/common_coreutils.py" ] options: dict = { "py2exe": { diff --git a/plugins/common_coreutils.py b/plugins/common_coreutils.py new file mode 100644 index 00000000..615708f2 --- /dev/null +++ b/plugins/common_coreutils.py @@ -0,0 +1,190 @@ +""" +common_coreutils.py - Common Plugin Functions. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. + +This is an EDMC 'core' plugin. + +All EDMC plugins are *dynamically* loaded at run-time. + +We build for Windows using `py2exe`. +`py2exe` can't possibly know about anything in the dynamically loaded core plugins. + +Thus, you **MUST** check if any imports you add in this file are only +referenced in this file (or only in any other core plugin), and if so... + + YOU MUST ENSURE THAT PERTINENT ADJUSTMENTS ARE MADE IN + `build.py` TO ENSURE THE FILES ARE ACTUALLY PRESENT + IN AN END-USER INSTALLATION ON WINDOWS. +""" +# pylint: disable=import-error +from __future__ import annotations + +from typing import Any, Mapping, cast +import tkinter as tk +import base64 +import gzip +import io +import json +import myNotebook as nb # noqa: N813 +from EDMCLogging import get_main_logger +from companion import CAPIData +from l10n import translations as tr + +logger = get_main_logger() + +# Global Padding Preferences +PADX = 10 +BUTTONX = 12 # indent Checkbuttons and Radiobuttons +PADY = 1 # close spacing +BOXY = 2 # box spacing +SEPY = 10 # seperator line spacing +STATION_UNDOCKED = '×' # "Station" name to display when not docked = U+00D7 + + +def plugin_start3(plugin_dir: str) -> str: + """ + Start the plugin. + + :param plugin_dir: NAme of directory this was loaded from. + :return: Identifier string for this plugin. + """ + return 'CommonCoreUtils' + + +def api_keys_label_common(this, cur_row: int, frame: nb.Frame): + """ + Prepare the box for API Key Loading. This is an EDMC Common Function. + + :param this: The module global from the calling module. + :param cur_row: The current row in the calling module's config page. + :param frame: The current frame in the calling module's config page. + :return: The updated module global from the calling module. + """ + # LANG: EDSM API key label + this.apikey_label = nb.Label(frame, text=tr.tl('API Key')) + this.apikey_label.grid(row=cur_row, padx=PADX, pady=PADY, sticky=tk.W) + this.apikey = nb.EntryMenu(frame, show="*", width=50) + this.apikey.grid(row=cur_row, column=1, padx=PADX, pady=BOXY, sticky=tk.EW) + return this + + +def show_pwd_var_common(frame: nb.Frame, cur_row: int, this): + """ + Allow unmasking of the API Key. This is an EDMC Common Function. + + :param cur_row: The current row in the calling module's config page. + :param frame: The current frame in the calling module's config page. + """ + show_password_var.set(False) # Password is initially masked + + show_password_checkbox = nb.Checkbutton( + frame, + text=tr.tl('Show API Key'), # LANG: Text EDSM Show API Key + variable=show_password_var, + command=lambda: toggle_password_visibility_common(this) + ) + show_password_checkbox.grid(row=cur_row, columnspan=2, padx=BUTTONX, pady=PADY, sticky=tk.W) + + +# Return a URL for the current ship +def shipyard_url_common(loadout: Mapping[str, Any]) -> str: + """ + Construct a URL for ship loadout. This is an EDMC Common Function. + + :param loadout: The ship loadout data. + :return: The constructed URL for the ship loadout. + """ + # Convert loadout to JSON and gzip compress it + string = json.dumps(loadout, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8') + if not string: + return '' + + out = io.BytesIO() + with gzip.GzipFile(fileobj=out, mode='w') as f: + f.write(string) + + encoded_data = base64.urlsafe_b64encode(out.getvalue()).decode().replace('=', '%3D') + return encoded_data + + +def station_link_common(data: CAPIData, this): + """ + Set the Staion Name. This is an EDMC Common Function. + + :param data: A CAPI Data Entry. + :param this: The module global from the calling module. + """ + if data['commander']['docked'] or this.on_foot and this.station_name: + this.station_link['text'] = this.station_name + elif data['lastStarport']['name'] and data['lastStarport']['name'] != "": + this.station_link['text'] = STATION_UNDOCKED + else: + this.station_link['text'] = '' + + +def this_format_common(this, state: Mapping[str, Any]): + """ + Gather Common 'This' Elements. This is an EDMC Common Function. + + :param this: The module global from the calling module. + :param state: `monitor.state`. + """ + this.system_address = state['SystemAddress'] + this.system_name = state['SystemName'] + this.system_population = state['SystemPopulation'] + this.station_name = state['StationName'] + this.station_marketid = state['MarketID'] + this.station_type = state['StationType'] + this.on_foot = state['OnFoot'] + + +def toggle_password_visibility_common(this): + """ + Toggle if the API Key is visible or not. This is an EDMC Common Function. + + :param this: The module global from the calling module. + """ + if show_password_var.get(): + this.apikey.config(show="") # type: ignore + else: + this.apikey.config(show="*") # type: ignore + + +def station_name_setter_common(this): + """ + Set the Station Name. This is an EDMC Common Function. + + :param this: The module global from the calling module. + """ + to_set: str = cast(str, this.station_name) + if not to_set: + if this.system_population is not None and this.system_population > 0: + to_set = STATION_UNDOCKED + else: + to_set = '' + + this.station_link['text'] = to_set + + +def cmdr_data_initial_common(this, data: CAPIData): + """ + Set the common CMDR Data. This is an EDMC Common Function. + + :param this: The module global from the calling module. + :param data: The latest merged CAPI data. + """ + # Always store initially, even if we're not the *current* system provider. + if not this.station_marketid and data['commander']['docked']: + this.station_marketid = data['lastStarport']['id'] + + # Only trust CAPI if these aren't yet set + if not this.system_name: + this.system_name = data['lastSystem']['name'] + if not this.station_name and data['commander']['docked']: + this.station_name = data['lastStarport']['name'] + + +show_password_var = tk.BooleanVar() diff --git a/plugins/coriolis.py b/plugins/coriolis.py index a9eabced..89f128f7 100644 --- a/plugins/coriolis.py +++ b/plugins/coriolis.py @@ -19,12 +19,10 @@ referenced in this file (or only in any other core plugin), and if so... `build.py` TO ENSURE THE FILES ARE ACTUALLY PRESENT IN AN END-USER INSTALLATION ON WINDOWS. """ +# pylint: disable=import-error from __future__ import annotations -import base64 -import gzip -import io -import json +from typing import Any, Mapping import tkinter as tk from tkinter import ttk import myNotebook as nb # noqa: N813 # its not my fault. @@ -32,6 +30,7 @@ from EDMCLogging import get_main_logger from plug import show_error from config import config from l10n import translations as tr +from plugins.common_coreutils import PADX, PADY, BOXY, shipyard_url_common class CoriolisConfig: @@ -82,10 +81,6 @@ def plugin_start3(path: str) -> str: def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> nb.Frame: """Set up plugin preferences.""" - PADX = 10 # noqa: N806 - PADY = 1 # noqa: N806 - BOXY = 2 # noqa: N806 # box spacing - # Save the old text values for the override mode, so we can update them if the language is changed coriolis_config.override_text_old_auto = tr.tl('Auto') # LANG: Coriolis normal/beta selection - auto coriolis_config.override_text_old_normal = tr.tl('Normal') # LANG: Coriolis normal/beta selection - normal @@ -207,14 +202,14 @@ def _get_target_url(is_beta: bool) -> str: return coriolis_config.normal_url -def shipyard_url(loadout, is_beta) -> str | bool: - """Return a URL for the current ship.""" - # most compact representation - string = json.dumps(loadout, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8') - if not string: - return False - out = io.BytesIO() - with gzip.GzipFile(fileobj=out, mode='w') as f: - f.write(string) - encoded = base64.urlsafe_b64encode(out.getvalue()).decode().replace('=', '%3D') - return _get_target_url(is_beta) + encoded +# Return a URL for the current ship +def shipyard_url(loadout: Mapping[str, Any], is_beta: bool) -> bool | str: + """ + Construct a URL for ship loadout. + + :param loadout: The ship loadout data. + :param is_beta: Whether the game is in beta. + :return: The constructed URL for the ship loadout. + """ + encoded_data = shipyard_url_common(loadout) + return _get_target_url(is_beta) + encoded_data if encoded_data else False diff --git a/plugins/eddn.py b/plugins/eddn.py index 01d0a46a..9bfab900 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -18,6 +18,7 @@ referenced in this file (or only in any other core plugin), and if so... `build.py` TO ENSURE THE FILES ARE ACTUALLY PRESENT IN AN END-USER INSTALLATION ON WINDOWS. """ +# pylint: disable=import-error from __future__ import annotations import http @@ -47,6 +48,7 @@ from prefs import prefsVersion from ttkHyperlinkLabel import HyperlinkLabel from util import text from l10n import translations as tr +from plugins.common_coreutils import PADX, PADY, BUTTONX, this_format_common logger = get_main_logger() @@ -2145,10 +2147,6 @@ def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: :param is_beta: `bool` - True if this is a beta version of the Game. :return: The tkinter frame we created. """ - PADX = 10 # noqa: N806 - BUTTONX = 12 # noqa: N806 # indent Checkbuttons and Radiobuttons - PADY = 1 # noqa: N806 - if prefsVersion.shouldSetDefaults('0.0.0.0', not bool(config.get_int('output'))): output: int = config.OUT_EDDN_SEND_STATION_DATA | config.OUT_EDDN_SEND_NON_STATION # default settings @@ -2349,11 +2347,7 @@ def journal_entry( # noqa: C901, CCR001 this.body_id = state['BodyID'] this.body_type = state['BodyType'] this.coordinates = state['StarPos'] - this.system_address = state['SystemAddress'] - this.system_name = state['SystemName'] - this.station_name = state['StationName'] - this.station_type = state['StationType'] - this.station_marketid = state['MarketID'] + this_format_common(this, state) if event_name == 'docked': # Trigger a send/retry of pending EDDN messages diff --git a/plugins/edsm.py b/plugins/edsm.py index 1d9f8cb8..a2e5004f 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -18,6 +18,7 @@ referenced in this file (or only in any other core plugin), and if so... `build.py` TO ENSURE THE FILES ARE ACTUALLY PRESENT IN AN END-USER INSTALLATION ON WINDOWS. """ +# pylint: disable=import-error from __future__ import annotations import json @@ -40,6 +41,9 @@ from edmc_data import DEBUG_WEBSERVER_HOST, DEBUG_WEBSERVER_PORT from EDMCLogging import get_main_logger from ttkHyperlinkLabel import HyperlinkLabel from l10n import translations as tr +from plugins.common_coreutils import (api_keys_label_common, PADX, PADY, BUTTONX, SEPY, BOXY, STATION_UNDOCKED, + show_pwd_var_common, station_link_common, this_format_common, + cmdr_data_initial_common) # TODO: @@ -118,9 +122,7 @@ class This: this = This() -show_password_var = tk.BooleanVar() -STATION_UNDOCKED: str = '×' # "Station" name to display when not docked = U+00D7 __cleanup = str.maketrans({' ': None, '\n': None}) IMG_KNOWN_B64 = """ R0lGODlhEAAQAMIEAFWjVVWkVWS/ZGfFZ////////////////yH5BAEKAAQALAAAAAAQABAAAAMvSLrc/lAFIUIkYOgNXt5g14Dk0AQlaC1CuglM6w7wgs7r @@ -269,14 +271,6 @@ def plugin_stop() -> None: logger.debug('Done.') -def toggle_password_visibility(): - """Toggle if the API Key is visible or not.""" - if show_password_var.get(): - this.apikey.config(show="") # type: ignore - else: - this.apikey.config(show="*") # type: ignore - - def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> nb.Frame: """ Plugin preferences setup hook. @@ -289,12 +283,6 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> nb.Fr :param is_beta: Whether game beta was detected. :return: An instance of `myNotebook.Frame`. """ - PADX = 10 # noqa: N806 - BUTTONX = 12 # noqa: N806 - PADY = 1 # noqa: N806 - BOXY = 2 # noqa: N806 - SEPY = 10 # noqa: N806 - frame = nb.Frame(parent) frame.columnconfigure(1, weight=1) @@ -349,23 +337,10 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> nb.Fr cur_row += 1 # LANG: EDSM API key label - this.apikey_label = nb.Label(frame, text=tr.tl('API Key')) - this.apikey_label.grid(row=cur_row, padx=PADX, pady=PADY, sticky=tk.W) - this.apikey = nb.EntryMenu(frame, show="*", width=50) - this.apikey.grid(row=cur_row, column=1, padx=PADX, pady=BOXY, sticky=tk.EW) + api_keys_label_common(this, cur_row, frame) cur_row += 1 - prefs_cmdr_changed(cmdr, is_beta) - - show_password_var.set(False) # Password is initially masked - - show_password_checkbox = nb.Checkbutton( - frame, - text=tr.tl('Show API Key'), # LANG: Text EDSM Show API Key - variable=show_password_var, - command=toggle_password_visibility - ) - show_password_checkbox.grid(row=cur_row, columnspan=2, padx=BUTTONX, pady=PADY, sticky=tk.W) + show_pwd_var_common(frame, cur_row, this) return frame @@ -544,11 +519,7 @@ def journal_entry( # noqa: C901, CCR001 this.game_version = state['GameVersion'] this.game_build = state['GameBuild'] - this.system_address = state['SystemAddress'] - this.system_name = state['SystemName'] - this.system_population = state['SystemPopulation'] - this.station_name = state['StationName'] - this.station_marketid = state['MarketID'] + this_format_common(this, state) entry = new_entry @@ -658,7 +629,7 @@ Queueing: {entry!r}''' # Update system data -def cmdr_data(data: CAPIData, is_beta: bool) -> str | None: # noqa: CCR001 +def cmdr_data(data: CAPIData, is_beta: bool) -> str | None: """ Process new CAPI data. @@ -668,14 +639,7 @@ def cmdr_data(data: CAPIData, is_beta: bool) -> str | None: # noqa: CCR001 """ system = data['lastSystem']['name'] - # Always store initially, even if we're not the *current* system provider. - if not this.station_marketid and data['commander']['docked']: - this.station_marketid = data['lastStarport']['id'] - # Only trust CAPI if these aren't yet set - if not this.system_name: - this.system_name = data['lastSystem']['name'] - if not this.station_name and data['commander']['docked']: - this.station_name = data['lastStarport']['name'] + cmdr_data_initial_common(this, data) # TODO: Fire off the EDSM API call to trigger the callback for the icons @@ -687,13 +651,7 @@ def cmdr_data(data: CAPIData, is_beta: bool) -> str | None: # noqa: CCR001 this.system_link.update_idletasks() if config.get_str('station_provider') == 'EDSM': if this.station_link: - if data['commander']['docked'] or this.on_foot and this.station_name: - this.station_link['text'] = this.station_name - elif data['lastStarport']['name'] and data['lastStarport']['name'] != "": - this.station_link['text'] = STATION_UNDOCKED - else: - this.station_link['text'] = '' - + station_link_common(data, this) # Do *NOT* set 'url' here, as it's set to a function that will call # through correctly. We don't want a static string. this.station_link.update_idletasks() diff --git a/plugins/edsy.py b/plugins/edsy.py index a02d3424..b1bdbaf1 100644 --- a/plugins/edsy.py +++ b/plugins/edsy.py @@ -20,11 +20,8 @@ referenced in this file (or only in any other core plugin), and if so... """ from __future__ import annotations -import base64 -import gzip -import io -import json from typing import Any, Mapping +from plugins.common_coreutils import shipyard_url_common # pylint: disable=E0401 def plugin_start3(plugin_dir: str) -> str: @@ -46,17 +43,7 @@ def shipyard_url(loadout: Mapping[str, Any], is_beta: bool) -> bool | str: :param is_beta: Whether the game is in beta. :return: The constructed URL for the ship loadout. """ - # Convert loadout to JSON and gzip compress it - string = json.dumps(loadout, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8') - if not string: - return False - - out = io.BytesIO() - with gzip.GzipFile(fileobj=out, mode='w') as f: - f.write(string) - + encoded_data = shipyard_url_common(loadout) # Construct the URL using the appropriate base URL based on is_beta base_url = 'https://edsy.org/beta/#/I=' if is_beta else 'https://edsy.org/#/I=' - encoded_data = base64.urlsafe_b64encode(out.getvalue()).decode().replace('=', '%3D') - - return base_url + encoded_data + return base_url + encoded_data if encoded_data else False diff --git a/plugins/inara.py b/plugins/inara.py index 6c243172..c7426f46 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -18,6 +18,7 @@ referenced in this file (or only in any other core plugin), and if so... `build.py` TO ENSURE THE FILES ARE ACTUALLY PRESENT IN AN END-USER INSTALLATION ON WINDOWS. """ +# pylint: disable=import-error from __future__ import annotations import json @@ -43,6 +44,8 @@ from EDMCLogging import get_main_logger from monitor import monitor from ttkHyperlinkLabel import HyperlinkLabel from l10n import translations as tr +from plugins.common_coreutils import (api_keys_label_common, PADX, PADY, BUTTONX, SEPY, station_name_setter_common, + show_pwd_var_common, station_link_common, this_format_common) logger = get_main_logger() @@ -115,7 +118,7 @@ class This: self.system_address: str | None = None # type: ignore self.system_population: int | None = None self.station_link: tk.Widget = None # type: ignore - self.station = None + self.station_name = None self.station_marketid = None # Prefs UI @@ -144,7 +147,6 @@ class This: this = This() -show_password_var = tk.BooleanVar() # last time we updated, if unset in config this is 0, which means an instant update LAST_UPDATE_CONF_KEY = 'inara_last_update' @@ -187,9 +189,9 @@ def station_url(system_name: str, station_name: str) -> str: if system_name and station_name: return requests.utils.requote_uri(f'https://inara.cz/galaxy-station/?search={system_name}%20[{station_name}]') - if this.system_name and this.station: + if this.system_name and this.station_name: return requests.utils.requote_uri( - f'https://inara.cz/galaxy-station/?search={this.system_name}%20[{this.station}]') + f'https://inara.cz/galaxy-station/?search={this.system_name}%20[{this.station_name}]') if system_name: return system_url(system_name) @@ -233,21 +235,8 @@ def plugin_stop() -> None: logger.debug('Done.') -def toggle_password_visibility(): - """Toggle if the API Key is visible or not.""" - if show_password_var.get(): - this.apikey.config(show="") - else: - this.apikey.config(show="*") - - def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> nb.Frame: """Plugin Preferences UI hook.""" - PADX = 10 # noqa: N806 - BUTTONX = 12 # noqa: N806 # indent Checkbuttons and Radiobuttons - PADY = 1 # noqa: N806 # close spacing - BOXY = 2 # noqa: N806 # box spacing - SEPY = 10 # noqa: N806 # seperator line spacing cur_row = 0 frame = nb.Frame(parent) @@ -287,22 +276,10 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> nb.Frame: cur_row += 1 # LANG: Inara API key label - this.apikey_label = nb.Label(frame, text=tr.tl('API Key')) # Inara setting - this.apikey_label.grid(row=cur_row, padx=PADX, pady=PADY, sticky=tk.W) - this.apikey = nb.EntryMenu(frame, show="*", width=50) - this.apikey.grid(row=cur_row, column=1, padx=PADX, pady=BOXY, sticky=tk.EW) + api_keys_label_common(this, cur_row, frame) cur_row += 1 - prefs_cmdr_changed(cmdr, is_beta) - - show_password_var.set(False) # Password is initially masked - show_password_checkbox = nb.Checkbutton( - frame, - text=tr.tl('Show API Key'), # LANG: Text Inara Show API key - variable=show_password_var, - command=toggle_password_visibility, - ) - show_password_checkbox.grid(row=cur_row, columnspan=2, padx=BUTTONX, pady=PADY, sticky=tk.W) + show_pwd_var_common(frame, cur_row, this) return frame @@ -411,15 +388,11 @@ def journal_entry( # noqa: C901, CCR001 # But then we update all the tracking copies before any other checks, # because they're relevant for URL providing even if *sending* isn't # appropriate. - this.on_foot = state['OnFoot'] event_name: str = entry['event'] this.cmdr = cmdr this.FID = state['FID'] this.multicrew = bool(state['Role']) - this.system_name = state['SystemName'] - this.system_address = state['SystemAddress'] - this.station = state['StationName'] - this.station_marketid = state['MarketID'] + this_format_common(this, state) if not monitor.is_live_galaxy(): # Since Update 14 on 2022-11-29 Inara only accepts Live data. @@ -613,7 +586,7 @@ def journal_entry( # noqa: C901, CCR001 elif event_name == 'Undocked': this.undocked = True - this.station = None + this.station_name = None elif event_name == 'SupercruiseEntry': this.undocked = False @@ -1368,14 +1341,7 @@ def journal_entry( # noqa: C901, CCR001 this.system_link.update_idletasks() if config.get_str('station_provider') == 'Inara': - to_set: str = cast(str, this.station) - if not to_set: - if this.system_population is not None and this.system_population > 0: - to_set = STATION_UNDOCKED - else: - to_set = '' - - this.station_link['text'] = to_set + station_name_setter_common(this) # Do *NOT* set 'url' here, as it's set to a function that will call # through correctly. We don't want a static string. this.station_link.update_idletasks() @@ -1383,7 +1349,7 @@ def journal_entry( # noqa: C901, CCR001 return '' # No error -def cmdr_data(data: CAPIData, is_beta): # noqa: CCR001, reanalyze me later +def cmdr_data(data: CAPIData, is_beta): """CAPI event hook.""" this.cmdr = data['commander']['name'] @@ -1394,8 +1360,8 @@ def cmdr_data(data: CAPIData, is_beta): # noqa: CCR001, reanalyze me later # Only trust CAPI if these aren't yet set this.system_name = this.system_name if this.system_name else data['lastSystem']['name'] - if not this.station and data['commander']['docked']: - this.station = data['lastStarport']['name'] + if not this.station_name and data['commander']['docked']: + this.station_name = data['lastStarport']['name'] # Override standard URL functions if config.get_str('system_provider') == 'Inara': @@ -1405,14 +1371,7 @@ def cmdr_data(data: CAPIData, is_beta): # noqa: CCR001, reanalyze me later this.system_link.update_idletasks() if config.get_str('station_provider') == 'Inara': - if data['commander']['docked'] or this.on_foot and this.station: - this.station_link['text'] = this.station - - elif data['lastStarport']['name'] and data['lastStarport']['name'] != "": - this.station_link['text'] = STATION_UNDOCKED - - else: - this.station_link['text'] = '' + station_link_common(data, this) # Do *NOT* set 'url' here, as it's set to a function that will call # through correctly. We don't want a static string. diff --git a/plugins/spansh_core.py b/plugins/spansh_core.py index 77106da8..b28556ac 100644 --- a/plugins/spansh_core.py +++ b/plugins/spansh_core.py @@ -18,14 +18,17 @@ referenced in this file (or only in any other core plugin), and if so... `build.py` TO ENSURE THE FILES ARE ACTUALLY PRESENT IN AN END-USER INSTALLATION ON WINDOWS. """ +# pylint: disable=import-error from __future__ import annotations import tkinter as tk -from typing import Any, cast +from typing import Any import requests from companion import CAPIData from config import appname, config from EDMCLogging import get_main_logger +from plugins.common_coreutils import (station_link_common, this_format_common, + cmdr_data_initial_common, station_name_setter_common) logger = get_main_logger() @@ -91,12 +94,7 @@ def journal_entry( :param state: `monitor.state` :return: None if no error, else an error string. """ - this.on_foot = state['OnFoot'] - this.system_address = state['SystemAddress'] - this.system_name = state['SystemName'] - this.system_population = state['SystemPopulation'] - this.station_name = state['StationName'] - this.station_marketid = state['MarketID'] + this_format_common(this, state) # Only actually change URLs if we are current provider. if config.get_str('system_provider') == 'spansh': @@ -106,14 +104,7 @@ def journal_entry( this.system_link.update_idletasks() if config.get_str('station_provider') == 'spansh': - to_set: str = cast(str, this.station_name) - if not to_set: - if this.system_population is not None and this.system_population > 0: - to_set = STATION_UNDOCKED - else: - to_set = '' - - this.station_link['text'] = to_set + station_name_setter_common(this) # Do *NOT* set 'url' here, as it's set to a function that will call # through correctly. We don't want a static string. this.station_link.update_idletasks() @@ -129,15 +120,7 @@ def cmdr_data(data: CAPIData, is_beta: bool) -> str | None: :param is_beta: Whether game beta was detected. :return: Optional error string. """ - # Always store initially, even if we're not the *current* system provider. - if not this.station_marketid and data['commander']['docked']: - this.station_marketid = data['lastStarport']['id'] - - # Only trust CAPI if these aren't yet set - if not this.system_name: - this.system_name = data['lastSystem']['name'] - if not this.station_name and data['commander']['docked']: - this.station_name = data['lastStarport']['name'] + cmdr_data_initial_common(this, data) # Override standard URL functions if config.get_str('system_provider') == 'spansh': @@ -146,12 +129,7 @@ def cmdr_data(data: CAPIData, is_beta: bool) -> str | None: # through correctly. We don't want a static string. this.system_link.update_idletasks() if config.get_str('station_provider') == 'spansh': - if data['commander']['docked'] or this.on_foot and this.station_name: - this.station_link['text'] = this.station_name - elif data['lastStarport']['name'] and data['lastStarport']['name'] != "": - this.station_link['text'] = STATION_UNDOCKED - else: - this.station_link['text'] = '' + station_link_common(data, this) # Do *NOT* set 'url' here, as it's set to a function that will call # through correctly. We don't want a static string. this.station_link.update_idletasks() From 5c14a7afc7aa2ce96ec021a5dbcff5c82b179b60 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 13 Apr 2025 13:44:51 -0400 Subject: [PATCH 27/62] [Minor] Slight Refactorings --- EDMCLogging.py | 2 -- EDMCSystemProfiler.py | 21 +++++++++++---------- EDMarketConnector.py | 24 +++++++++--------------- prefs.py | 7 ++++--- 4 files changed, 24 insertions(+), 30 deletions(-) diff --git a/EDMCLogging.py b/EDMCLogging.py index 49b1aa40..15a7b4f6 100644 --- a/EDMCLogging.py +++ b/EDMCLogging.py @@ -338,8 +338,6 @@ class EDMCContextFilter(logging.Filter): # try: frame_info = inspect.getframeinfo(frame) - # raise(IndexError) # TODO: Remove, only for testing - except Exception: # Separate from the print below to guarantee we see at least this much. print('EDMCLogging:EDMCContextFilter:caller_attributes(): Failed in `inspect.getframinfo(frame)`') diff --git a/EDMCSystemProfiler.py b/EDMCSystemProfiler.py index 873282b8..a5d97ce4 100644 --- a/EDMCSystemProfiler.py +++ b/EDMCSystemProfiler.py @@ -38,17 +38,17 @@ from monitor import monitor from EDMCLogging import get_main_logger -def get_sys_report(config: config.AbstractConfig) -> str: +def get_sys_report(active_config: config.AbstractConfig) -> str: """Gather system information about Elite, the Host Computer, and EDMC.""" # Calculate Requested Information plt = platform.uname() locale.setlocale(locale.LC_ALL, "") lcl = locale.getlocale() - monitor.currentdir = config.get_str( - "journaldir", default=config.default_journal_dir + monitor.currentdir = active_config.get_str( + "journaldir", default=active_config.default_journal_dir ) if not monitor.currentdir: - monitor.currentdir = config.default_journal_dir + monitor.currentdir = active_config.default_journal_dir try: logfile = monitor.journal_newest_filename(monitor.currentdir) if logfile is None: @@ -108,21 +108,21 @@ def copy_sys_report(root: tk.Tk, report: str) -> None: messagebox.showinfo("System Profiler", "System Report copied to Clipboard", parent=root) -def main() -> None: +def main(active_config: config.AbstractConfig) -> None: """Entry Point for the System Profiler.""" # Now Let's Begin root: tk.Tk = tk.Tk() root.withdraw() # Hide the window initially to calculate the dimensions try: icon_image = tk.PhotoImage( - file=path.join(cur_config.respath_path, "io.edcd.EDMarketConnector.png") + file=path.join(active_config.respath_path, "io.edcd.EDMarketConnector.png") ) root.iconphoto(True, icon_image) except tk.TclError: - root.iconbitmap(path.join(cur_config.respath_path, "EDMarketConnector.ico")) + root.iconbitmap(path.join(active_config.respath_path, "EDMarketConnector.ico")) - sys_report = get_sys_report(cur_config) + sys_report = get_sys_report(active_config) # Set up styling style = ttk.Style(root) @@ -182,7 +182,8 @@ if __name__ == "__main__": # Args: Only work if not frozen parser = argparse.ArgumentParser( prog=appname, - description="Prints diagnostic and debugging information about the current EDMC configuration.", + description="Prints diagnostic and debugging information " + "about the current EDMC configuration.", ) parser.add_argument( "--out-console", @@ -203,4 +204,4 @@ if __name__ == "__main__": print(sys_report) sys.exit(0) - main() + main(cur_config) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 28e83686..98496c0a 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -840,8 +840,7 @@ class AppWindow: r' if downgrading between major versions with significant changes.\r\n\r\n' 'Do you want to open GitHub to download the latest release?' ) - update_msg = update_msg.replace('\\n', '\n') - update_msg = update_msg.replace('\\r', '\r') + update_msg = update_msg.replace('\\n', '\n').replace('\\r', '\r') stable_popup = tk.messagebox.askyesno(title=title, message=update_msg) if stable_popup: webbrowser.open("https://github.com/EDCD/eDMarketConnector/releases/latest") @@ -2064,17 +2063,15 @@ def validate_providers(): # LANG: Popup-text about Reset Providers popup_text = tr.tl(r'One or more of your URL Providers were invalid, and have been reset:\r\n\r\n') - for provider in reset_providers: + for provider, (old_prov, new_prov) in reset_providers.items(): # LANG: Text About What Provider Was Reset - popup_text += tr.tl(r'{PROVIDER} was set to {OLDPROV}, and has been reset to {NEWPROV}\r\n') - popup_text = popup_text.format( + popup_text += tr.tl(r'{PROVIDER} was set to {OLDPROV}, and has been reset to {NEWPROV}\r\n').format( PROVIDER=provider, - OLDPROV=reset_providers[provider][0], - NEWPROV=reset_providers[provider][1] + OLDPROV=old_prov, + NEWPROV=new_prov ) # And now we do need these to be actual \r\n - popup_text = popup_text.replace('\\n', '\n') - popup_text = popup_text.replace('\\r', '\r') + popup_text = popup_text.replace('\\n', '\n').replace('\\r', '\r') tk.messagebox.showinfo( # LANG: Popup window title for Reset Providers @@ -2246,8 +2243,7 @@ sys.path: {sys.path}''' detail = tr.tl( # LANG: EDMC Critical Error Details r"Here's what EDMC Detected:\r\n\r\n{ERR}\r\n\r\nDo you want to file a Bug Report on GitHub?" ).format(ERR=err) - detail = detail.replace('\\n', '\n') - detail = detail.replace('\\r', '\r') + detail = detail.replace('\\n', '\n').replace('\\r', '\r') msg = tk.messagebox.askyesno( title=title, message=message, detail=detail, icon=tkinter.messagebox.ERROR, type=tkinter.messagebox.YESNO, parent=root @@ -2278,8 +2274,7 @@ sys.path: {sys.path}''' DISABLED='.disabled' ) # And now we do need these to be actual \r\n - popup_text = popup_text.replace('\\n', '\n') - popup_text = popup_text.replace('\\r', '\r') + popup_text = popup_text.replace('\\n', '\n').replace('\\r', '\r') tk.messagebox.showinfo( # LANG: Popup window title for list of 'broken' plugins that failed to load @@ -2309,8 +2304,7 @@ sys.path: {sys.path}''' DISABLED='.disabled' ) # And now we do need these to be actual \r\n - popup_text = popup_text.replace('\\n', '\n') - popup_text = popup_text.replace('\\r', '\r') + popup_text = popup_text.replace('\\n', '\n').replace('\\r', '\r') tk.messagebox.showinfo( # LANG: Popup window title for list of 'enabled' plugins that don't work with Python 3.x diff --git a/prefs.py b/prefs.py index 95f29e7f..f694f617 100644 --- a/prefs.py +++ b/prefs.py @@ -829,7 +829,8 @@ class PreferencesDialog(tk.Toplevel): appearance_frame, # LANG: Appearance - Help/hint text for UI scaling selection text=tr.tl('100 means Default{CR}Restart Required for{CR}changes to take effect!') - ).grid(column=3, padx=self.PADX, pady=self.PADY, sticky=tk.E, row=cur_row) + ) # E1111 + self.ui_scaling_defaultis.grid(column=3, padx=self.PADX, pady=self.PADY, sticky=tk.E, row=cur_row) # Transparency slider ttk.Separator(appearance_frame, orient=tk.HORIZONTAL).grid( @@ -1310,10 +1311,10 @@ class PreferencesDialog(tk.Toplevel): self._destroy() # Send to the Post Config if we updated the update branch or need to restart post_flags = { - 'Update': True if self.curr_update_track != self.update_paths.get() else False, + 'Update': self.curr_update_track != self.update_paths.get(), # Just needs bool not true if else false 'Track': self.update_paths.get(), 'Parent': self, - 'Restart_Req': True if self.req_restart else False + 'Restart_Req': self.req_restart # Sipmle Bool Needed } if self.callback: self.callback(**post_flags) From f0d20f653421ce2500afe06509295d4381167715 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 13 Apr 2025 13:51:25 -0400 Subject: [PATCH 28/62] [Minor] Remove Dupe Undock --- plugins/common_coreutils.py | 4 +--- plugins/inara.py | 2 -- plugins/spansh_core.py | 1 - 3 files changed, 1 insertion(+), 6 deletions(-) diff --git a/plugins/common_coreutils.py b/plugins/common_coreutils.py index 615708f2..c65be029 100644 --- a/plugins/common_coreutils.py +++ b/plugins/common_coreutils.py @@ -34,6 +34,7 @@ from companion import CAPIData from l10n import translations as tr logger = get_main_logger() +show_password_var = tk.BooleanVar() # Global Padding Preferences PADX = 10 @@ -185,6 +186,3 @@ def cmdr_data_initial_common(this, data: CAPIData): this.system_name = data['lastSystem']['name'] if not this.station_name and data['commander']['docked']: this.station_name = data['lastStarport']['name'] - - -show_password_var = tk.BooleanVar() diff --git a/plugins/inara.py b/plugins/inara.py index c7426f46..f6a336f9 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -153,8 +153,6 @@ LAST_UPDATE_CONF_KEY = 'inara_last_update' EVENT_COLLECT_TIME = 31 # Minimum time to take collecting events before requesting a send WORKER_WAIT_TIME = 35 # Minimum time for worker to wait between sends -STATION_UNDOCKED: str = '×' # "Station" name to display when not docked = U+00D7 - TARGET_URL = 'https://inara.cz/inapi/v1/' DEBUG = 'inara' in debug_senders diff --git a/plugins/spansh_core.py b/plugins/spansh_core.py index b28556ac..1b7536c5 100644 --- a/plugins/spansh_core.py +++ b/plugins/spansh_core.py @@ -50,7 +50,6 @@ class This: this = This() -STATION_UNDOCKED: str = '×' # "Station" name to display when not docked = U+00D7 def plugin_start3(plugin_dir: str) -> str: From e31de6a9990202c2ae55afec30ee60f969c4e1de Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Mon, 14 Apr 2025 21:33:17 -0400 Subject: [PATCH 29/62] [2406] Update BooleanVar when on CMDLINE --- plugins/common_coreutils.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/plugins/common_coreutils.py b/plugins/common_coreutils.py index c65be029..6b90d4dc 100644 --- a/plugins/common_coreutils.py +++ b/plugins/common_coreutils.py @@ -28,13 +28,15 @@ import base64 import gzip import io import json +import os import myNotebook as nb # noqa: N813 from EDMCLogging import get_main_logger from companion import CAPIData from l10n import translations as tr logger = get_main_logger() -show_password_var = tk.BooleanVar() +if not os.getenv('EDMC_NO_UI'): # Functions using show_password_var MUST have TK set up + show_password_var = tk.BooleanVar() # Global Padding Preferences PADX = 10 From 08bfbe15827d2fccab6f9a16b27d8ee838236c0f Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Mon, 14 Apr 2025 21:33:54 -0400 Subject: [PATCH 30/62] [2406] Refactor Non-Plugin Modules --- EDMC.py | 23 +----------- EDMarketConnector.py | 14 +------ common_utils.py | 61 +++++++++++++++++++++++++++++++ prefs.py | 12 +----- scripts/find_localised_strings.py | 40 +++++++++----------- stats.py | 28 +------------- 6 files changed, 85 insertions(+), 93 deletions(-) create mode 100644 common_utils.py diff --git a/EDMC.py b/EDMC.py index 6b72c7d1..fd241ec2 100755 --- a/EDMC.py +++ b/EDMC.py @@ -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 diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 98496c0a..7c45d4f8 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -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...') diff --git a/common_utils.py b/common_utils.py new file mode 100644 index 00000000..7e3a361e --- /dev/null +++ b/common_utils.py @@ -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)}''' + ) diff --git a/prefs.py b/prefs.py index f694f617..123e82f1 100644 --- a/prefs.py +++ b/prefs.py @@ -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') diff --git a/scripts/find_localised_strings.py b/scripts/find_localised_strings.py index 8187f262..85df27be 100644 --- a/scripts/find_localised_strings.py +++ b/scripts/find_localised_strings.py @@ -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 diff --git a/stats.py b/stats.py index b0ba34b3..4c4b0e3d 100644 --- a/stats.py +++ b/stats.py @@ -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 From a93389c3d4426a6b561c3003f18a13301d22e0d7 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 18 Apr 2025 01:02:28 -0400 Subject: [PATCH 31/62] [Docs] Update PLUGINS.md on how to use common functions --- PLUGINS.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/PLUGINS.md b/PLUGINS.md index da7303f4..a120985e 100644 --- a/PLUGINS.md +++ b/PLUGINS.md @@ -153,6 +153,16 @@ See [#1327 - ModuleNotFound when creating a new plugin.](https://github.com/EDCD for some discussion. +## Common Resources + +Some plugins may wish to use resources available in a different plugin, or use +common assets across plugins. This is possible, however care must be taken to +ensure that the plugins do not attempt to load non-existent data or create +circular imports. + +For an example of how this is done, look at the code in `plugins/common_coreutils.py` +and the usage of these functions in other core plugins. + --- ## Logging From eae04177970f3cc69753e0d01b49b6d0d662facb Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Tue, 22 Apr 2025 22:48:31 -0400 Subject: [PATCH 32/62] [#1346] Option to Disable Systray --- EDMarketConnector.py | 29 +++++++++++++++++++++-------- L10n/en.template | 3 +++ prefs.py | 15 ++++++++++++++- 3 files changed, 38 insertions(+), 9 deletions(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 2397393f..ec4b8cee 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -446,13 +446,20 @@ class AppWindow: self.prefsdialog = None - if sys.platform == 'win32': + if sys.platform == 'win32' and not bool(config.get_int('no_systray')): from simplesystray import SysTrayIcon def open_window(systray: 'SysTrayIcon', *args) -> None: self.w.deiconify() - menu_options = (("Open", None, open_window),) + logfile_loc = pathlib.Path(config.app_dir_path / 'logs') + menu_options = ( + ("Open", None, open_window), + ("Report a Bug", None, self.help_report_a_bug), + ("About EDMC", None, lambda: not self.HelpAbout.showing and self.HelpAbout(self.w)), + ("Open Log Folder", None, lambda: prefs.open_folder(logfile_loc)), + ("Open System Profiler", None, lambda: prefs.help_open_system_profiler(self)), + ) # Method associated with on_quit is called whenever the systray is closing self.systray = SysTrayIcon("EDMarketConnector.ico", applongname, menu_options, on_quit=self.exit_tray) self.systray.start() @@ -616,7 +623,7 @@ class AppWindow: self.help_menu.add_command(command=lambda: not self.HelpAbout.showing and self.HelpAbout(self.w)) logfile_loc = pathlib.Path(config.app_dir_path / 'logs') self.help_menu.add_command(command=lambda: prefs.open_folder(logfile_loc)) # Open Log Folder - self.help_menu.add_command(command=lambda: prefs.help_open_system_profiler(self)) # Open Log Folde + self.help_menu.add_command(command=lambda: prefs.help_open_system_profiler(self)) # Open System Profiler self.menubar.add_cascade(menu=self.help_menu) if sys.platform == 'win32': @@ -1857,10 +1864,14 @@ class AppWindow: def onexit(self, event=None, restart: bool = False) -> None: """Application shutdown procedure.""" if sys.platform == 'win32': - shutdown_thread = threading.Thread( - target=self.systray.shutdown, - daemon=True, - ) + try: + shutdown_thread = threading.Thread( + target=self.systray.shutdown, + daemon=True, + ) + except AttributeError: # No SysTray + shutdown_thread = threading.Thread(daemon=True) + shutdown_thread.start() config.set_shutdown() # Signal we're in shutdown now. @@ -1938,7 +1949,9 @@ class AppWindow: def default_iconify(self, event=None) -> None: """Handle the Windows default theme 'minimise' button.""" # If we're meant to "minimize to system tray" then hide the window so no taskbar icon is seen - if sys.platform == 'win32' and config.get_bool('minimize_system_tray'): + if (sys.platform == 'win32' + and config.get_bool('minimize_system_tray') + and not bool(config.get_int('no_systray'))): # This gets called for more than the root widget, so only react to that if str(event.widget) == '.': self.w.withdraw() diff --git a/L10n/en.template b/L10n/en.template index 6e4d6392..f054b85d 100644 --- a/L10n/en.template +++ b/L10n/en.template @@ -78,6 +78,9 @@ /* EDMarketConnector.py: Label for 'Station' line in main UI; prefs.py: Configuration - Label for selection of 'Station' provider website; prefs.py: Appearance - Example 'Normal' text; stats.py: Status dialog subtitle; In files: EDMarketConnector.py:918; prefs.py:632; prefs.py:770; stats.py:408; */ "Station" = "Station"; +/* prefs.py: Appearance option for Windows "Disable Systray"; */ +"Disable Systray" = "Disable Systray"; + /* EDMarketConnector.py: 'File' menu title on OSX; EDMarketConnector.py: 'File' menu title; EDMarketConnector.py: 'File' menu; In files: EDMarketConnector.py:921; EDMarketConnector.py:939; EDMarketConnector.py:942; EDMarketConnector.py:2264; */ "File" = "File"; diff --git a/prefs.py b/prefs.py index fb2c7747..e8a2a757 100644 --- a/prefs.py +++ b/prefs.py @@ -704,6 +704,7 @@ class PreferencesDialog(tk.Toplevel): self.lang = tk.StringVar(value=self.languages.get(config.get_str('language'), tr.tl('Default'))) self.always_ontop = tk.BooleanVar(value=bool(config.get_int('always_ontop'))) self.minimize_system_tray = tk.BooleanVar(value=config.get_bool('minimize_system_tray')) + self.disable_system_tray = tk.BooleanVar(value=config.get_bool('no_systray')) self.theme = tk.IntVar(value=config.get_int('theme')) self.theme_colors = [config.get_str('dark_text'), config.get_str('dark_highlight')] self.theme_prompts = [ @@ -881,7 +882,7 @@ class PreferencesDialog(tk.Toplevel): columnspan=3, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W, row=row.get() ) # Appearance setting - if sys.platform == 'win32': + if sys.platform == 'win32' and not bool(config.get_int('no_systray')): nb.Checkbutton( appearance_frame, # LANG: Appearance option for Windows "minimize to system tray" @@ -890,6 +891,15 @@ class PreferencesDialog(tk.Toplevel): command=self.themevarchanged ).grid(columnspan=3, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W, row=row.get()) # Appearance setting + if sys.platform == 'win32': + nb.Checkbutton( + appearance_frame, + # LANG: Appearance option for Windows "Disable Systray" + text=tr.tl('Disable Systray'), + variable=self.disable_system_tray, + command=self.themevarchanged, + ).grid(columnspan=3, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W, row=row.get()) # Appearance setting + nb.Label(appearance_frame).grid(sticky=tk.W) # big spacer # LANG: Label for Settings > Appearance tab @@ -1280,6 +1290,9 @@ class PreferencesDialog(tk.Toplevel): config.set('ui_transparency', self.transparency.get()) config.set('always_ontop', self.always_ontop.get()) config.set('minimize_system_tray', self.minimize_system_tray.get()) + if self.disable_system_tray.get() != config.get('no_systray'): + self.req_restart = True + config.set('no_systray', self.disable_system_tray.get()) config.set('theme', self.theme.get()) config.set('dark_text', self.theme_colors[0]) config.set('dark_highlight', self.theme_colors[1]) From e9c4ca6b9d29589196f072371db88e3d7c41db8b Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sat, 26 Apr 2025 11:04:04 -0400 Subject: [PATCH 33/62] [1346] Only Shutdown When Present --- EDMarketConnector.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index ec4b8cee..72973b1a 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -1869,10 +1869,9 @@ class AppWindow: target=self.systray.shutdown, daemon=True, ) + shutdown_thread.start() except AttributeError: # No SysTray - shutdown_thread = threading.Thread(daemon=True) - - shutdown_thread.start() + logger.info("No Systray, No Thread to Shutdown") config.set_shutdown() # Signal we're in shutdown now. From 86d5f6d44add43298e85c524755f4a65927e739e Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sat, 26 Apr 2025 13:32:17 -0400 Subject: [PATCH 34/62] [Fix] Include Plugins dir for Imports --- build.py | 1 + 1 file changed, 1 insertion(+) diff --git a/build.py b/build.py index e17c0979..94585461 100644 --- a/build.py +++ b/build.py @@ -132,6 +132,7 @@ def build() -> None: "multiprocessing", "sqlite3", "util", + "plugins" ], "includes": ["dataclasses", "shutil", "timeout_session", "zipfile"], "excludes": [ From 4427ae6f25423e5230612284533a46bf86143335 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sat, 26 Apr 2025 16:06:01 -0400 Subject: [PATCH 35/62] [#1805] More Handover of Ctypes --- EDMarketConnector.py | 21 ++++++---- hotkey/windows.py | 14 +++---- l10n.py | 43 ++++---------------- prefs.py | 97 +++++++++++++++++++++++--------------------- 4 files changed, 75 insertions(+), 100 deletions(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 72973b1a..ec7821b9 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -268,19 +268,22 @@ if __name__ == '__main__': # noqa: C901 # If *this* instance hasn't locked, then another already has and we # now need to do the edmc:// checks for auth callback if locked != JournalLockResult.LOCKED: - from ctypes import windll, create_unicode_buffer, WINFUNCTYPE + from ctypes import create_unicode_buffer, WINFUNCTYPE from ctypes.wintypes import BOOL, HWND, LPARAM import win32gui import win32api import win32con + import win32process + import pythoncom - GetProcessHandleFromHwnd = windll.oleacc.GetProcessHandleFromHwnd # noqa: N806 - ShowWindowAsync = windll.user32.ShowWindowAsync # noqa: N806 + def get_process_handle_from_hwnd(hwnd): + # Get thread and process IDs + thread_id, process_id = win32process.GetWindowThreadProcessId(hwnd) + # Get the process handle + process_handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, process_id) + return process_handle COINIT_MULTITHREADED = 0 # noqa: N806,F841 - COINIT_APARTMENTTHREADED = 0x2 # noqa: N806 - COINIT_DISABLE_OLE1DDE = 0x4 # noqa: N806 - CoInitializeEx = windll.ole32.CoInitializeEx # noqa: N806 def window_title(h: int) -> str | None: if h: @@ -309,16 +312,16 @@ if __name__ == '__main__': # noqa: C901 if win32gui.GetClassName(window_handle): if cls.value == 'TkTopLevel': if window_title(window_handle) == applongname: - if GetProcessHandleFromHwnd(window_handle): + if get_process_handle_from_hwnd(window_handle): # If GetProcessHandleFromHwnd succeeds then the app is already running as this user if len(sys.argv) > 1 and sys.argv[1].startswith(protocolhandler_redirect): - CoInitializeEx(0, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE) + pythoncom.CoInitializeEx(0) # Wait for it to be responsive to avoid ShellExecute recursing win32gui.ShowWindow(window_handle, win32con.SW_RESTORE) win32api.ShellExecute(0, None, sys.argv[1], None, None, win32con.SW_RESTORE) else: - ShowWindowAsync(window_handle, win32con.SW_RESTORE) + win32gui.ShowWindow(window_handle, win32con.SW_RESTORE) win32gui.SetForegroundWindow(window_handle) return False # Indicate window found, so stop iterating diff --git a/hotkey/windows.py b/hotkey/windows.py index ddccc333..994fe879 100644 --- a/hotkey/windows.py +++ b/hotkey/windows.py @@ -8,7 +8,7 @@ import sys import threading import tkinter as tk import winsound -from ctypes.wintypes import DWORD, LONG, MSG, ULONG, WORD, HWND, BOOL, UINT +from ctypes.wintypes import DWORD, LONG, MSG, ULONG, WORD, UINT import pywintypes import win32api import win32gui @@ -21,10 +21,6 @@ assert sys.platform == 'win32' logger = get_main_logger() -UnregisterHotKey = ctypes.windll.user32.UnregisterHotKey # TODO: Coming Soon -UnregisterHotKey.argtypes = [HWND, ctypes.c_int] -UnregisterHotKey.restype = BOOL - MOD_NOREPEAT = 0x4000 WM_SND_GOOD = win32con.WM_APP + 1 WM_SND_BAD = win32con.WM_APP + 2 @@ -191,7 +187,7 @@ class WindowsHotkeyMgr(AbstractHotkeyMgr): msg = MSG() logger.debug('Entering GetMessage() loop...') - while win32gui.GetMessage(ctypes.byref(msg), None, 0, 0) != 0: + while win32gui.GetMessage(None, 0, 0) != 0: logger.debug('Got message') if msg.message == win32con.WM_HOTKEY: logger.debug('WM_HOTKEY') @@ -206,7 +202,7 @@ class WindowsHotkeyMgr(AbstractHotkeyMgr): else: logger.debug('Passing key on') - UnregisterHotKey(None, 1) + win32gui.UnregisterHotKey(None, 1) SendInput(1, fake, ctypes.sizeof(INPUT)) try: win32gui.RegisterHotKey(None, 1, modifiers | MOD_NOREPEAT, keycode) @@ -228,7 +224,7 @@ class WindowsHotkeyMgr(AbstractHotkeyMgr): win32gui.DispatchMessage(ctypes.byref(msg)) logger.debug('Exited GetMessage() loop.') - UnregisterHotKey(None, 1) + win32gui.UnregisterHotKey(None, 1) self.thread = None # type: ignore logger.debug('Done.') @@ -282,7 +278,7 @@ class WindowsHotkeyMgr(AbstractHotkeyMgr): # See if the keycode is usable and available try: win32gui.RegisterHotKey(None, 2, modifiers | MOD_NOREPEAT, keycode) - UnregisterHotKey(None, 2) + win32gui.UnregisterHotKey(None, 2) return keycode, modifiers except pywintypes.error: winsound.MessageBeep() diff --git a/l10n.py b/l10n.py index 6557169e..8d1f1130 100755 --- a/l10n.py +++ b/l10n.py @@ -18,7 +18,7 @@ import sys import warnings from contextlib import suppress from os import listdir, sep -from typing import TYPE_CHECKING, Iterable, TextIO, cast +from typing import Iterable, TextIO, cast import pathlib from config import config from EDMCLogging import get_main_logger @@ -38,23 +38,7 @@ LOCALISATION_DIR: pathlib.Path = pathlib.Path('L10n') if sys.platform == 'win32': import ctypes - from ctypes.wintypes import BOOL, DWORD, LPCVOID, LPCWSTR, LPWSTR - if TYPE_CHECKING: - import ctypes.windll # type: ignore # Magic to make linters not complain that windll is special - - # https://msdn.microsoft.com/en-us/library/windows/desktop/dd318124%28v=vs.85%29.aspx - MUI_LANGUAGE_ID = 4 - MUI_LANGUAGE_NAME = 8 - GetUserPreferredUILanguages = ctypes.windll.kernel32.GetUserPreferredUILanguages - GetUserPreferredUILanguages.argtypes = [ - DWORD, ctypes.POINTER(ctypes.c_ulong), LPCVOID, ctypes.POINTER(ctypes.c_ulong) - ] - GetUserPreferredUILanguages.restype = BOOL - - LOCALE_NAME_USER_DEFAULT = None - GetNumberFormatEx = ctypes.windll.kernel32.GetNumberFormatEx - GetNumberFormatEx.argtypes = [LPCWSTR, DWORD, LPCWSTR, LPCVOID, LPWSTR, ctypes.c_int] - GetNumberFormatEx.restype = ctypes.c_int + import win32api class Translations: @@ -332,28 +316,17 @@ class _Locale: if sys.platform != 'win32': # POSIX lang = locale.getlocale()[0] - languages = [lang.replace('_', '-')] if lang else [] - else: - num = ctypes.c_ulong() - size = ctypes.c_ulong(0) - languages = [] - if GetUserPreferredUILanguages( - MUI_LANGUAGE_NAME, ctypes.byref(num), None, ctypes.byref(size) - ) and size.value: - buf = ctypes.create_unicode_buffer(size.value) - - if GetUserPreferredUILanguages( - MUI_LANGUAGE_NAME, ctypes.byref(num), ctypes.byref(buf), ctypes.byref(size) - ): - languages = self.wszarray_to_list(buf) - + current_locale = win32api.GetUserDefaultLangID() + lang = locale.windows_locale[current_locale] + print(lang) # HACK: | 2021-12-11: OneSky calls "Chinese Simplified" "zh-Hans" # in the name of the file, but that will be zh-CN in terms of # locale. So map zh-CN -> zh-Hans + languages = [lang.replace('_', '-')] if lang else [] languages = ['zh-Hans' if lang == 'zh-CN' else lang for lang in languages] - - return languages + print(languages) + return ['en-US'] # singletons diff --git a/prefs.py b/prefs.py index e8a2a757..a47f6d60 100644 --- a/prefs.py +++ b/prefs.py @@ -4,7 +4,7 @@ from __future__ import annotations import contextlib import logging -from os.path import expandvars, join, normpath +from os.path import join, normpath from pathlib import Path import subprocess import sys @@ -185,10 +185,10 @@ class AutoInc(contextlib.AbstractContextManager): if sys.platform == 'win32': - import ctypes import winreg - from ctypes.wintypes import LPCWSTR, LPWSTR, MAX_PATH, POINT, RECT, SIZE, UINT, BOOL import win32api + from win32com.shell import shell, shellcon + import pythoncom is_wine = False try: WINE_REGISTRY_KEY = r'HKEY_LOCAL_MACHINE\Software\Wine' @@ -199,30 +199,51 @@ if sys.platform == 'win32': except OSError: # Assumed to be 'path not found', i.e. not-wine pass - CalculatePopupWindowPosition = None - if not is_wine: - try: - CalculatePopupWindowPosition = ctypes.windll.user32.CalculatePopupWindowPosition - CalculatePopupWindowPosition.argtypes = [POINT, SIZE, UINT, RECT, RECT] - CalculatePopupWindowPosition.restype = BOOL + def get_localized_path(path: str, config_home: str) -> str: + """ + Get the localized display path for a Windows file system path. + Shows only drive letters without labels. - except AttributeError as e: - logger.error( - 'win32 and not is_wine, but ctypes.windll.user32.CalculatePopupWindowPosition invalid', - exc_info=e - ) + Args: + path: The path to localize + config_home: The home directory path + Returns: + Localized path as string + """ + if not path: + return path - else: - CalculatePopupWindowPosition.argtypes = [ - ctypes.POINTER(POINT), - ctypes.POINTER(SIZE), - UINT, - ctypes.POINTER(RECT), - ctypes.POINTER(RECT) - ] + # Determine start index based on if path starts with home directory + start_idx = len(config_home.split('\\')) if path.lower().startswith(config_home.lower()) else 0 - SHGetLocalizedName = ctypes.windll.shell32.SHGetLocalizedName - SHGetLocalizedName.argtypes = [LPCWSTR, LPWSTR, UINT, ctypes.POINTER(ctypes.c_int)] + # Split path into components + components = normpath(path).split('\\') + display_components = [] + + # Process each path component + for i in range(start_idx, len(components)): + current_path = '\\'.join(components[:i + 1]) + + # Handle drive letter specially + if i == 0 and ':' in components[i]: + display_components.append(components[i]) + continue + + try: + # Get localized name info using shell API + pidl = shell.SHParseDisplayName(current_path, 0)[0] + name_info = shell.SHGetNameFromIDList(pidl, shellcon.SIGDN_NORMALDISPLAY) + + if name_info: + display_components.append(name_info) + else: + display_components.append(components[i]) + + except (pythoncom.com_error, win32api.error): + # Fall back to original component name if localization fails + display_components.append(components[i]) + + return '\\'.join(display_components) class PreferencesDialog(tk.Toplevel): @@ -1099,27 +1120,9 @@ class PreferencesDialog(tk.Toplevel): entryfield['state'] = tk.NORMAL # must be writable to update entryfield.delete(0, tk.END) if sys.platform == 'win32': - start = len(config.home.split('\\')) if pathvar.get().lower().startswith(config.home.lower()) else 0 - display = [] - components = normpath(pathvar.get()).split('\\') - buf = ctypes.create_unicode_buffer(MAX_PATH) - pidsRes = ctypes.c_int() # noqa: N806 # Windows convention - for i in range(start, len(components)): - try: - if (not SHGetLocalizedName('\\'.join(components[:i+1]), buf, MAX_PATH, ctypes.byref(pidsRes)) and - win32api.LoadString(ctypes.WinDLL(expandvars(buf.value))._handle, - pidsRes.value, buf, MAX_PATH)): - display.append(buf.value) - - else: - display.append(components[i]) - - except Exception: - display.append(components[i]) - - entryfield.insert(0, '\\'.join(display)) - - # None if path doesn't exist + localized_path = get_localized_path(pathvar.get(), config.home) + entryfield.insert(0, localized_path) + # None if path doesn't exist else: if pathvar.get().startswith(config.home): entryfield.insert(0, '~' + pathvar.get()[len(config.home):]) @@ -1290,14 +1293,14 @@ class PreferencesDialog(tk.Toplevel): config.set('ui_transparency', self.transparency.get()) config.set('always_ontop', self.always_ontop.get()) config.set('minimize_system_tray', self.minimize_system_tray.get()) - if self.disable_system_tray.get() != config.get('no_systray'): + if self.disable_system_tray.get() != config.get_int('no_systray'): self.req_restart = True config.set('no_systray', self.disable_system_tray.get()) config.set('theme', self.theme.get()) config.set('dark_text', self.theme_colors[0]) config.set('dark_highlight', self.theme_colors[1]) theme.apply(self.parent) - if self.plugdir.get() != config.get('plugin_dir'): + if self.plugdir.get() != config.get_str('plugin_dir'): config.set( 'plugin_dir', join(config.home_path, self.plugdir.get()[2:]) if self.plugdir.get().startswith( From a159a980f7f2c668d75efe8132766de3d1bd8944 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 27 Apr 2025 10:22:06 -0400 Subject: [PATCH 36/62] [1805] Redo Hotkey File --- hotkey/windows.py | 197 ++++++++++++++++------------------------------ 1 file changed, 67 insertions(+), 130 deletions(-) diff --git a/hotkey/windows.py b/hotkey/windows.py index 994fe879..46df6dd7 100644 --- a/hotkey/windows.py +++ b/hotkey/windows.py @@ -2,17 +2,15 @@ from __future__ import annotations import atexit -import ctypes import pathlib import sys import threading import tkinter as tk import winsound -from ctypes.wintypes import DWORD, LONG, MSG, ULONG, WORD, UINT -import pywintypes import win32api -import win32gui import win32con +import win32gui +import pywintypes from config import config from EDMCLogging import get_main_logger from hotkey import AbstractHotkeyMgr @@ -21,18 +19,14 @@ assert sys.platform == 'win32' logger = get_main_logger() +# Constants MOD_NOREPEAT = 0x4000 WM_SND_GOOD = win32con.WM_APP + 1 WM_SND_BAD = win32con.WM_APP + 2 VK_OEM_MINUS = 0xbd # VirtualKey mapping values -# -MAPVK_VK_TO_VSC = 0 -MAPVK_VSC_TO_VK = 1 MAPVK_VK_TO_CHAR = 2 -MAPVK_VSC_TO_VK_EX = 3 -MAPVK_VK_TO_VSC_EX = 4 def window_title(h) -> str: @@ -47,69 +41,6 @@ def window_title(h) -> str: return '' -class MOUSEINPUT(ctypes.Structure): - """Mouse Input structure.""" - - _fields_ = [ - ('dx', LONG), - ('dy', LONG), - ('mouseData', DWORD), - ('dwFlags', DWORD), - ('time', DWORD), - ('dwExtraInfo', ctypes.POINTER(ULONG)) - ] - - -class KEYBDINPUT(ctypes.Structure): - """Keyboard Input structure.""" - - _fields_ = [ - ('wVk', WORD), - ('wScan', WORD), - ('dwFlags', DWORD), - ('time', DWORD), - ('dwExtraInfo', ctypes.POINTER(ULONG)) - ] - - -class HARDWAREINPUT(ctypes.Structure): - """Hardware Input structure.""" - - _fields_ = [ - ('uMsg', DWORD), - ('wParamL', WORD), - ('wParamH', WORD) - ] - - -class INPUTUNION(ctypes.Union): - """Input union.""" - - _fields_ = [ - ('mi', MOUSEINPUT), - ('ki', KEYBDINPUT), - ('hi', HARDWAREINPUT) - ] - - -class INPUT(ctypes.Structure): - """Input structure.""" - - _fields_ = [ - ('type', DWORD), - ('union', INPUTUNION) - ] - - -SendInput = ctypes.windll.user32.SendInput -SendInput.argtypes = [ctypes.c_uint, ctypes.POINTER(INPUT), ctypes.c_int] -SendInput.restype = UINT - -INPUT_MOUSE = 0 -INPUT_KEYBOARD = 1 -INPUT_HARDWARE = 2 - - class WindowsHotkeyMgr(AbstractHotkeyMgr): """Hot key management.""" @@ -158,7 +89,6 @@ class WindowsHotkeyMgr(AbstractHotkeyMgr): def unregister(self) -> None: """Unregister the hotkey handling.""" thread = self.thread - if thread: logger.debug('Thread is/was running') self.thread = None # type: ignore @@ -169,13 +99,11 @@ class WindowsHotkeyMgr(AbstractHotkeyMgr): else: logger.debug('No thread') - logger.debug('Done.') def worker(self, keycode, modifiers) -> None: # noqa: CCR001 """Handle hotkeys.""" logger.debug('Begin...') - # Hotkey must be registered by the thread that handles it try: win32gui.RegisterHotKey(None, 1, modifiers | MOD_NOREPEAT, keycode) except pywintypes.error: @@ -183,45 +111,63 @@ class WindowsHotkeyMgr(AbstractHotkeyMgr): self.thread = None # type: ignore return - fake = INPUT(INPUT_KEYBOARD, INPUTUNION(ki=KEYBDINPUT(keycode, keycode, 0, 0, None))) - - msg = MSG() logger.debug('Entering GetMessage() loop...') - while win32gui.GetMessage(None, 0, 0) != 0: - logger.debug('Got message') - if msg.message == win32con.WM_HOTKEY: - logger.debug('WM_HOTKEY') + while True: + try: + result = win32gui.GetMessage(None, 0, 0) + if result[0] == 0: # WM_QUIT + break - if ( - config.get_int('hotkey_always') - or window_title(win32gui.GetForegroundWindow()).startswith('Elite - Dangerous') - ): - if not config.shutting_down: - logger.debug('Sending event <>') - self.root.event_generate('<>', when="tail") + msg_hwnd, msg_id, wparam, lparam, msg_time, msg_point = result[1] + + if msg_id == win32con.WM_HOTKEY: + logger.debug('WM_HOTKEY') + if (config.get_int('hotkey_always') or + window_title(win32gui.GetForegroundWindow()).startswith('Elite - Dangerous')): + if not config.shutting_down: + logger.debug('Sending event <>') + self.root.event_generate('<>', when="tail") + else: + logger.debug('Passing key on') + win32gui.UnregisterHotKey(None, 1) + + # Simulate key press + win32api.keybd_event( + keycode, + win32api.MapVirtualKey(keycode, 0), + 0, + 0 + ) + # Simulate key release + win32api.keybd_event( + keycode, + win32api.MapVirtualKey(keycode, 0), + win32con.KEYEVENTF_KEYUP, + 0 + ) + + try: + win32gui.RegisterHotKey(None, 1, modifiers | MOD_NOREPEAT, keycode) + except pywintypes.error: + logger.exception("Failed to re-register hotkey") + break + + elif msg_id == WM_SND_GOOD: + logger.debug('WM_SND_GOOD') + winsound.PlaySound(self.snd_good, winsound.SND_MEMORY) + + elif msg_id == WM_SND_BAD: + logger.debug('WM_SND_BAD') + winsound.PlaySound(self.snd_bad, winsound.SND_MEMORY) else: - logger.debug('Passing key on') - win32gui.UnregisterHotKey(None, 1) - SendInput(1, fake, ctypes.sizeof(INPUT)) - try: - win32gui.RegisterHotKey(None, 1, modifiers | MOD_NOREPEAT, keycode) - except pywintypes.error: - logger.exception("We aren't registered for this ?") - break + # Use win32gui for message processing + win32gui.TranslateMessage(result[1]) + win32gui.DispatchMessage(result[1]) - elif msg.message == WM_SND_GOOD: - logger.debug('WM_SND_GOOD') - winsound.PlaySound(self.snd_good, winsound.SND_MEMORY) # synchronous - - elif msg.message == WM_SND_BAD: - logger.debug('WM_SND_BAD') - winsound.PlaySound(self.snd_bad, winsound.SND_MEMORY) # synchronous - - else: - logger.debug('Something else') - win32gui.TranslateMessage(ctypes.byref(msg)) - win32gui.DispatchMessage(ctypes.byref(msg)) + except Exception as e: + logger.exception(f"Error in message loop: {e}") + break logger.debug('Exited GetMessage() loop.') win32gui.UnregisterHotKey(None, 1) @@ -254,25 +200,24 @@ class WindowsHotkeyMgr(AbstractHotkeyMgr): | ((win32api.GetKeyState(win32con.VK_RWIN) & 0x8000) and win32con.MOD_WIN) keycode = event.keycode - if keycode in (win32con.VK_SHIFT, win32con.VK_CONTROL, win32con.VK_MENU, win32con.VK_LWIN, win32con.VK_RWIN): + if keycode in (win32con.VK_SHIFT, win32con.VK_CONTROL, win32con.VK_MENU, + win32con.VK_LWIN, win32con.VK_RWIN): return 0, modifiers if not modifiers: if keycode == win32con.VK_ESCAPE: # Esc = retain previous return False - if keycode in (win32con.VK_BACK, win32con.VK_DELETE, - win32con.VK_CLEAR, win32con.VK_OEM_CLEAR): # BkSp, Del, Clear = clear hotkey + if (keycode in (win32con.VK_BACK, win32con.VK_DELETE, win32con.VK_CLEAR, win32con.VK_OEM_CLEAR) or + keycode in (win32con.VK_RETURN, win32con.VK_SPACE, VK_OEM_MINUS) or + ord('A') <= keycode <= ord( + 'Z')): # BkSp, Del, Clear = clear hotkey, or don't allow keys needed for typing + if keycode not in (win32con.VK_BACK, win32con.VK_DELETE, win32con.VK_CLEAR, win32con.VK_OEM_CLEAR): + winsound.MessageBeep() # Only beep for typing keys, not for clear hotkey return None - if ( - keycode in (win32con.VK_RETURN, win32con.VK_SPACE, VK_OEM_MINUS) or ord('A') <= keycode <= ord('Z') - ): # don't allow keys needed for typing in System Map - winsound.MessageBeep() - return None - - if (keycode in (win32con.VK_NUMLOCK, win32con.VK_SCROLL, win32con.VK_PROCESSKEY) - or win32con.VK_CAPITAL <= keycode <= win32con.VK_MODECHANGE): # ignore unmodified mode switch keys + if (keycode in (win32con.VK_NUMLOCK, win32con.VK_SCROLL, win32con.VK_PROCESSKEY) or + win32con.VK_CAPITAL <= keycode <= win32con.VK_MODECHANGE): # ignore unmodified mode switch keys return 0, modifiers # See if the keycode is usable and available @@ -295,13 +240,10 @@ class WindowsHotkeyMgr(AbstractHotkeyMgr): text = '' if modifiers & win32con.MOD_WIN: text += '❖+' - if modifiers & win32con.MOD_CONTROL: text += 'Ctrl+' - if modifiers & win32con.MOD_ALT: text += 'Alt+' - if modifiers & win32con.MOD_SHIFT: text += '⇧+' @@ -310,21 +252,16 @@ class WindowsHotkeyMgr(AbstractHotkeyMgr): if not keycode: pass - elif win32con.VK_F1 <= keycode <= win32con.VK_F24: text += f'F{keycode + 1 - win32con.VK_F1}' - - elif keycode in WindowsHotkeyMgr.DISPLAY: # specials - text += WindowsHotkeyMgr.DISPLAY[keycode] - + elif keycode in self.DISPLAY: + text += self.DISPLAY[keycode] else: c = win32api.MapVirtualKey(keycode, MAPVK_VK_TO_CHAR) if not c: # oops not printable text += '⁈' - elif c < 0x20: # control keys text += chr(c + 0x40) - else: text += chr(c).upper() From e78154e2ff243bdf50d9a51de17fb74b1fb1e9ab Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 27 Apr 2025 10:29:33 -0400 Subject: [PATCH 37/62] [1805] Update common_utils ctypes --- common_utils.py | 40 +++++++++++++++++++--------------------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/common_utils.py b/common_utils.py index 7e3a361e..a6f78356 100644 --- a/common_utils.py +++ b/common_utils.py @@ -18,17 +18,8 @@ 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 + import win32api + import win32con def ensure_on_screen(self, parent: tk.Tk): @@ -38,16 +29,23 @@ def ensure_on_screen(self, parent: tk.Tk): :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}") + if sys.platform != 'win32': + return + try: + # Get monitor info for the monitor containing the parent window + monitor = win32api.MonitorFromWindow(parent.winfo_id(), win32con.MONITOR_DEFAULTTONEAREST) + monitor_info = win32api.GetMonitorInfo(monitor) + work_area = monitor_info['Work'] # Gets the working area (excludes taskbar) + + # Calculate optimal position + x = max(work_area[0], min(parent.winfo_rootx(), work_area[2] - self.winfo_width())) + y = max(work_area[1], min(parent.winfo_rooty(), work_area[3] - self.winfo_height())) + + # Update window position + self.geometry(f"+{x}+{y}") + + except Exception as e: + logger.debug(f"Failed to ensure window is on screen: {e}") def log_locale(prefix: str) -> None: From c2e685f561793fe060eb54ee687da382f8919cf7 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 27 Apr 2025 10:37:27 -0400 Subject: [PATCH 38/62] [1805] Remove Unused Function --- l10n.py | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/l10n.py b/l10n.py index 8d1f1130..e1efb70a 100755 --- a/l10n.py +++ b/l10n.py @@ -37,7 +37,6 @@ LANGUAGE_ID = '!Language' LOCALISATION_DIR: pathlib.Path = pathlib.Path('L10n') if sys.platform == 'win32': - import ctypes import win32api @@ -165,14 +164,13 @@ class Translations: if lang: contents: dict[str, str] = self.contents(lang=lang, plugin_path=plugin_path) - if not contents or type(contents) is not dict: + if not contents or not isinstance(contents, dict): logger.debug(f'Failure loading translations for overridden language {lang!r}') return self.translate(x) - elif x not in contents.keys(): + if x not in contents: logger.debug(f'Missing translation: {x!r} for overridden language {lang!r}') return self.translate(x) - else: - return contents.get(x) or self.translate(x) + return contents.get(x) or self.translate(x) if plugin_name: if self.translations[None] and plugin_name not in self.translations: @@ -290,16 +288,6 @@ class _Locale: return None - def wszarray_to_list(self, array): - offset = 0 - while offset < len(array): - sz = ctypes.wstring_at(ctypes.addressof(array) + offset * 2) # type: ignore - if sz: - yield sz - offset += len(sz) + 1 - else: - break - def preferred_languages(self) -> Iterable[str]: """ Return a list of preferred language codes. From 20b39e3afcaba2a3c6b4301d03585f4d86f86a35 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 27 Apr 2025 11:20:37 -0400 Subject: [PATCH 39/62] [1805] Remove windll call --- protocol.py | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/protocol.py b/protocol.py index 01be09de..d89980fd 100644 --- a/protocol.py +++ b/protocol.py @@ -12,7 +12,6 @@ import sys import threading from urllib import parse from typing import TYPE_CHECKING, Type - from config import config from constants import appname, protocolhandler_redirect from EDMCLogging import get_main_logger @@ -25,13 +24,7 @@ logger = get_main_logger() is_wine = False if sys.platform == 'win32': - from ctypes import windll # type: ignore - - try: - if windll.ntdll.wine_get_version: - is_wine = True - except Exception: - pass + is_wine = bool(os.getenv('WINEPREFIX')) class GenericProtocolHandler: From 272a0c6cb35b9aa4f56b179b901ed59b1cfd2975 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 27 Apr 2025 12:40:12 -0400 Subject: [PATCH 40/62] [1805] Update Some Protocol.py ctypes --- protocol.py | 38 +++++++++++++++++--------------------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/protocol.py b/protocol.py index d89980fd..09ad4584 100644 --- a/protocol.py +++ b/protocol.py @@ -66,10 +66,12 @@ if (config.auth_force_edmc_protocol # noqa: C901 windll, POINTER, WINFUNCTYPE, Structure, byref, c_long, c_void_p, create_unicode_buffer, wstring_at ) from ctypes.wintypes import ( - ATOM, BOOL, DWORD, HBRUSH, HGLOBAL, HICON, HINSTANCE, HMENU, HWND, INT, LPARAM, LPCWSTR, LPMSG, LPVOID, LPWSTR, + ATOM, BOOL, HBRUSH, HGLOBAL, HICON, HINSTANCE, HWND, INT, LPARAM, LPCWSTR, LPMSG, LPVOID, LPWSTR, MSG, UINT, WPARAM ) import win32gui + import win32api + import win32con class WNDCLASS(Structure): """ @@ -94,15 +96,9 @@ if (config.auth_force_edmc_protocol # noqa: C901 CW_USEDEFAULT = 0x80000000 - CreateWindowExW = windll.user32.CreateWindowExW - CreateWindowExW.argtypes = [DWORD, LPCWSTR, LPCWSTR, DWORD, INT, INT, INT, INT, HWND, HMENU, HINSTANCE, LPVOID] - CreateWindowExW.restype = HWND RegisterClassW = windll.user32.RegisterClassW RegisterClassW.argtypes = [POINTER(WNDCLASS)] - GetParent = windll.user32.GetParent - SetForegroundWindow = windll.user32.SetForegroundWindow - # # NB: Despite 'BOOL' return type, it *can* be >0, 0 or -1, so is actually # c_long @@ -112,7 +108,6 @@ if (config.auth_force_edmc_protocol # noqa: C901 TranslateMessage = windll.user32.TranslateMessage DispatchMessageW = windll.user32.DispatchMessageW - PostThreadMessageW = windll.user32.PostThreadMessageW SendMessageW = windll.user32.SendMessageW SendMessageW.argtypes = [HWND, UINT, WPARAM, LPARAM] PostMessageW = windll.user32.PostMessageW @@ -215,7 +210,7 @@ if (config.auth_force_edmc_protocol # noqa: C901 thread = self.thread if thread: self.thread = None - PostThreadMessageW(thread.ident, WM_QUIT, 0, 0) + win32gui.PostThreadMessage(thread.ident, WM_QUIT, 0, 0) thread.join() # Wait for it to quit def worker(self) -> None: @@ -225,7 +220,7 @@ if (config.auth_force_edmc_protocol # noqa: C901 wndclass.lpfnWndProc = WndProc wndclass.cbClsExtra = 0 wndclass.cbWndExtra = 0 - wndclass.hInstance = windll.kernel32.GetModuleHandleW(0) + wndclass.hInstance = win32api.GetModuleHandle(None) wndclass.hIcon = None wndclass.hCursor = None wndclass.hbrBackground = None @@ -237,16 +232,17 @@ if (config.auth_force_edmc_protocol # noqa: C901 return # https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw - hwnd = CreateWindowExW( + hwnd = win32gui.CreateWindowEx( 0, # dwExStyle - wndclass.lpszClassName, # lpClassName - "DDE Server", # lpWindowName - 0, # dwStyle - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, # X, Y, nWidth, nHeight - self.master.winfo_id(), # hWndParent # Don't use HWND_MESSAGE since the window won't get DDE broadcasts - None, # hMenu - wndclass.hInstance, # hInstance - None # lpParam + 'DDEServer', # lpClassName (use string directly as win32gui expects it) + "DDE Server", # lpWindowName + 0, # dwStyle + win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, + win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, # X, Y, nWidth, nHeight + self.master.winfo_id(), # hWndParent + 0, # hMenu (use 0 instead of None for win32gui) + wndclass.hInstance, # hInstance + None # lpParam ) msg = MSG() @@ -277,8 +273,8 @@ if (config.auth_force_edmc_protocol # noqa: C901 logger.debug(f'Message starts with {self.redirect}') self.event(url) - SetForegroundWindow(GetParent(self.master.winfo_id())) # raise app window # Send back a WM_DDE_ACK. this is _required_ with WM_DDE_EXECUTE + win32gui.SetForegroundWindow(win32gui.GetParent(self.master.winfo_id())) PostMessageW(msg.wParam, WM_DDE_ACK, hwnd, PackDDElParam(WM_DDE_ACK, 0x80, msg.lParam)) else: @@ -286,7 +282,7 @@ if (config.auth_force_edmc_protocol # noqa: C901 PostMessageW(msg.wParam, WM_DDE_ACK, hwnd, PackDDElParam(WM_DDE_ACK, 0, msg.lParam)) elif msg.message == WM_DDE_TERMINATE: - PostMessageW(msg.wParam, WM_DDE_TERMINATE, hwnd, 0) + win32gui.PostMessage(msg.wParam, WM_DDE_TERMINATE, hwnd, 0) else: TranslateMessage(byref(msg)) # "Translates virtual key messages into character messages" ??? From e8497c22e60d567d26c128f0c62c30fdb4e3f6b1 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 27 Apr 2025 13:09:23 -0400 Subject: [PATCH 41/62] [1805] Replace Unicode Buffer --- EDMarketConnector.py | 39 ++++++++++++++++++++------------------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index ec7821b9..1b45225a 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -268,7 +268,7 @@ if __name__ == '__main__': # noqa: C901 # If *this* instance hasn't locked, then another already has and we # now need to do the edmc:// checks for auth callback if locked != JournalLockResult.LOCKED: - from ctypes import create_unicode_buffer, WINFUNCTYPE + from ctypes import WINFUNCTYPE from ctypes.wintypes import BOOL, HWND, LPARAM import win32gui import win32api @@ -277,19 +277,27 @@ if __name__ == '__main__': # noqa: C901 import pythoncom def get_process_handle_from_hwnd(hwnd): - # Get thread and process IDs - thread_id, process_id = win32process.GetWindowThreadProcessId(hwnd) + try: + # Get thread and process IDs + _, process_id = win32process.GetWindowThreadProcessId(hwnd) # Get the process handle - process_handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, process_id) - return process_handle + return win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, process_id) + except Exception: + return None - COINIT_MULTITHREADED = 0 # noqa: N806,F841 + def window_title(hwnd: int) -> str | None: + try: + return win32gui.GetWindowText(hwnd) if hwnd else None + except Exception: + return None - def window_title(h: int) -> str | None: - if h: - return win32gui.GetWindowText(h) - return None + def get_window_class(hwnd: int) -> str: + try: + return win32gui.GetClassName(hwnd) + except Exception: + return "" + # We still need WINFUNCTYPE for the callback as win32gui doesn't provide an alternative @WINFUNCTYPE(BOOL, HWND, LPARAM) def enumwindowsproc(window_handle, l_param): # noqa: CCR001 """ @@ -306,11 +314,8 @@ if __name__ == '__main__': # noqa: C901 :param l_param: The second parameter to the EnumWindows() call. :return: False if we found a match, else True to continue iteration """ - # class name limited to 256 - https://msdn.microsoft.com/en-us/library/windows/desktop/ms633576 - cls = create_unicode_buffer(257) - # This conditional is exploded to make debugging slightly easier - if win32gui.GetClassName(window_handle): - if cls.value == 'TkTopLevel': + if window_class := get_window_class(window_handle): + if window_class == 'TkTopLevel': if window_title(window_handle) == applongname: if get_process_handle_from_hwnd(window_handle): # If GetProcessHandleFromHwnd succeeds then the app is already running as this user @@ -319,16 +324,12 @@ if __name__ == '__main__': # noqa: C901 # Wait for it to be responsive to avoid ShellExecute recursing win32gui.ShowWindow(window_handle, win32con.SW_RESTORE) win32api.ShellExecute(0, None, sys.argv[1], None, None, win32con.SW_RESTORE) - else: win32gui.ShowWindow(window_handle, win32con.SW_RESTORE) win32gui.SetForegroundWindow(window_handle) - return False # Indicate window found, so stop iterating - # Indicate that EnumWindows() needs to continue iterating return True # Do not remove, else this function as a callback breaks - # This performs the edmc://auth check and forward # EnumWindows() will iterate through all open windows, calling # enumwindwsproc() on each. When an invocation returns False it From 22aa4adc6ea23849a9223b0dd2d893fa4e62ad62 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 27 Apr 2025 13:21:00 -0400 Subject: [PATCH 42/62] [Minor] Remove Debug Print Statements --- l10n.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/l10n.py b/l10n.py index e1efb70a..e3403a06 100755 --- a/l10n.py +++ b/l10n.py @@ -307,14 +307,12 @@ class _Locale: else: current_locale = win32api.GetUserDefaultLangID() lang = locale.windows_locale[current_locale] - print(lang) # HACK: | 2021-12-11: OneSky calls "Chinese Simplified" "zh-Hans" # in the name of the file, but that will be zh-CN in terms of # locale. So map zh-CN -> zh-Hans languages = [lang.replace('_', '-')] if lang else [] languages = ['zh-Hans' if lang == 'zh-CN' else lang for lang in languages] - print(languages) - return ['en-US'] + return languages # singletons From bc098090e60570099dbdf8f4e9add8f6a4f37b2e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 27 Apr 2025 17:32:06 +0000 Subject: [PATCH 43/62] Bump pillow from 11.1.0 to 11.2.1 Bumps [pillow](https://github.com/python-pillow/Pillow) from 11.1.0 to 11.2.1. - [Release notes](https://github.com/python-pillow/Pillow/releases) - [Changelog](https://github.com/python-pillow/Pillow/blob/main/CHANGES.rst) - [Commits](https://github.com/python-pillow/Pillow/compare/11.1.0...11.2.1) --- updated-dependencies: - dependency-name: pillow dependency-version: 11.2.1 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 430617c2..dc8508da 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,5 @@ requests==2.32.3 -pillow==11.1.0 +pillow==11.2.1 watchdog==6.0.0 simplesystray==0.1.0; sys_platform == 'win32' semantic-version==2.10.0 From 3b08d7e078680823aa9f810bf55e8b02c70c0fd4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 27 Apr 2025 17:32:13 +0000 Subject: [PATCH 44/62] Bump coverage[toml] from 7.6.1 to 7.8.0 Bumps [coverage[toml]](https://github.com/nedbat/coveragepy) from 7.6.1 to 7.8.0. - [Release notes](https://github.com/nedbat/coveragepy/releases) - [Changelog](https://github.com/nedbat/coveragepy/blob/master/CHANGES.rst) - [Commits](https://github.com/nedbat/coveragepy/compare/7.6.1...7.8.0) --- updated-dependencies: - dependency-name: coverage[toml] dependency-version: 7.8.0 dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index a36ee506..e5cdd295 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -36,7 +36,7 @@ py2exe==0.13.0.2; sys_platform == 'win32' # Testing pytest==8.3.5 pytest-cov==6.1.0 # Pytest code coverage support -coverage[toml]==7.6.1 # pytest-cov dep. This is here to ensure that it includes TOML support for pyproject.toml configs +coverage[toml]==7.8.0 # pytest-cov dep. This is here to ensure that it includes TOML support for pyproject.toml configs coverage-conditional-plugin==0.9.0 From cb32b44f682e47ede833e124c7d8f762063c3deb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 27 Apr 2025 17:32:21 +0000 Subject: [PATCH 45/62] Bump pre-commit from 4.1.0 to 4.2.0 Bumps [pre-commit](https://github.com/pre-commit/pre-commit) from 4.1.0 to 4.2.0. - [Release notes](https://github.com/pre-commit/pre-commit/releases) - [Changelog](https://github.com/pre-commit/pre-commit/blob/main/CHANGELOG.md) - [Commits](https://github.com/pre-commit/pre-commit/compare/v4.1.0...v4.2.0) --- updated-dependencies: - dependency-name: pre-commit dependency-version: 4.2.0 dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index a36ee506..ab017886 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -24,7 +24,7 @@ types-setuptools==78.1.0.20250329 autopep8==2.3.2 # Git pre-commit checking -pre-commit==4.1.0 +pre-commit==4.2.0 # HTML changelogs mistune==3.1.1 From 55843cc00797fb21f452995f57710f968524a0e7 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 27 Apr 2025 13:38:56 -0400 Subject: [PATCH 46/62] [Minor] Update Safety --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index a36ee506..f2193d8b 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -16,7 +16,7 @@ flake8-use-fstring==1.4 mypy==1.15.0 pep8-naming==0.14.1 -safety==3.3.1 +safety==3.4.0 types-requests==2.32.0.20250328 types-setuptools==78.1.0.20250329 From 1c4960b0d284e88bbec270c8e306077dd504c616 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 27 Apr 2025 17:40:20 +0000 Subject: [PATCH 47/62] Bump flake8 from 7.1.2 to 7.2.0 Bumps [flake8](https://github.com/pycqa/flake8) from 7.1.2 to 7.2.0. - [Commits](https://github.com/pycqa/flake8/compare/7.1.2...7.2.0) --- updated-dependencies: - dependency-name: flake8 dependency-version: 7.2.0 dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 0901f71a..4256682c 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -4,7 +4,7 @@ setuptools==75.8.0 # Static analysis tools -flake8==7.1.2 +flake8==7.2.0 flake8-annotations-coverage==0.0.6 flake8-cognitive-complexity==0.1.0 flake8-comprehensions==3.16.0 From 29813a6f822af57db770c5a42a636b849ed10353 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 27 Apr 2025 14:12:00 -0400 Subject: [PATCH 48/62] [Minor] Update WinSparkle Version --- .github/workflows/windows-build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/windows-build.yml b/.github/workflows/windows-build.yml index 6e681f54..a44a20cd 100644 --- a/.github/workflows/windows-build.yml +++ b/.github/workflows/windows-build.yml @@ -113,9 +113,9 @@ jobs: - name: Download winsparkle run: | - Invoke-Webrequest -UseBasicParsing https://github.com/vslavik/winsparkle/releases/download/v0.8.3/WinSparkle-0.8.3.zip -OutFile out.zip + Invoke-Webrequest -UseBasicParsing https://github.com/vslavik/winsparkle/releases/download/v0.9.0/WinSparkle-0.9.0.zip -OutFile out.zip Expand-Archive out.zip - Move-Item 'out\WinSparkle-0.8.3\Release\*' '.\' + Move-Item 'out\WinSparkle-0.9.0\Release\*' '.\' - name: Build EDMC run: | From 9d6d9d145be10a66e204dcc7e874ba472d99e00c Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 27 Apr 2025 14:55:49 -0400 Subject: [PATCH 49/62] [Minor] Update Changelog-In-Progress --- ChangeLog.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ prefs.py | 2 +- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/ChangeLog.md b/ChangeLog.md index 3e46a5d8..165b920e 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -6,6 +6,50 @@ This is the master changelog for Elite Dangerous Market Connector. Entries are in the source (not distributed with the Windows installer) for the currently used version. --- +Pre-Release 5.13.0-alpha0 +=== +This is the Changelog-In-Progress for the next release of EDMarketConnector. This is subject to change. + +This release contains a significant refactoring away from ctypes code for interating with the Windows API, +establishment of a Common Code file and plugin, adds a timestamp check to discovered events, and more! + +This release adds the new `plugins/common_coreutils.py` plugin and `common_utils.py` core file. Developers +can use this as an example of how to call one plugin from another. + +This release also removes the check for WiX-based installer versions of EDMC prior to 5.9.1. + +**Changes and Enhancements** +* Adds a check to the timestamp of all events before passing to Plugins. +* Adds the new `--skip-timecheck` argument to disable the new timestamp checker +* Adds the option to disable the Windows SysTray +* Adds some new options to the SysTray right-click menu +* Adds PowerPlayMerits and PowerPlayRank event support +* Adds a warning if the updater fails to initialize +* Updates the WinSparkle Updater +* Updates a number of type hints +* Updates a number of dependencies +* Improves the detection of Wine for program compatibilty +* Improves the detection of the current language for translation compatibilty +* Fixes a bug where directory paths starting with `~` would not be processed by the journal lock +* Fixes (and redoes) the Hotkey functionality on Windows +* Fixes a few typos +* Fixes a few calls from `config.get()` to their proper `get_x()` +* Minor efficiency and readability updates +* Reduces duplicate code by refactoring to common code files +* Removes the old check for WiX based installers to improve performance. +* Removes a few unused functions that aren't part of the public API +* Refactors a significant amount of ctypes code to utilize pywin32 + +**Bug Fixes** + + +**Plugin Developers** +* nb.Entry is deprecated, and is slated for removal in 6.0 or later. Please migrate to nb.EntryMenu +* nb.ColoredButton is deprecated, and is slated for removal in 6.0 or later. Please migrate to tk.Button +* Calling internal translations with `_()` is deprecated, and is slated for removal in 6.0 or later. Please migrate to importing `translations` and calling `translations.translate` or `translations.tl` directly +* `Translations` as the translate system singleton is deprecated, and is slated for removal in 6.0 or later. Please migrate to the `translations` singleton +* `help_open_log_folder()` is deprecated, and is slated for removal in 6.0 or later. Please migrate to open_folder() +* `update_feed` is deprecated, and is slated for removal in 6.0 or later. Please migrate to `get_update_feed()`. Release 5.12.5 === diff --git a/prefs.py b/prefs.py index e8a2a757..690e32b6 100644 --- a/prefs.py +++ b/prefs.py @@ -1317,7 +1317,7 @@ class PreferencesDialog(tk.Toplevel): 'Update': self.curr_update_track != self.update_paths.get(), # Just needs bool not true if else false 'Track': self.update_paths.get(), 'Parent': self, - 'Restart_Req': self.req_restart # Sipmle Bool Needed + 'Restart_Req': self.req_restart # Simple Bool Needed } if self.callback: self.callback(**post_flags) From 7a5635b3fba4631914a3082f0707e5a26cef61c0 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 27 Apr 2025 16:26:33 -0400 Subject: [PATCH 50/62] [#579] Allow EDMC to Iterate Known CMDRs --- EDMC.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/EDMC.py b/EDMC.py index fd241ec2..a0a94a30 100755 --- a/EDMC.py +++ b/EDMC.py @@ -126,6 +126,12 @@ def main() -> None: # noqa: C901, CCR001 action='store_true' ) + parser.add_argument( + '--refresh-all', + help='Iterate over all known CMDRs to try and refresh access tokens', + action='store_true', + ) + parser.add_argument('-a', metavar='FILE', help='write ship loadout to FILE in Companion API json format') parser.add_argument('-e', metavar='FILE', help='write ship loadout to FILE in E:D Shipyard plain text format') parser.add_argument('-l', metavar='FILE', help='write ship locations to FILE in CSV format') @@ -184,6 +190,16 @@ def main() -> None: # noqa: C901, CCR001 logger.info(f'marked {d} for TRACE') log_locale('Initial Locale') + if args.refresh_all: + logger.info("Refreshing all known CMDRs") + cmdrs = config.get_list('cmdrs', default=[]) + for cmdr in cmdrs: + logger.info(f'Attempting to use commander "{cmdr}"') + try: + companion.session.login(cmdr, monitor.is_beta) + logger.debug("Succeeded!") + except AttributeError: + logger.debug(f"Unable to refresh CMDR {cmdr}.") if args.j: logger.debug('Import and collate from JSON dump') From e8d4b95bd268d0cdefccdd2341423952998ba0f6 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 27 Apr 2025 16:29:04 -0400 Subject: [PATCH 51/62] [579] Alter Logging --- EDMC.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/EDMC.py b/EDMC.py index a0a94a30..b8e95a55 100755 --- a/EDMC.py +++ b/EDMC.py @@ -191,10 +191,11 @@ def main() -> None: # noqa: C901, CCR001 log_locale('Initial Locale') if args.refresh_all: - logger.info("Refreshing all known CMDRs") + # Attempt to refresh all known CMDRs. This MAY cause additional output if a token is invalid. + logger.debug("Refreshing all known CMDRs") cmdrs = config.get_list('cmdrs', default=[]) for cmdr in cmdrs: - logger.info(f'Attempting to use commander "{cmdr}"') + logger.debug(f'Attempting to use commander "{cmdr}"') try: companion.session.login(cmdr, monitor.is_beta) logger.debug("Succeeded!") From 65273742d0b21404e22a9312fc8009bf01330e5a Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 27 Apr 2025 21:58:01 -0400 Subject: [PATCH 52/62] [#1775] Retire Usage of Assert Removes assert statements from EDMC non-test code, paving the way to enable -OO code. --- config/linux.py | 3 ++- config/windows.py | 3 ++- coriolis-update-files.py | 15 +++++++---- edshipyard.py | 9 ++++--- hotkey/linux.py | 3 ++- hotkey/windows.py | 3 ++- killswitch.py | 3 ++- l10n.py | 3 ++- monitor.py | 12 ++++++--- outfitting.py | 44 ++++++++++++++++++------------- plug.py | 13 ++++----- protocol.py | 3 ++- scripts/find_localised_strings.py | 3 ++- shipyard.py | 9 ++++--- theme.py | 8 +++--- 15 files changed, 81 insertions(+), 53 deletions(-) diff --git a/config/linux.py b/config/linux.py index a7a472f4..651fea09 100644 --- a/config/linux.py +++ b/config/linux.py @@ -13,7 +13,8 @@ import sys from configparser import ConfigParser from config import AbstractConfig, appname, logger -assert sys.platform == 'linux' +if sys.platform != 'linux': + raise EnvironmentError("This file is for Linux only.") class LinuxConfig(AbstractConfig): diff --git a/config/windows.py b/config/windows.py index 550b0e4a..f5676424 100644 --- a/config/windows.py +++ b/config/windows.py @@ -16,7 +16,8 @@ from typing import Literal from config import AbstractConfig, applongname, appname, logger from win32comext.shell import shell -assert sys.platform == 'win32' +if sys.platform != 'win32': + raise EnvironmentError("This file is for Windows only.") REG_RESERVED_ALWAYS_ZERO = 0 diff --git a/coriolis-update-files.py b/coriolis-update-files.py index 729d2ef6..40d25fb3 100755 --- a/coriolis-update-files.py +++ b/coriolis-update-files.py @@ -20,12 +20,15 @@ import sys import outfitting from edmc_data import coriolis_ship_map, ship_name_map -if __name__ == "__main__": +if __name__ == "__main__": # noqa: C901 def add(modules, name, attributes) -> None: """Add the given module to the modules dict.""" - assert name not in modules or modules[name] == attributes, f'{name}: {modules.get(name)} != {attributes}' - assert name not in modules, name + if name in modules and modules[name] != attributes: + raise ValueError(f'{name}: {modules.get(name)} != {attributes}') + if name in modules: + raise ValueError(f'{name} already exists in modules') + modules[name] = attributes try: @@ -50,7 +53,8 @@ if __name__ == "__main__": # Ship and armour masses for m in list(data['Ships'].values()): name = coriolis_ship_map.get(m['properties']['name'], str(m['properties']['name'])) - assert name in reverse_ship_map, name + if name not in reverse_ship_map: + raise ValueError(f'Unknown ship: {name}') ships[name] = {'hullMass': m['properties']['hullMass'], 'reserveFuelCapacity': m['properties']['reserveFuelCapacity']} for i, bulkhead in enumerate(bulkheads): @@ -64,7 +68,8 @@ if __name__ == "__main__": for cat in list(data['Modules'].values()): for grp, mlist in list(cat.items()): for m in mlist: - assert 'symbol' in m, m + if 'symbol' not in m: + raise ValueError(f'No symbol in {m}') key = str(m['symbol'].lower()) if grp == 'fsd': modules[key] = { diff --git a/edshipyard.py b/edshipyard.py index 2c29959f..28e6dc2f 100644 --- a/edshipyard.py +++ b/edshipyard.py @@ -128,7 +128,7 @@ def export(data, filename=None) -> None: # noqa: C901, CCR001 elif not slot.lower().startswith('planetaryapproachsuite'): logger.debug(f'EDShipyard: Unknown slot {slot}') - except AssertionError as e: + except ValueError as e: logger.debug(f'EDShipyard: {e!r}') continue # Silently skip unrecognized modules @@ -161,8 +161,11 @@ def export(data, filename=None) -> None: # noqa: C901, CCR001 string += f'---\nCargo : {cargo} T\nFuel : {fuel} T\n' # Add mass and range - assert data['ship']['name'].lower() in ship_name_map, data['ship']['name'] - assert ship_name_map[data['ship']['name'].lower()] in ships, ship_name_map[data['ship']['name'].lower()] + ship_name = data['ship']['name'].lower() + if ship_name not in ship_name_map: + raise ValueError(f"Ship name '{data['ship']['name']}' not found in ship_name_map") + if ship_name_map[ship_name] not in ships: + raise ValueError(f"Mapped ship name '{ship_name_map[ship_name]}' not found in ships") try: mass += ships[ship_name_map[data['ship']['name'].lower()]]['hullMass'] diff --git a/hotkey/linux.py b/hotkey/linux.py index 11d95a62..7e4b9862 100644 --- a/hotkey/linux.py +++ b/hotkey/linux.py @@ -5,7 +5,8 @@ import sys from EDMCLogging import get_main_logger from hotkey import AbstractHotkeyMgr -assert sys.platform == 'linux' +if sys.platform != 'linux': + raise EnvironmentError("This file is for Linux only.") logger = get_main_logger() diff --git a/hotkey/windows.py b/hotkey/windows.py index ddccc333..ad4da9db 100644 --- a/hotkey/windows.py +++ b/hotkey/windows.py @@ -17,7 +17,8 @@ from config import config from EDMCLogging import get_main_logger from hotkey import AbstractHotkeyMgr -assert sys.platform == 'win32' +if sys.platform != 'win32': + raise EnvironmentError("This file is for Windows only.") logger = get_main_logger() diff --git a/killswitch.py b/killswitch.py index 89a55292..22a40049 100644 --- a/killswitch.py +++ b/killswitch.py @@ -275,7 +275,8 @@ class KillSwitchSet: return True, data if TYPE_CHECKING: # pyright, mypy, please -_- - assert res.kill is not None + if res.kill is None: + raise ValueError('Killswitch has rules but no kill data') try: new_data = res.kill.apply_rules(deepcopy(data)) diff --git a/l10n.py b/l10n.py index 6557169e..afb6acaf 100755 --- a/l10n.py +++ b/l10n.py @@ -133,7 +133,8 @@ class Translations: def contents(self, lang: str, plugin_path: pathlib.Path | None = None) -> dict[str, str]: """Load all the translations from a translation file.""" - assert lang in self.available() + if lang not in self.available(): + raise KeyError(f'Language {lang} not available') translations = {} h = self.file(lang, plugin_path) diff --git a/monitor.py b/monitor.py index 5bb418c0..32e58c78 100644 --- a/monitor.py +++ b/monitor.py @@ -311,7 +311,8 @@ class EDLogs(FileSystemEventHandler): if self.observed: logger.debug('self.observed: Calling unschedule_all()') self.observed = None - assert self.observer is not None, 'Observer was none but it is in use?' + if self.observer is None: + raise RuntimeError("Observer was None but it is in use?") self.observer.unschedule_all() logger.debug('Done') @@ -416,7 +417,8 @@ class EDLogs(FileSystemEventHandler): # Watchdog thread -- there is a way to get this by using self.observer.emitters and checking for an attribute: # watch, but that may have unforseen differences in behaviour. if self.observed: - assert self.observer is not None, 'self.observer is None but also in use?' + if self.observer is None: + raise RuntimeError("Observer was None but is it in use?") # Note: Uses undocumented attribute emitter = self.observed and self.observer._emitter_for_watch[self.observed] @@ -555,7 +557,8 @@ class EDLogs(FileSystemEventHandler): try: # Preserve property order because why not? entry: MutableMapping[str, Any] = json.loads(line) - assert 'timestamp' in entry, "Timestamp does not exist in the entry" + if 'timestamp' not in entry: + raise KeyError("Timestamp does not exist in the entry") self.__navroute_retry() @@ -1658,7 +1661,8 @@ class EDLogs(FileSystemEventHandler): self.state[category].pop(material) module = self.state['Modules'][entry['Slot']] - assert module['Item'] == self.canonicalise(entry['Module']) + if module['Item'] != self.canonicalise(entry['Module']): + raise ValueError(f"Module {entry['Slot']} is not {entry['Module']}") module['Engineering'] = { 'Engineer': entry['Engineer'], 'EngineerID': entry['EngineerID'], diff --git a/outfitting.py b/outfitting.py index 770c47cd..207c4883 100644 --- a/outfitting.py +++ b/outfitting.py @@ -59,7 +59,7 @@ def lookup(module, ship_map, entitled=False) -> dict | None: # noqa: C901, CCR0 moduledata.update(json.loads(modules_path.read_text())) if not module.get('name'): - raise AssertionError(f'{module["id"]}') + raise ValueError(f"Module with ID {module['id']} is missing a 'name' field") name = module['name'].lower().split('_') new = {'id': module['id'], 'symbol': module['name']} @@ -69,7 +69,7 @@ def lookup(module, ship_map, entitled=False) -> dict | None: # noqa: C901, CCR0 # Armour is ship-specific, and ship names can have underscores ship_name, armour, armour_grade = module["name"].lower().rsplit("_", 2)[0:3] if ship_name not in ship_map: - raise AssertionError(f"Unknown ship: {ship_name}") + raise ValueError(f"Unknown ship: {ship_name}") new['category'] = 'standard' new["name"] = armour_map[armour_grade] new["ship"] = ship_map[ship_name] @@ -115,7 +115,7 @@ def lookup(module, ship_map, entitled=False) -> dict | None: # noqa: C901, CCR0 new['category'] = 'utility' new['name'] = utility_map[name[1]] if not name[2].startswith('size') or not name[3].startswith('class'): - raise AssertionError(f'{module["id"]}: Unknown class/rating "{name[2]}/{name[3]}"') + raise ValueError(f'{module["id"]}: Unknown class/rating "{name[2]}/{name[3]}"') new['class'] = str(name[2][4:]) new['rating'] = rating_map[name[3][5:]] @@ -128,13 +128,13 @@ def lookup(module, ship_map, entitled=False) -> dict | None: # noqa: C901, CCR0 name[1] = f'{prefix}_{name[1]}' if name[1] not in weapon_map: - raise AssertionError(f'{module["id"]}: Unknown weapon "{name[0]}"') + raise ValueError(f'{module["id"]}: Unknown weapon "{name[0]}"') if name[2] not in weaponmount_map: - raise AssertionError(f'{module["id"]}: Unknown weapon mount "{name[2]}"') + raise ValueError(f'{module["id"]}: Unknown weapon mount "{name[2]}"') if name[3] not in weaponclass_map: - raise AssertionError(f'{module["id"]}: Unknown weapon class "{name[3]}"') + raise ValueError(f'{module["id"]}: Unknown weapon class "{name[3]}"') new['category'] = 'hardpoint' if len(name) > 4: @@ -143,7 +143,7 @@ def lookup(module, ship_map, entitled=False) -> dict | None: # noqa: C901, CCR0 new['rating'] = '?' elif '_'.join(name[:4]) not in weaponrating_map: - raise AssertionError(f'{module["id"]}: Unknown weapon rating "{module["name"]}"') + raise ValueError(f'{module["id"]}: Unknown weapon rating "{module["name"]}"') else: # PP faction-specific weapons e.g. Hpt_Slugshot_Fixed_Large_Range @@ -151,7 +151,7 @@ def lookup(module, ship_map, entitled=False) -> dict | None: # noqa: C901, CCR0 new['rating'] = weaponrating_map['_'.join(name[:4])] # assumes same rating as base weapon elif module['name'].lower() not in weaponrating_map: - raise AssertionError(f'{module["id"]}: Unknown weapon rating "{module["name"]}"') + raise ValueError(f'{module["id"]}: Unknown weapon rating "{module["name"]}"') else: new['name'] = weapon_map[name[1]] @@ -165,7 +165,7 @@ def lookup(module, ship_map, entitled=False) -> dict | None: # noqa: C901, CCR0 new['class'] = weaponclass_map[name[3]] elif name[0] != 'int': - raise AssertionError(f'{module["id"]}: Unknown prefix "{name[0]}"') + raise ValueError(f'{module["id"]}: Unknown prefix "{name[0]}"') # Miscellaneous Class 1 # e.g. Int_PlanetApproachSuite, Int_StellarBodyDiscoveryScanner_Advanced, Int_DockingComputer_Standard @@ -207,7 +207,7 @@ def lookup(module, ship_map, entitled=False) -> dict | None: # noqa: C901, CCR0 new['name'] = internal_map[len(name) > 4 and (name[1], name[4]) or name[1]] else: - raise AssertionError(f'{module["id"]}: Unknown module "{name[1]}"') + raise ValueError(f'{module["id"]}: Unknown module "{name[1]}"') if len(name) < 4 and name[1] == 'unkvesselresearch': # Hack! No size or class. (new['class'], new['rating']) = ('1', 'E') @@ -226,10 +226,10 @@ def lookup(module, ship_map, entitled=False) -> dict | None: # noqa: C901, CCR0 else: if len(name) < 3: - raise AssertionError(f'{name}: length < 3]') + raise ValueError(f'{name}: length < 3]') if not name[2].startswith('size') or not name[3].startswith('class'): - raise AssertionError(f'{module["id"]}: Unknown class/rating "{name[2]}/{name[3]}"') + raise ValueError(f'{module["id"]}: Unknown class/rating "{name[2]}/{name[3]}"') new['class'] = str(name[2][4:]) new['rating'] = (name[1] == 'buggybay' and planet_rating_map or @@ -258,10 +258,14 @@ def lookup(module, ship_map, entitled=False) -> dict | None: # noqa: C901, CCR0 print(f'No data for module {key}') elif new['name'] == 'Frame Shift Drive' or new['name'] == 'Frame Shift Drive (SCO)': - assert 'mass' in m and 'optmass' in m and 'maxfuel' in m and 'fuelmul' in m and 'fuelpower' in m, m + required_keys = ['mass', 'optmass', 'maxfuel', 'fuelmul', 'fuelpower'] + missing_keys = [key for key in required_keys if key not in m] + if missing_keys: + raise KeyError(f"Missing keys: {', '.join(missing_keys)} in {m}") else: - assert 'mass' in m, m + if 'mass' not in m: + raise KeyError(f"Missing key 'mass' in {m}") new.update(moduledata.get(module['name'].lower(), {})) @@ -269,10 +273,10 @@ def lookup(module, ship_map, entitled=False) -> dict | None: # noqa: C901, CCR0 mandatory_fields = ["id", "symbol", "category", "name", "class", "rating"] for field in mandatory_fields: if not new.get(field): - raise AssertionError(f'{module["id"]}: failed to set {field}') + raise ValueError(f'{module["id"]}: failed to set {field}') if new['category'] == 'hardpoint' and not new.get('mount'): - raise AssertionError(f'{module["id"]}: failed to set mount') + raise ValueError(f'{module["id"]}: failed to set mount') return new @@ -284,8 +288,10 @@ def export(data, filename) -> None: :param data: CAPI data to export. :param filename: Filename to export into. """ - assert "name" in data["lastSystem"] - assert "name" in data["lastStarport"] + if "name" not in data["lastSystem"]: + raise KeyError("Missing 'name' key in 'lastSystem'") + if "name" not in data["lastStarport"]: + raise KeyError("Missing 'name' key in 'lastStarport'") header = 'System,Station,Category,Name,Mount,Guidance,Ship,Class,Rating,FDevID,Date\n' rowheader = f'{data["lastSystem"]["name"]},{data["lastStarport"]["name"]}' @@ -300,6 +306,6 @@ def export(data, filename) -> None: f'{m.get("guidance","")}, {m.get("ship","")}, {m["class"]}, {m["rating"]},' f'{m["id"]}, {data["timestamp"]}\n') - except AssertionError as e: + except ValueError as e: # Log unrecognised modules logger.debug('Outfitting', exc_info=e) diff --git a/plug.py b/plug.py index 9841ee0a..eaf23d0d 100644 --- a/plug.py +++ b/plug.py @@ -113,20 +113,16 @@ class Plugin: appitem = plugin_app(parent) if appitem is None: return None - if isinstance(appitem, tuple): if ( len(appitem) != 2 or not isinstance(appitem[0], tk.Widget) or not isinstance(appitem[1], tk.Widget) ): - raise AssertionError - + raise TypeError("Expected a tuple of two tk.Widget instances from plugin_app") elif not isinstance(appitem, tk.Widget): - raise AssertionError - + raise TypeError("Expected a tk.Widget or tuple of two tk.Widgets from plugin_app") return appitem - except Exception: logger.exception(f'Failed for Plugin "{self.name}"') @@ -148,7 +144,7 @@ class Plugin: frame = plugin_prefs(parent, cmdr, is_beta) if isinstance(frame, nb.Frame): return frame - raise AssertionError + raise TypeError(f'Expected nb.Frame from plugin_prefs, got {type(frame).__name__}') except Exception: logger.exception(f'Failed for Plugin "{self.name}"') return None @@ -249,7 +245,8 @@ def invoke( for plugin in PLUGINS: if plugin.name == fallback: plugin_func = plugin._get_func(fn_name) - assert plugin_func, plugin.name # fallback plugin should provide the function + if not plugin_func: + raise ValueError(f"Fallback plugin '{plugin.name}' does not provide the function '{fn_name}'") return plugin_func(*args) return None diff --git a/protocol.py b/protocol.py index 01be09de..6f2bf406 100644 --- a/protocol.py +++ b/protocol.py @@ -67,7 +67,8 @@ if (config.auth_force_edmc_protocol # noqa: C901 and not config.auth_force_localserver )): # This could be false if you use auth_force_edmc_protocol, but then you get to keep the pieces - assert sys.platform == 'win32' + if sys.platform != 'win32': + raise EnvironmentError("This code is for Windows only.") # spell-checker: words HBRUSH HICON WPARAM wstring WNDCLASS HMENU HGLOBAL from ctypes import ( # type: ignore windll, POINTER, WINFUNCTYPE, Structure, byref, c_long, c_void_p, create_unicode_buffer, wstring_at diff --git a/scripts/find_localised_strings.py b/scripts/find_localised_strings.py index 85df27be..362d54bc 100644 --- a/scripts/find_localised_strings.py +++ b/scripts/find_localised_strings.py @@ -260,7 +260,8 @@ def generate_lang_template(data: dict[pathlib.Path, list[ast.Call]]) -> str: """ print(f"Done Deduping entries {len(entries)=} {len(deduped)=}", file=sys.stderr) for entry in deduped: - assert len(entry.comments) == len(entry.locations) + if len(entry.comments) != len(entry.locations): + raise ValueError("Mismatch: 'comments' and 'locations' must have the same length.") comment_set = set() for comment, loc in zip(entry.comments, entry.locations): diff --git a/shipyard.py b/shipyard.py index a5234c0a..199398e4 100644 --- a/shipyard.py +++ b/shipyard.py @@ -13,9 +13,12 @@ def export(data: companion.CAPIData, filename: str) -> None: :param filename: Optional filename to write to. :return: """ - assert data['lastSystem'].get('name') - assert data['lastStarport'].get('name') - assert data['lastStarport'].get('ships') + if not data['lastSystem'].get('name'): + raise ValueError("Missing 'name' in 'lastSystem'") + if not data['lastStarport'].get('name'): + raise ValueError("Missing 'name' in 'lastStarport'") + if not data['lastStarport'].get('ships'): + raise ValueError("Missing 'ships' in 'lastStarport'") with open(filename, 'w', newline='') as f: c = csv.writer(f) diff --git a/theme.py b/theme.py index 5eed9fe1..2f00731e 100644 --- a/theme.py +++ b/theme.py @@ -146,7 +146,8 @@ class _Theme: def register(self, widget: tk.Widget | tk.BitmapImage) -> None: # noqa: CCR001, C901 # Note widget and children for later application of a theme. Note if # the widget has explicit fg or bg attributes. - assert isinstance(widget, (tk.BitmapImage, tk.Widget)), widget + if not isinstance(widget, (tk.Widget, tk.BitmapImage)): + raise TypeError(f'Expected widget, got {type(widget)}') if not self.defaults: # Can't initialise this til window is created # Windows self.defaults = { @@ -301,7 +302,8 @@ class _Theme: Also, register it for future updates. :param widget: Target widget. """ - assert isinstance(widget, (tk.BitmapImage, tk.Widget)), widget + if not isinstance(widget, (tk.Widget, tk.BitmapImage)): + raise TypeError(f'Expected widget, got {type(widget)}') if not self.current: return # No need to call this for widgets created in plugin_app() @@ -325,7 +327,7 @@ class _Theme: w_keys = [] assert_str = f'{w_class} {widget} "{"text" in w_keys and widget["text"]}"' - raise AssertionError(assert_str) + raise ValueError(assert_str) attribs: set = self.widgets.get(widget, set()) From 4cfe3ac45da9146b2399ee399270b7e742211684 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 1 May 2025 17:04:19 +0000 Subject: [PATCH 53/62] Bump pytest-cov from 6.1.0 to 6.1.1 Bumps [pytest-cov](https://github.com/pytest-dev/pytest-cov) from 6.1.0 to 6.1.1. - [Changelog](https://github.com/pytest-dev/pytest-cov/blob/master/CHANGELOG.rst) - [Commits](https://github.com/pytest-dev/pytest-cov/compare/v6.1.0...v6.1.1) --- updated-dependencies: - dependency-name: pytest-cov dependency-version: 6.1.1 dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 011508a8..528003f3 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -35,7 +35,7 @@ py2exe==0.13.0.2; sys_platform == 'win32' # Testing pytest==8.3.5 -pytest-cov==6.1.0 # Pytest code coverage support +pytest-cov==6.1.1 # Pytest code coverage support coverage[toml]==7.8.0 # pytest-cov dep. This is here to ensure that it includes TOML support for pyproject.toml configs coverage-conditional-plugin==0.9.0 From 1e233e9a99f18f481c2d5922710b8bf40e5e3b14 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 1 May 2025 17:04:21 +0000 Subject: [PATCH 54/62] Bump mistune from 3.1.1 to 3.1.3 Bumps [mistune](https://github.com/lepture/mistune) from 3.1.1 to 3.1.3. - [Release notes](https://github.com/lepture/mistune/releases) - [Changelog](https://github.com/lepture/mistune/blob/main/docs/changes.rst) - [Commits](https://github.com/lepture/mistune/compare/v3.1.1...v3.1.3) --- updated-dependencies: - dependency-name: mistune dependency-version: 3.1.3 dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 011508a8..3521f760 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -27,7 +27,7 @@ autopep8==2.3.2 pre-commit==4.2.0 # HTML changelogs -mistune==3.1.1 +mistune==3.1.3 # Packaging # We only need py2exe on windows. From ff0741f849874246a8ca6da3d2e5bff9ddebb067 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 1 May 2025 17:04:32 +0000 Subject: [PATCH 55/62] Bump types-setuptools from 78.1.0.20250329 to 80.0.0.20250429 Bumps [types-setuptools](https://github.com/typeshed-internal/stub_uploader) from 78.1.0.20250329 to 80.0.0.20250429. - [Commits](https://github.com/typeshed-internal/stub_uploader/commits) --- updated-dependencies: - dependency-name: types-setuptools dependency-version: 80.0.0.20250429 dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 011508a8..da1754e4 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -18,7 +18,7 @@ mypy==1.15.0 pep8-naming==0.14.1 safety==3.4.0 types-requests==2.32.0.20250328 -types-setuptools==78.1.0.20250329 +types-setuptools==80.0.0.20250429 # Code formatting tools autopep8==2.3.2 From 73e134e39d42016e2cbfb59546673045b64f75fc Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sat, 3 May 2025 19:39:28 -0400 Subject: [PATCH 56/62] [#2415] Fix Inara Linking --- plugins/inara.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/plugins/inara.py b/plugins/inara.py index f6a336f9..7bc31a30 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -164,11 +164,11 @@ if DEBUG: def system_url(system_name: str) -> str: """Get a URL for the current system.""" if this.system_address: - return requests.utils.requote_uri(f'https://inara.cz/galaxy-starsystem/' + return requests.utils.requote_uri(f'https://inara.cz/elite/starsystem/' f'?search={this.system_address}') if system_name: - return requests.utils.requote_uri(f'https://inara.cz/galaxy-starsystem/' + return requests.utils.requote_uri(f'https://inara.cz/elite/starsystem/' f'?search={system_name}') return '' @@ -185,11 +185,11 @@ def station_url(system_name: str, station_name: str) -> str: :return: A URL to inara for the given system and station """ if system_name and station_name: - return requests.utils.requote_uri(f'https://inara.cz/galaxy-station/?search={system_name}%20[{station_name}]') + return requests.utils.requote_uri(f'https://inara.cz/elite/station/?search={station_name}%20[{system_name}]') if this.system_name and this.station_name: return requests.utils.requote_uri( - f'https://inara.cz/galaxy-station/?search={this.system_name}%20[{this.station_name}]') + f'https://inara.cz/elite/station/?search={this.station_name}%20[{this.system_name}]') if system_name: return system_url(system_name) From 3063bbb94f08338fcb954c1a3e75066ea533cf8d Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sat, 3 May 2025 19:52:14 -0400 Subject: [PATCH 57/62] [#2378] Update PLUGINS Example --- PLUGINS.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/PLUGINS.md b/PLUGINS.md index a120985e..6fd20ef9 100644 --- a/PLUGINS.md +++ b/PLUGINS.md @@ -612,9 +612,14 @@ for an example of these techniques. #### Journal Entry ```python +from __future__ import annotations +from typing import Any +from EDMCLogging import get_main_logger + +logger = get_main_logger() def journal_entry( - cmdr: str, is_beta: bool, system: str, station: str, entry: Dict[str, Any], state: Dict[str, Any] -) -> Optional[str]: + cmdr: str, is_beta: bool, system: str, station: str, entry: dict[str, Any], state: dict[str, Any] +) -> str | None: if entry['event'] == 'FSDJump': # We arrived at a new system! if 'StarPos' in entry: From f63774ebc60d1f4b5e241d3cbe7834a603dc5be8 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sat, 3 May 2025 20:12:10 -0400 Subject: [PATCH 58/62] [#1318] Update Lagging Message --- L10n/en.template | 2 +- L10n/uwu.strings | 4 ++-- companion.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/L10n/en.template b/L10n/en.template index f054b85d..559dbb82 100644 --- a/L10n/en.template +++ b/L10n/en.template @@ -13,7 +13,7 @@ "Error: Frontier CAPI didn't respond" = "Error: Frontier CAPI didn't respond"; /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ -"Error: Frontier server is lagging" = "Error: Frontier server is lagging"; +"Error: Frontier CAPI data out of sync" = "Error: Frontier CAPI data out of sync"; /* companion.py: Commander is docked at an EDO settlement, got out and back in, we forgot the station; In files: companion.py:261; */ "Docked but unknown station: EDO Settlement?" = "Docked but unknown station: EDO Settlement?"; diff --git a/L10n/uwu.strings b/L10n/uwu.strings index c0ab284b..63e1fe2a 100644 --- a/L10n/uwu.strings +++ b/L10n/uwu.strings @@ -13,7 +13,7 @@ "Error: Frontier CAPI didn't respond" = "Ewwow: fwontiew capi didn't wespond"; /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ -"Error: Frontier server is lagging" = "Ewwow: fwontiew sewvew iws wagging"; +"Error: Frontier CAPI data out of sync" = "Error: Fwontiew CAPI data out of sinwk"; /* companion.py: Commander is docked at an EDO settlement, got out and back in, we forgot the station; In files: companion.py:261; */ "Docked but unknown station: EDO Settlement?" = "Docked but unknown station: edo settwement?"; @@ -832,4 +832,4 @@ "Open in {URL}" = "OwOpen in {URL}"; /* ttkHyperlinkLabel.py: Copy the Inara SLEF Format of the active ship to the clipboard; */ -"Copy Inara SLEF" = "Copy Inyawa SWEF"; \ No newline at end of file +"Copy Inara SLEF" = "Copy Inyawa SWEF"; diff --git a/companion.py b/companion.py index 82db868d..0f16e237 100644 --- a/companion.py +++ b/companion.py @@ -240,7 +240,7 @@ class ServerLagging(Exception): self.args = args if not args: # LANG: Frontier CAPI data doesn't agree with latest Journal game location - self.args = (tr.tl('Error: Frontier server is lagging'),) + self.args = (tr.tl('Error: Frontier CAPI data out of sync'),) class NoMonitorStation(Exception): From d65c299eda25625464b4e0b3cfb0126de329e96f Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sat, 3 May 2025 21:01:41 -0400 Subject: [PATCH 59/62] [PRE-RELEASE] 5.13.0-rc1 --- ChangeLog.md | 31 ++++++++++++++++++------------- config/__init__.py | 2 +- 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/ChangeLog.md b/ChangeLog.md index 165b920e..00e1f500 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -6,9 +6,9 @@ This is the master changelog for Elite Dangerous Market Connector. Entries are in the source (not distributed with the Windows installer) for the currently used version. --- -Pre-Release 5.13.0-alpha0 +Pre-Release 5.13.0-rc1 === -This is the Changelog-In-Progress for the next release of EDMarketConnector. This is subject to change. +This is a release candidate for 5.13.0. It has been pushed to the "Beta" track for updates! This release contains a significant refactoring away from ctypes code for interating with the Windows API, establishment of a Common Code file and plugin, adds a timestamp check to discovered events, and more! @@ -19,8 +19,9 @@ can use this as an example of how to call one plugin from another. This release also removes the check for WiX-based installer versions of EDMC prior to 5.9.1. **Changes and Enhancements** -* Adds a check to the timestamp of all events before passing to Plugins. +* Adds a check to the timestamp of all events before passing to Plugins * Adds the new `--skip-timecheck` argument to disable the new timestamp checker +* Adds the ability to have EDMC iterate over all known CMDRs to keep Frontier Auth valid * Adds the option to disable the Windows SysTray * Adds some new options to the SysTray right-click menu * Adds PowerPlayMerits and PowerPlayRank event support @@ -28,20 +29,24 @@ This release also removes the check for WiX-based installer versions of EDMC pri * Updates the WinSparkle Updater * Updates a number of type hints * Updates a number of dependencies +* Updates a few internal references for stations for consistency +* Updates a confusing error when the CAPI API is out of date +* Updates the example journal_entry function in PLUGINS.md for current type hints * Improves the detection of Wine for program compatibilty * Improves the detection of the current language for translation compatibilty +* Minor efficiency and readability updates +* Reduces duplicate code by refactoring to common code files +* Removes the old check for WiX based installers to improve performance +* Removes a few unused functions that aren't part of the public API +* Refactors a significant amount of ctypes code to utilize pywin32 +* Removes a number of assert statements for future compatibilty + +**Bug Fixes** +* Fixes a bug where Inara Station and System links were broken * Fixes a bug where directory paths starting with `~` would not be processed by the journal lock * Fixes (and redoes) the Hotkey functionality on Windows * Fixes a few typos -* Fixes a few calls from `config.get()` to their proper `get_x()` -* Minor efficiency and readability updates -* Reduces duplicate code by refactoring to common code files -* Removes the old check for WiX based installers to improve performance. -* Removes a few unused functions that aren't part of the public API -* Refactors a significant amount of ctypes code to utilize pywin32 - -**Bug Fixes** - +* Fixes a few calls from `config.get()` to their proper `get_x() **Plugin Developers** * nb.Entry is deprecated, and is slated for removal in 6.0 or later. Please migrate to nb.EntryMenu @@ -49,7 +54,7 @@ This release also removes the check for WiX-based installer versions of EDMC pri * Calling internal translations with `_()` is deprecated, and is slated for removal in 6.0 or later. Please migrate to importing `translations` and calling `translations.translate` or `translations.tl` directly * `Translations` as the translate system singleton is deprecated, and is slated for removal in 6.0 or later. Please migrate to the `translations` singleton * `help_open_log_folder()` is deprecated, and is slated for removal in 6.0 or later. Please migrate to open_folder() -* `update_feed` is deprecated, and is slated for removal in 6.0 or later. Please migrate to `get_update_feed()`. +* `update_feed` is deprecated, and is slated for removal in 6.0 or later. Please migrate to `get_update_feed()` Release 5.12.5 === diff --git a/config/__init__.py b/config/__init__.py index b92b3177..b6b8285c 100644 --- a/config/__init__.py +++ b/config/__init__.py @@ -52,7 +52,7 @@ appcmdname = 'EDMC' # # Major.Minor.Patch(-prerelease)(+buildmetadata) # NB: Do *not* import this, use the functions appversion() and appversion_nobuild() -_static_appversion = '5.12.5' +_static_appversion = '5.13.0-rc1' _cached_version: semantic_version.Version | None = None copyright = '© 2015-2019 Jonathan Harris, 2020-2024 EDCD' From b4f5a7ec2c31156f9d4e10f7969f1982b684f575 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sat, 3 May 2025 21:43:42 -0400 Subject: [PATCH 60/62] [Minor] Spelling is Hard --- ChangeLog.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ChangeLog.md b/ChangeLog.md index 00e1f500..76309944 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -10,7 +10,7 @@ Pre-Release 5.13.0-rc1 === This is a release candidate for 5.13.0. It has been pushed to the "Beta" track for updates! -This release contains a significant refactoring away from ctypes code for interating with the Windows API, +This release contains a significant refactoring away from ctypes code for interacting with the Windows API, establishment of a Common Code file and plugin, adds a timestamp check to discovered events, and more! This release adds the new `plugins/common_coreutils.py` plugin and `common_utils.py` core file. Developers @@ -32,14 +32,14 @@ This release also removes the check for WiX-based installer versions of EDMC pri * Updates a few internal references for stations for consistency * Updates a confusing error when the CAPI API is out of date * Updates the example journal_entry function in PLUGINS.md for current type hints -* Improves the detection of Wine for program compatibilty -* Improves the detection of the current language for translation compatibilty +* Improves the detection of Wine for program compatibility +* Improves the detection of the current language for translation compatibility * Minor efficiency and readability updates * Reduces duplicate code by refactoring to common code files * Removes the old check for WiX based installers to improve performance * Removes a few unused functions that aren't part of the public API * Refactors a significant amount of ctypes code to utilize pywin32 -* Removes a number of assert statements for future compatibilty +* Removes a number of assert statements for future compatibility **Bug Fixes** * Fixes a bug where Inara Station and System links were broken From fc3da6d936c154f8a9a5c32cf1f2675ffd90f33a Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 9 May 2025 21:18:22 -0400 Subject: [PATCH 61/62] [Lang] Update Translations --- L10n/cs.strings | 3 +- L10n/de.strings | 9 +++- L10n/es.strings | 3 +- L10n/fi.strings | 3 +- L10n/fr.strings | 3 +- L10n/hu.strings | 3 +- L10n/it.strings | 8 +++- L10n/ja.strings | 3 +- L10n/ko.strings | 3 +- L10n/lv.strings | 3 +- L10n/nl.strings | 3 +- L10n/pl.strings | 2 +- L10n/pt-BR.strings | 8 +++- L10n/pt-PT.strings | 8 +++- L10n/ru.strings | 8 +++- L10n/sr-Latn-BA.strings | 3 +- L10n/sr-Latn.strings | 3 +- L10n/sv-SE.strings | 3 +- L10n/tr.strings | 9 +++- L10n/uk.strings | 2 +- L10n/zh-Hans.strings | 96 ++++++++++++++++++++++++++++++++++++++++- 21 files changed, 152 insertions(+), 34 deletions(-) diff --git a/L10n/cs.strings b/L10n/cs.strings index f4d1bcea..a726760e 100644 --- a/L10n/cs.strings +++ b/L10n/cs.strings @@ -4,9 +4,9 @@ /* companion.py: Frontier CAPI didn't respond; In files: companion.py:226; */ "Error: Frontier CAPI didn't respond" = "Chyba: Frontier CAPI neodpovídá"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Chyba: Server Frontieru laguje"; - /* companion.py: Generic "something went wrong with Frontier Auth" error; In files: companion.py:271; */ "Error: Invalid Credentials" = "Chyba: Chybné přihlašovací údaje"; @@ -588,4 +588,3 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Lodě"; - diff --git a/L10n/de.strings b/L10n/de.strings index 313f893e..dd5d21b7 100644 --- a/L10n/de.strings +++ b/L10n/de.strings @@ -1,3 +1,9 @@ +/* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ +"Error: Frontier CAPI data out of sync" = "Fehler: Frontier CAPI-Daten nicht synchron"; + +/* prefs.py: Appearance option for Windows "Disable Systray"; */ +"Disable Systray" = "Infobereich-Icon deaktivieren"; + /* edsm.py:Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:316; */ "Send flight log and CMDR status to EDSM" = "Sende Fluglog und CMDR-Status an EDSM"; @@ -12,9 +18,9 @@ /* companion.py: Frontier CAPI didn't respond; In files: companion.py:226; */ "Error: Frontier CAPI didn't respond" = "Fehler: Frontier CAPI antwortet nicht"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Fehler: Frontier-Server ist überlastet"; - /* companion.py: Commander is docked at an EDO settlement, got out and back in, we forgot the station; In files: companion.py:261; */ "Docked but unknown station: EDO Settlement?" = "Angedockt aber unbekannte Station: EDO-Siedlung?"; @@ -788,4 +794,3 @@ /* ttkHyperlinkLabel.py: Open Element In Selected Provider; */ "Open in {URL}" = "Öffnen in {URL}"; - diff --git a/L10n/es.strings b/L10n/es.strings index 9cdfa007..d7309181 100644 --- a/L10n/es.strings +++ b/L10n/es.strings @@ -4,9 +4,9 @@ /* companion.py: Frontier CAPI didn't respond; In files: companion.py:226; */ "Error: Frontier CAPI didn't respond" = "Error: El CAPI de Frontier no respondió"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Error: El servidor de Frontier está retrasado"; - /* companion.py: Commander is docked at an EDO settlement, got out and back in, we forgot the station; In files: companion.py:261; */ "Docked but unknown station: EDO Settlement?" = "Atracado pero estación desconocida: ¿Asentamiento EDO?"; @@ -603,4 +603,3 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Naves"; - diff --git a/L10n/fi.strings b/L10n/fi.strings index 2893f2d2..6b31e41d 100644 --- a/L10n/fi.strings +++ b/L10n/fi.strings @@ -4,9 +4,9 @@ /* companion.py: Frontier CAPI didn't respond; In files: companion.py:226; */ "Error: Frontier CAPI didn't respond" = "Virhe: Frontier CAPI ei vastaa."; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Virhe: Frontierin palvelin vastaa vanhoilla tiedoilla"; - /* companion.py: Generic "something went wrong with Frontier Auth" error; In files: companion.py:271; */ "Error: Invalid Credentials" = "Virhe: kirjautuminen ei kelpaa"; @@ -561,4 +561,3 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Alukset"; - diff --git a/L10n/fr.strings b/L10n/fr.strings index 3922bbbc..c3c96db6 100644 --- a/L10n/fr.strings +++ b/L10n/fr.strings @@ -12,9 +12,9 @@ /* companion.py: Frontier CAPI didn't respond; In files: companion.py:226; */ "Error: Frontier CAPI didn't respond" = "L'API Compagnon de Frontier ne répond pas"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Erreur : Le serveur Frontier ne répond pas"; - /* companion.py: Commander is docked at an EDO settlement, got out and back in, we forgot the station; In files: companion.py:261; */ "Docked but unknown station: EDO Settlement?" = "Amarré, mais station inconnue : colonie EDO ?"; @@ -533,4 +533,3 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Vaisseaux"; - diff --git a/L10n/hu.strings b/L10n/hu.strings index face43a5..dbbeb622 100644 --- a/L10n/hu.strings +++ b/L10n/hu.strings @@ -1,9 +1,9 @@ /* Language name */ "!Language" = "Magyar"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Hiba:Frontier szerver laggol"; - /* companion.py: Generic "something went wrong with Frontier Auth" error; In files: companion.py:271; */ "Error: Invalid Credentials" = "Hiba:Érvénytelen hitelesítő adatok"; @@ -471,4 +471,3 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Hajók"; - diff --git a/L10n/it.strings b/L10n/it.strings index 4d948883..c6de5bea 100644 --- a/L10n/it.strings +++ b/L10n/it.strings @@ -1,3 +1,9 @@ +/* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ +"Error: Frontier CAPI data out of sync" = "Errore: I dati del CAPI di Frontier non sono sincronizzati"; + +/* prefs.py: Appearance option for Windows "Disable Systray"; */ +"Disable Systray" = "Non mostrare nel Vassoio di sistema"; + /* edsm.py:Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:316; */ "Send flight log and CMDR status to EDSM" = "Invia il registro di volo e lo stato del CMDR a EDSM"; @@ -12,9 +18,9 @@ /* companion.py: Frontier CAPI didn't respond; In files: companion.py:226; */ "Error: Frontier CAPI didn't respond" = "Errore: Frontier CAPI non ha risposto"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Errore: il server Frontier sta laggando"; - /* companion.py: Commander is docked at an EDO settlement, got out and back in, we forgot the station; In files: companion.py:261; */ "Docked but unknown station: EDO Settlement?" = "Stazione attraccata ma sconosciuta: insediamento EDO?"; diff --git a/L10n/ja.strings b/L10n/ja.strings index 9ef405c1..20d0956f 100644 --- a/L10n/ja.strings +++ b/L10n/ja.strings @@ -12,9 +12,9 @@ /* companion.py: Frontier CAPI didn't respond; In files: companion.py:226; */ "Error: Frontier CAPI didn't respond" = "エラー: Frontier CAPIからの応答がありません"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "エラー: Frontier社のサーバが混雑しています"; - /* companion.py: Commander is docked at an EDO settlement, got out and back in, we forgot the station; In files: companion.py:261; */ "Docked but unknown station: EDO Settlement?" = "不明なステーションに着艦: EDOの基地?"; @@ -809,4 +809,3 @@ /* ttkHyperlinkLabel.py: Open Element In Selected Provider; */ "Open in {URL}" = "{URL} で開く"; - diff --git a/L10n/ko.strings b/L10n/ko.strings index 63f4c613..de46a1fc 100644 --- a/L10n/ko.strings +++ b/L10n/ko.strings @@ -4,9 +4,9 @@ /* companion.py: Frontier CAPI didn't respond; In files: companion.py:226; */ "Error: Frontier CAPI didn't respond" = "오류: Frontier CAPI가 응답이 없음"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "오류: Frontier 서버 응답이 지연되고 있음"; - /* companion.py: Commander is docked at an EDO settlement, got out and back in, we forgot the station; In files: companion.py:261; */ "Docked but unknown station: EDO Settlement?" = "알 수 없는 정거장에 도킹함: Odyssey 지상 기지입니까?"; @@ -636,4 +636,3 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "함선(들)"; - diff --git a/L10n/lv.strings b/L10n/lv.strings index c89e16de..3890e059 100644 --- a/L10n/lv.strings +++ b/L10n/lv.strings @@ -1,9 +1,9 @@ /* Language name */ "!Language" = "Latviešu"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Kļūda: Frontier serveris aizkavējas"; - /* companion.py: Generic "something went wrong with Frontier Auth" error; In files: companion.py:271; */ "Error: Invalid Credentials" = "Kļūda: Nederīga lietotāja informācija"; @@ -453,4 +453,3 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Kuģi"; - diff --git a/L10n/nl.strings b/L10n/nl.strings index 677236bc..eca89960 100644 --- a/L10n/nl.strings +++ b/L10n/nl.strings @@ -9,9 +9,9 @@ /* Language name */ "!Language" = "Nederlands"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Fout: Frontier server is vertraagd"; - /* companion.py: Generic "something went wrong with Frontier Auth" error; In files: companion.py:271; */ "Error: Invalid Credentials" = "Fout: Ongeldige inlog gegevens"; @@ -611,4 +611,3 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Schepen"; - diff --git a/L10n/pl.strings b/L10n/pl.strings index 26696140..9d5bdb22 100644 --- a/L10n/pl.strings +++ b/L10n/pl.strings @@ -12,9 +12,9 @@ /* companion.py: Frontier CAPI didn't respond; In files: companion.py:226; */ "Error: Frontier CAPI didn't respond" = "Błąd: Brak odpowiedzi od CAPI Frontier"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Błąd: Serwer Frontiera laguje"; - /* companion.py: Commander is docked at an EDO settlement, got out and back in, we forgot the station; In files: companion.py:261; */ "Docked but unknown station: EDO Settlement?" = "Zadokowany na nieznanej stacji: czyżby kolonia EDO?"; diff --git a/L10n/pt-BR.strings b/L10n/pt-BR.strings index 187a0627..c9541ac7 100644 --- a/L10n/pt-BR.strings +++ b/L10n/pt-BR.strings @@ -1,3 +1,9 @@ +/* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ +"Error: Frontier CAPI data out of sync" = "Erro: dados do Frontier CAPI fora de sincronia"; + +/* prefs.py: Appearance option for Windows "Disable Systray"; */ +"Disable Systray" = "Desativar ícone na área de notificação"; + /* edsm.py:Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:316; */ "Send flight log and CMDR status to EDSM" = "Enviar registro de voo e status do CMDT para o EDSM"; @@ -12,9 +18,9 @@ /* companion.py: Frontier CAPI didn't respond; In files: companion.py:226; */ "Error: Frontier CAPI didn't respond" = "Erro: o CAPI da Frontier não respondeu"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Erro: O servidor da Frontier está com lag"; - /* companion.py: Commander is docked at an EDO settlement, got out and back in, we forgot the station; In files: companion.py:261; */ "Docked but unknown station: EDO Settlement?" = "Docado, mas estação desconhecida: Assentamento Odyssey?"; diff --git a/L10n/pt-PT.strings b/L10n/pt-PT.strings index c9b1af58..5630cad5 100644 --- a/L10n/pt-PT.strings +++ b/L10n/pt-PT.strings @@ -1,3 +1,9 @@ +/* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ +"Error: Frontier CAPI data out of sync" = "Erro: Dados da CAPI da Frontier não estão em sincronia"; + +/* prefs.py: Appearance option for Windows "Disable Systray"; */ +"Disable Systray" = "Desactivar ícone na área de notificação"; + /* edsm.py:Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:316; */ "Send flight log and CMDR status to EDSM" = "Enviar registos de voo e estado de CMDR para o EDSM"; @@ -12,9 +18,9 @@ /* companion.py: Frontier CAPI didn't respond; In files: companion.py:226; */ "Error: Frontier CAPI didn't respond" = "Erro: CAPI da Frontier não respondeu."; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Erro: O servidor da Frontier está atrasado"; - /* companion.py: Commander is docked at an EDO settlement, got out and back in, we forgot the station; In files: companion.py:261; */ "Docked but unknown station: EDO Settlement?" = "Atracado numa estação desconhecida. É uma colónia EDO?"; diff --git a/L10n/ru.strings b/L10n/ru.strings index d302d445..35047f6d 100644 --- a/L10n/ru.strings +++ b/L10n/ru.strings @@ -1,3 +1,9 @@ +/* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ +"Error: Frontier CAPI data out of sync" = "Ошибка: Данные Frontier CAPI не синхронизированы"; + +/* prefs.py: Appearance option for Windows "Disable Systray"; */ +"Disable Systray" = "Отключить Systray"; + /* edsm.py:Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:316; */ "Send flight log and CMDR status to EDSM" = "Отправить журнал полетов и статус командира в EDSM"; @@ -12,9 +18,9 @@ /* companion.py: Frontier CAPI didn't respond; In files: companion.py:226; */ "Error: Frontier CAPI didn't respond" = "Ошибка: CAPI Frontier не отвечает"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Ошибка: сервера Frontier нестабильны"; - /* companion.py: Commander is docked at an EDO settlement, got out and back in, we forgot the station; In files: companion.py:261; */ "Docked but unknown station: EDO Settlement?" = "Неизвестный тип станции: поселение EDO?"; diff --git a/L10n/sr-Latn-BA.strings b/L10n/sr-Latn-BA.strings index 46cc4632..9d6b413d 100644 --- a/L10n/sr-Latn-BA.strings +++ b/L10n/sr-Latn-BA.strings @@ -12,9 +12,9 @@ /* companion.py: Frontier CAPI didn't respond; In files: companion.py:226; */ "Error: Frontier CAPI didn't respond" = "Greška: Frontier CAPI nije odgovorio"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Greška: Frontier server je usporen"; - /* companion.py: Commander is docked at an EDO settlement, got out and back in, we forgot the station; In files: companion.py:261; */ "Docked but unknown station: EDO Settlement?" = "Pristali ste, ali stanica je nepoznata: EDO naselje?"; @@ -809,4 +809,3 @@ /* ttkHyperlinkLabel.py: Open Element In Selected Provider; */ "Open in {URL}" = "Otvori u {URL}"; - diff --git a/L10n/sr-Latn.strings b/L10n/sr-Latn.strings index 6fb8b7db..5d154d90 100644 --- a/L10n/sr-Latn.strings +++ b/L10n/sr-Latn.strings @@ -12,9 +12,9 @@ /* companion.py: Frontier CAPI didn't respond; In files: companion.py:226; */ "Error: Frontier CAPI didn't respond" = "Greška: Frontier CAPI nije odgovorio"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Greška: Frontier server je usporen"; - /* companion.py: Commander is docked at an EDO settlement, got out and back in, we forgot the station; In files: companion.py:261; */ "Docked but unknown station: EDO Settlement?" = "Dokovan ali stanica nepoznata: EDO Naselje?"; @@ -776,4 +776,3 @@ /* ttkHyperlinkLabel.py: Open Element In Selected Provider; */ "Open in {URL}" = "Otvori na {URL}"; - diff --git a/L10n/sv-SE.strings b/L10n/sv-SE.strings index 4bcce399..1fe7cf4f 100644 --- a/L10n/sv-SE.strings +++ b/L10n/sv-SE.strings @@ -1,9 +1,9 @@ /* Language name */ "!Language" = "Svenska"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Fel: Frontier lag på server"; - /* companion.py: Generic "something went wrong with Frontier Auth" error; In files: companion.py:271; */ "Error: Invalid Credentials" = "Fel: ogiltligt användarnamn eller lösenord"; @@ -483,4 +483,3 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Skepp"; - diff --git a/L10n/tr.strings b/L10n/tr.strings index ea19246c..ec416819 100644 --- a/L10n/tr.strings +++ b/L10n/tr.strings @@ -1,3 +1,10 @@ +/* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ +"Error: Frontier CAPI data out of sync" = "Frontier CAPI datası senkronize değil"; + +/* prefs.py: Appearance option for Windows "Disable Systray"; */ +"Disable Systray" = "Sistem tepsisi ikonunu devre dışı bırak +"; + /* edsm.py:Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:316; */ "Send flight log and CMDR status to EDSM" = "Uçuş günlüğünü ve CMDR durumunu EDSM'e gönder"; @@ -12,9 +19,9 @@ /* companion.py: Frontier CAPI didn't respond; In files: companion.py:226; */ "Error: Frontier CAPI didn't respond" = "Hata: Frontier CAPI yanıt vermedi"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Hata: Frontier sunucusu gecikmesi"; - /* companion.py: Commander is docked at an EDO settlement, got out and back in, we forgot the station; In files: companion.py:261; */ "Docked but unknown station: EDO Settlement?" = "Kenetlendi ancak bilinmeyen istasyon: EDO yerleşimi?"; diff --git a/L10n/uk.strings b/L10n/uk.strings index 23febdef..a8e33f77 100644 --- a/L10n/uk.strings +++ b/L10n/uk.strings @@ -12,9 +12,9 @@ /* companion.py: Frontier CAPI didn't respond; In files: companion.py:226; */ "Error: Frontier CAPI didn't respond" = "Помилка: Frontier CAPI не відповідає"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "Помилка: З`єднання з сервером гри з затримками!"; - /* companion.py: Commander is docked at an EDO settlement, got out and back in, we forgot the station; In files: companion.py:261; */ "Docked but unknown station: EDO Settlement?" = "Пристикований, проте станція невідома: поселення EDO?"; diff --git a/L10n/zh-Hans.strings b/L10n/zh-Hans.strings index 0aee0b8b..b3d47686 100644 --- a/L10n/zh-Hans.strings +++ b/L10n/zh-Hans.strings @@ -1,12 +1,20 @@ +/* edsm.py:Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:316; */ +"Send flight log and CMDR status to EDSM" = "将飞行日志和指挥官状态发送到 EDSM"; + +/* prefs.py:Label on button used to open a filesystem folder; In files: prefs.py:706; */ +"Open Log Folder" = "打开日志文件夹"; + +/* inara.py:Text Inara Show API key; In files: inara.py:305; */ +"Show API Key" = "显示 API 密钥"; /* Language name */ "!Language" = "简体中文"; /* companion.py: Frontier CAPI didn't respond; In files: companion.py:226; */ "Error: Frontier CAPI didn't respond" = "错误:Frontier CAPI 无响应"; + /* companion.py: Frontier CAPI data doesn't agree with latest Journal game location; In files: companion.py:245; */ "Error: Frontier server is lagging" = "错误:Frontier 服务器繁忙"; - /* companion.py: Commander is docked at an EDO settlement, got out and back in, we forgot the station; In files: companion.py:261; */ "Docked but unknown station: EDO Settlement?" = "已靠站但站点未知:可能是 ED: Odyssey 的地面设施?"; @@ -28,6 +36,12 @@ /* companion.py: Failed to get Access Token from Frontier Auth service; In files: companion.py:508; */ "Error: unable to get token" = "错误:无法获取令牌"; +/* EDMarketConnector.py: EDMC Critical Error Notification; */ +"EDMC encountered a critical error, and cannot recover. EDMC is shutting down for its own protection!" = "EDMC 遇到严重错误,无法恢复。 EDMC 正在关闭以保护自身!"; + +/* EDMarketConnector.py: EDMC Critical Error Details; */ +"Here's what EDMC Detected:\r\n\r\n{ERR}\r\n\r\nDo you want to file a Bug Report on GitHub?" = "以下是 EDMC 检测到的错误:\n\n{ERR}\n\n您是否希望在 GitHub 上提交错误报告?"; + /* companion.py: Frontier CAPI returned 418, meaning down for maintenance; In files: companion.py:844; */ "Frontier CAPI down for maintenance" = "Frontier CAPI 下线维护"; @@ -79,6 +93,9 @@ /* EDMarketConnector.py: Help > Check for Updates...; In files: EDMarketConnector.py:930; EDMarketConnector.py:958; */ "Check for Updates..." = "检查版本更新…"; +/* EDMarketConnector.py: Help > Open System Profiler; In files: EDMarketConnector.py:888; */ +"Open System Profiler" = "打开系统分析器"; + /* EDMarketConnector.py: File > Save Raw Data...; In files: EDMarketConnector.py:931; EDMarketConnector.py:948; */ "Save Raw Data..." = "保存原始数据…"; @@ -109,6 +126,15 @@ /* EDMarketConnector.py: Label for 'Copy' as in 'Copy and Paste'; ttkHyperlinkLabel.py: Label for 'Copy' as in 'Copy and Paste'; In files: EDMarketConnector.py:962; ttkHyperlinkLabel.py:53; */ "Copy" = "复制"; +/* myNotebook.py: Label for 'Cut' as in 'Cut and Paste'; */ +"Cut" = "剪切"; + +/* myNotebook.py: Label for 'Paste' as in 'Copy and Paste'; */ +"Paste" = "粘贴"; + +/* myNotebook.py: Label for 'Select All'; */ +"Select All" = "选择全部"; + /* EDMarketConnector.py: CAPI auth aborted because of killswitch; EDMarketConnector.py: CAPI auth query aborted because of killswitch; In files: EDMarketConnector.py:973; EDMarketConnector.py:1067; */ "CAPI auth disabled by killswitch" = "CAPI 验证被 killswitch 禁用"; @@ -151,6 +177,12 @@ /* EDMarketConnector.py: CAPI fleetcarrier query aborted because of killswitch; In files: EDMarketConnector.py:1157; */ "CAPI fleetcarrier disabled by killswitch" = "CAPI 舰队母舰 (fleet carrier) 被 killswitch 禁用"; +/* EDMarketConnector.py: No data was returned for the Fleet Carrier from the Frontier CAPI; In files: EDMarketConnector.py:1219; */ +"CAPI: No Fleet Carrier data returned" = "CAPI: 未接收到舰队母舰的数据"; + +/* EDMarketConnector.py: We didn't have the Fleet Carrier callsign when we should have; In files: EDMarketConnector.py:1223; */ +"CAPI: Fleet Carrier data incomplete" = "CAPI: 舰队航母数据不完整"; + /* EDMarketConnector.py: No data was returned for the commander from the Frontier CAPI; In files: EDMarketConnector.py:1242; */ "CAPI: No commander data returned" = "CAPI:没有指挥官数据"; @@ -199,6 +231,24 @@ /* EDMarketConnector.py: Popup window title for list of 'enabled' plugins that don't work with Python 3.x; In files: EDMarketConnector.py:2274; */ "EDMC: Plugins Without Python 3.x Support" = "EDMC:不支持 Python 3.x 的插件"; +/* EDMarketConnector.py: Popup window title for list of 'broken' plugins that failed to load; In files: EDMarketConnector.py:2285; */ +"EDMC: Broken Plugins" = "EDMC: 损坏的插件"; + +/* EDMarketConnector.py: Popup-text about 'broken' plugins that failed to load; In files: EDMarketConnector.py:2266; */ +"One or more of your enabled plugins failed to load. Please see the list on the '{PLUGINS}' tab of '{FILE}' > '{SETTINGS}'. This could be caused by a wrong folder structure. The load.py file should be located under plugins/PLUGIN_NAME/load.py.\r\n\r\nYou can disable a plugin by renaming its folder to have '{DISABLED}' on the end of the name." = "您启用的一个或多个插件未能加载。请查看 '{FILE}' > '{SETTINGS}' 中的 '{PLUGINS}' 选项卡上的列表。这可能是由于文件夹结构错误导致的。load.py 文件应位于 plugins/插件名称/load.py 路径下。\n\n您可以通过在插件文件夹名称末尾添加 '{DISABLED}' 来禁用该插件。"; + +/* EDMarketConnector.py: Popup-text about Reset Providers; In files: EDMarketConnector.py:2146; */ +"One or more of your URL Providers were invalid, and have been reset:\r\n\r\n" = "您的一个或多个 URL 提供程序无效,已被重置:\n\n"; + +/* EDMarketConnector.py: Text About What Provider Was Reset; In files: EDMarketConnector.py:2148; */ +"{PROVIDER} was set to {OLDPROV}, and has been reset to {NEWPROV}\r\n" = "{PROVIDER} 原设置为 {OLDPROV},现已被重置为 {NEWPROV}\n"; + +/* EDMarketConnector.py: Popup window title for Reset Providers; In files: EDMarketConnector.py:2161; */ +"EDMC: Default Providers Reset" = "EDMC: 默认提供程序已重置"; + +/* EDMarketConnector.py: Await Full CMDR Login to Game; In files: EDMarketConnector.py:813; */ +"Awaiting Full CMDR Login" = "等待指挥官完整登录"; + /* journal_lock.py: Title text on popup when Journal directory already locked; In files: journal_lock.py:208; */ "Journal directory already locked" = "日志目录已被锁定"; @@ -337,6 +387,9 @@ /* prefs.py: Settings > Configuration - Label for CAPI section; In files: prefs.py:469; */ "CAPI Settings" = "CAPI 设置"; +/* prefs.py: Configuration - Enable or disable the Fleet Carrier CAPI calls; In files: prefs.py:475; */ +"Enable Fleet Carrier CAPI Queries" = "启用舰队航母 CAPI 查询"; + /* prefs.py: Hotkey/Shortcut settings prompt on Windows; In files: prefs.py:492; */ "Hotkey" = "快捷键"; @@ -415,6 +468,12 @@ /* prefs.py: Label for location of third-party plugins folder; In files: prefs.py:908; */ "Plugins folder" = "插件文件夹"; +/* prefs.py: Label on button used to open the Plugin Folder; */ +"Open Plugins Folder" = "打开插件目录"; + +/* prefs.py: Selecting the Location of the Plugin Directory on the Filesystem; */ +"Plugin Directory Location" = "插件目录的位置"; + /* prefs.py: Tip/label about how to disable plugins; In files: prefs.py:923; */ "Tip: You can disable a plugin by{CR}adding '{EXT}' to its folder name" = "提示:想要禁用某一项插件,{CR}你可以添加 {EXT} 到其文件夹名称中"; @@ -427,9 +486,15 @@ /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "关于插件迁移"; +/* prefs.py: Plugins - Label for list of 'broken' plugins that failed to load; In files: prefs.py:1039; */ +"Broken Plugins" = "损坏的插件"; + /* prefs.py: Lable on list of user-disabled plugins; In files: prefs.py:977; */ "Disabled Plugins" = "已禁用插件"; +/* prefs.py: Catch & Record Profiler Errors; */ +"Error in System Profiler" = "系统分析器中有错误"; + /* stats.py: Cmdr stats; In files: stats.py:58; */ "Balance" = "资金结余"; @@ -730,3 +795,32 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "所有飞船"; +/* update.py: Update Available Text; In files: update.py:229; */ +"{NEWVER} is available" = "有新的 {NEWVER} 版本可用"; + +/* prefs.py: Stable Version of EDMC; */ +"Stable" = "稳定版"; + +/* prefs.py: Select the Update Track (Beta, Stable); */ +"Update Track" = "更新通道"; + +/* EDMarketConnector.py: Inform the user the Update Track has changed; */ +"Update Track Changed to {TRACK}" = "更新通道已更改为 {TRACK}"; + +/* EDMarketConnector.py: Inform User of Beta -> Stable Transition Risks; */ +"Update track changed to Stable from Beta. You will no longer receive Beta updates. You will stay on your current Beta version until the next Stable release.\r\n\r\nYou can manually revert to the latest Stable version. To do so, you must download and install the latest Stable version manually. Note that this may introduce bugs or break completely if downgrading between major versions with significant changes.\r\n\r\nDo you want to open GitHub to download the latest release?" = "更新通道已从 \\"测试版\\" 更改为 \\"稳定版\\"。您将不再收到 \\"测试版\\" 更新。您将保持在当前的 \\"测试版\\" 版本,直到下一个 \\"稳定版\\" 版本发布。\n\n您可以手动恢复到最新的 \\"稳定版\\" 版本。为此,您必须手动下载并安装最新的 \\"稳定版\\" 版本。请注意,如果在有重大更改的主要版本之间降级,可能会引入错误或完全无法使用。\n\n您是否要打开 GitHub 以下载最新版本?"; + +/* EDMarketConnector.py: Title of Notification Popup for EDMC Restart; */ +"Restart Required" = "需要重新启动"; + +/* EDMarketConnector.py: Text of Notification Popup for EDMC Restart; */ +"A restart of EDMC is required. EDMC will now restart." = "需要重新启动EDMC。EDMC现在将重新启动。"; + +/* myNotebook.py: Can't Paste Images or Files in Text; */ +"Cannot paste non-text content." = "无法添加非文本内容。"; + +/* ttkHyperlinkLabel.py: Open Element In Selected Provider; */ +"Open in {URL}" = "在 {URL} 中打开"; + +/* ttkHyperlinkLabel.py: Copy the Inara SLEF Format of the active ship to the clipboard; */ +"Copy Inara SLEF" = "复制 Inara SLEF 数据"; From ddfc956e34650d547f7922ddef2febfc36d7b4b1 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 9 May 2025 21:25:31 -0400 Subject: [PATCH 62/62] [RELEASE[ 5.13.0 --- ChangeLog.md | 5 ++--- config/__init__.py | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/ChangeLog.md b/ChangeLog.md index 76309944..cb716373 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -6,10 +6,8 @@ This is the master changelog for Elite Dangerous Market Connector. Entries are in the source (not distributed with the Windows installer) for the currently used version. --- -Pre-Release 5.13.0-rc1 +Release 5.13.0-rc1 === -This is a release candidate for 5.13.0. It has been pushed to the "Beta" track for updates! - This release contains a significant refactoring away from ctypes code for interacting with the Windows API, establishment of a Common Code file and plugin, adds a timestamp check to discovered events, and more! @@ -56,6 +54,7 @@ This release also removes the check for WiX-based installer versions of EDMC pri * `help_open_log_folder()` is deprecated, and is slated for removal in 6.0 or later. Please migrate to open_folder() * `update_feed` is deprecated, and is slated for removal in 6.0 or later. Please migrate to `get_update_feed()` + Release 5.12.5 === Well that was certainly something. Happy April! This release removes the April 1 UwUification of EDMC diff --git a/config/__init__.py b/config/__init__.py index b6b8285c..580e68ec 100644 --- a/config/__init__.py +++ b/config/__init__.py @@ -52,7 +52,7 @@ appcmdname = 'EDMC' # # Major.Minor.Patch(-prerelease)(+buildmetadata) # NB: Do *not* import this, use the functions appversion() and appversion_nobuild() -_static_appversion = '5.13.0-rc1' +_static_appversion = '5.13.0' _cached_version: semantic_version.Version | None = None copyright = '© 2015-2019 Jonathan Harris, 2020-2024 EDCD'