From 8839e6d672ece4234a7860e11f260f8b83b690c0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 2 Aug 2023 19:11:36 +0000 Subject: [PATCH 01/83] build(deps-dev): bump flake8 from 6.0.0 to 6.1.0 Bumps [flake8](https://github.com/pycqa/flake8) from 6.0.0 to 6.1.0. - [Commits](https://github.com/pycqa/flake8/compare/6.0.0...6.1.0) --- updated-dependencies: - dependency-name: flake8 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 c2ca4a6b..e7b405cd 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -8,7 +8,7 @@ wheel setuptools==68.0.0 # Static analysis tools -flake8==6.0.0 +flake8==6.1.0 flake8-annotations-coverage==0.0.6 flake8-cognitive-complexity==0.1.0 flake8-comprehensions==3.14.0 From 281c93efe30be5bd3dc1d2f9c798a07c28734ec7 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 6 Aug 2023 01:41:21 -0400 Subject: [PATCH 02/83] #510 Add Log File Opener to Help Menu --- EDMarketConnector.py | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index da7683ee..1fc43cb3 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -13,7 +13,7 @@ import sys import threading import webbrowser from builtins import object, str -from os import chdir, environ +from os import chdir, environ, system from os.path import dirname, join from time import localtime, strftime, time from typing import TYPE_CHECKING, Any, Literal, Optional, Tuple, Union @@ -699,6 +699,7 @@ class AppWindow(object): self.help_menu.add_command(command=lambda: self.updater.check_for_updates()) # Check for Updates... # About E:D Market Connector self.help_menu.add_command(command=lambda: not self.HelpAbout.showing and self.HelpAbout(self.w)) + self.help_menu.add_command(command=self.help_open_log_folder) # Open Log Folder self.menubar.add_cascade(menu=self.help_menu) if sys.platform == 'win32': @@ -935,6 +936,8 @@ class AppWindow(object): self.help_menu.entryconfigure(3, label=_('Report A Bug')) # LANG: Help > Report A Bug self.help_menu.entryconfigure(4, label=_('Privacy Policy')) # LANG: Help > Privacy Policy self.help_menu.entryconfigure(5, label=_('Release Notes')) # LANG: Help > Release Notes + self.help_menu.entryconfigure(6, label=_('Open Log Folder')) # LANG: Help > Open Log Folder + else: self.menubar.entryconfigure(1, label=_('File')) # LANG: 'File' menu title self.menubar.entryconfigure(2, label=_('Edit')) # LANG: 'Edit' menu title @@ -957,6 +960,7 @@ class AppWindow(object): self.help_menu.entryconfigure(4, label=_('Release Notes')) # LANG: Help > Release Notes self.help_menu.entryconfigure(5, label=_('Check for Updates...')) # LANG: Help > Check for Updates... self.help_menu.entryconfigure(6, label=_("About {APP}").format(APP=applongname)) # LANG: Help > About App + self.help_menu.entryconfigure(7, label=_('Open Log Folder')) # LANG: Help > Open Log Folder # Edit menu self.edit_menu.entryconfigure(0, label=_('Copy')) # LANG: Label for 'Copy' as in 'Copy and Paste' @@ -1790,6 +1794,20 @@ class AppWindow(object): webbrowser.open("https://github.com/EDCD/EDMarketConnector/issues/new?assignees=&labels=bug%2C+unconfirmed" "&template=bug_report.md&title=") + def help_open_log_folder(self, event=None) -> None: + """Open the folder logs are stored in.""" + logfile_loc = pathlib.Path(tempfile.gettempdir()) + logfile_loc /= f'{appname}' + if sys.platform.startswith('win'): + # On Windows, use the "start" command to open the folder + system(f'start "" "{logfile_loc}"') + elif sys.platform.startswith('darwin'): + # On macOS, use the "open" command to open the folder + system(f'open "{logfile_loc}"') + elif sys.platform.startswith('linux'): + # On Linux, use the "xdg-open" command to open the folder + system(f'xdg-open "{logfile_loc}"') + def help_privacy(self, event=None) -> None: """Open Wiki Privacy page in browser.""" webbrowser.open('https://github.com/EDCD/EDMarketConnector/wiki/Privacy-Policy') From 0d26fbfe8916d4769c7099454db64372b0085619 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 6 Aug 2023 13:36:05 -0400 Subject: [PATCH 03/83] #510 Add open log folder to prefs menu --- EDMarketConnector.py | 16 +--------------- prefs.py | 27 ++++++++++++++++++++++++++- 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 1fc43cb3..1a9fb1b2 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -699,7 +699,7 @@ class AppWindow(object): self.help_menu.add_command(command=lambda: self.updater.check_for_updates()) # Check for Updates... # About E:D Market Connector self.help_menu.add_command(command=lambda: not self.HelpAbout.showing and self.HelpAbout(self.w)) - self.help_menu.add_command(command=self.help_open_log_folder) # Open Log Folder + self.help_menu.add_command(command=prefs.help_open_log_folder) # Open Log Folder self.menubar.add_cascade(menu=self.help_menu) if sys.platform == 'win32': @@ -1794,20 +1794,6 @@ class AppWindow(object): webbrowser.open("https://github.com/EDCD/EDMarketConnector/issues/new?assignees=&labels=bug%2C+unconfirmed" "&template=bug_report.md&title=") - def help_open_log_folder(self, event=None) -> None: - """Open the folder logs are stored in.""" - logfile_loc = pathlib.Path(tempfile.gettempdir()) - logfile_loc /= f'{appname}' - if sys.platform.startswith('win'): - # On Windows, use the "start" command to open the folder - system(f'start "" "{logfile_loc}"') - elif sys.platform.startswith('darwin'): - # On macOS, use the "open" command to open the folder - system(f'open "{logfile_loc}"') - elif sys.platform.startswith('linux'): - # On Linux, use the "xdg-open" command to open the folder - system(f'xdg-open "{logfile_loc}"') - def help_privacy(self, event=None) -> None: """Open Wiki Privacy page in browser.""" webbrowser.open('https://github.com/EDCD/EDMarketConnector/wiki/Privacy-Policy') diff --git a/prefs.py b/prefs.py index 51c7bc47..034d451e 100644 --- a/prefs.py +++ b/prefs.py @@ -3,9 +3,12 @@ import contextlib import logging +import pathlib import sys +import tempfile import tkinter as tk import webbrowser +from os import system from os.path import expanduser, expandvars, join, normpath from tkinter import colorchooser as tkColorChooser # type: ignore # noqa: N812 from tkinter import ttk @@ -16,12 +19,12 @@ import myNotebook as nb # noqa: N813 import plug from config import applongname, appversion_nobuild, config from EDMCLogging import edmclogger, get_main_logger +from constants import appname from hotkey import hotkeymgr from l10n import Translations from monitor import monitor from theme import theme from ttkHyperlinkLabel import HyperlinkLabel - logger = get_main_logger() if TYPE_CHECKING: @@ -38,6 +41,21 @@ if TYPE_CHECKING: # May be imported by plugins +def help_open_log_folder() -> None: + """Open the folder logs are stored in.""" + logfile_loc = pathlib.Path(tempfile.gettempdir()) + logfile_loc /= f'{appname}' + if sys.platform.startswith('win'): + # On Windows, use the "start" command to open the folder + system(f'start "" "{logfile_loc}"') + elif sys.platform.startswith('darwin'): + # On macOS, use the "open" command to open the folder + system(f'open "{logfile_loc}"') + elif sys.platform.startswith('linux'): + # On Linux, use the "xdg-open" command to open the folder + system(f'xdg-open "{logfile_loc}"') + + class PrefsVersion: """ PrefsVersion contains versioned preferences. @@ -674,6 +692,13 @@ class PreferencesDialog(tk.Toplevel): self.loglevel_dropdown.configure(width=15) self.loglevel_dropdown.grid(column=1, sticky=tk.W, row=cur_row) + nb.Button( + config_frame, + # LANG: Label on button used to open a filesystem folder + text=_('Open Log Folder'), # Button that opens a folder in Explorer/Finder + command=lambda: help_open_log_folder() + ).grid(column=2, padx=(0, self.PADX), sticky=tk.NSEW, row=cur_row) + # Big spacer nb.Label(config_frame).grid(sticky=tk.W, row=row.get()) From 7df1972423d854cae1a254f118b166bd49f9e3da Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sun, 6 Aug 2023 13:44:34 -0400 Subject: [PATCH 04/83] #510 Remove Unused Import --- EDMarketConnector.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 1a9fb1b2..0b457c9c 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -13,7 +13,7 @@ import sys import threading import webbrowser from builtins import object, str -from os import chdir, environ, system +from os import chdir, environ from os.path import dirname, join from time import localtime, strftime, time from typing import TYPE_CHECKING, Any, Literal, Optional, Tuple, Union From 264aaeee6423325e65e4701c5e81a85deb78182d Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Thu, 31 Aug 2023 12:01:17 -0400 Subject: [PATCH 05/83] #1009 Force Latest Winsparkle for Builds --- .github/workflows/windows-build.yml | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/.github/workflows/windows-build.yml b/.github/workflows/windows-build.yml index eaf29244..695a9bbf 100644 --- a/.github/workflows/windows-build.yml +++ b/.github/workflows/windows-build.yml @@ -103,11 +103,18 @@ jobs: pip install wheel pip install -r requirements-dev.txt - - name: Download winsparkle + - name: Download latest WinSparkle release run: | - Invoke-Webrequest -UseBasicParsing https://github.com/vslavik/winsparkle/releases/download/v0.8.0/WinSparkle-0.8.0.zip -OutFile out.zip - Expand-Archive out.zip - Move-Item 'out\WinSparkle-0.8.0\Release\*' '.\' + $url = "https://api.github.com/repos/vslavik/winsparkle/releases/latest" + $response = Invoke-RestMethod -Uri $url + $latestAsset = $response.assets | Where-Object { $_.name -match "WinSparkle.*\.zip" -and $_.name -notmatch "-src" } + + $downloadUrl = $latestAsset.browser_download_url + Invoke-WebRequest -Uri $downloadUrl -OutFile WinSparkle-Latest.zip + + Expand-Archive -Path WinSparkle-Latest.zip -DestinationPath . + $extractedFolder = Get-ChildItem -Filter "WinSparkle-*" -Directory + Move-Item -Path "$($extractedFolder.FullName)\Release\*" -Destination . - name: Build EDMC run: | From 233a3a9fac15d85698e1c4b83885a45b1f0ded2e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 1 Sep 2023 17:30:28 +0000 Subject: [PATCH 06/83] build(deps-dev): bump autopep8 from 2.0.2 to 2.0.4 Bumps [autopep8](https://github.com/hhatto/autopep8) from 2.0.2 to 2.0.4. - [Release notes](https://github.com/hhatto/autopep8/releases) - [Commits](https://github.com/hhatto/autopep8/compare/v2.0.2...v2.0.4) --- updated-dependencies: - dependency-name: autopep8 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 e7b405cd..2c1c36c8 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -25,7 +25,7 @@ types-requests==2.31.0.2 types-pkg-resources==0.1.3 # Code formatting tools -autopep8==2.0.2 +autopep8==2.0.4 # Git pre-commit checking pre-commit==3.3.3 From 02f62b8ee6824832ca4032a769c5c3f00a4ae610 Mon Sep 17 00:00:00 2001 From: Philipp Trulson Date: Mon, 18 Sep 2023 22:48:00 +0200 Subject: [PATCH 07/83] Fix Inara URLs for station & system search --- plugins/inara.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/plugins/inara.py b/plugins/inara.py index 7f7abbd1..d50c2e6d 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -171,11 +171,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}') elif 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 '' @@ -192,12 +192,12 @@ 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/' + return requests.utils.requote_uri(f'https://inara.cz/elite/station/' f'?search={system_name}%20[{station_name}]') # monitor state might think these are gone, but we don't yet if this.system_name and this.station: - return requests.utils.requote_uri(f'https://inara.cz/galaxy-station/' + return requests.utils.requote_uri(f'https://inara.cz/elite/station/' f'?search={this.system_name}%20[{this.station}]') if system_name: From 3b663c18ff466dc66297290ddbd8d17e906ed4ec Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 1 Oct 2023 17:22:33 +0000 Subject: [PATCH 08/83] build(deps): bump actions/checkout from 3 to 4 Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v3...v4) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/pr-checks.yml | 2 +- .github/workflows/push-checks.yml | 2 +- .github/workflows/submodule-update.yml | 2 +- .github/workflows/windows-build.yml | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 8547540a..ea9a3093 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -28,7 +28,7 @@ jobs: # based on. - name: Checkout head commits # https://github.com/actions/checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 #with: #ref: ${{github.head.sha}} #repository: ${{github.event.pull_request.head.repo.full_name}} diff --git a/.github/workflows/push-checks.yml b/.github/workflows/push-checks.yml index 07f45e75..803bfe95 100644 --- a/.github/workflows/push-checks.yml +++ b/.github/workflows/push-checks.yml @@ -22,7 +22,7 @@ jobs: runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: fetch-depth: 0 - name: Set up Python diff --git a/.github/workflows/submodule-update.yml b/.github/workflows/submodule-update.yml index 61b4da3b..17301d66 100644 --- a/.github/workflows/submodule-update.yml +++ b/.github/workflows/submodule-update.yml @@ -17,7 +17,7 @@ jobs: OWNER: 'EDCD' steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: ref: '${{ env.CHECKOUT_BRANCH }}' submodules: true diff --git a/.github/workflows/windows-build.yml b/.github/workflows/windows-build.yml index 695a9bbf..7f465497 100644 --- a/.github/workflows/windows-build.yml +++ b/.github/workflows/windows-build.yml @@ -26,7 +26,7 @@ jobs: name: Linux environment build steps runs-on: "ubuntu-latest" steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: true @@ -70,7 +70,7 @@ jobs: shell: powershell steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: true From 79233ef808d075bb34694a1f49aec2082c580111 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 1 Oct 2023 17:25:56 +0000 Subject: [PATCH 09/83] build(deps-dev): bump setuptools from 68.0.0 to 68.2.2 Bumps [setuptools](https://github.com/pypa/setuptools) from 68.0.0 to 68.2.2. - [Release notes](https://github.com/pypa/setuptools/releases) - [Changelog](https://github.com/pypa/setuptools/blob/main/NEWS.rst) - [Commits](https://github.com/pypa/setuptools/compare/v68.0.0...v68.2.2) --- updated-dependencies: - dependency-name: setuptools 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 e7b405cd..f68ab5dc 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -5,7 +5,7 @@ wheel # We can't rely on just picking this up from either the base (not venv), # or venv-init-time version. Specify here so that dependabot will prod us # about new versions. -setuptools==68.0.0 +setuptools==68.2.2 # Static analysis tools flake8==6.1.0 From 2c803d7f4cb0146d11ec3cf512004f3e2bfc84fd Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Thu, 19 Oct 2023 17:44:33 -0400 Subject: [PATCH 10/83] [2051] Core Plugin Audit Broken out of #2068 --- plugins/coriolis.py | 189 ++++++++++---------- plugins/eddn.py | 211 +++++++++++------------ plugins/edsm.py | 327 ++++++++++++++--------------------- plugins/edsy.py | 62 ++++--- plugins/inara.py | 409 +++++++++++++++++++++----------------------- 5 files changed, 545 insertions(+), 653 deletions(-) diff --git a/plugins/coriolis.py b/plugins/coriolis.py index 9dae230d..7161a4e0 100644 --- a/plugins/coriolis.py +++ b/plugins/coriolis.py @@ -1,86 +1,86 @@ -"""Coriolis ship export.""" +""" +coriolis.py - Coriolis Ship Export. + +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. +""" -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# -# -# 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` SO AS TO ENSURE THE FILES ARE ACTUALLY PRESENT -# IN AN END-USER INSTALLATION ON WINDOWS. -# -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# import base64 import gzip import io import json import tkinter as tk from tkinter import ttk -from typing import TYPE_CHECKING, Union - +from typing import TYPE_CHECKING, Union, Optional import myNotebook as nb # noqa: N813 # its not my fault. from EDMCLogging import get_main_logger from plug import show_error +from config import config if TYPE_CHECKING: def _(s: str) -> str: ... -# Migrate settings from <= 3.01 -from config import config -if not config.get_str('shipyard_provider') and config.get_int('shipyard'): - config.set('shipyard_provider', 'Coriolis') +class CoriolisConfig: + """Coriolis Configuration.""" -config.delete('shipyard', suppress=True) + def __init__(self): + self.normal_url = '' + self.beta_url = '' + self.override_mode = '' + self.normal_textvar = tk.StringVar() + self.beta_textvar = tk.StringVar() + self.override_textvar = tk.StringVar() + + def initialize_urls(self): + """Initialize Coriolis URLs and override mode from configuration.""" + self.normal_url = config.get_str('coriolis_normal_url', default=DEFAULT_NORMAL_URL) + self.beta_url = config.get_str('coriolis_beta_url', default=DEFAULT_BETA_URL) + self.override_mode = config.get_str('coriolis_overide_url_selection', default=DEFAULT_OVERRIDE_MODE) + + self.normal_textvar.set(value=self.normal_url) + self.beta_textvar.set(value=self.beta_url) + self.override_textvar.set( + value={ + 'auto': _('Auto'), # LANG: 'Auto' label for Coriolis site override selection + 'normal': _('Normal'), # LANG: 'Normal' label for Coriolis site override selection + 'beta': _('Beta') # LANG: 'Beta' label for Coriolis site override selection + }.get(self.override_mode, _('Auto')) # LANG: 'Auto' label for Coriolis site override selection + ) + + +coriolis_config = CoriolisConfig() logger = get_main_logger() DEFAULT_NORMAL_URL = 'https://coriolis.io/import?data=' DEFAULT_BETA_URL = 'https://beta.coriolis.io/import?data=' DEFAULT_OVERRIDE_MODE = 'auto' -normal_url = '' -beta_url = '' -override_mode = '' - -normal_textvar = tk.StringVar() -beta_textvar = tk.StringVar() -override_textvar = tk.StringVar() # This will always contain a _localised_ version - def plugin_start3(path: str) -> str: """Set up URLs.""" - global normal_url, beta_url, override_mode - normal_url = config.get_str('coriolis_normal_url', default=DEFAULT_NORMAL_URL) - beta_url = config.get_str('coriolis_beta_url', default=DEFAULT_BETA_URL) - override_mode = config.get_str('coriolis_overide_url_selection', default=DEFAULT_OVERRIDE_MODE) - - normal_textvar.set(value=normal_url) - beta_textvar.set(value=beta_url) - override_textvar.set( - value={ - 'auto': _('Auto'), # LANG: 'Auto' label for Coriolis site override selection - 'normal': _('Normal'), # LANG: 'Normal' label for Coriolis site override selection - 'beta': _('Beta') # LANG: 'Beta' label for Coriolis site override selection - }.get(override_mode, _('Auto')) # LANG: 'Auto' label for Coriolis site override selection - ) - + coriolis_config.initialize_urls() return 'Coriolis' -def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Frame: +def plugin_prefs(parent: ttk.Notebook, cmdr: Optional[str], is_beta: bool) -> tk.Frame: """Set up plugin preferences.""" PADX = 10 # noqa: N806 @@ -95,18 +95,21 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr # LANG: Settings>Coriolis: Label for 'NOT alpha/beta game version' URL nb.Label(conf_frame, text=_('Normal URL')).grid(sticky=tk.W, row=cur_row, column=0, padx=PADX) - nb.Entry(conf_frame, textvariable=normal_textvar).grid(sticky=tk.EW, row=cur_row, column=1, padx=PADX) + nb.Entry(conf_frame, + textvariable=coriolis_config.normal_textvar).grid(sticky=tk.EW, row=cur_row, column=1, padx=PADX) # LANG: Generic 'Reset' button label - nb.Button(conf_frame, text=_("Reset"), command=lambda: normal_textvar.set(value=DEFAULT_NORMAL_URL)).grid( + nb.Button(conf_frame, text=_("Reset"), + command=lambda: coriolis_config.normal_textvar.set(value=DEFAULT_NORMAL_URL)).grid( sticky=tk.W, row=cur_row, column=2, padx=PADX ) cur_row += 1 # LANG: Settings>Coriolis: Label for 'alpha/beta game version' URL nb.Label(conf_frame, text=_('Beta URL')).grid(sticky=tk.W, row=cur_row, column=0, padx=PADX) - nb.Entry(conf_frame, textvariable=beta_textvar).grid(sticky=tk.EW, row=cur_row, column=1, padx=PADX) + nb.Entry(conf_frame, textvariable=coriolis_config.beta_textvar).grid(sticky=tk.EW, row=cur_row, column=1, padx=PADX) # LANG: Generic 'Reset' button label - nb.Button(conf_frame, text=_('Reset'), command=lambda: beta_textvar.set(value=DEFAULT_BETA_URL)).grid( + nb.Button(conf_frame, text=_('Reset'), + command=lambda: coriolis_config.beta_textvar.set(value=DEFAULT_BETA_URL)).grid( sticky=tk.W, row=cur_row, column=2, padx=PADX ) cur_row += 1 @@ -116,8 +119,8 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr nb.Label(conf_frame, text=_('Override Beta/Normal Selection')).grid(sticky=tk.W, row=cur_row, column=0, padx=PADX) nb.OptionMenu( conf_frame, - override_textvar, - override_textvar.get(), + coriolis_config.override_textvar, + coriolis_config.override_textvar.get(), _('Normal'), # LANG: 'Normal' label for Coriolis site override selection _('Beta'), # LANG: 'Beta' label for Coriolis site override selection _('Auto') # LANG: 'Auto' label for Coriolis site override selection @@ -127,50 +130,49 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr return conf_frame -def prefs_changed(cmdr: str | None, is_beta: bool) -> None: - """Update URLs.""" - global normal_url, beta_url, override_mode - normal_url = normal_textvar.get() - beta_url = beta_textvar.get() - override_mode = override_textvar.get() - override_mode = { # Convert to unlocalised names +def prefs_changed(cmdr: Optional[str], is_beta: bool) -> None: + """ + Update URLs and override mode based on user preferences. + + :param cmdr: Commander name, if available + :param is_beta: Whether the game mode is beta + """ + coriolis_config.normal_url = coriolis_config.normal_textvar.get() + coriolis_config.beta_url = coriolis_config.beta_textvar.get() + coriolis_config.override_mode = coriolis_config.override_textvar.get() + + # Convert to unlocalised names + coriolis_config.override_mode = { _('Normal'): 'normal', # LANG: Coriolis normal/beta selection - normal - _('Beta'): 'beta', # LANG: Coriolis normal/beta selection - beta - _('Auto'): 'auto', # LANG: Coriolis normal/beta selection - auto - }.get(override_mode, override_mode) + _('Beta'): 'beta', # LANG: Coriolis normal/beta selection - beta + _('Auto'): 'auto', # LANG: Coriolis normal/beta selection - auto + }.get(coriolis_config.override_mode, coriolis_config.override_mode) - if override_mode not in ('beta', 'normal', 'auto'): - logger.warning(f'Unexpected value {override_mode=!r}. defaulting to "auto"') - override_mode = 'auto' - override_textvar.set(value=_('Auto')) # LANG: 'Auto' label for Coriolis site override selection + if coriolis_config.override_mode not in ('beta', 'normal', 'auto'): + logger.warning(f'Unexpected value {coriolis_config.override_mode=!r}. Defaulting to "auto"') + coriolis_config.override_mode = 'auto' + coriolis_config.override_textvar.set(value=_('Auto')) # LANG: 'Auto' label for Coriolis site override selection - config.set('coriolis_normal_url', normal_url) - config.set('coriolis_beta_url', beta_url) - config.set('coriolis_overide_url_selection', override_mode) + config.set('coriolis_normal_url', coriolis_config.normal_url) + config.set('coriolis_beta_url', coriolis_config.beta_url) + config.set('coriolis_overide_url_selection', coriolis_config.override_mode) def _get_target_url(is_beta: bool) -> str: - global override_mode - if override_mode not in ('auto', 'normal', 'beta'): + if coriolis_config.override_mode not in ('auto', 'normal', 'beta'): # LANG: Settings>Coriolis - invalid override mode found show_error(_('Invalid Coriolis override mode!')) - logger.warning(f'Unexpected override mode {override_mode!r}! defaulting to auto!') - override_mode = 'auto' - - if override_mode == 'beta': - return beta_url - - elif override_mode == 'normal': - return normal_url - + logger.warning(f'Unexpected override mode {coriolis_config.override_mode!r}! defaulting to auto!') + coriolis_config.override_mode = 'auto' + if coriolis_config.override_mode == 'beta': + return coriolis_config.beta_url + if coriolis_config.override_mode == 'normal': + return coriolis_config.normal_url # Must be auto if is_beta: - return beta_url + return coriolis_config.beta_url - return normal_url - -# to anyone reading this, no, this is NOT the correct return type. Its magic internal stuff that I WILL be changing -# some day. Check PLUGINS.md for the right way to do this. -A_D + return coriolis_config.normal_url def shipyard_url(loadout, is_beta) -> Union[str, bool]: @@ -179,11 +181,8 @@ def shipyard_url(loadout, is_beta) -> Union[str, bool]: 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 diff --git a/plugins/eddn.py b/plugins/eddn.py index 25033c48..d2e7d01e 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -1,26 +1,23 @@ -"""Handle exporting data to EDDN.""" +""" +eddn.py - Exporting Data to EDDN. -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# -# -# 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` SO AS TO ENSURE THE FILES ARE ACTUALLY PRESENT -# IN AN END-USER INSTALLATION ON WINDOWS. -# -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# +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. +""" import http import itertools import json @@ -34,12 +31,19 @@ from collections import OrderedDict from platform import system from textwrap import dedent from threading import Lock -from typing import TYPE_CHECKING, Any, Iterator, Mapping, MutableMapping, Optional +from typing import ( + TYPE_CHECKING, + Any, + Iterator, + Mapping, + MutableMapping, + Optional, + Dict, + List, +) from typing import OrderedDict as OrderedDictT from typing import Tuple, Union - import requests - import companion import edmc_data import killswitch @@ -88,21 +92,21 @@ class This: self.body_name: Optional[str] = None self.body_id: Optional[int] = None self.body_type: Optional[int] = None - self.station_name: str | None = None - self.station_type: str | None = None - self.station_marketid: str | None = None + self.station_name: Optional[str] = None + self.station_type: Optional[str] = None + self.station_marketid: Optional[str] = None # Track Status.json data self.status_body_name: Optional[str] = None # Avoid duplicates self.marketId: Optional[str] = None - self.commodities: Optional[list[OrderedDictT[str, Any]]] = None - self.outfitting: Optional[Tuple[bool, list[str]]] = None - self.shipyard: Optional[Tuple[bool, list[Mapping[str, Any]]]] = None + self.commodities: Optional[List[OrderedDictT[str, Any]]] = None + self.outfitting: Optional[Tuple[bool, List[str]]] = None + self.shipyard: Optional[Tuple[bool, List[Mapping[str, Any]]]] = None self.fcmaterials_marketid: int = 0 - self.fcmaterials: Optional[list[OrderedDictT[str, Any]]] = None + self.fcmaterials: Optional[List[OrderedDictT[str, Any]]] = None self.fcmaterials_capi_marketid: int = 0 - self.fcmaterials_capi: Optional[list[OrderedDictT[str, Any]]] = None + self.fcmaterials_capi: Optional[List[OrderedDictT[str, Any]]] = None # For the tkinter parent window, so we can call update_idletasks() self.parent: tk.Tk @@ -156,7 +160,7 @@ class EDDNSender: UNKNOWN_SCHEMA_RE = re.compile( r"^FAIL: \[JsonValidationException\('Schema " r"https://eddn.edcd.io/schemas/(?P.+)/(?P[0-9]+) is unknown, " - r"unable to validate.',\)\]$" + r"unable to validate.',\)]$" ) def __init__(self, eddn: 'EDDN', eddn_endpoint: str) -> None: @@ -203,10 +207,8 @@ class EDDNSender: db = db_conn.cursor() try: - db.execute( - """ - CREATE TABLE messages - ( + db.execute(""" + CREATE TABLE IF NOT EXISTS messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, created TEXT NOT NULL, cmdr TEXT NOT NULL, @@ -215,26 +217,12 @@ class EDDNSender: game_build TEXT, message TEXT NOT NULL ) - """ - ) + """) - db.execute( - """ - CREATE INDEX messages_created ON messages - ( - created - ) - """ - ) + db.execute("CREATE INDEX IF NOT EXISTS messages_created ON messages (created)") + db.execute("CREATE INDEX IF NOT EXISTS messages_cmdr ON messages (cmdr)") - db.execute( - """ - CREATE INDEX messages_cmdr ON messages - ( - cmdr - ) - """ - ) + logger.info("New 'eddn_queue-v1.db' created") except sqlite3.OperationalError as e: if str(e) != "table messages already exists": @@ -243,12 +231,6 @@ class EDDNSender: db_conn.close() raise e - else: - logger.info("New `eddn_queue-v1.db` created") - - # We return only the connection, so tidy up - db.close() - return db_conn def convert_legacy_file(self): @@ -264,11 +246,10 @@ class EDDNSender: except FileNotFoundError: return + logger.info("Conversion to `eddn_queue-v1.db` complete, removing `replay.jsonl`") # Best effort at removing the file/contents - # NB: The legacy code assumed it could write to the file. - logger.info("Conversion` to `eddn_queue-v1.db` complete, removing `replay.jsonl`") - replay_file = open(filename, 'w') # Will truncate - replay_file.close() + with open(filename, 'w') as replay_file: + replay_file.truncate() os.unlink(filename) def close(self) -> None: @@ -414,7 +395,7 @@ class EDDNSender: """ logger.trace_if("plugin.eddn.send", "Sending message") should_return: bool - new_data: dict[str, Any] + new_data: Dict[str, Any] should_return, new_data = killswitch.check_killswitch('plugins.eddn.send', json.loads(msg)) if should_return: @@ -423,7 +404,7 @@ class EDDNSender: # Even the smallest possible message compresses somewhat, so always compress encoded, compressed = text.gzip(json.dumps(new_data, separators=(',', ':')), max_size=0) - headers: None | dict[str, str] = None + headers: Optional[Dict[str, str]] = None if compressed: headers = {'Content-Encoding': 'gzip'} @@ -454,14 +435,13 @@ class EDDNSender: # This dropping is to cater for the time period when EDDN doesn't *yet* support a new schema. return True - elif e.response.status_code == http.HTTPStatus.BAD_REQUEST: + if e.response.status_code == http.HTTPStatus.BAD_REQUEST: # EDDN straight up says no, so drop the message logger.debug(f"EDDN responded '400 Bad Request' to the message, dropping:\n{msg!r}") return True - else: - # This should catch anything else, e.g. timeouts, gateway errors - self.set_ui_status(self.http_error_to_log(e)) + # This should catch anything else, e.g. timeouts, gateway errors + self.set_ui_status(self.http_error_to_log(e)) except requests.exceptions.RequestException as e: logger.debug('Failed sending', exc_info=e) @@ -485,19 +465,26 @@ class EDDNSender: if not self.queue_processing.acquire(blocking=False): logger.trace_if("plugin.eddn.send", "Couldn't obtain mutex") if reschedule: - logger.trace_if("plugin.eddn.send", f"Next run scheduled for {self.eddn.REPLAY_PERIOD}ms from now") - self.eddn.parent.after(self.eddn.REPLAY_PERIOD, self.queue_check_and_send, reschedule) + logger.trace_if( + "plugin.eddn.send", + f"Next run scheduled for {self.eddn.REPLAY_PERIOD}ms from now", + ) + self.eddn.parent.after( + self.eddn.REPLAY_PERIOD, self.queue_check_and_send, reschedule + ) else: - logger.trace_if("plugin.eddn.send", "NO next run scheduled (there should be another one already set)") + logger.trace_if( + "plugin.eddn.send", + "NO next run scheduled (there should be another one already set)", + ) return - logger.trace_if("plugin.eddn.send", "Obtained mutex") # Used to indicate if we've rescheduled at the faster rate already. have_rescheduled = False # We send either if docked or 'Delay sending until docked' not set - if this.docked or not (config.get_int('output') & config.OUT_EDDN_DELAY): + if this.docked or not config.get_int('output') & config.OUT_EDDN_DELAY: logger.trace_if("plugin.eddn.send", "Should send") # We need our own cursor here, in case the semantics of # tk `after()` could allow this to run in the middle of other @@ -516,7 +503,7 @@ class EDDNSender: db_cursor.execute( """ SELECT id FROM messages - ORDER BY created ASC + ORDER BY created LIMIT 1 """ ) @@ -586,16 +573,15 @@ class EDDNSender: # LANG: EDDN has banned this version of our client return _('EDDN Error: EDMC is too old for EDDN. Please update.') - elif status_code == 400: + if status_code == 400: # we a validation check or something else. logger.warning(f'EDDN Error: {status_code} -- {exception.response}') # LANG: EDDN returned an error that indicates something about what we sent it was wrong return _('EDDN Error: Validation Failed (EDMC Too Old?). See Log') - else: - logger.warning(f'Unknown status code from EDDN: {status_code} -- {exception.response}') - # LANG: EDDN returned some sort of HTTP error, one we didn't expect. {STATUS} contains a number - return _('EDDN Error: Returned {STATUS} status code').format(STATUS=status_code) + logger.warning(f'Unknown status code from EDDN: {status_code} -- {exception.response}') + # LANG: EDDN returned some sort of HTTP error, one we didn't expect. {STATUS} contains a number + return _('EDDN Error: Returned {STATUS} status code').format(STATUS=status_code) # TODO: a good few of these methods are static or could be classmethods. they should be created as such. @@ -626,7 +612,7 @@ class EDDN: self.sender = EDDNSender(self, self.eddn_url) - self.fss_signals: list[Mapping[str, Any]] = [] + self.fss_signals: List[Mapping[str, Any]] = [] def close(self): """Close down the EDDN class instance.""" @@ -650,7 +636,7 @@ class EDDN: :param is_beta: whether or not we're currently in beta mode """ should_return: bool - new_data: dict[str, Any] + new_data: Dict[str, Any] should_return, new_data = killswitch.check_killswitch('capi.request./market', {}) if should_return: logger.warning("capi.request./market has been disabled by killswitch. Returning.") @@ -667,7 +653,7 @@ class EDDN: modules, ships ) - commodities: list[OrderedDictT[str, Any]] = [] + commodities: List[OrderedDictT[str, Any]] = [] for commodity in data['lastStarport'].get('commodities') or []: # Check 'marketable' and 'not prohibited' if (category_map.get(commodity['categoryname'], True) @@ -740,7 +726,7 @@ class EDDN: :param data: The raw CAPI data. :return: Sanity-checked data. """ - modules: dict[str, Any] = data['lastStarport'].get('modules') + modules: Dict[str, Any] = data['lastStarport'].get('modules') if modules is None or not isinstance(modules, dict): if modules is None: logger.debug('modules was None. FC or Damaged Station?') @@ -757,7 +743,7 @@ class EDDN: # Set a safe value modules = {} - ships: dict[str, Any] = data['lastStarport'].get('ships') + ships: Dict[str, Any] = data['lastStarport'].get('ships') if ships is None or not isinstance(ships, dict): if ships is None: logger.debug('ships was None') @@ -783,7 +769,7 @@ class EDDN: :param is_beta: whether or not we're currently in beta mode """ should_return: bool - new_data: dict[str, Any] + new_data: Dict[str, Any] should_return, new_data = killswitch.check_killswitch('capi.request./shipyard', {}) if should_return: logger.warning("capi.request./shipyard has been disabled by killswitch. Returning.") @@ -810,7 +796,7 @@ class EDDN: modules.values() ) - outfitting: list[str] = sorted( + outfitting: List[str] = sorted( self.MODULE_RE.sub(lambda match: match.group(0).capitalize(), mod['name'].lower()) for mod in to_search ) @@ -851,7 +837,7 @@ class EDDN: :param is_beta: whether or not we are in beta mode """ should_return: bool - new_data: dict[str, Any] + new_data: Dict[str, Any] should_return, new_data = killswitch.check_killswitch('capi.request./shipyard', {}) if should_return: logger.warning("capi.request./shipyard has been disabled by killswitch. Returning.") @@ -870,7 +856,7 @@ class EDDN: ships ) - shipyard: list[Mapping[str, Any]] = sorted( + shipyard: List[Mapping[str, Any]] = sorted( itertools.chain( (ship['name'].lower() for ship in (ships['shipyard_list'] or {}).values()), (ship['name'].lower() for ship in ships['unavailable_list'] or {}), @@ -913,8 +899,8 @@ class EDDN: :param is_beta: whether or not we're in beta mode :param entry: the journal entry containing the commodities data """ - items: list[Mapping[str, Any]] = entry.get('Items') or [] - commodities: list[OrderedDictT[str, Any]] = sorted((OrderedDict([ + items: List[Mapping[str, Any]] = entry.get('Items') or [] + commodities: List[OrderedDictT[str, Any]] = sorted((OrderedDict([ ('name', self.canonicalise(commodity['Name'])), ('meanPrice', commodity['MeanPrice']), ('buyPrice', commodity['BuyPrice']), @@ -961,11 +947,11 @@ class EDDN: :param is_beta: Whether or not we're in beta mode :param entry: The relevant journal entry """ - modules: list[Mapping[str, Any]] = entry.get('Items', []) + modules: List[Mapping[str, Any]] = entry.get('Items', []) horizons: bool = entry.get('Horizons', False) # outfitting = sorted([self.MODULE_RE.sub(lambda m: m.group(0).capitalize(), module['Name']) # for module in modules if module['Name'] != 'int_planetapproachsuite']) - outfitting: list[str] = sorted( + outfitting: List[str] = sorted( self.MODULE_RE.sub(lambda m: m.group(0).capitalize(), mod['Name']) for mod in filter(lambda m: m['Name'] != 'int_planetapproachsuite', modules) ) @@ -1000,7 +986,7 @@ class EDDN: :param is_beta: Whether or not we're in beta mode :param entry: the relevant journal entry """ - ships: list[Mapping[str, Any]] = entry.get('PriceList') or [] + ships: List[Mapping[str, Any]] = entry.get('PriceList') or [] horizons: bool = entry.get('Horizons', False) shipyard = sorted(ship['ShipType'] for ship in ships) # Don't send empty ships list - shipyard data is only guaranteed present if user has visited the shipyard. @@ -1050,7 +1036,7 @@ class EDDN: msg['header'] = self.standard_header() msg_id = self.sender.add_message(cmdr, msg) - if this.docked or not (config.get_int('output') & config.OUT_EDDN_DELAY): + if this.docked or not config.get_int('output') & config.OUT_EDDN_DELAY: # No delay in sending configured, so attempt immediately logger.trace_if("plugin.eddn.send", "Sending 'non-station' message") self.sender.send_message_by_id(msg_id) @@ -1123,8 +1109,7 @@ class EDDN: logger.warning(f'No system name in entry, and system_name was not set either! entry:\n{entry!r}\n') return "passed-in system_name is empty, can't add System" - else: - entry['StarSystem'] = system_name + entry['StarSystem'] = system_name if 'SystemAddress' not in entry: if this.system_address is None: @@ -1918,7 +1903,7 @@ class EDDN: gv = '' ####################################################################### # Base string - if capi_host == companion.SERVER_LIVE or capi_host == companion.SERVER_BETA: + if capi_host in (companion.SERVER_LIVE, companion.SERVER_BETA): gv = 'CAPI-Live-' elif capi_host == companion.SERVER_LEGACY: @@ -2107,7 +2092,7 @@ def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: BUTTONX = 12 # noqa: N806 # indent Checkbuttons and Radiobuttons 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 + output: int = config.OUT_EDDN_SEND_STATION_DATA | config.OUT_EDDN_SEND_NON_STATION # default settings else: output = config.get_int('output') @@ -2167,7 +2152,7 @@ def prefsvarchanged(event=None) -> None: this.eddn_system_button['state'] = tk.NORMAL # This line will grey out the 'Delay sending ...' option if the 'Send # system and scan data' option is off. - this.eddn_delay_button['state'] = this.eddn_system.get() and tk.NORMAL or tk.DISABLED + this.eddn_delay_button['state'] = tk.NORMAL if this.eddn_system.get() else tk.DISABLED def prefs_changed(cmdr: str, is_beta: bool) -> None: @@ -2324,22 +2309,22 @@ def journal_entry( # noqa: C901, CCR001 if event_name == 'fssdiscoveryscan': return this.eddn.export_journal_fssdiscoveryscan(cmdr, system, state['StarPos'], is_beta, entry) - elif event_name == 'navbeaconscan': + if event_name == 'navbeaconscan': return this.eddn.export_journal_navbeaconscan(cmdr, system, state['StarPos'], is_beta, entry) - elif event_name == 'codexentry': + if event_name == 'codexentry': return this.eddn.export_journal_codexentry(cmdr, state['StarPos'], is_beta, entry) - elif event_name == 'scanbarycentre': + if event_name == 'scanbarycentre': return this.eddn.export_journal_scanbarycentre(cmdr, state['StarPos'], is_beta, entry) - elif event_name == 'navroute': + if event_name == 'navroute': return this.eddn.export_journal_navroute(cmdr, is_beta, entry) - elif event_name == 'fcmaterials': + if event_name == 'fcmaterials': return this.eddn.export_journal_fcmaterials(cmdr, is_beta, entry) - elif event_name == 'approachsettlement': + if event_name == 'approachsettlement': # An `ApproachSettlement` can appear *before* `Location` if you # logged at one. We won't have necessary augmentation data # at this point, so bail. @@ -2354,10 +2339,10 @@ def journal_entry( # noqa: C901, CCR001 entry ) - elif event_name == 'fsssignaldiscovered': + if event_name == 'fsssignaldiscovered': this.eddn.enqueue_journal_fsssignaldiscovered(entry) - elif event_name == 'fssallbodiesfound': + if event_name == 'fssallbodiesfound': return this.eddn.export_journal_fssallbodiesfound( cmdr, system, @@ -2366,7 +2351,7 @@ def journal_entry( # noqa: C901, CCR001 entry ) - elif event_name == 'fssbodysignals': + if event_name == 'fssbodysignals': return this.eddn.export_journal_fssbodysignals( cmdr, system, @@ -2626,7 +2611,7 @@ def capi_is_horizons(economies: MAP_STR_ANY, modules: MAP_STR_ANY, ships: MAP_ST return economies_colony or modules_horizons or ship_horizons -def dashboard_entry(cmdr: str, is_beta: bool, entry: dict[str, Any]) -> None: +def dashboard_entry(cmdr: str, is_beta: bool, entry: Dict[str, Any]) -> None: """ Process Status.json data to track things like current Body. diff --git a/plugins/edsm.py b/plugins/edsm.py index 9f2602b6..2f644dcb 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -1,36 +1,23 @@ -"""Show EDSM data in display and handle lookups.""" +""" +edsm.py - Handling EDSM Data and Display. -# TODO: -# 1) Re-factor EDSM API calls out of journal_entry() into own function. -# 2) Fix how StartJump already changes things, but only partially. -# 3) Possibly this and other two 'provider' plugins could do with being -# based on a single class that they extend. There's a lot of duplicated -# logic. -# 4) Ensure the EDSM API call(back) for setting the image at end of system -# text is always fired. i.e. CAPI cmdr_data() processing. +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` SO AS TO ENSURE THE FILES ARE ACTUALLY PRESENT IN -# AN END-USER INSTALLATION ON WINDOWS. -# -# -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# +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. +""" import json import threading import tkinter as tk @@ -40,12 +27,9 @@ from threading import Thread from time import sleep from tkinter import ttk from typing import TYPE_CHECKING, Any, Dict, List, Literal, Mapping, MutableMapping, Optional, Set, Tuple, Union, cast - import requests - import killswitch import monitor -import myNotebook import myNotebook as nb # noqa: N813 import plug from companion import CAPIData @@ -58,6 +42,15 @@ if TYPE_CHECKING: def _(x: str) -> str: return x +# TODO: +# 1) Re-factor EDSM API calls out of journal_entry() into own function. +# 2) Fix how StartJump already changes things, but only partially. +# 3) Possibly this and other two 'provider' plugins could do with being +# based on a single class that they extend. There's a lot of duplicated +# logic. +# 4) Ensure the EDSM API call(back) for setting the image at end of system +# text is always fired. i.e. CAPI cmdr_data() processing. + logger = get_main_logger() EDSM_POLL = 0.1 @@ -93,13 +86,13 @@ class This: self.newgame: bool = False # starting up - batch initial burst of events self.newgame_docked: bool = False # starting up while docked self.navbeaconscan: int = 0 # batch up burst of Scan events after NavBeaconScan - self.system_link: tk.Widget | None = None - self.system_name: tk.Tk | None = None - self.system_address: int | None = None # Frontier SystemAddress - self.system_population: int | None = None - self.station_link: tk.Widget | None = None - self.station_name: str | None = None - self.station_marketid: int | None = None # Frontier MarketID + self.system_link: Optional[tk.Widget] = None + self.system_name: Optional[tk.Tk] = None + self.system_address: Optional[int] = None # Frontier SystemAddress + self.system_population: Optional[int] = None + self.station_link: Optional[tk.Widget] = None + self.station_name: Optional[str] = None + self.station_marketid: Optional[int] = None # Frontier MarketID self.on_foot = False self._IMG_KNOWN = None @@ -109,19 +102,19 @@ class This: self.thread: Optional[threading.Thread] = None - self.log: tk.IntVar | None = None - self.log_button: ttk.Checkbutton | None = None + self.log: Optional[tk.IntVar] = None + self.log_button: Optional[ttk.Checkbutton] = None - self.label: tk.Widget | None = None + self.label: Optional[tk.Widget] = None - self.cmdr_label: myNotebook.Label | None = None - self.cmdr_text: myNotebook.Label | None = None + self.cmdr_label: Optional[nb.Label] = None + self.cmdr_text: Optional[nb.Label] = None - self.user_label: myNotebook.Label | None = None - self.user: myNotebook.Entry | None = None + self.user_label: Optional[nb.Label] = None + self.user: Optional[nb.Entry] = None - self.apikey_label: myNotebook.Label | None = None - self.apikey: myNotebook.Entry | None = None + self.apikey_label: Optional[nb.Label] = None + self.apikey: Optional[nb.Entry] = None this = This() @@ -284,7 +277,7 @@ def toggle_password_visibility(): this.apikey.config(show="*") # type: ignore -def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Frame: +def plugin_prefs(parent: ttk.Notebook, cmdr: Optional[str], is_beta: bool) -> tk.Frame: """ Plugin preferences setup hook. @@ -297,8 +290,8 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr :return: An instance of `myNotebook.Frame`. """ PADX = 10 # noqa: N806 - BUTTONX = 12 # indent Checkbuttons and Radiobuttons # noqa: N806 - PADY = 2 # close spacing # noqa: N806 + BUTTONX = 12 # noqa: N806 + PADY = 2 # noqa: N806 frame = nb.Frame(parent) frame.columnconfigure(1, weight=1) @@ -309,51 +302,46 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr background=nb.Label().cget('background'), url='https://www.edsm.net/', underline=True - ).grid(columnspan=2, padx=PADX, sticky=tk.W) # Don't translate + ).grid(columnspan=2, padx=PADX, sticky=tk.W) this.log = tk.IntVar(value=config.get_int('edsm_out') and 1) this.log_button = nb.Checkbutton( - # LANG: Settings>EDSM - Label on checkbox for 'send data' - frame, text=_('Send flight log and Cmdr status to EDSM'), variable=this.log, command=prefsvarchanged + frame, + text=_('Send flight log and Cmdr status to EDSM'), + variable=this.log, + command=prefsvarchanged ) - if this.log_button: this.log_button.grid(columnspan=2, padx=BUTTONX, pady=(5, 0), sticky=tk.W) nb.Label(frame).grid(sticky=tk.W) # big spacer - # Section heading in settings + this.label = HyperlinkLabel( frame, - # LANG: Settings>EDSM - Label on header/URL to EDSM API key page text=_('Elite Dangerous Star Map credentials'), background=nb.Label().cget('background'), url='https://www.edsm.net/settings/api', underline=True ) - cur_row = 10 - if this.label: this.label.grid(columnspan=2, padx=PADX, sticky=tk.W) - # LANG: Game Commander name label in EDSM settings - this.cmdr_label = nb.Label(frame, text=_('Cmdr')) # Main window + this.cmdr_label = nb.Label(frame, text=_('Cmdr')) this.cmdr_label.grid(row=cur_row, padx=PADX, sticky=tk.W) this.cmdr_text = nb.Label(frame) this.cmdr_text.grid(row=cur_row, column=1, padx=PADX, pady=PADY, sticky=tk.W) cur_row += 1 - # LANG: EDSM Commander name label in EDSM settings - this.user_label = nb.Label(frame, text=_('Commander Name')) # EDSM setting + this.user_label = nb.Label(frame, text=_('Commander Name')) this.user_label.grid(row=cur_row, padx=PADX, sticky=tk.W) this.user = nb.Entry(frame) this.user.grid(row=cur_row, column=1, padx=PADX, pady=PADY, sticky=tk.EW) cur_row += 1 - # LANG: EDSM API key label - this.apikey_label = nb.Label(frame, text=_('API Key')) # EDSM setting + this.apikey_label = nb.Label(frame, text=_('API Key')) this.apikey_label.grid(row=cur_row, padx=PADX, sticky=tk.W) this.apikey = nb.Entry(frame, show="*", width=50) this.apikey.grid(row=cur_row, column=1, padx=PADX, pady=PADY, sticky=tk.EW) @@ -361,18 +349,19 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr prefs_cmdr_changed(cmdr, is_beta) show_password_var.set(False) # Password is initially masked + show_password_checkbox = nb.Checkbutton( frame, text="Show API Key", variable=show_password_var, - command=toggle_password_visibility, + command=toggle_password_visibility ) show_password_checkbox.grid(columnspan=2, padx=BUTTONX, pady=(5, 0), sticky=tk.W) return frame -def prefs_cmdr_changed(cmdr: str | None, is_beta: bool) -> None: # noqa: CCR001 +def prefs_cmdr_changed(cmdr: Optional[str], is_beta: bool) -> None: # noqa: CCR001 """ Handle the Commander name changing whilst Settings was open. @@ -381,28 +370,21 @@ def prefs_cmdr_changed(cmdr: str | None, is_beta: bool) -> None: # noqa: CCR001 """ if this.log_button: this.log_button['state'] = tk.NORMAL if cmdr and not is_beta else tk.DISABLED - if this.user: this.user['state'] = tk.NORMAL this.user.delete(0, tk.END) - if this.apikey: this.apikey['state'] = tk.NORMAL this.apikey.delete(0, tk.END) - if cmdr: if this.cmdr_text: this.cmdr_text['text'] = f'{cmdr}{" [Beta]" if is_beta else ""}' - cred = credentials(cmdr) - if cred: if this.user: this.user.insert(0, cred[0]) - if this.apikey: this.apikey.insert(0, cred[1]) - else: if this.cmdr_text: # LANG: We have no data on the current commander @@ -429,18 +411,22 @@ def set_prefs_ui_states(state: str) -> None: Set the state of various config UI entries. :param state: the state to set each entry to + + # NOTE: This may break things, watch out in testing. (5.10) """ - if ( - this.label and this.cmdr_label and this.cmdr_text and this.user_label and this.user - and this.apikey_label and this.apikey - ): - this.label['state'] = state - this.cmdr_label['state'] = state - this.cmdr_text['state'] = state - this.user_label['state'] = state - this.user['state'] = state - this.apikey_label['state'] = state - this.apikey['state'] = state + elements = [ + this.label, + this.cmdr_label, + this.cmdr_text, + this.user_label, + this.user, + this.apikey_label, + this.apikey + ] + + for element in elements: + if element: + element['state'] = state def prefs_changed(cmdr: str, is_beta: bool) -> None: @@ -454,7 +440,6 @@ def prefs_changed(cmdr: str, is_beta: bool) -> None: config.set('edsm_out', this.log.get()) if cmdr and not is_beta: - # TODO: remove this when config is rewritten. cmdrs: List[str] = config.get_list('edsm_cmdrs', default=[]) usernames: List[str] = config.get_list('edsm_usernames', default=[]) apikeys: List[str] = config.get_list('edsm_apikeys', default=[]) @@ -466,7 +451,6 @@ def prefs_changed(cmdr: str, is_beta: bool) -> None: usernames[idx] = this.user.get().strip() apikeys.extend([''] * (1 + idx - len(apikeys))) apikeys[idx] = this.apikey.get().strip() - else: config.set('edsm_cmdrs', cmdrs + [cmdr]) usernames.append(this.user.get().strip()) @@ -495,20 +479,17 @@ def credentials(cmdr: str) -> Optional[Tuple[str, str]]: cmdrs = [cmdr] config.set('edsm_cmdrs', cmdrs) - if (cmdr in cmdrs and (edsm_usernames := config.get_list('edsm_usernames')) - and (edsm_apikeys := config.get_list('edsm_apikeys'))): + edsm_usernames = config.get_list('edsm_usernames') + edsm_apikeys = config.get_list('edsm_apikeys') + + if cmdr in cmdrs and len(cmdrs) == len(edsm_usernames) == len(edsm_apikeys): idx = cmdrs.index(cmdr) - # The EDSM cmdr and apikey might not exist yet! - if idx >= len(edsm_usernames) or idx >= len(edsm_apikeys): - return None + if idx < len(edsm_usernames) and idx < len(edsm_apikeys): + logger.trace_if(CMDR_CREDS, f'{cmdr=}: returning ({edsm_usernames[idx]=}, {edsm_apikeys[idx]=})') + return edsm_usernames[idx], edsm_apikeys[idx] - logger.trace_if(CMDR_CREDS, f'{cmdr=}: returning ({edsm_usernames[idx]=}, {edsm_apikeys[idx]=})') - - return (edsm_usernames[idx], edsm_apikeys[idx]) - - else: - logger.trace_if(CMDR_CREDS, f'{cmdr=}: returning None') - return None + logger.trace_if(CMDR_CREDS, f'{cmdr=}: returning None') + return None def journal_entry( # noqa: C901, CCR001 @@ -564,7 +545,6 @@ entry: {entry!r}''' if not this.station_name: if this.system_population and this.system_population > 0: to_set = STATION_UNDOCKED - else: to_set = '' @@ -582,7 +562,6 @@ entry: {entry!r}''' this.multicrew = bool(state['Role']) if 'StarPos' in entry: this.coordinates = entry['StarPos'] - elif entry['event'] == 'LoadGame': this.coordinates = None @@ -590,20 +569,16 @@ entry: {entry!r}''' this.newgame = True this.newgame_docked = False this.navbeaconscan = 0 - elif entry['event'] == 'StartUp': this.newgame = False this.newgame_docked = False this.navbeaconscan = 0 - elif entry['event'] == 'Location': this.newgame = True this.newgame_docked = entry.get('Docked', False) this.navbeaconscan = 0 - elif entry['event'] == 'NavBeaconScan': this.navbeaconscan = entry['NumBodies'] - elif entry['event'] == 'BackPack': # Use the stored file contents, not the empty journal event if state['BackpackJSON']: @@ -646,7 +621,6 @@ entry: {entry!r}''' } materials.update(transient) logger.trace_if(CMDR_EVENTS, f'"LoadGame" event, queueing Materials: {cmdr=}') - this.queue.put((cmdr, this.game_version, this.game_build, materials)) if entry['event'] in ('CarrierJump', 'FSDJump', 'Location', 'Docked'): @@ -655,7 +629,6 @@ entry: {entry!r}''' Queueing: {entry!r}''' ) logger.trace_if(CMDR_EVENTS, f'"{entry["event"]=}" event, queueing: {cmdr=}') - this.queue.put((cmdr, this.game_version, this.game_build, entry)) return '' @@ -675,11 +648,9 @@ def cmdr_data(data: CAPIData, is_beta: bool) -> Optional[str]: # noqa: CCR001 # 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'] @@ -691,21 +662,17 @@ def cmdr_data(data: CAPIData, is_beta: bool) -> Optional[str]: # noqa: CCR001 # 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.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'] = '' # 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() if this.system_link and not this.system_link['text']: @@ -722,30 +689,37 @@ if 'edsm' in debug_senders: def get_discarded_events_list() -> None: - """Retrieve the list of to-discard events from EDSM.""" + """ + Retrieve the list of events to discard from EDSM. + + This function queries the EDSM API to obtain the list of events that should be discarded, + and stores them in the `discarded_events` attribute. + + :return: None + """ try: r = this.session.get('https://www.edsm.net/api-journal-v1/discard', timeout=_TIMEOUT) r.raise_for_status() this.discarded_events = set(r.json()) - - this.discarded_events.discard('Docked') # should_send() assumes that we send 'Docked' events + # We discard 'Docked' events because should_send() assumes that we send them + this.discarded_events.discard('Docked') if not this.discarded_events: logger.warning( 'Unexpected empty discarded events list from EDSM: ' f'{type(this.discarded_events)} -- {this.discarded_events}' ) - except Exception as e: - logger.warning('Exception whilst trying to set this.discarded_events:', exc_info=e) + logger.warning('Exception while trying to set this.discarded_events:', exc_info=e) -def worker() -> None: # noqa: CCR001 C901 # Cant be broken up currently +def worker() -> None: # noqa: CCR001 C901 """ Handle uploading events to EDSM API. - Target function of a thread. + This function is the target function of a thread. It processes events from the queue until the + queued item is None, uploading the events to the EDSM API. - Processes `this.queue` until the queued item is None. + :return: None """ logger.debug('Starting...') pending: List[Mapping[str, Any]] = [] # Unsent events @@ -753,13 +727,11 @@ def worker() -> None: # noqa: CCR001 C901 # Cant be broken up currently cmdr: str = "" last_game_version = "" last_game_build = "" - entry: Mapping[str, Any] = {} while not this.discarded_events: if this.shutting_down: logger.debug(f'returning from discarded_events loop due to {this.shutting_down=}') return - get_discarded_events_list() if this.discarded_events: break @@ -776,17 +748,15 @@ def worker() -> None: # noqa: CCR001 C901 # Cant be broken up currently if item: (cmdr, game_version, game_build, entry) = item logger.trace_if(CMDR_EVENTS, f'De-queued ({cmdr=}, {game_version=}, {game_build=}, {entry["event"]=})') - else: logger.debug('Empty queue message, setting closing = True') closing = True # Try to send any unsent events before we close - entry = {'event': 'ShutDown'} # Dummy to allow for `uentry['event']` belowt + entry = {'event': 'ShutDown'} # Dummy to allow for `entry['event']` below retrying = 0 while retrying < 3: if item is None: item = cast(Tuple[str, str, str, Mapping[str, Any]], ("", {})) - should_skip, new_item = killswitch.check_killswitch( 'plugins.edsm.worker', item, @@ -795,7 +765,6 @@ def worker() -> None: # noqa: CCR001 C901 # Cant be broken up currently if should_skip: break - if item is not None: item = new_item @@ -817,18 +786,14 @@ def worker() -> None: # noqa: CCR001 C901 # Cant be broken up currently or last_game_version != game_version or last_game_build != game_build ): pending = [] - pending.append(entry) - # drop events if required by killswitch new_pending = [] for e in pending: skip, new = killswitch.check_killswitch(f'plugin.edsm.worker.{e["event"]}', e, logger) if skip: continue - new_pending.append(new) - pending = new_pending if pending and should_send(pending, entry['event']): @@ -840,10 +805,10 @@ def worker() -> None: # noqa: CCR001 C901 # Cant be broken up currently "('CarrierJump', 'FSDJump', 'Location', 'Docked')" " and it passed should_send()") for p in pending: - if p['event'] in ('Location'): + if p['event'] in 'Location': logger.trace_if( 'journal.locations', - f'"Location" event in pending passed should_send(),timestamp: {p["timestamp"]}' + f'"Location" event in pending passed should_send(), timestamp: {p["timestamp"]}' ) creds = credentials(cmdr) @@ -868,24 +833,20 @@ def worker() -> None: # noqa: CCR001 C901 # Cant be broken up currently data_elided['apiKey'] = '' if isinstance(data_elided['message'], bytes): data_elided['message'] = data_elided['message'].decode('utf-8') - if isinstance(data_elided['commanderName'], bytes): data_elided['commanderName'] = data_elided['commanderName'].decode('utf-8') - logger.trace_if( 'journal.locations', "pending has at least one of ('CarrierJump', 'FSDJump', 'Location', 'Docked')" " Attempting API call with the following events:" ) - for p in pending: logger.trace_if('journal.locations', f"Event: {p!r}") - if p['event'] in ('Location'): + if p['event'] in 'Location': logger.trace_if( 'journal.locations', f'Attempting API call for "Location" event with timestamp: {p["timestamp"]}' ) - logger.trace_if( 'journal.locations', f'Overall POST data (elided) is:\n{json.dumps(data_elided, indent=2)}' ) @@ -906,17 +867,13 @@ def worker() -> None: # noqa: CCR001 C901 # Cant be broken up currently logger.warning(f'EDSM\t{msg_num} {msg}\t{json.dumps(pending, separators=(",", ": "))}') # LANG: EDSM Plugin - Error message from EDSM API plug.show_error(_('Error: EDSM {MSG}').format(MSG=msg)) - else: - if msg_num // 100 == 1: logger.trace_if('plugin.edsm.api', 'Overall OK') pass - elif msg_num // 100 == 5: logger.trace_if('plugin.edsm.api', 'Event(s) not currently processed, but saved for later') pass - else: logger.warning(f'EDSM API call status not 1XX, 2XX or 5XX: {msg.num}') @@ -927,13 +884,10 @@ def worker() -> None: # noqa: CCR001 C901 # Cant be broken up currently # calls update_status in main thread if not config.shutting_down and this.system_link is not None: this.system_link.event_generate('<>', when="tail") - - if r['msgnum'] // 100 != 1: # type: ignore - logger.warning(f'EDSM event with not-1xx status:\n{r["msgnum"]}\n' # type: ignore + if r['msgnum'] // 100 != 1: + logger.warning(f'EDSM event with not-1xx status:\n{r["msgnum"]}\n' f'{r["msg"]}\n{json.dumps(e, separators = (",", ": "))}') - pending = [] - break # No exception, so assume success except Exception as e: @@ -943,12 +897,10 @@ def worker() -> None: # noqa: CCR001 C901 # Cant be broken up currently else: # LANG: EDSM Plugin - Error connecting to EDSM API plug.show_error(_("Error: Can't connect to EDSM")) - if entry['event'].lower() in ('shutdown', 'commander', 'fileheader'): # Game shutdown or new login, so we MUST not hang on to pending pending = [] logger.trace_if(CMDR_EVENTS, f'Blanked pending because of event: {entry["event"]}') - if closing: logger.debug('closing, so returning.') return @@ -956,8 +908,6 @@ def worker() -> None: # noqa: CCR001 C901 # Cant be broken up currently last_game_version = game_version last_game_build = game_build - logger.debug('Done.') - def should_send(entries: List[Mapping[str, Any]], event: str) -> bool: # noqa: CCR001 """ @@ -967,54 +917,42 @@ def should_send(entries: List[Mapping[str, Any]], event: str) -> bool: # noqa: :param event: The latest event being processed :return: bool indicating whether or not to send said entries """ - # We MUST flush pending on logout, in case new login is a different Commander + def should_send_entry(entry: Mapping[str, Any]) -> bool: + if entry['event'] == 'Cargo': + return not this.newgame_docked + if entry['event'] == 'Docked': + return True + if this.newgame: + return True + if entry['event'] not in ( + 'CommunityGoal', + 'ModuleBuy', + 'ModuleSell', + 'ModuleSwap', + 'ShipyardBuy', + 'ShipyardNew', + 'ShipyardSwap' + ): + return True + return False + if event.lower() in ('shutdown', 'fileheader'): logger.trace_if(CMDR_EVENTS, f'True because {event=}') - return True - # batch up burst of Scan events after NavBeaconScan if this.navbeaconscan: if entries and entries[-1]['event'] == 'Scan': this.navbeaconscan -= 1 - if this.navbeaconscan: - logger.trace_if(CMDR_EVENTS, f'False because {this.navbeaconscan=}') + should_send_result = this.navbeaconscan == 0 + logger.trace_if(CMDR_EVENTS, f'False because {this.navbeaconscan=}' if not should_send_result else '') + return should_send_result + logger.error('Invalid state NavBeaconScan exists, but passed entries either ' + "doesn't exist or doesn't have the expected content") + this.navbeaconscan = 0 - return False - - else: - logger.error( - 'Invalid state NavBeaconScan exists, but passed entries either ' - "doesn't exist or doesn't have the expected content" - ) - this.navbeaconscan = 0 - - for entry in entries: - if (entry['event'] == 'Cargo' and not this.newgame_docked) or entry['event'] == 'Docked': - # Cargo is the last event on startup, unless starting when docked in which case Docked is the last event - this.newgame = False - this.newgame_docked = False - logger.trace_if(CMDR_EVENTS, f'True because {entry["event"]=}') - - return True - - elif this.newgame: - pass - - elif entry['event'] not in ( - 'CommunityGoal', # Spammed periodically - 'ModuleBuy', 'ModuleSell', 'ModuleSwap', # will be shortly followed by "Loadout" - 'ShipyardBuy', 'ShipyardNew', 'ShipyardSwap'): # " - logger.trace_if(CMDR_EVENTS, f'True because {entry["event"]=}') - - return True - - else: - logger.trace_if(CMDR_EVENTS, f'{entry["event"]=}, {this.newgame_docked=}') - - logger.trace_if(CMDR_EVENTS, f'False as default: {this.newgame_docked=}') - - return False + should_send_result = any(should_send_entry(entry) for entry in entries) + logger.trace_if(CMDR_EVENTS, f'False as default: {this.newgame_docked=}' if not should_send_result else '') + return should_send_result def update_status(event=None) -> None: @@ -1033,14 +971,11 @@ def edsm_notify_system(reply: Mapping[str, Any]) -> None: this.system_link['image'] = this._IMG_ERROR # LANG: EDSM Plugin - Error connecting to EDSM API plug.show_error(_("Error: Can't connect to EDSM")) - elif reply['msgnum'] // 100 not in (1, 4): this.system_link['image'] = this._IMG_ERROR # LANG: EDSM Plugin - Error message from EDSM API plug.show_error(_('Error: EDSM {MSG}').format(MSG=reply['msg'])) - elif reply.get('systemCreated'): this.system_link['image'] = this._IMG_NEW - else: this.system_link['image'] = this._IMG_KNOWN diff --git a/plugins/edsy.py b/plugins/edsy.py index 17b16ef0..0c78a429 100644 --- a/plugins/edsy.py +++ b/plugins/edsy.py @@ -1,32 +1,28 @@ -"""Export data for ED Shipyard.""" +""" +edsy.py - Exporting Data to EDSY. -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# -# -# 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` SO AS TO ENSURE THE FILES ARE ACTUALLY PRESENT IN -# AN END-USER INSTALLATION ON WINDOWS. -# -# -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# +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. +""" import base64 import gzip import io import json -from typing import Any, Mapping +from typing import Any, Mapping, Union def plugin_start3(plugin_dir: str) -> str: @@ -40,15 +36,15 @@ def plugin_start3(plugin_dir: str) -> str: # Return a URL for the current ship -def shipyard_url(loadout: Mapping[str, Any], is_beta) -> bool | str: +def shipyard_url(loadout: Mapping[str, Any], is_beta: bool) -> Union[bool, str]: """ Construct a URL for ship loadout. - :param loadout: - :param is_beta: - :return: + :param loadout: The ship loadout data. + :param is_beta: Whether the game is in beta. + :return: The constructed URL for the ship loadout. """ - # most compact representation + # 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 @@ -57,6 +53,8 @@ def shipyard_url(loadout: Mapping[str, Any], is_beta) -> bool | str: with gzip.GzipFile(fileobj=out, mode='w') as f: f.write(string) - return ( - is_beta and 'http://edsy.org/beta/#/I=' or 'http://edsy.org/#/I=' - ) + base64.urlsafe_b64encode(out.getvalue()).decode().replace('=', '%3D') + # 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 diff --git a/plugins/inara.py b/plugins/inara.py index d50c2e6d..efe010df 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -1,26 +1,24 @@ -"""Inara Sync.""" +""" +inara.py - Sync with INARA. + +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. +""" -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# -# -# 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` SO AS TO ENSURE THE FILES ARE ACTUALLY PRESENT -# IN AN END-USER INSTALLATION ON WINDOWS. -# -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# -# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# import json import threading import time @@ -34,9 +32,7 @@ from tkinter import ttk from typing import TYPE_CHECKING, Any, Callable, Deque, Dict, List, Mapping, NamedTuple, Optional from typing import OrderedDict as OrderedDictT from typing import Sequence, Union, cast - import requests - import edmc_data import killswitch import myNotebook as nb # noqa: N813 @@ -168,14 +164,15 @@ if DEBUG: TARGET_URL = f'http://{edmc_data.DEBUG_WEBSERVER_HOST}:{edmc_data.DEBUG_WEBSERVER_PORT}/inara' +# noinspection PyUnresolvedReferences 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/elite/starsystem/' + return requests.utils.requote_uri(f'https://inara.cz/galaxy-starsystem/' f'?search={this.system_address}') - elif system_name: - return requests.utils.requote_uri(f'https://inara.cz/elite/starsystem/' + if system_name: + return requests.utils.requote_uri(f'https://inara.cz/galaxy-starsystem/' f'?search={system_name}') return '' @@ -192,13 +189,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/elite/station/' - f'?search={system_name}%20[{station_name}]') + return requests.utils.requote_uri(f'https://inara.cz/galaxy-station/?search={system_name}%20[{station_name}]') - # monitor state might think these are gone, but we don't yet if this.system_name and this.station: - return requests.utils.requote_uri(f'https://inara.cz/elite/station/' - f'?search={this.system_name}%20[{this.station}]') + return requests.utils.requote_uri( + f'https://inara.cz/galaxy-station/?search={this.system_name}%20[{this.station}]') if system_name: return system_url(system_name) @@ -224,9 +219,7 @@ def plugin_start3(plugin_dir: str) -> str: def plugin_app(parent: tk.Tk) -> None: """Plugin UI setup Hook.""" this.parent = parent - # system label in main window this.system_link = parent.nametowidget(f".{appname.lower()}.system") - # station label in main window this.station_link = parent.nametowidget(f".{appname.lower()}.station") this.system_link.bind_all('<>', update_location) this.system_link.bind_all('<>', update_ship) @@ -379,11 +372,14 @@ def credentials(cmdr: Optional[str]) -> Optional[str]: return None cmdrs = config.get_list('inara_cmdrs', default=[]) - if cmdr in cmdrs and config.get_list('inara_apikeys'): - return config.get_list('inara_apikeys')[cmdrs.index(cmdr)] + apikeys = config.get_list('inara_apikeys', default=[]) - else: - return None + if cmdr in cmdrs: + idx = cmdrs.index(cmdr) + if idx < len(apikeys): + return apikeys[idx] + + return None def journal_entry( # noqa: C901, CCR001 @@ -422,11 +418,9 @@ def journal_entry( # noqa: C901, CCR001 if not monitor.is_live_galaxy(): # Since Update 14 on 2022-11-29 Inara only accepts Live data. if ( - ( - this.legacy_galaxy_last_notified is None - or (datetime.now(timezone.utc) - this.legacy_galaxy_last_notified) > timedelta(seconds=300) - ) - and config.get_int('inara_out') and not is_beta and not this.multicrew and credentials(cmdr) + (this.legacy_galaxy_last_notified is None or + (datetime.now(timezone.utc) - this.legacy_galaxy_last_notified) > timedelta(seconds=300)) + and config.get_int('inara_out') and not (is_beta or this.multicrew or credentials(cmdr)) ): # LANG: The Inara API only accepts Live galaxy data, not Legacy galaxy data logger.info(_("Inara only accepts Live galaxy data")) @@ -475,92 +469,49 @@ def journal_entry( # noqa: C901, CCR001 if config.get_int('inara_out') and not is_beta and not this.multicrew and credentials(cmdr): current_credentials = Credentials(this.cmdr, this.FID, str(credentials(this.cmdr))) try: - # Dump starting state to Inara - if (this.newuser or event_name == 'StartUp' or (this.newsession and event_name == 'Cargo')): + if this.newuser or event_name == 'StartUp' or (this.newsession and event_name == 'Cargo'): this.newuser = False this.newsession = False - # Don't send the API call with no values. if state['Reputation']: - new_add_event( - 'setCommanderReputationMajorFaction', - entry['timestamp'], - [ - {'majorfactionName': k.lower(), 'majorfactionReputation': v / 100.0} - for k, v in state['Reputation'].items() if v is not None - ] - ) - - if state['Engineers']: # Not populated < 3.3 - to_send_list: List[Mapping[str, Any]] = [] - for k, v in state['Engineers'].items(): - e = {'engineerName': k} - if isinstance(v, tuple): - e['rankValue'] = v[0] - - else: - e['rankStage'] = v - - to_send_list.append(e) - - new_add_event( - 'setCommanderRankEngineer', - entry['timestamp'], - to_send_list, - ) - - # Update location - # Might not be available if this event is a 'StartUp' and we're replaying - # a log. - # XXX: This interferes with other more specific setCommanderTravelLocation events in the same - # batch. - # if system: - # new_add_event( - # 'setCommanderTravelLocation', - # entry['timestamp'], - # OrderedDict([ - # ('starsystemName', system), - # ('stationName', station), # Can be None - # ]) - # ) + reputation_data = [ + {'majorfactionName': k.lower(), 'majorfactionReputation': v / 100.0} + for k, v in state['Reputation'].items() if v is not None + ] + new_add_event('setCommanderReputationMajorFaction', entry['timestamp'], reputation_data) + if state['Engineers']: + engineer_data = [ + {'engineerName': k, 'rankValue': v[0] if isinstance(v, tuple) else None, 'rankStage': v} + for k, v in state['Engineers'].items() + ] + new_add_event('setCommanderRankEngineer', entry['timestamp'], engineer_data) # Update ship - if state['ShipID']: # Unknown if started in Fighter or SRV - cur_ship: Dict[str, Any] = { + if state['ShipID']: + cur_ship = { 'shipType': state['ShipType'], 'shipGameID': state['ShipID'], 'shipName': state['ShipName'], 'shipIdent': state['ShipIdent'], 'isCurrentShip': True, - } - if state['HullValue']: cur_ship['shipHullValue'] = state['HullValue'] - if state['ModulesValue']: cur_ship['shipModulesValue'] = state['ModulesValue'] - cur_ship['shipRebuyCost'] = state['Rebuy'] new_add_event('setCommanderShip', entry['timestamp'], cur_ship) - this.loadout = make_loadout(state) new_add_event('setCommanderShipLoadout', entry['timestamp'], this.loadout) - # Trigger off the "only observed as being after Ranks" event so that # we have both current Ranks *and* current Progress within them. elif event_name == 'Progress': - # Send rank info to Inara on startup - new_add_event( - 'setCommanderRankPilot', - entry['timestamp'], - [ - {'rankName': k.lower(), 'rankValue': v[0], 'rankProgress': v[1] / 100.0} - for k, v in state['Rank'].items() if v is not None - ] - ) + rank_data = [ + {'rankName': k.lower(), 'rankValue': v[0], 'rankProgress': v[1] / 100.0} + for k, v in state['Rank'].items() if v is not None + ] + new_add_event('setCommanderRankPilot', entry['timestamp'], rank_data) - # Promotions elif event_name == 'Promotion': for k, v in state['Rank'].items(): if k in entry: @@ -571,41 +522,25 @@ def journal_entry( # noqa: C901, CCR001 ) elif event_name == 'EngineerProgress' and 'Engineer' in entry: - # TODO: due to this var name being used above, the types are weird - to_send_dict = {'engineerName': entry['Engineer']} - if 'Rank' in entry: - to_send_dict['rankValue'] = entry['Rank'] - - else: - to_send_dict['rankStage'] = entry['Progress'] - - new_add_event( - 'setCommanderRankEngineer', - entry['timestamp'], - to_send_dict - ) + engineer_rank_data = { + 'engineerName': entry['Engineer'], + 'rankValue': entry['Rank'] if 'Rank' in entry else None, + 'rankStage': entry['Progress'] if 'Progress' in entry else None, + } + new_add_event('setCommanderRankEngineer', entry['timestamp'], engineer_rank_data) # PowerPlay status change - if event_name == 'PowerplayJoin': - new_add_event( - 'setCommanderRankPower', - entry['timestamp'], - {'powerName': entry['Power'], 'rankValue': 1} - ) + elif event_name == 'PowerplayJoin': + power_join_data = {'powerName': entry['Power'], 'rankValue': 1} + new_add_event('setCommanderRankPower', entry['timestamp'], power_join_data) elif event_name == 'PowerplayLeave': - new_add_event( - 'setCommanderRankPower', - entry['timestamp'], - {'powerName': entry['Power'], 'rankValue': 0} - ) + power_leave_data = {'powerName': entry['Power'], 'rankValue': 0} + new_add_event('setCommanderRankPower', entry['timestamp'], power_leave_data) elif event_name == 'PowerplayDefect': - new_add_event( - 'setCommanderRankPower', - entry['timestamp'], - {'powerName': entry['ToPower'], 'rankValue': 1} - ) + power_defect_data = {'powerName': entry["ToPower"], 'rankValue': 1} + new_add_event('setCommanderRankPower', entry['timestamp'], power_defect_data) # Ship change if event_name == 'Loadout' and this.shipswap: @@ -683,7 +618,7 @@ def journal_entry( # noqa: C901, CCR001 elif event_name == 'SupercruiseExit': to_send = { - 'starsystemName': entry['StarSystem'], + 'starsystemName': entry['StarSystem'], } if entry['BodyType'] == 'Planet': @@ -696,9 +631,9 @@ def journal_entry( # noqa: C901, CCR001 # we might not yet have system logged for use. if system: to_send = { - 'starsystemName': system, - 'stationName': entry['Name'], - 'starsystemBodyName': entry['BodyName'], + 'starsystemName': system, + 'stationName': entry['Name'], + 'starsystemBodyName': entry['BodyName'], 'starsystemBodyCoords': [entry['Latitude'], entry['Longitude']] } # Not present on, e.g. Ancient Ruins @@ -775,22 +710,19 @@ def journal_entry( # noqa: C901, CCR001 # Ignore the following 'Docked' event this.suppress_docked = True - cargo: List[OrderedDictT[str, Any]] - cargo = [OrderedDict({'itemName': k, 'itemCount': state['Cargo'][k]}) for k in sorted(state['Cargo'])] - # Send cargo and materials if changed + cargo = [OrderedDict({'itemName': k, 'itemCount': state['Cargo'][k]}) for k in sorted(state['Cargo'])] if this.cargo != cargo: new_add_event('setCommanderInventoryCargo', entry['timestamp'], cargo) this.cargo = cargo - materials: List[OrderedDictT[str, Any]] = [] - for category in ('Raw', 'Manufactured', 'Encoded'): - materials.extend( - [OrderedDict([('itemName', k), ('itemCount', state[category][k])]) for k in sorted(state[category])] - ) - + materials = [ + OrderedDict([('itemName', k), ('itemCount', state[category][k])]) + for category in ('Raw', 'Manufactured', 'Encoded') + for k in sorted(state[category]) + ] if this.materials != materials: - new_add_event('setCommanderInventoryMaterials', entry['timestamp'], materials) + new_add_event('setCommanderInventoryMaterials', entry['timestamp'], materials) this.materials = materials except Exception as e: @@ -1398,7 +1330,7 @@ def journal_entry( # noqa: C901, CCR001 return '' # No error -def cmdr_data(data: CAPIData, is_beta): # noqa: CCR001 +def cmdr_data(data: CAPIData, is_beta): # noqa: CCR001, reanalyze me later """CAPI event hook.""" this.cmdr = data['commander']['name'] @@ -1539,17 +1471,22 @@ def new_add_event( def clean_event_list(event_list: List[Event]) -> List[Event]: - """Check for killswitched events and remove or modify them as requested.""" - out = [] - for e in event_list: - bad, new_event = killswitch.check_killswitch(f'plugins.inara.worker.{e.name}', e.data, logger) - if bad: + """ + Check for killswitched events and remove or modify them as requested. + + :param event_list: List of events to clean + :return: Cleaned list of events + """ + cleaned_events = [] + for event in event_list: + is_bad, new_event = killswitch.check_killswitch(f'plugins.inara.worker.{event.name}', event.data, logger) + if is_bad: continue - e.data = new_event - out.append(e) + event.data = new_event + cleaned_events.append(event) - return out + return cleaned_events def new_worker(): @@ -1561,8 +1498,9 @@ def new_worker(): logger.debug('Starting...') while True: events = get_events() - if (res := killswitch.get_disabled("plugins.inara.worker")).disabled: - logger.warning(f"Inara worker disabled via killswitch. ({res.reason})") + disabled_killswitch = killswitch.get_disabled("plugins.inara.worker") + if disabled_killswitch.disabled: + logger.warning(f"Inara worker disabled via killswitch. ({disabled_killswitch.reason})") continue for creds, event_list in events.items(): @@ -1570,6 +1508,10 @@ def new_worker(): if not event_list: continue + event_data = [ + {'eventName': e.name, 'eventTimestamp': e.timestamp, 'eventData': e.data} for e in event_list + ] + data = { 'header': { 'appName': applongname, @@ -1578,12 +1520,10 @@ def new_worker(): 'commanderName': creds.cmdr, 'commanderFrontierID': creds.fid, }, - 'events': [ - {'eventName': e.name, 'eventTimestamp': e.timestamp, 'eventData': e.data} for e in event_list - ] + 'events': event_data } - logger.info(f'sending {len(data["events"])} events for {creds.cmdr}') + logger.info(f'Sending {len(event_data)} events for {creds.cmdr}') logger.trace_if('plugin.inara.events', f'Events:\n{json.dumps(data)}\n') try_send_data(TARGET_URL, data) @@ -1595,94 +1535,129 @@ def new_worker(): def get_events(clear: bool = True) -> Dict[Credentials, List[Event]]: """ - Fetch a frozen copy of all events from the current queue. + Fetch a copy of all events from the current queue. - :param clear: whether or not to clear the queues as we go, defaults to True - :return: the frozen event list + :param clear: whether to clear the queues as we go, defaults to True + :return: a copy of the event dictionary """ - out: Dict[Credentials, List[Event]] = {} + events_copy: Dict[Credentials, List[Event]] = {} + with this.event_lock: for key, events in this.events.items(): - out[key] = list(events) + events_copy[key] = list(events) if clear: events.clear() - return out + return events_copy def try_send_data(url: str, data: Mapping[str, Any]) -> None: """ - Attempt repeatedly to send the payload forward. + Attempt repeatedly to send the payload. :param url: target URL for the payload :param data: the payload """ - for i in range(3): - logger.debug(f"sending data to API, attempt #{i}") + for attempt in range(3): + logger.debug(f"Sending data to API, attempt #{attempt + 1}") try: if send_data(url, data): break except Exception as e: - logger.debug('unable to send events', exc_info=e) + logger.debug('Unable to send events', exc_info=e) return -def send_data(url: str, data: Mapping[str, Any]) -> bool: # noqa: CCR001 +def send_data(url: str, data: Mapping[str, Any]) -> bool: """ - Write a set of events to the inara API. + Send a set of events to the Inara API. - :param url: the target URL to post to - :param data: the data to POST - :return: success state + :param url: The target URL to post the data. + :param data: The data to be POSTed. + :return: True if the data was sent successfully, False otherwise. """ - # NB: As of 2022-01-25 Artie has stated the Inara API does *not* support compression - r = this.session.post(url, data=json.dumps(data, separators=(',', ':')), timeout=_TIMEOUT) - r.raise_for_status() - reply = r.json() + response = this.session.post(url, data=json.dumps(data, separators=(',', ':')), timeout=_TIMEOUT) + response.raise_for_status() + reply = response.json() status = reply['header']['eventStatus'] if status // 100 != 2: # 2xx == OK (maybe with warnings) - # Log fatal errors - logger.warning(f'Inara\t{status} {reply["header"].get("eventStatusText", "")}') - logger.debug(f'JSON data:\n{json.dumps(data, indent=2, separators = (",", ": "))}') - # LANG: INARA API returned some kind of error (error message will be contained in {MSG}) - plug.show_error(_('Error: Inara {MSG}').format(MSG=reply['header'].get('eventStatusText', status))) - + handle_api_error(data, status, reply) else: - # Log individual errors and warnings - for data_event, reply_event in zip(data['events'], reply['events']): - if reply_event['eventStatus'] != 200: - if ("Everything was alright, the near-neutral status just wasn't stored." - not in reply_event.get("eventStatusText")): - logger.warning(f'Inara\t{status} {reply_event.get("eventStatusText", "")}') - logger.debug(f'JSON data:\n{json.dumps(data_event)}') + handle_success_reply(data, reply) - if reply_event['eventStatus'] // 100 != 2: - # LANG: INARA API returned some kind of error (error message will be contained in {MSG}) - plug.show_error(_('Error: Inara {MSG}').format( - MSG=f'{data_event["eventName"]},' - f'{reply_event.get("eventStatusText", reply_event["eventStatus"])}' - )) + return True # Regardless of errors above, we DID manage to send it, therefore inform our caller as such - if data_event['eventName'] in ( - 'addCommanderTravelCarrierJump', - 'addCommanderTravelDock', - 'addCommanderTravelFSDJump', - 'setCommanderTravelLocation' - ): - this.lastlocation = reply_event.get('eventData', {}) - # calls update_location in main thread - if not config.shutting_down: - this.system_link.event_generate('<>', when="tail") - elif data_event['eventName'] in ['addCommanderShip', 'setCommanderShip']: - this.lastship = reply_event.get('eventData', {}) - # calls update_ship in main thread - if not config.shutting_down: - this.system_link.event_generate('<>', when="tail") +def handle_api_error(data: Mapping[str, Any], status: int, reply: Dict[str, Any]) -> None: + """ + Handle API error response. - return True # regardless of errors above, we DID manage to send it, therefore inform our caller as such + :param data: The original data that was sent. + :param status: The HTTP status code of the API response. + :param reply: The JSON reply from the API. + """ + error_message = reply['header'].get('eventStatusText', "") + logger.warning(f'Inara\t{status} {error_message}') + logger.debug(f'JSON data:\n{json.dumps(data, indent=2, separators = (",", ": "))}') + plug.show_error(_('Error: Inara {MSG}').format(MSG=error_message)) + + +def handle_success_reply(data: Mapping[str, Any], reply: Dict[str, Any]) -> None: + """ + Handle successful API response. + + :param data: The original data that was sent. + :param reply: The JSON reply from the API. + """ + for data_event, reply_event in zip(data['events'], reply['events']): + reply_status = reply_event['eventStatus'] + reply_text = reply_event.get("eventStatusText", "") + if reply_status != 200: + handle_individual_error(data_event, reply_status, reply_text) + handle_special_events(data_event, reply_event) + + +def handle_individual_error(data_event: Dict[str, Any], reply_status: int, reply_text: str) -> None: + """ + Handle individual API error. + + :param data_event: The event data that was sent. + :param reply_status: The event status code from the API response. + :param reply_text: The event status text from the API response. + """ + if ("Everything was alright, the near-neutral status just wasn't stored." + not in reply_text): + logger.warning(f'Inara\t{reply_status} {reply_text}') + logger.debug(f'JSON data:\n{json.dumps(data_event)}') + + if reply_status // 100 != 2: + plug.show_error(_('Error: Inara {MSG}').format( + MSG=f'{data_event["eventName"]}, {reply_text}' + )) + + +def handle_special_events(data_event: Dict[str, Any], reply_event: Dict[str, Any]) -> None: + """ + Handle special events in the API response. + + :param data_event: The event data that was sent. + :param reply_event: The event data from the API reply. + """ + if data_event['eventName'] in ( + 'addCommanderTravelCarrierJump', + 'addCommanderTravelDock', + 'addCommanderTravelFSDJump', + 'setCommanderTravelLocation' + ): + this.lastlocation = reply_event.get('eventData', {}) + if not config.shutting_down: + this.system_link.event_generate('<>', when="tail") + elif data_event['eventName'] in ['addCommanderShip', 'setCommanderShip']: + this.lastship = reply_event.get('eventData', {}) + if not config.shutting_down: + this.system_link.event_generate('<>', when="tail") def update_location(event=None) -> None: From 239c5b6e249f260ecbff413560cc3b94c855f4c2 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Thu, 19 Oct 2023 19:24:43 -0400 Subject: [PATCH 11/83] [2051] Config Files --- config/__init__.py | 72 +++++++++++------------- config/darwin.py | 24 ++++---- config/linux.py | 136 ++++++++++++++++++++++----------------------- config/windows.py | 98 +++++++++++++++----------------- 4 files changed, 156 insertions(+), 174 deletions(-) diff --git a/config/__init__.py b/config/__init__.py index a31cdd89..ae08f3a0 100644 --- a/config/__init__.py +++ b/config/__init__.py @@ -1,12 +1,14 @@ """ -Code dealing with the configuration of the program. +__init__.py - Code dealing with the configuration of the program. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. Windows uses the Registry to store values in a flat manner. Linux uses a file, but for commonality it's still a flat data structure. macOS uses a 'defaults' object. """ - - __all__ = [ # defined in the order they appear in the file 'GITVERSION_FILE', @@ -40,10 +42,8 @@ import sys import traceback import warnings from abc import abstractmethod -from typing import Any, Callable, Optional, Type, TypeVar - +from typing import Any, Callable, Optional, Type, TypeVar, Union, List import semantic_version - from constants import GITVERSION_FILE, applongname, appname # Any of these may be imported by plugins @@ -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.9.5' +_static_appversion = '5.10.0-alpha0' _cached_version: Optional[semantic_version.Version] = None copyright = '© 2015-2019 Jonathan Harris, 2020-2023 EDCD' @@ -60,10 +60,10 @@ copyright = '© 2015-2019 Jonathan Harris, 2020-2023 EDCD' update_feed = 'https://raw.githubusercontent.com/EDCD/EDMarketConnector/releases/edmarketconnector.xml' update_interval = 8*60*60 # Providers marked to be in debug mode. Generally this is expected to switch to sending data to a log file -debug_senders: list[str] = [] +debug_senders: List[str] = [] # TRACE logging code that should actually be used. Means not spamming it # *all* if only interested in some things. -trace_on: list[str] = [] +trace_on: List[str] = [] capi_pretend_down: bool = False capi_debug_access_token: Optional[str] = None @@ -79,7 +79,6 @@ else: _T = TypeVar('_T') -########################################################################### def git_shorthash_from_head() -> str: """ Determine short hash for current git HEAD. @@ -91,13 +90,14 @@ def git_shorthash_from_head() -> str: shorthash: str = None # type: ignore try: - git_cmd = subprocess.Popen('git rev-parse --short HEAD'.split(), - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT - ) + git_cmd = subprocess.Popen( + "git rev-parse --short HEAD".split(), + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) out, err = git_cmd.communicate() - except Exception as e: + except subprocess.CalledProcessError as e: logger.info(f"Couldn't run git command for short hash: {e!r}") else: @@ -131,7 +131,7 @@ def appversion() -> semantic_version.Version: if getattr(sys, 'frozen', False): # Running frozen, so we should have a .gitversion file # Yes, .parent because if frozen we're inside library.zip - with open(pathlib.Path(sys.path[0]).parent / GITVERSION_FILE, 'r', encoding='utf-8') as gitv: + with open(pathlib.Path(sys.path[0]).parent / GITVERSION_FILE, encoding='utf-8') as gitv: shorthash = gitv.read() else: @@ -157,23 +157,15 @@ def appversion_nobuild() -> semantic_version.Version: :return: App version without any build meta data. """ return appversion().truncate('prerelease') -########################################################################### class AbstractConfig(abc.ABC): """Abstract root class of all platform specific Config implementations.""" OUT_EDDN_SEND_STATION_DATA = 1 - # OUT_MKT_BPC = 2 # No longer supported OUT_MKT_TD = 4 OUT_MKT_CSV = 8 OUT_SHIP = 16 - # OUT_SHIP_EDS = 16 # Replaced by OUT_SHIP - # OUT_SYS_FILE = 32 # No longer supported - # OUT_STAT = 64 # No longer available - # OUT_SHIP_CORIOLIS = 128 # Replaced by OUT_SHIP - # OUT_SYS_EDSM = 256 # Now a plugin - # OUT_SYS_AUTO = 512 # Now always automatic OUT_MKT_MANUAL = 1024 OUT_EDDN_SEND_NON_STATION = 2048 OUT_EDDN_DELAY = 4096 @@ -185,7 +177,6 @@ class AbstractConfig(abc.ABC): respath_path: pathlib.Path home_path: pathlib.Path default_journal_dir_path: pathlib.Path - identifier: str __in_shutdown = False # Is the application currently shutting down ? @@ -294,7 +285,7 @@ class AbstractConfig(abc.ABC): @staticmethod def _suppress_call( - func: Callable[..., _T], exceptions: Type[BaseException] | list[Type[BaseException]] = Exception, + func: Callable[..., _T], exceptions: Union[Type[BaseException], List[Type[BaseException]]] = Exception, *args: Any, **kwargs: Any ) -> Optional[_T]: if exceptions is None: @@ -303,15 +294,15 @@ class AbstractConfig(abc.ABC): if not isinstance(exceptions, list): exceptions = [exceptions] - with contextlib.suppress(*exceptions): # type: ignore # it works fine, mypy + with contextlib.suppress(*exceptions): return func(*args, **kwargs) return None def get( self, key: str, - default: list | str | bool | int | None = None - ) -> list | str | bool | int | None: + default: Union[list, str, bool, int, None] = None + ) -> Union[list, str, bool, int, None]: """ Return the data for the requested key, or a default. @@ -326,19 +317,19 @@ class AbstractConfig(abc.ABC): if (a_list := self._suppress_call(self.get_list, ValueError, key, default=None)) is not None: return a_list - elif (a_str := self._suppress_call(self.get_str, ValueError, key, default=None)) is not None: + if (a_str := self._suppress_call(self.get_str, ValueError, key, default=None)) is not None: return a_str - elif (a_bool := self._suppress_call(self.get_bool, ValueError, key, default=None)) is not None: + if (a_bool := self._suppress_call(self.get_bool, ValueError, key, default=None)) is not None: return a_bool - elif (an_int := self._suppress_call(self.get_int, ValueError, key, default=None)) is not None: + if (an_int := self._suppress_call(self.get_int, ValueError, key, default=None)) is not None: return an_int - return default # type: ignore + return default @abstractmethod - def get_list(self, key: str, *, default: list | None = None) -> list: + def get_list(self, key: str, *, default: Optional[list] = None) -> list: """ Return the list referred to by the given key if it exists, or the default. @@ -347,7 +338,7 @@ class AbstractConfig(abc.ABC): raise NotImplementedError @abstractmethod - def get_str(self, key: str, *, default: str | None = None) -> str: + def get_str(self, key: str, *, default: Optional[str] = None) -> str: """ Return the string referred to by the given key if it exists, or the default. @@ -360,7 +351,7 @@ class AbstractConfig(abc.ABC): raise NotImplementedError @abstractmethod - def get_bool(self, key: str, *, default: bool | None = None) -> bool: + def get_bool(self, key: str, *, default: Optional[bool] = None) -> bool: """ Return the bool referred to by the given key if it exists, or the default. @@ -400,7 +391,7 @@ class AbstractConfig(abc.ABC): raise NotImplementedError @abstractmethod - def set(self, key: str, val: int | str | list[str] | bool) -> None: + def set(self, key: str, val: Union[int, str, List[str], bool]) -> None: """ Set the given key's data to the given value. @@ -462,16 +453,15 @@ def get_config(*args, **kwargs) -> AbstractConfig: from .darwin import MacConfig return MacConfig(*args, **kwargs) - elif sys.platform == "win32": # pragma: sys-platform-win32 + if sys.platform == "win32": # pragma: sys-platform-win32 from .windows import WinConfig return WinConfig(*args, **kwargs) - elif sys.platform == "linux": # pragma: sys-platform-linux + if sys.platform == "linux": # pragma: sys-platform-linux from .linux import LinuxConfig return LinuxConfig(*args, **kwargs) - else: # pragma: sys-platform-not-known - raise ValueError(f'Unknown platform: {sys.platform=}') + raise ValueError(f'Unknown platform: {sys.platform=}') config = get_config() diff --git a/config/darwin.py b/config/darwin.py index 895218a8..68d30306 100644 --- a/config/darwin.py +++ b/config/darwin.py @@ -1,13 +1,17 @@ -"""Darwin/macOS implementation of AbstractConfig.""" +""" +darwin.py - Darwin/macOS implementation of AbstractConfig. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" import pathlib import sys from typing import Any, Dict, List, Union - from Foundation import ( # type: ignore NSApplicationSupportDirectory, NSBundle, NSDocumentDirectory, NSSearchPathForDirectoriesInDomains, NSUserDefaults, NSUserDomainMask ) - from config import AbstractConfig, appname, logger assert sys.platform == 'darwin' @@ -82,7 +86,7 @@ class MacConfig(AbstractConfig): """ res = self.__raw_get(key) if res is None: - return default # type: ignore # Yes it could be None, but we're _assuming_ that people gave us a default + return default # Yes it could be None, but we're _assuming_ that people gave us a default if not isinstance(res, str): raise ValueError(f'unexpected data returned from __raw_get: {type(res)=} {res}') @@ -97,9 +101,9 @@ class MacConfig(AbstractConfig): """ res = self.__raw_get(key) if res is None: - return default # type: ignore # Yes it could be None, but we're _assuming_ that people gave us a default + return default # Yes it could be None, but we're _assuming_ that people gave us a default - elif not isinstance(res, list): + if not isinstance(res, list): raise ValueError(f'__raw_get returned unexpected type {type(res)=} {res!r}') return res @@ -114,7 +118,7 @@ class MacConfig(AbstractConfig): if res is None: return default - elif not isinstance(res, (str, int)): + if not isinstance(res, (str, int)): raise ValueError(f'__raw_get returned unexpected type {type(res)=} {res!r}') try: @@ -122,7 +126,7 @@ class MacConfig(AbstractConfig): except ValueError as e: logger.error(f'__raw_get returned {res!r} which cannot be parsed to an int: {e}') - return default # type: ignore # Yes it could be None, but we're _assuming_ that people gave us a default + return default # Yes it could be None, but we're _assuming_ that people gave us a default def get_bool(self, key: str, *, default: bool = None) -> bool: """ @@ -132,9 +136,9 @@ class MacConfig(AbstractConfig): """ res = self.__raw_get(key) if res is None: - return default # type: ignore # Yes it could be None, but we're _assuming_ that people gave us a default + return default # Yes it could be None, but we're _assuming_ that people gave us a default - elif not isinstance(res, bool): + if not isinstance(res, bool): raise ValueError(f'__raw_get returned unexpected type {type(res)=} {res!r}') return res diff --git a/config/linux.py b/config/linux.py index 5d543d3f..07876481 100644 --- a/config/linux.py +++ b/config/linux.py @@ -1,9 +1,15 @@ -"""Linux config implementation.""" +""" +linux.py - Linux config implementation. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" import os import pathlib import sys from configparser import ConfigParser - +from typing import Optional, Union, List from config import AbstractConfig, appname, logger assert sys.platform == 'linux' @@ -13,100 +19,97 @@ class LinuxConfig(AbstractConfig): """Linux implementation of AbstractConfig.""" SECTION = 'config' - # TODO: I dislike this, would rather use a sane config file format. But here we are. + __unescape_lut = {'\\': '\\', 'n': '\n', ';': ';', 'r': '\r', '#': '#'} __escape_lut = {'\\': '\\', '\n': 'n', ';': ';', '\r': 'r'} - def __init__(self, filename: str | None = None) -> None: + def __init__(self, filename: Optional[str] = None) -> None: + """ + Initialize LinuxConfig instance. + + :param filename: Optional file name to use for configuration storage. + """ super().__init__() - # http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html + + # Initialize directory paths xdg_data_home = pathlib.Path(os.getenv('XDG_DATA_HOME', default='~/.local/share')).expanduser() self.app_dir_path = xdg_data_home / appname self.app_dir_path.mkdir(exist_ok=True, parents=True) self.plugin_dir_path = self.app_dir_path / 'plugins' self.plugin_dir_path.mkdir(exist_ok=True) - self.respath_path = pathlib.Path(__file__).parent.parent - self.internal_plugin_dir_path = self.respath_path / 'plugins' self.default_journal_dir_path = None # type: ignore - self.identifier = f'uk.org.marginal.{appname.lower()}' # TODO: Unused? + # Configure the filename config_home = pathlib.Path(os.getenv('XDG_CONFIG_HOME', default='~/.config')).expanduser() - - self.filename = config_home / appname / f'{appname}.ini' - if filename is not None: - self.filename = pathlib.Path(filename) - + self.filename = pathlib.Path(filename) if filename is not None else config_home / appname / f'{appname}.ini' self.filename.parent.mkdir(exist_ok=True, parents=True) - self.config: ConfigParser | None = ConfigParser(comment_prefixes=('#',), interpolation=None) - self.config.read(self.filename) # read() ignores files that dont exist + # Initialize the configuration + self.config = ConfigParser(comment_prefixes=('#',), interpolation=None) + self.config.read(self.filename) # Ensure that our section exists. This is here because configparser will happily create files for us, but it # does not magically create sections try: - self.config[self.SECTION].get("this_does_not_exist", fallback=None) + self.config[self.SECTION].get("this_does_not_exist") except KeyError: - logger.info("Config section not found. Backing up existing file (if any) and readding a section header") + logger.info("Config section not found. Backing up existing file (if any) and re-adding a section header") if self.filename.exists(): - (self.filename.parent / f'{appname}.ini.backup').write_bytes(self.filename.read_bytes()) - + backup_filename = self.filename.parent / f'{appname}.ini.backup' + backup_filename.write_bytes(self.filename.read_bytes()) self.config.add_section(self.SECTION) - if (outdir := self.get_str('outdir')) is None or not pathlib.Path(outdir).is_dir(): + # Set 'outdir' if not specified or invalid + outdir = self.get_str('outdir') + if outdir is None or not pathlib.Path(outdir).is_dir(): self.set('outdir', self.home) def __escape(self, s: str) -> str: """ - Escape a string using self.__escape_lut. + Escape special characters in a string. - This does NOT support multi-character escapes. - - :param s: str - String to be escaped. - :return: str - The escaped string. + :param s: The input string. + :return: The escaped string. """ - out = "" + escaped_chars = [] + for c in s: - if c not in self.__escape_lut: - out += c - continue + escaped_chars.append(self.__escape_lut.get(c, c)) - out += '\\' + self.__escape_lut[c] - - return out + return ''.join(escaped_chars) def __unescape(self, s: str) -> str: """ - Unescape a string. + Unescape special characters in a string. - :param s: str - The string to unescape. - :return: str - The unescaped string. + :param s: The input string. + :return: The unescaped string. """ - out: list[str] = [] + unescaped_chars = [] i = 0 while i < len(s): - c = s[i] - if c != '\\': - out.append(c) + current_char = s[i] + if current_char != '\\': + unescaped_chars.append(current_char) i += 1 continue - # We have a backslash, check what its escaping - if i == len(s)-1: + if i == len(s) - 1: raise ValueError('Escaped string has unescaped trailer') - unescaped = self.__unescape_lut.get(s[i+1]) + unescaped = self.__unescape_lut.get(s[i + 1]) if unescaped is None: - raise ValueError(f'Unknown escape: \\ {s[i+1]}') + raise ValueError(f'Unknown escape: \\{s[i + 1]}') - out.append(unescaped) + unescaped_chars.append(unescaped) i += 2 - return "".join(out) + return "".join(unescaped_chars) - def __raw_get(self, key: str) -> str | None: + def __raw_get(self, key: str) -> Optional[str]: """ Get a raw data value from the config file. @@ -118,7 +121,7 @@ class LinuxConfig(AbstractConfig): return self.config[self.SECTION].get(key) - def get_str(self, key: str, *, default: str | None = None) -> str: + def get_str(self, key: str, *, default: Optional[str] = None) -> str: """ Return the string referred to by the given key if it exists, or the default. @@ -126,29 +129,28 @@ class LinuxConfig(AbstractConfig): """ data = self.__raw_get(key) if data is None: - return default # type: ignore # Yes it could be None, but we're _assuming_ that people gave us a default + return default or "" if '\n' in data: - raise ValueError('asked for string, got list') + raise ValueError('Expected string, but got list') return self.__unescape(data) - def get_list(self, key: str, *, default: list | None = None) -> list: + def get_list(self, key: str, *, default: Optional[list] = None) -> list: """ Return the list referred to by the given key if it exists, or the default. Implements :meth:`AbstractConfig.get_list`. """ data = self.__raw_get(key) - if data is None: - return default # type: ignore # Yes it could be None, but we're _assuming_ that people gave us a default + return default or [] split = data.split('\n') if split[-1] != ';': raise ValueError('Encoded list does not have trailer sentinel') - return list(map(self.__unescape, split[:-1])) + return [self.__unescape(item) for item in split[:-1]] def get_int(self, key: str, *, default: int = 0) -> int: """ @@ -157,55 +159,47 @@ class LinuxConfig(AbstractConfig): Implements :meth:`AbstractConfig.get_int`. """ data = self.__raw_get(key) - if data is None: return default try: return int(data) - except ValueError as e: - raise ValueError(f'requested {key=} as int cannot be converted to int') from e + raise ValueError(f'Failed to convert {key=} to int') from e - def get_bool(self, key: str, *, default: bool | None = None) -> bool: + def get_bool(self, key: str, *, default: Optional[bool] = None) -> bool: """ Return the bool referred to by the given key if it exists, or the default. Implements :meth:`AbstractConfig.get_bool`. """ if self.config is None: - raise ValueError('attempt to use a closed config') + raise ValueError('Attempt to use a closed config') data = self.__raw_get(key) if data is None: - return default # type: ignore # Yes it could be None, but we're _assuming_ that people gave us a default + return default or False return bool(int(data)) - def set(self, key: str, val: int | str | list[str]) -> None: + def set(self, key: str, val: Union[int, str, List[str]]) -> None: """ Set the given key's data to the given value. Implements :meth:`AbstractConfig.set`. """ if self.config is None: - raise ValueError('attempt to use a closed config') - - to_set: str | None = None + raise ValueError('Attempt to use a closed config') if isinstance(val, bool): to_set = str(int(val)) - elif isinstance(val, str): to_set = self.__escape(val) - elif isinstance(val, int): to_set = str(val) - elif isinstance(val, list): to_set = '\n'.join([self.__escape(s) for s in val] + [';']) - else: - raise ValueError(f'Unexpected type for value {type(val)=}') + raise ValueError(f'Unexpected type for value {type(val).__name__}') self.config.set(self.SECTION, key, to_set) self.save() @@ -217,7 +211,7 @@ class LinuxConfig(AbstractConfig): Implements :meth:`AbstractConfig.delete`. """ if self.config is None: - raise ValueError('attempt to use a closed config') + raise ValueError('Attempt to delete from a closed config') self.config.remove_option(self.SECTION, key) self.save() @@ -229,7 +223,7 @@ class LinuxConfig(AbstractConfig): Implements :meth:`AbstractConfig.save`. """ if self.config is None: - raise ValueError('attempt to use a closed config') + raise ValueError('Attempt to save a closed config') with open(self.filename, 'w', encoding='utf-8') as f: self.config.write(f) @@ -241,4 +235,4 @@ class LinuxConfig(AbstractConfig): Implements :meth:`AbstractConfig.close`. """ self.save() - self.config = None + self.config = None # type: ignore diff --git a/config/windows.py b/config/windows.py index f7590a92..94a158f1 100644 --- a/config/windows.py +++ b/config/windows.py @@ -1,6 +1,10 @@ -"""Windows config implementation.""" +""" +windows.py - Windows config implementation. -# spell-checker: words folderid deps hkey edcd +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" import ctypes import functools import pathlib @@ -9,7 +13,6 @@ import uuid import winreg from ctypes.wintypes import DWORD, HANDLE from typing import List, Literal, Optional, Union - from config import AbstractConfig, applongname, appname, logger, update_interval assert sys.platform == 'win32' @@ -43,7 +46,8 @@ class WinConfig(AbstractConfig): """Implementation of AbstractConfig for Windows.""" def __init__(self, do_winsparkle=True) -> None: - self.app_dir_path = pathlib.Path(str(known_folder_path(FOLDERID_LocalAppData))) / appname + super().__init__() + self.app_dir_path = pathlib.Path(known_folder_path(FOLDERID_LocalAppData)) / appname # type: ignore self.app_dir_path.mkdir(exist_ok=True) self.plugin_dir_path = self.app_dir_path / 'plugins' @@ -52,19 +56,17 @@ class WinConfig(AbstractConfig): if getattr(sys, 'frozen', False): self.respath_path = pathlib.Path(sys.executable).parent self.internal_plugin_dir_path = self.respath_path / 'plugins' - else: self.respath_path = pathlib.Path(__file__).parent.parent self.internal_plugin_dir_path = self.respath_path / 'plugins' self.home_path = pathlib.Path.home() - journal_dir_str = known_folder_path(FOLDERID_SavedGames) - journaldir = pathlib.Path(journal_dir_str) if journal_dir_str is not None else None - self.default_journal_dir_path = None # type: ignore - if journaldir is not None: - self.default_journal_dir_path = journaldir / 'Frontier Developments' / 'Elite Dangerous' + journal_dir_path = pathlib.Path( + known_folder_path(FOLDERID_SavedGames)) / 'Frontier Developments' / 'Elite Dangerous' # type: ignore + self.default_journal_dir_path = journal_dir_path if journal_dir_path.is_dir() else None # type: ignore + REGISTRY_SUBKEY = r'Software\Marginal\EDMarketConnector' # noqa: N806 create_key_defaults = functools.partial( winreg.CreateKeyEx, key=winreg.HKEY_CURRENT_USER, @@ -72,20 +74,18 @@ class WinConfig(AbstractConfig): ) try: - self.__reg_handle: winreg.HKEYType = create_key_defaults( - sub_key=r'Software\Marginal\EDMarketConnector' - ) + self.__reg_handle: winreg.HKEYType = create_key_defaults(sub_key=REGISTRY_SUBKEY) if do_winsparkle: self.__setup_winsparkle() except OSError: - logger.exception('could not create required registry keys') + logger.exception('Could not create required registry keys') raise self.identifier = applongname if (outdir_str := self.get_str('outdir')) is None or not pathlib.Path(outdir_str).is_dir(): docs = known_folder_path(FOLDERID_Documents) - self.set('outdir', docs if docs is not None else self.home) + self.set("outdir", docs if docs is not None else self.home) def __setup_winsparkle(self): """Ensure the necessary Registry keys for WinSparkle are present.""" @@ -94,31 +94,29 @@ class WinConfig(AbstractConfig): key=winreg.HKEY_CURRENT_USER, access=winreg.KEY_ALL_ACCESS | winreg.KEY_WOW64_64KEY, ) - try: - edcd_handle: winreg.HKEYType = create_key_defaults(sub_key=r'Software\EDCD\EDMarketConnector') - winsparkle_reg: winreg.HKEYType = winreg.CreateKeyEx( - edcd_handle, sub_key='WinSparkle', access=winreg.KEY_ALL_ACCESS | winreg.KEY_WOW64_64KEY - ) + try: + with create_key_defaults(sub_key=r'Software\EDCD\EDMarketConnector') as edcd_handle: + with winreg.CreateKeyEx(edcd_handle, sub_key='WinSparkle', + access=winreg.KEY_ALL_ACCESS | winreg.KEY_WOW64_64KEY) as winsparkle_reg: + # Set WinSparkle defaults - https://github.com/vslavik/winsparkle/wiki/Registry-Settings + UPDATE_INTERVAL_NAME = 'UpdateInterval' # noqa: N806 + CHECK_FOR_UPDATES_NAME = 'CheckForUpdates' # noqa: N806 + REG_SZ = winreg.REG_SZ # noqa: N806 + + winreg.SetValueEx(winsparkle_reg, UPDATE_INTERVAL_NAME, REG_RESERVED_ALWAYS_ZERO, REG_SZ, + str(update_interval)) + + try: + winreg.QueryValueEx(winsparkle_reg, CHECK_FOR_UPDATES_NAME) + except FileNotFoundError: + # Key doesn't exist, set it to a default + winreg.SetValueEx(winsparkle_reg, CHECK_FOR_UPDATES_NAME, REG_RESERVED_ALWAYS_ZERO, REG_SZ, + '1') except OSError: - logger.exception('could not open WinSparkle handle') + logger.exception('Could not open WinSparkle handle') raise - # set WinSparkle defaults - https://github.com/vslavik/winsparkle/wiki/Registry-Settings - winreg.SetValueEx( - winsparkle_reg, 'UpdateInterval', REG_RESERVED_ALWAYS_ZERO, winreg.REG_SZ, str(update_interval) - ) - - try: - winreg.QueryValueEx(winsparkle_reg, 'CheckForUpdates') - - except FileNotFoundError: - # Key doesn't exist, set it to a default - winreg.SetValueEx(winsparkle_reg, 'CheckForUpdates', REG_RESERVED_ALWAYS_ZERO, winreg.REG_SZ, '1') - - winsparkle_reg.Close() - edcd_handle.Close() - def __get_regentry(self, key: str) -> Union[None, list, str, int]: """Access the Registry for the raw entry.""" try: @@ -127,22 +125,20 @@ class WinConfig(AbstractConfig): # Key doesn't exist return None - # The type returned is actually as we'd expect for each of these. The casts are here for type checkers and # For programmers who want to actually know what is going on if _type == winreg.REG_SZ: return str(value) - elif _type == winreg.REG_DWORD: + if _type == winreg.REG_DWORD: return int(value) - elif _type == winreg.REG_MULTI_SZ: + if _type == winreg.REG_MULTI_SZ: return list(value) - else: - logger.warning(f'registry key {key=} returned unknown type {_type=} {value=}') - return None + logger.warning(f'Registry key {key=} returned unknown type {_type=} {value=}') + return None - def get_str(self, key: str, *, default: str | None = None) -> str: + def get_str(self, key: str, *, default: Optional[str] = None) -> str: """ Return the string referred to by the given key if it exists, or the default. @@ -152,12 +148,12 @@ class WinConfig(AbstractConfig): if res is None: return default # type: ignore # Yes it could be None, but we're _assuming_ that people gave us a default - elif not isinstance(res, str): + if not isinstance(res, str): raise ValueError(f'Data from registry is not a string: {type(res)=} {res=}') return res - def get_list(self, key: str, *, default: list | None = None) -> list: + def get_list(self, key: str, *, default: Optional[list] = None) -> list: """ Return the list referred to by the given key if it exists, or the default. @@ -167,7 +163,7 @@ class WinConfig(AbstractConfig): if res is None: return default # type: ignore # Yes it could be None, but we're _assuming_ that people gave us a default - elif not isinstance(res, list): + if not isinstance(res, list): raise ValueError(f'Data from registry is not a list: {type(res)=} {res}') return res @@ -187,7 +183,7 @@ class WinConfig(AbstractConfig): return res - def get_bool(self, key: str, *, default: bool | None = None) -> bool: + def get_bool(self, key: str, *, default: Optional[bool] = None) -> bool: """ Return the bool referred to by the given key if it exists, or the default. @@ -195,7 +191,7 @@ class WinConfig(AbstractConfig): """ res = self.get_int(key, default=default) # type: ignore if res is None: - return default # type: ignore # Yes it could be None, but we're _assuming_ that people gave us a default + return default # Yes it could be None, but we're _assuming_ that people gave us a default return bool(res) @@ -206,12 +202,11 @@ class WinConfig(AbstractConfig): Implements :meth:`AbstractConfig.set`. """ # These are the types that winreg.REG_* below resolve to. - reg_type: Literal[1] | Literal[4] | Literal[7] + reg_type: Union[Literal[1], Literal[4], Literal[7]] if isinstance(val, str): reg_type = winreg.REG_SZ - winreg.SetValueEx(self.__reg_handle, key, REG_RESERVED_ALWAYS_ZERO, winreg.REG_SZ, val) - elif isinstance(val, int): # The original code checked for numbers.Integral, I dont think that is needed. + elif isinstance(val, int): reg_type = winreg.REG_DWORD elif isinstance(val, list): @@ -224,7 +219,6 @@ class WinConfig(AbstractConfig): else: raise ValueError(f'Unexpected type for value {type(val)=}') - # Its complaining about the list, it works, tested on windows, ignored. winreg.SetValueEx(self.__reg_handle, key, REG_RESERVED_ALWAYS_ZERO, reg_type, val) # type: ignore def delete(self, key: str, *, suppress=False) -> None: From 28e10b70ef140cf23b5b01695875962f4d807bbd Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Thu, 19 Oct 2023 20:06:52 -0400 Subject: [PATCH 12/83] [2051] Add Tests and gitignore File --- .gitignore | 37 ++++++++++++--- tests/EDMCLogging.py/test_logging_classvar.py | 2 +- tests/config/_old_config.py | 45 +++++++++---------- tests/config/test_config.py | 4 +- tests/journal_lock.py/test_journal_lock.py | 12 +++-- tests/killswitch.py/test_apply.py | 6 +-- tests/killswitch.py/test_killswitch.py | 4 +- 7 files changed, 64 insertions(+), 46 deletions(-) diff --git a/.gitignore b/.gitignore index 35fa7565..4283fcb0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,18 @@ +# Ignore version file .gitversion + +# Ignore macOS DS_Store files .DS_Store + +# Ignore build artifacts build -ChangeLog.html +dist.win32/ dist.* + +# Ignore generated ChangeLog.html file +ChangeLog.html + +# Ignore files dump *.bak *.pyc @@ -11,20 +21,37 @@ dump *.pdb *.msi *.wixobj +*.zip + +# Ignore Update Things EDMarketConnector_Installer_*.exe appcast_win_*.xml appcast_mac_*.xml -EDMarketConnector.VisualElementsManifest.xml -*.zip EDMC_Installer_Config.iss +EDMarketConnector.wxs +wix/components.wxs +# Ignore Visual Elements Manifest file for Windows +EDMarketConnector.VisualElementsManifest.xml + +# Ignore IDE and editor configuration files .idea .vscode + +# Ignore virtual environments .venv/ venv/ +venv2 + +# Ignore workspace file for Visual Studio Code *.code-workspace + +# Ignore coverage reports htmlcov/ .ignored .coverage -EDMarketConnector.wxs -wix/components.wxs +pylintrc +pylint.txt + +# Ignore Submodule data directory +coriolis-data/ diff --git a/tests/EDMCLogging.py/test_logging_classvar.py b/tests/EDMCLogging.py/test_logging_classvar.py index 24ab009e..89d3220e 100644 --- a/tests/EDMCLogging.py/test_logging_classvar.py +++ b/tests/EDMCLogging.py/test_logging_classvar.py @@ -37,7 +37,7 @@ def test_class_logger(caplog: 'LogCaptureFixture') -> None: ClassVarLogger.set_logger(logger) ClassVarLogger.logger.debug('test') # type: ignore # its there ClassVarLogger.logger.info('test2') # type: ignore # its there - log_stuff('test3') # type: ignore # its there + log_stuff('test3') # Dont move these, it relies on the line numbres. assert 'EDMarketConnector.EDMCLogging.py:test_logging_classvar.py:38 test' in caplog.text diff --git a/tests/config/_old_config.py b/tests/config/_old_config.py index 211c1e72..6eab451b 100644 --- a/tests/config/_old_config.py +++ b/tests/config/_old_config.py @@ -1,4 +1,4 @@ -# type: ignore +"""Old Configuration Test File.""" import numbers import sys import warnings @@ -6,7 +6,6 @@ from configparser import NoOptionError from os import getenv, makedirs, mkdir, pardir from os.path import dirname, expanduser, isdir, join, normpath from typing import TYPE_CHECKING, Optional, Union - from config import applongname, appname, update_interval from EDMCLogging import get_main_logger @@ -95,7 +94,7 @@ elif sys.platform == 'linux': from configparser import RawConfigParser -class OldConfig(): +class OldConfig: """Object that holds all configuration data.""" OUT_EDDN_SEND_STATION_DATA = 1 @@ -139,7 +138,7 @@ class OldConfig(): self.identifier = f'uk.org.marginal.{appname.lower()}' NSBundle.mainBundle().infoDictionary()['CFBundleIdentifier'] = self.identifier - self.default_journal_dir: str | None = join( + self.default_journal_dir: Optional[str] = join( NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], 'Frontier Developments', 'Elite Dangerous' @@ -159,14 +158,13 @@ class OldConfig(): if val is None: return default - elif isinstance(val, str): + if isinstance(val, str): return str(val) - elif isinstance(val, list): + if isinstance(val, list): return list(val) # make writeable - else: - return default + return default def getint(self, key: str, default: int = 0) -> int: """Look up an integer configuration value.""" @@ -202,7 +200,7 @@ class OldConfig(): elif sys.platform == 'win32': def __init__(self): - self.app_dir = join(known_folder_path(FOLDERID_LocalAppData), appname) # type: ignore # Not going to change + self.app_dir = join(known_folder_path(FOLDERID_LocalAppData), appname) # type: ignore if not isdir(self.app_dir): mkdir(self.app_dir) @@ -223,13 +221,13 @@ class OldConfig(): journaldir = known_folder_path(FOLDERID_SavedGames) if journaldir: - self.default_journal_dir: str | None = join(journaldir, 'Frontier Developments', 'Elite Dangerous') + self.default_journal_dir: Optional[str] = join(journaldir, 'Frontier Developments', 'Elite Dangerous') else: self.default_journal_dir = None self.identifier = applongname - self.hkey: ctypes.c_void_p | None = HKEY() + self.hkey: Optional[ctypes.c_void_p] = HKEY() disposition = DWORD() if RegCreateKeyEx( HKEY_CURRENT_USER, @@ -279,7 +277,7 @@ class OldConfig(): RegSetValueEx(sparklekey, 'UpdateInterval', 0, 1, buf, len(buf) * 2) RegCloseKey(sparklekey) - if not self.get('outdir') or not isdir(self.get('outdir')): # type: ignore # Not going to change + if not self.get('outdir') or not isdir(self.get('outdir')): # type: ignore self.set('outdir', known_folder_path(FOLDERID_Documents) or self.home) def get(self, key: str, default: Union[None, list, str] = None) -> Union[None, list, str]: @@ -304,11 +302,10 @@ class OldConfig(): if RegQueryValueEx(self.hkey, key, 0, ctypes.byref(key_type), buf, ctypes.byref(key_size)): return default - elif key_type.value == REG_MULTI_SZ: + if key_type.value == REG_MULTI_SZ: return list(ctypes.wstring_at(buf, len(buf)-2).split('\x00')) - else: - return str(buf.value) + return str(buf.value) def getint(self, key: str, default: int = 0) -> int: """Look up an integer configuration value.""" @@ -328,8 +325,7 @@ class OldConfig(): ): return default - else: - return key_val.value + return key_val.value def set(self, key: str, val: Union[int, str, list]) -> None: """Set value on the specified configuration key.""" @@ -377,7 +373,7 @@ class OldConfig(): mkdir(self.plugin_dir) self.internal_plugin_dir = join(dirname(__file__), 'plugins') - self.default_journal_dir: str | None = None + self.default_journal_dir: Optional[str] = None self.home = expanduser('~') self.respath = dirname(__file__) self.identifier = f'uk.org.marginal.{appname.lower()}' @@ -388,7 +384,7 @@ class OldConfig(): self.config = RawConfigParser(comment_prefixes=('#',)) try: - with codecs.open(self.filename, 'r') as h: + with codecs.open(self.filename) as h: self.config.read_file(h) except Exception as e: @@ -407,8 +403,7 @@ class OldConfig(): # so we add a spurious ';' entry in set() and remove it here assert val.split('\n')[-1] == ';', val.split('\n') return [self._unescape(x) for x in val.split('\n')[:-1]] - else: - return self._unescape(val) + return self._unescape(val) except NoOptionError: logger.debug(f'attempted to get key {key} that does not exist') @@ -437,10 +432,10 @@ class OldConfig(): def set(self, key: str, val: Union[int, str, list]) -> None: """Set value on the specified configuration key.""" if isinstance(val, bool): - self.config.set(self.SECTION, key, val and '1' or '0') # type: ignore # Not going to change + self.config.set(self.SECTION, key, val and '1' or '0') - elif isinstance(val, str) or isinstance(val, numbers.Integral): - self.config.set(self.SECTION, key, self._escape(val)) # type: ignore # Not going to change + elif isinstance(val, (numbers.Integral, str)): + self.config.set(self.SECTION, key, self._escape(val)) elif isinstance(val, list): self.config.set(self.SECTION, key, '\n'.join([self._escape(x) for x in val] + [';'])) @@ -460,7 +455,7 @@ class OldConfig(): def close(self) -> None: """Close the configuration.""" self.save() - self.config = None + self.config = None # type: ignore def _escape(self, val: str) -> str: """Escape a string for storage.""" diff --git a/tests/config/test_config.py b/tests/config/test_config.py index ad6bbd6f..ae80701c 100644 --- a/tests/config/test_config.py +++ b/tests/config/test_config.py @@ -7,8 +7,6 @@ key deletions. Said modifications are to keys that are generated internally. Most of these tests are parity tests with the "old" config, and likely one day can be entirely removed. """ -from __future__ import annotations - import contextlib import itertools import pathlib @@ -81,7 +79,7 @@ def _build_test_list(static_data, random_data, random_id_name='random_test_{i}') class TestNewConfig: - """Test the new config with an array of hand picked and random data.""" + """Test the new config with an array of hand-picked and random data.""" def __update_linuxconfig(self) -> None: """On linux config uses ConfigParser, which doesn't update from disk changes. Force the update here.""" diff --git a/tests/journal_lock.py/test_journal_lock.py b/tests/journal_lock.py/test_journal_lock.py index c617d52c..148c2cb5 100644 --- a/tests/journal_lock.py/test_journal_lock.py +++ b/tests/journal_lock.py/test_journal_lock.py @@ -3,11 +3,9 @@ import multiprocessing as mp import os import pathlib import sys -from typing import Generator - +from typing import Generator, Optional import pytest from pytest import MonkeyPatch, TempdirFactory, TempPathFactory - from config import config from journal_lock import JournalLock, JournalLockResult @@ -120,7 +118,7 @@ class TestJournalLock: tmp_path_factory: TempdirFactory ) -> Generator: """Fixture for mocking config.get_str('journaldir').""" - def get_str(key: str, *, default: str | None = None) -> str: + def get_str(key: str, *, default: Optional[str] = None) -> str: """Mock config.*Config get_str to provide fake journaldir.""" if key == 'journaldir': return str(tmp_path_factory.getbasetemp()) @@ -139,10 +137,10 @@ class TestJournalLock: tmp_path_factory: TempdirFactory ) -> Generator: """Fixture for mocking config.get_str('journaldir').""" - def get_str(key: str, *, default: str | None = None) -> str: + def get_str(key: str, *, default: Optional[str] = None) -> str: """Mock config.*Config get_str to provide fake journaldir.""" if key == 'journaldir': - return tmp_path_factory.mktemp("changing") + return tmp_path_factory.mktemp("changing") # type: ignore print('Other key, calling up ...') return config.get_str(key) # Call the non-mocked @@ -301,7 +299,7 @@ class TestJournalLock: # Need to release any handles on the lockfile else the sub-process # might not be able to clean up properly, and that will impact # on later tests. - jlock.journal_dir_lockfile.close() + jlock.journal_dir_lockfile.close() # type: ignore print('Telling sub-process to quit...') exit_q.put('quit') diff --git a/tests/killswitch.py/test_apply.py b/tests/killswitch.py/test_apply.py index c199ec48..63657c69 100644 --- a/tests/killswitch.py/test_apply.py +++ b/tests/killswitch.py/test_apply.py @@ -33,11 +33,11 @@ def test_apply(source: UPDATABLE_DATA, key: str, action: str, to_set: Any, resul def test_apply_errors() -> None: """_apply should fail when passed something that isn't a Sequence or MutableMapping.""" with pytest.raises(ValueError, match=r'Dont know how to'): - killswitch._apply(set(), '0', None, False) # type: ignore # Its intentional that its broken - killswitch._apply(None, '', None) # type: ignore # Its intentional that its broken + killswitch._apply(set(), '0') # type: ignore # Its intentional that its broken + killswitch._apply(None, '') # type: ignore # Its intentional that its broken with pytest.raises(ValueError, match=r'Cannot use string'): - killswitch._apply([], 'test', None, False) + killswitch._apply([], 'test') def test_apply_no_error() -> None: diff --git a/tests/killswitch.py/test_killswitch.py b/tests/killswitch.py/test_killswitch.py index cda672ac..3b004a48 100644 --- a/tests/killswitch.py/test_killswitch.py +++ b/tests/killswitch.py/test_killswitch.py @@ -1,6 +1,6 @@ """Tests of killswitch behaviour.""" import copy -from typing import Optional +from typing import Optional, List import pytest import semantic_version @@ -85,7 +85,7 @@ def test_operator_precedence( ] ) def test_check_multiple( - names: list[str], input: killswitch.UPDATABLE_DATA, result: killswitch.UPDATABLE_DATA, expected_return: bool + names: List[str], input: killswitch.UPDATABLE_DATA, result: killswitch.UPDATABLE_DATA, expected_return: bool ) -> None: """Check that order is correct when checking multiple killswitches.""" should_return, data = TEST_SET.check_multiple_killswitches(input, *names, version='1.0.0') From b0ae7f140c0b99a2c6a4c926fd8766064e5a0776 Mon Sep 17 00:00:00 2001 From: Giampiero <54741923+GLWine@users.noreply.github.com> Date: Tue, 31 Oct 2023 01:23:59 +0100 Subject: [PATCH 13/83] Fixed translation hook line 295 Corrected the text of code line 295; The text text="Show API Key" cannot be translated as indicated, so I rewrote it as text=_('Show API Key'). --- plugins/inara.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/inara.py b/plugins/inara.py index efe010df..ec034840 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -292,7 +292,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> tk.Frame: show_password_var.set(False) # Password is initially masked show_password_checkbox = nb.Checkbutton( frame, - text="Show API Key", + text=_('Show API Key'), # LANG: Text Inara Show API key variable=show_password_var, command=toggle_password_visibility, ) From 98e9765391d444e46b33c4b0554b260cf984f742 Mon Sep 17 00:00:00 2001 From: Giampiero <54741923+GLWine@users.noreply.github.com> Date: Tue, 31 Oct 2023 01:31:29 +0100 Subject: [PATCH 14/83] Fixed translation hook line 355 Corrected the text of code line 355; The text text="Show API Key" cannot be translated as indicated, so I rewrote it as text=_('Show API Key'). --- plugins/edsm.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/edsm.py b/plugins/edsm.py index 2f644dcb..82324ced 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -352,7 +352,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: Optional[str], is_beta: bool) -> tk show_password_checkbox = nb.Checkbutton( frame, - text="Show API Key", + text=_('Show API Key'), # LANG: Text EDSM Show API Key variable=show_password_var, command=toggle_password_visibility ) From 493421f56783928ad156076146c9489c0cdf258b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 1 Nov 2023 17:43:14 +0000 Subject: [PATCH 15/83] build(deps-dev): bump coverage[toml] from 7.2.7 to 7.3.2 Bumps [coverage[toml]](https://github.com/nedbat/coveragepy) from 7.2.7 to 7.3.2. - [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.2.7...7.3.2) --- updated-dependencies: - dependency-name: coverage[toml] 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 e7b405cd..be484bd2 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -40,7 +40,7 @@ py2exe==0.13.0.0; sys_platform == 'win32' # Testing pytest==7.4.0 pytest-cov==4.1.0 # Pytest code coverage support -coverage[toml]==7.2.7 # pytest-cov dep. This is here to ensure that it includes TOML support for pyproject.toml configs +coverage[toml]==7.3.2 # pytest-cov dep. This is here to ensure that it includes TOML support for pyproject.toml configs coverage-conditional-plugin==0.9.0 # For manipulating folder permissions and the like. pywin32==306; sys_platform == 'win32' From 5c5cd5855a350fc033c0c112673c8d35c7c3d0b6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 1 Nov 2023 17:43:20 +0000 Subject: [PATCH 16/83] build(deps-dev): bump mypy from 1.4.1 to 1.6.1 Bumps [mypy](https://github.com/python/mypy) from 1.4.1 to 1.6.1. - [Changelog](https://github.com/python/mypy/blob/master/CHANGELOG.md) - [Commits](https://github.com/python/mypy/compare/v1.4.1...v1.6.1) --- 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 e7b405cd..0a021d32 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -18,7 +18,7 @@ flake8-noqa==1.3.2 flake8-polyfill==1.0.2 flake8-use-fstring==1.4 -mypy==1.4.1 +mypy==1.6.1 pep8-naming==0.13.3 safety==2.3.5 types-requests==2.31.0.2 From 2b15ef65c8302d508fd49b299c3a72a1496c4ddf Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 1 Nov 2023 17:43:46 +0000 Subject: [PATCH 17/83] build(deps-dev): bump pytest from 7.4.0 to 7.4.3 Bumps [pytest](https://github.com/pytest-dev/pytest) from 7.4.0 to 7.4.3. - [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/7.4.0...7.4.3) --- 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 e7b405cd..de68162e 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -38,7 +38,7 @@ grip==4.6.1 py2exe==0.13.0.0; sys_platform == 'win32' # Testing -pytest==7.4.0 +pytest==7.4.3 pytest-cov==4.1.0 # Pytest code coverage support coverage[toml]==7.2.7 # pytest-cov dep. This is here to ensure that it includes TOML support for pyproject.toml configs coverage-conditional-plugin==0.9.0 From cb4a26186a43f67daed506a08ebf1b588bc87f33 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 10 Nov 2023 11:22:49 -0500 Subject: [PATCH 18/83] [2051] Revert Linux Changes I can't adequately test this right now, so not touching it. --- config/linux.py | 129 ++++++++++++++++++++++++++---------------------- 1 file changed, 70 insertions(+), 59 deletions(-) diff --git a/config/linux.py b/config/linux.py index 07876481..73100800 100644 --- a/config/linux.py +++ b/config/linux.py @@ -9,7 +9,6 @@ import os import pathlib import sys from configparser import ConfigParser -from typing import Optional, Union, List from config import AbstractConfig, appname, logger assert sys.platform == 'linux' @@ -19,97 +18,100 @@ class LinuxConfig(AbstractConfig): """Linux implementation of AbstractConfig.""" SECTION = 'config' - + # TODO: I dislike this, would rather use a sane config file format. But here we are. __unescape_lut = {'\\': '\\', 'n': '\n', ';': ';', 'r': '\r', '#': '#'} __escape_lut = {'\\': '\\', '\n': 'n', ';': ';', '\r': 'r'} - def __init__(self, filename: Optional[str] = None) -> None: - """ - Initialize LinuxConfig instance. - - :param filename: Optional file name to use for configuration storage. - """ + def __init__(self, filename: str | None = None) -> None: super().__init__() - - # Initialize directory paths + # http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html xdg_data_home = pathlib.Path(os.getenv('XDG_DATA_HOME', default='~/.local/share')).expanduser() self.app_dir_path = xdg_data_home / appname self.app_dir_path.mkdir(exist_ok=True, parents=True) self.plugin_dir_path = self.app_dir_path / 'plugins' self.plugin_dir_path.mkdir(exist_ok=True) + self.respath_path = pathlib.Path(__file__).parent.parent + self.internal_plugin_dir_path = self.respath_path / 'plugins' self.default_journal_dir_path = None # type: ignore + self.identifier = f'uk.org.marginal.{appname.lower()}' # TODO: Unused? - # Configure the filename config_home = pathlib.Path(os.getenv('XDG_CONFIG_HOME', default='~/.config')).expanduser() - self.filename = pathlib.Path(filename) if filename is not None else config_home / appname / f'{appname}.ini' + + self.filename = config_home / appname / f'{appname}.ini' + if filename is not None: + self.filename = pathlib.Path(filename) + self.filename.parent.mkdir(exist_ok=True, parents=True) - # Initialize the configuration - self.config = ConfigParser(comment_prefixes=('#',), interpolation=None) - self.config.read(self.filename) + self.config: ConfigParser | None = ConfigParser(comment_prefixes=('#',), interpolation=None) + self.config.read(self.filename) # read() ignores files that dont exist # Ensure that our section exists. This is here because configparser will happily create files for us, but it # does not magically create sections try: - self.config[self.SECTION].get("this_does_not_exist") + self.config[self.SECTION].get("this_does_not_exist", fallback=None) except KeyError: - logger.info("Config section not found. Backing up existing file (if any) and re-adding a section header") + logger.info("Config section not found. Backing up existing file (if any) and readding a section header") if self.filename.exists(): - backup_filename = self.filename.parent / f'{appname}.ini.backup' - backup_filename.write_bytes(self.filename.read_bytes()) + (self.filename.parent / f'{appname}.ini.backup').write_bytes(self.filename.read_bytes()) + self.config.add_section(self.SECTION) - # Set 'outdir' if not specified or invalid - outdir = self.get_str('outdir') - if outdir is None or not pathlib.Path(outdir).is_dir(): + if (outdir := self.get_str('outdir')) is None or not pathlib.Path(outdir).is_dir(): self.set('outdir', self.home) def __escape(self, s: str) -> str: """ - Escape special characters in a string. + Escape a string using self.__escape_lut. - :param s: The input string. - :return: The escaped string. + This does NOT support multi-character escapes. + + :param s: str - String to be escaped. + :return: str - The escaped string. """ - escaped_chars = [] - + out = "" for c in s: - escaped_chars.append(self.__escape_lut.get(c, c)) + if c not in self.__escape_lut: + out += c + continue - return ''.join(escaped_chars) + out += '\\' + self.__escape_lut[c] + + return out def __unescape(self, s: str) -> str: """ - Unescape special characters in a string. + Unescape a string. - :param s: The input string. - :return: The unescaped string. + :param s: str - The string to unescape. + :return: str - The unescaped string. """ - unescaped_chars = [] + out: list[str] = [] i = 0 while i < len(s): - current_char = s[i] - if current_char != '\\': - unescaped_chars.append(current_char) + c = s[i] + if c != '\\': + out.append(c) i += 1 continue - if i == len(s) - 1: + # We have a backslash, check what its escaping + if i == len(s)-1: raise ValueError('Escaped string has unescaped trailer') - unescaped = self.__unescape_lut.get(s[i + 1]) + unescaped = self.__unescape_lut.get(s[i+1]) if unescaped is None: - raise ValueError(f'Unknown escape: \\{s[i + 1]}') + raise ValueError(f'Unknown escape: \\ {s[i+1]}') - unescaped_chars.append(unescaped) + out.append(unescaped) i += 2 - return "".join(unescaped_chars) + return "".join(out) - def __raw_get(self, key: str) -> Optional[str]: + def __raw_get(self, key: str) -> str | None: """ Get a raw data value from the config file. @@ -121,7 +123,7 @@ class LinuxConfig(AbstractConfig): return self.config[self.SECTION].get(key) - def get_str(self, key: str, *, default: Optional[str] = None) -> str: + def get_str(self, key: str, *, default: str | None = None) -> str: """ Return the string referred to by the given key if it exists, or the default. @@ -129,28 +131,29 @@ class LinuxConfig(AbstractConfig): """ data = self.__raw_get(key) if data is None: - return default or "" + return default # type: ignore # Yes it could be None, but we're _assuming_ that people gave us a default if '\n' in data: - raise ValueError('Expected string, but got list') + raise ValueError('asked for string, got list') return self.__unescape(data) - def get_list(self, key: str, *, default: Optional[list] = None) -> list: + def get_list(self, key: str, *, default: list | None = None) -> list: """ Return the list referred to by the given key if it exists, or the default. Implements :meth:`AbstractConfig.get_list`. """ data = self.__raw_get(key) + if data is None: - return default or [] + return default # type: ignore # Yes it could be None, but we're _assuming_ that people gave us a default split = data.split('\n') if split[-1] != ';': raise ValueError('Encoded list does not have trailer sentinel') - return [self.__unescape(item) for item in split[:-1]] + return list(map(self.__unescape, split[:-1])) def get_int(self, key: str, *, default: int = 0) -> int: """ @@ -159,47 +162,55 @@ class LinuxConfig(AbstractConfig): Implements :meth:`AbstractConfig.get_int`. """ data = self.__raw_get(key) + if data is None: return default try: return int(data) - except ValueError as e: - raise ValueError(f'Failed to convert {key=} to int') from e - def get_bool(self, key: str, *, default: Optional[bool] = None) -> bool: + except ValueError as e: + raise ValueError(f'requested {key=} as int cannot be converted to int') from e + + def get_bool(self, key: str, *, default: bool | None = None) -> bool: """ Return the bool referred to by the given key if it exists, or the default. Implements :meth:`AbstractConfig.get_bool`. """ if self.config is None: - raise ValueError('Attempt to use a closed config') + raise ValueError('attempt to use a closed config') data = self.__raw_get(key) if data is None: - return default or False + return default # type: ignore # Yes it could be None, but we're _assuming_ that people gave us a default return bool(int(data)) - def set(self, key: str, val: Union[int, str, List[str]]) -> None: + def set(self, key: str, val: int | str | list[str]) -> None: """ Set the given key's data to the given value. Implements :meth:`AbstractConfig.set`. """ if self.config is None: - raise ValueError('Attempt to use a closed config') + raise ValueError('attempt to use a closed config') + + to_set: str | None = None if isinstance(val, bool): to_set = str(int(val)) + elif isinstance(val, str): to_set = self.__escape(val) + elif isinstance(val, int): to_set = str(val) + elif isinstance(val, list): to_set = '\n'.join([self.__escape(s) for s in val] + [';']) + else: - raise ValueError(f'Unexpected type for value {type(val).__name__}') + raise ValueError(f'Unexpected type for value {type(val)=}') self.config.set(self.SECTION, key, to_set) self.save() @@ -211,7 +222,7 @@ class LinuxConfig(AbstractConfig): Implements :meth:`AbstractConfig.delete`. """ if self.config is None: - raise ValueError('Attempt to delete from a closed config') + raise ValueError('attempt to use a closed config') self.config.remove_option(self.SECTION, key) self.save() @@ -223,7 +234,7 @@ class LinuxConfig(AbstractConfig): Implements :meth:`AbstractConfig.save`. """ if self.config is None: - raise ValueError('Attempt to save a closed config') + raise ValueError('attempt to use a closed config') with open(self.filename, 'w', encoding='utf-8') as f: self.config.write(f) @@ -235,4 +246,4 @@ class LinuxConfig(AbstractConfig): Implements :meth:`AbstractConfig.close`. """ self.save() - self.config = None # type: ignore + self.config = None From 070a3989a08e343e2373e2a302386db7d984dd18 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 10 Nov 2023 11:33:04 -0500 Subject: [PATCH 19/83] [2051] Prevent Typing Reversion Thanks to @norohind for catching this one! I'm not up to date on my PEP585. --- config/__init__.py | 30 ++++++------ config/darwin.py | 10 ++-- config/windows.py | 18 ++++--- plugins/coriolis.py | 9 ++-- plugins/eddn.py | 115 ++++++++++++++++++++++---------------------- plugins/edsm.py | 70 ++++++++++++++------------- plugins/edsy.py | 6 ++- plugins/inara.py | 66 ++++++++++++------------- 8 files changed, 167 insertions(+), 157 deletions(-) diff --git a/config/__init__.py b/config/__init__.py index ae08f3a0..e86a60d1 100644 --- a/config/__init__.py +++ b/config/__init__.py @@ -9,6 +9,8 @@ Windows uses the Registry to store values in a flat manner. Linux uses a file, but for commonality it's still a flat data structure. macOS uses a 'defaults' object. """ +from __future__ import annotations + __all__ = [ # defined in the order they appear in the file 'GITVERSION_FILE', @@ -42,7 +44,7 @@ import sys import traceback import warnings from abc import abstractmethod -from typing import Any, Callable, Optional, Type, TypeVar, Union, List +from typing import Any, Callable, Type, TypeVar import semantic_version from constants import GITVERSION_FILE, applongname, appname @@ -54,19 +56,19 @@ appcmdname = 'EDMC' # NB: Do *not* import this, use the functions appversion() and appversion_nobuild() _static_appversion = '5.10.0-alpha0' -_cached_version: Optional[semantic_version.Version] = None +_cached_version: semantic_version.Version | None = None copyright = '© 2015-2019 Jonathan Harris, 2020-2023 EDCD' update_feed = 'https://raw.githubusercontent.com/EDCD/EDMarketConnector/releases/edmarketconnector.xml' update_interval = 8*60*60 # Providers marked to be in debug mode. Generally this is expected to switch to sending data to a log file -debug_senders: List[str] = [] +debug_senders: list[str] = [] # TRACE logging code that should actually be used. Means not spamming it # *all* if only interested in some things. -trace_on: List[str] = [] +trace_on: list[str] = [] capi_pretend_down: bool = False -capi_debug_access_token: Optional[str] = None +capi_debug_access_token: str | None = None # This must be done here in order to avoid an import cycle with EDMCLogging. # Other code should use EDMCLogging.get_main_logger if os.getenv("EDMC_NO_UI"): @@ -232,7 +234,7 @@ class AbstractConfig(abc.ABC): self.__eddn_url = eddn_url @property - def eddn_url(self) -> Optional[str]: + def eddn_url(self) -> str | None: """ Provide the custom EDDN URL. @@ -285,9 +287,9 @@ class AbstractConfig(abc.ABC): @staticmethod def _suppress_call( - func: Callable[..., _T], exceptions: Union[Type[BaseException], List[Type[BaseException]]] = Exception, + func: Callable[..., _T], exceptions: Type[BaseException] | list[Type[BaseException]] = Exception, *args: Any, **kwargs: Any - ) -> Optional[_T]: + ) -> _T | None: if exceptions is None: exceptions = [Exception] @@ -301,8 +303,8 @@ class AbstractConfig(abc.ABC): def get( self, key: str, - default: Union[list, str, bool, int, None] = None - ) -> Union[list, str, bool, int, None]: + default: list | str | bool | int | None = None + ) -> list | str | bool | int | None: """ Return the data for the requested key, or a default. @@ -329,7 +331,7 @@ class AbstractConfig(abc.ABC): return default @abstractmethod - def get_list(self, key: str, *, default: Optional[list] = None) -> list: + def get_list(self, key: str, *, default: list | None = None) -> list: """ Return the list referred to by the given key if it exists, or the default. @@ -338,7 +340,7 @@ class AbstractConfig(abc.ABC): raise NotImplementedError @abstractmethod - def get_str(self, key: str, *, default: Optional[str] = None) -> str: + def get_str(self, key: str, *, default: str | None = None) -> str: """ Return the string referred to by the given key if it exists, or the default. @@ -351,7 +353,7 @@ class AbstractConfig(abc.ABC): raise NotImplementedError @abstractmethod - def get_bool(self, key: str, *, default: Optional[bool] = None) -> bool: + def get_bool(self, key: str, *, default: bool | None = None) -> bool: """ Return the bool referred to by the given key if it exists, or the default. @@ -391,7 +393,7 @@ class AbstractConfig(abc.ABC): raise NotImplementedError @abstractmethod - def set(self, key: str, val: Union[int, str, List[str], bool]) -> None: + def set(self, key: str, val: int | str | list[str] | bool) -> None: """ Set the given key's data to the given value. diff --git a/config/darwin.py b/config/darwin.py index 68d30306..9c15ec32 100644 --- a/config/darwin.py +++ b/config/darwin.py @@ -5,9 +5,11 @@ Copyright (c) EDCD, All Rights Reserved Licensed under the GNU General Public License. See LICENSE file. """ +from __future__ import annotations + import pathlib import sys -from typing import Any, Dict, List, Union +from typing import Any from Foundation import ( # type: ignore NSApplicationSupportDirectory, NSBundle, NSDocumentDirectory, NSSearchPathForDirectoriesInDomains, NSUserDefaults, NSUserDomainMask @@ -52,14 +54,14 @@ class MacConfig(AbstractConfig): self.default_journal_dir_path = support_path / 'Frontier Developments' / 'Elite Dangerous' self._defaults: Any = NSUserDefaults.standardUserDefaults() - self._settings: Dict[str, Union[int, str, list]] = dict( + self._settings: dict[str, int | str | list] = dict( self._defaults.persistentDomainForName_(self.identifier) or {} ) # make writeable if (out_dir := self.get_str('out_dir')) is None or not pathlib.Path(out_dir).exists(): self.set('outdir', NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, True)[0]) - def __raw_get(self, key: str) -> Union[None, list, str, int]: + def __raw_get(self, key: str) -> None | list | str | int: """ Retrieve the raw data for the given key. @@ -143,7 +145,7 @@ class MacConfig(AbstractConfig): return res - def set(self, key: str, val: Union[int, str, List[str], bool]) -> None: + def set(self, key: str, val: int | str | list[str] | bool) -> None: """ Set the given key's data to the given value. diff --git a/config/windows.py b/config/windows.py index 94a158f1..7fb53a37 100644 --- a/config/windows.py +++ b/config/windows.py @@ -5,6 +5,8 @@ Copyright (c) EDCD, All Rights Reserved Licensed under the GNU General Public License. See LICENSE file. """ +from __future__ import annotations + import ctypes import functools import pathlib @@ -12,7 +14,7 @@ import sys import uuid import winreg from ctypes.wintypes import DWORD, HANDLE -from typing import List, Literal, Optional, Union +from typing import Literal from config import AbstractConfig, applongname, appname, logger, update_interval assert sys.platform == 'win32' @@ -32,7 +34,7 @@ CoTaskMemFree = ctypes.windll.ole32.CoTaskMemFree CoTaskMemFree.argtypes = [ctypes.c_void_p] -def known_folder_path(guid: uuid.UUID) -> Optional[str]: +def known_folder_path(guid: uuid.UUID) -> str | None: """Look up a Windows GUID to actual folder path name.""" buf = ctypes.c_wchar_p() if SHGetKnownFolderPath(ctypes.create_string_buffer(guid.bytes_le), 0, 0, ctypes.byref(buf)): @@ -117,7 +119,7 @@ class WinConfig(AbstractConfig): logger.exception('Could not open WinSparkle handle') raise - def __get_regentry(self, key: str) -> Union[None, list, str, int]: + def __get_regentry(self, key: str) -> None | list | str | int: """Access the Registry for the raw entry.""" try: value, _type = winreg.QueryValueEx(self.__reg_handle, key) @@ -138,7 +140,7 @@ class WinConfig(AbstractConfig): logger.warning(f'Registry key {key=} returned unknown type {_type=} {value=}') return None - def get_str(self, key: str, *, default: Optional[str] = None) -> str: + def get_str(self, key: str, *, default: str | None = None) -> str: """ Return the string referred to by the given key if it exists, or the default. @@ -153,7 +155,7 @@ class WinConfig(AbstractConfig): return res - def get_list(self, key: str, *, default: Optional[list] = None) -> list: + def get_list(self, key: str, *, default: list | None = None) -> list: """ Return the list referred to by the given key if it exists, or the default. @@ -183,7 +185,7 @@ class WinConfig(AbstractConfig): return res - def get_bool(self, key: str, *, default: Optional[bool] = None) -> bool: + def get_bool(self, key: str, *, default: bool | None = None) -> bool: """ Return the bool referred to by the given key if it exists, or the default. @@ -195,14 +197,14 @@ class WinConfig(AbstractConfig): return bool(res) - def set(self, key: str, val: Union[int, str, List[str], bool]) -> None: + def set(self, key: str, val: int | str | list[str] | bool) -> None: """ Set the given key's data to the given value. Implements :meth:`AbstractConfig.set`. """ # These are the types that winreg.REG_* below resolve to. - reg_type: Union[Literal[1], Literal[4], Literal[7]] + reg_type: Literal[1] | Literal[4] | Literal[7] if isinstance(val, str): reg_type = winreg.REG_SZ diff --git a/plugins/coriolis.py b/plugins/coriolis.py index 7161a4e0..283b49d8 100644 --- a/plugins/coriolis.py +++ b/plugins/coriolis.py @@ -19,6 +19,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. """ +from __future__ import annotations import base64 import gzip @@ -26,7 +27,7 @@ import io import json import tkinter as tk from tkinter import ttk -from typing import TYPE_CHECKING, Union, Optional +from typing import TYPE_CHECKING import myNotebook as nb # noqa: N813 # its not my fault. from EDMCLogging import get_main_logger from plug import show_error @@ -80,7 +81,7 @@ def plugin_start3(path: str) -> str: return 'Coriolis' -def plugin_prefs(parent: ttk.Notebook, cmdr: Optional[str], is_beta: bool) -> tk.Frame: +def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Frame: """Set up plugin preferences.""" PADX = 10 # noqa: N806 @@ -130,7 +131,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: Optional[str], is_beta: bool) -> tk return conf_frame -def prefs_changed(cmdr: Optional[str], is_beta: bool) -> None: +def prefs_changed(cmdr: str | None, is_beta: bool) -> None: """ Update URLs and override mode based on user preferences. @@ -175,7 +176,7 @@ def _get_target_url(is_beta: bool) -> str: return coriolis_config.normal_url -def shipyard_url(loadout, is_beta) -> Union[str, bool]: +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') diff --git a/plugins/eddn.py b/plugins/eddn.py index d2e7d01e..ee70d6e9 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -18,6 +18,8 @@ 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. """ +from __future__ import annotations + import http import itertools import json @@ -37,9 +39,6 @@ from typing import ( Iterator, Mapping, MutableMapping, - Optional, - Dict, - List, ) from typing import OrderedDict as OrderedDictT from typing import Tuple, Union @@ -86,27 +85,27 @@ class This: self.odyssey = False # Track location to add to Journal events - self.system_address: Optional[str] = None - self.system_name: Optional[str] = None - self.coordinates: Optional[Tuple] = None - self.body_name: Optional[str] = None - self.body_id: Optional[int] = None - self.body_type: Optional[int] = None - self.station_name: Optional[str] = None - self.station_type: Optional[str] = None - self.station_marketid: Optional[str] = None + self.system_address: str | None = None + self.system_name: str | None = None + self.coordinates: tuple | None = None + self.body_name: str | None = None + self.body_id: int | None = None + self.body_type: int | None = None + self.station_name: str | None = None + self.station_type: str | None = None + self.station_marketid: str | None = None # Track Status.json data - self.status_body_name: Optional[str] = None + self.status_body_name: str | None = None # Avoid duplicates - self.marketId: Optional[str] = None - self.commodities: Optional[List[OrderedDictT[str, Any]]] = None - self.outfitting: Optional[Tuple[bool, List[str]]] = None - self.shipyard: Optional[Tuple[bool, List[Mapping[str, Any]]]] = None + self.marketId: str | None = None + self.commodities: list[OrderedDictT[str, Any]] | None = None + self.outfitting: Tuple[bool, list[str]] | None = None + self.shipyard: Tuple[bool, list[Mapping[str, Any]]] | None = None self.fcmaterials_marketid: int = 0 - self.fcmaterials: Optional[List[OrderedDictT[str, Any]]] = None + self.fcmaterials: list[OrderedDictT[str, Any]] | None = None self.fcmaterials_capi_marketid: int = 0 - self.fcmaterials_capi: Optional[List[OrderedDictT[str, Any]]] = None + self.fcmaterials_capi: list[OrderedDictT[str, Any]] | None = None # For the tkinter parent window, so we can call update_idletasks() self.parent: tk.Tk @@ -395,7 +394,7 @@ class EDDNSender: """ logger.trace_if("plugin.eddn.send", "Sending message") should_return: bool - new_data: Dict[str, Any] + new_data: dict[str, Any] should_return, new_data = killswitch.check_killswitch('plugins.eddn.send', json.loads(msg)) if should_return: @@ -404,7 +403,7 @@ class EDDNSender: # Even the smallest possible message compresses somewhat, so always compress encoded, compressed = text.gzip(json.dumps(new_data, separators=(',', ':')), max_size=0) - headers: Optional[Dict[str, str]] = None + headers: dict[str, str] | None = None if compressed: headers = {'Content-Encoding': 'gzip'} @@ -612,7 +611,7 @@ class EDDN: self.sender = EDDNSender(self, self.eddn_url) - self.fss_signals: List[Mapping[str, Any]] = [] + self.fss_signals: list[Mapping[str, Any]] = [] def close(self): """Close down the EDDN class instance.""" @@ -636,7 +635,7 @@ class EDDN: :param is_beta: whether or not we're currently in beta mode """ should_return: bool - new_data: Dict[str, Any] + new_data: dict[str, Any] should_return, new_data = killswitch.check_killswitch('capi.request./market', {}) if should_return: logger.warning("capi.request./market has been disabled by killswitch. Returning.") @@ -653,7 +652,7 @@ class EDDN: modules, ships ) - commodities: List[OrderedDictT[str, Any]] = [] + commodities: list[OrderedDictT[str, Any]] = [] for commodity in data['lastStarport'].get('commodities') or []: # Check 'marketable' and 'not prohibited' if (category_map.get(commodity['categoryname'], True) @@ -726,7 +725,7 @@ class EDDN: :param data: The raw CAPI data. :return: Sanity-checked data. """ - modules: Dict[str, Any] = data['lastStarport'].get('modules') + modules: dict[str, Any] = data['lastStarport'].get('modules') if modules is None or not isinstance(modules, dict): if modules is None: logger.debug('modules was None. FC or Damaged Station?') @@ -743,13 +742,13 @@ class EDDN: # Set a safe value modules = {} - ships: Dict[str, Any] = data['lastStarport'].get('ships') + ships: dict[str, Any] = data['lastStarport'].get('ships') if ships is None or not isinstance(ships, dict): if ships is None: logger.debug('ships was None') else: - logger.error(f'ships was neither None nor a Dict! Type = {type(ships)}') + logger.error(f'ships was neither None nor a dict! Type = {type(ships)}') # Set a safe value ships = {'shipyard_list': {}, 'unavailable_list': []} @@ -769,7 +768,7 @@ class EDDN: :param is_beta: whether or not we're currently in beta mode """ should_return: bool - new_data: Dict[str, Any] + new_data: dict[str, Any] should_return, new_data = killswitch.check_killswitch('capi.request./shipyard', {}) if should_return: logger.warning("capi.request./shipyard has been disabled by killswitch. Returning.") @@ -796,7 +795,7 @@ class EDDN: modules.values() ) - outfitting: List[str] = sorted( + outfitting: list[str] = sorted( self.MODULE_RE.sub(lambda match: match.group(0).capitalize(), mod['name'].lower()) for mod in to_search ) @@ -837,7 +836,7 @@ class EDDN: :param is_beta: whether or not we are in beta mode """ should_return: bool - new_data: Dict[str, Any] + new_data: dict[str, Any] should_return, new_data = killswitch.check_killswitch('capi.request./shipyard', {}) if should_return: logger.warning("capi.request./shipyard has been disabled by killswitch. Returning.") @@ -856,7 +855,7 @@ class EDDN: ships ) - shipyard: List[Mapping[str, Any]] = sorted( + shipyard: list[Mapping[str, Any]] = sorted( itertools.chain( (ship['name'].lower() for ship in (ships['shipyard_list'] or {}).values()), (ship['name'].lower() for ship in ships['unavailable_list'] or {}), @@ -899,8 +898,8 @@ class EDDN: :param is_beta: whether or not we're in beta mode :param entry: the journal entry containing the commodities data """ - items: List[Mapping[str, Any]] = entry.get('Items') or [] - commodities: List[OrderedDictT[str, Any]] = sorted((OrderedDict([ + items: list[Mapping[str, Any]] = entry.get('Items') or [] + commodities: list[OrderedDictT[str, Any]] = sorted((OrderedDict([ ('name', self.canonicalise(commodity['Name'])), ('meanPrice', commodity['MeanPrice']), ('buyPrice', commodity['BuyPrice']), @@ -947,11 +946,11 @@ class EDDN: :param is_beta: Whether or not we're in beta mode :param entry: The relevant journal entry """ - modules: List[Mapping[str, Any]] = entry.get('Items', []) + modules: list[Mapping[str, Any]] = entry.get('Items', []) horizons: bool = entry.get('Horizons', False) # outfitting = sorted([self.MODULE_RE.sub(lambda m: m.group(0).capitalize(), module['Name']) # for module in modules if module['Name'] != 'int_planetapproachsuite']) - outfitting: List[str] = sorted( + outfitting: list[str] = sorted( self.MODULE_RE.sub(lambda m: m.group(0).capitalize(), mod['Name']) for mod in filter(lambda m: m['Name'] != 'int_planetapproachsuite', modules) ) @@ -986,7 +985,7 @@ class EDDN: :param is_beta: Whether or not we're in beta mode :param entry: the relevant journal entry """ - ships: List[Mapping[str, Any]] = entry.get('PriceList') or [] + ships: list[Mapping[str, Any]] = entry.get('Pricelist') or [] horizons: bool = entry.get('Horizons', False) shipyard = sorted(ship['ShipType'] for ship in ships) # Don't send empty ships list - shipyard data is only guaranteed present if user has visited the shipyard. @@ -1042,7 +1041,7 @@ class EDDN: self.sender.send_message_by_id(msg_id) def standard_header( - self, game_version: Optional[str] = None, game_build: Optional[str] = None + self, game_version: str | None = None, game_build: str | None = None ) -> MutableMapping[str, Any]: """ Return the standard header for an EDDN message, given tracked state. @@ -1134,7 +1133,7 @@ class EDDN: def export_journal_fssdiscoveryscan( self, cmdr: str, system_name: str, system_starpos: list, is_beta: bool, entry: Mapping[str, Any] - ) -> Optional[str]: + ) -> str | None: """ Send an FSSDiscoveryScan to EDDN on the correct schema. @@ -1176,7 +1175,7 @@ class EDDN: def export_journal_navbeaconscan( self, cmdr: str, system_name: str, system_starpos: list, is_beta: bool, entry: Mapping[str, Any] - ) -> Optional[str]: + ) -> str | None: """ Send an NavBeaconScan to EDDN on the correct schema. @@ -1218,7 +1217,7 @@ class EDDN: def export_journal_codexentry( # noqa: CCR001 self, cmdr: str, system_starpos: list, is_beta: bool, entry: MutableMapping[str, Any] - ) -> Optional[str]: + ) -> str | None: """ Send a CodexEntry to EDDN on the correct schema. @@ -1320,7 +1319,7 @@ class EDDN: def export_journal_scanbarycentre( self, cmdr: str, system_starpos: list, is_beta: bool, entry: Mapping[str, Any] - ) -> Optional[str]: + ) -> str | None: """ Send a ScanBaryCentre to EDDN on the correct schema. @@ -1374,7 +1373,7 @@ class EDDN: def export_journal_navroute( self, cmdr: str, is_beta: bool, entry: MutableMapping[str, Any] - ) -> Optional[str]: + ) -> str | None: """ Send a NavRoute to EDDN on the correct schema. @@ -1447,7 +1446,7 @@ class EDDN: def export_journal_fcmaterials( self, cmdr: str, is_beta: bool, entry: MutableMapping[str, Any] - ) -> Optional[str]: + ) -> str | None: """ Send an FCMaterials message to EDDN on the correct schema. @@ -1531,7 +1530,7 @@ class EDDN: def export_capi_fcmaterials( self, data: CAPIData, is_beta: bool, horizons: bool - ) -> Optional[str]: + ) -> str | None: """ Send CAPI-sourced 'onfootmicroresources' data on `fcmaterials/1` schema. @@ -1594,7 +1593,7 @@ class EDDN: def export_journal_approachsettlement( self, cmdr: str, system_name: str, system_starpos: list, is_beta: bool, entry: MutableMapping[str, Any] - ) -> Optional[str]: + ) -> str | None: """ Send an ApproachSettlement to EDDN on the correct schema. @@ -1669,7 +1668,7 @@ class EDDN: def export_journal_fssallbodiesfound( self, cmdr: str, system_name: str, system_starpos: list, is_beta: bool, entry: MutableMapping[str, Any] - ) -> Optional[str]: + ) -> str | None: """ Send an FSSAllBodiesFound message to EDDN on the correct schema. @@ -1719,7 +1718,7 @@ class EDDN: def export_journal_fssbodysignals( self, cmdr: str, system_name: str, system_starpos: list, is_beta: bool, entry: MutableMapping[str, Any] - ) -> Optional[str]: + ) -> str | None: """ Send an FSSBodySignals message to EDDN on the correct schema. @@ -1789,7 +1788,7 @@ class EDDN: def export_journal_fsssignaldiscovered( self, cmdr: str, system_name: str, system_starpos: list, is_beta: bool, entry: MutableMapping[str, Any] - ) -> Optional[str]: + ) -> str | None: """ Send an FSSSignalDiscovered message to EDDN on the correct schema. @@ -1892,7 +1891,7 @@ class EDDN: match = self.CANONICALISE_RE.match(item) return match and match.group(1) or item - def capi_gameversion_from_host_endpoint(self, capi_host: Optional[str], capi_endpoint: str) -> str: + def capi_gameversion_from_host_endpoint(self, capi_host: str | None, capi_endpoint: str) -> str: """ Return the correct CAPI gameversion string for the given host/endpoint. @@ -1910,7 +1909,7 @@ class EDDN: gv = 'CAPI-Legacy-' else: - # Technically incorrect, but it will inform Listeners + # Technically incorrect, but it will inform listeners logger.error(f"{capi_host=} lead to bad gameversion") gv = 'CAPI-UNKNOWN-' ####################################################################### @@ -1924,7 +1923,7 @@ class EDDN: gv += 'shipyard' else: - # Technically incorrect, but it will inform Listeners + # Technically incorrect, but it will inform listeners logger.error(f"{capi_endpoint=} lead to bad gameversion") gv += 'UNKNOWN' ####################################################################### @@ -1943,7 +1942,7 @@ def plugin_start3(plugin_dir: str) -> str: return 'EDDN' -def plugin_app(parent: tk.Tk) -> Optional[tk.Frame]: +def plugin_app(parent: tk.Tk) -> tk.Frame | None: """ Set up any plugin-specific UI. @@ -2183,7 +2182,7 @@ def filter_localised(d: Mapping[str, Any]) -> OrderedDictT[str, Any]: """ Recursively remove any dict keys with names ending `_Localised` from a dict. - :param d: Dict to filter keys of. + :param d: dict to filter keys of. :return: The filtered dict. """ filtered: OrderedDictT[str, Any] = OrderedDict() @@ -2207,7 +2206,7 @@ def capi_filter_localised(d: Mapping[str, Any]) -> OrderedDictT[str, Any]: """ Recursively remove any dict keys for known CAPI 'localised' names. - :param d: Dict to filter keys of. + :param d: dict to filter keys of. :return: The filtered dict. """ filtered: OrderedDictT[str, Any] = OrderedDict() @@ -2234,7 +2233,7 @@ def journal_entry( # noqa: C901, CCR001 station: str, entry: MutableMapping[str, Any], state: Mapping[str, Any] -) -> Optional[str]: +) -> str | None: """ Process a new Journal entry. @@ -2491,7 +2490,7 @@ def journal_entry( # noqa: C901, CCR001 return None -def cmdr_data_legacy(data: CAPIData, is_beta: bool) -> Optional[str]: +def cmdr_data_legacy(data: CAPIData, is_beta: bool) -> str | None: """ Process new CAPI data for Legacy galaxy. @@ -2510,7 +2509,7 @@ def cmdr_data_legacy(data: CAPIData, is_beta: bool) -> Optional[str]: return cmdr_data(data, is_beta) -def cmdr_data(data: CAPIData, is_beta: bool) -> Optional[str]: # noqa: CCR001 +def cmdr_data(data: CAPIData, is_beta: bool) -> str | None: # noqa: CCR001 """ Process new CAPI data for not-Legacy galaxy (might be beta). @@ -2611,7 +2610,7 @@ def capi_is_horizons(economies: MAP_STR_ANY, modules: MAP_STR_ANY, ships: MAP_ST return economies_colony or modules_horizons or ship_horizons -def dashboard_entry(cmdr: str, is_beta: bool, entry: Dict[str, Any]) -> None: +def dashboard_entry(cmdr: str, is_beta: bool, entry: dict[str, Any]) -> None: """ Process Status.json data to track things like current Body. diff --git a/plugins/edsm.py b/plugins/edsm.py index 2f644dcb..33af692b 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -18,6 +18,8 @@ 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. """ +from __future__ import annotations + import json import threading import tkinter as tk @@ -26,7 +28,7 @@ from queue import Queue from threading import Thread from time import sleep from tkinter import ttk -from typing import TYPE_CHECKING, Any, Dict, List, Literal, Mapping, MutableMapping, Optional, Set, Tuple, Union, cast +from typing import TYPE_CHECKING, Any, Literal, Mapping, MutableMapping, cast import requests import killswitch import monitor @@ -72,27 +74,27 @@ class This: self.game_build = "" # Handle only sending Live galaxy data - self.legacy_galaxy_last_notified: Optional[datetime] = None + self.legacy_galaxy_last_notified: datetime | None = None self.session: requests.Session = requests.Session() self.session.headers['User-Agent'] = user_agent self.queue: Queue = Queue() # Items to be sent to EDSM by worker thread - self.discarded_events: Set[str] = set() # List discarded events from EDSM - self.lastlookup: Dict[str, Any] # Result of last system lookup + self.discarded_events: set[str] = set() # List discarded events from EDSM + self.lastlookup: dict[str, Any] # Result of last system lookup # Game state self.multicrew: bool = False # don't send captain's ship info to EDSM while on a crew - self.coordinates: Optional[Tuple[int, int, int]] = None + self.coordinates: tuple[int, int, int] | None = None self.newgame: bool = False # starting up - batch initial burst of events self.newgame_docked: bool = False # starting up while docked self.navbeaconscan: int = 0 # batch up burst of Scan events after NavBeaconScan - self.system_link: Optional[tk.Widget] = None - self.system_name: Optional[tk.Tk] = None - self.system_address: Optional[int] = None # Frontier SystemAddress - self.system_population: Optional[int] = None - self.station_link: Optional[tk.Widget] = None - self.station_name: Optional[str] = None - self.station_marketid: Optional[int] = None # Frontier MarketID + self.system_link: tk.Widget | None = None + self.system_name: tk.Tk | None = None + self.system_address: int | None = None # Frontier SystemAddress + self.system_population: int | None = None + self.station_link: tk.Widget | None = None + self.station_name: str | None = None + self.station_marketid: int | None = None # Frontier MarketID self.on_foot = False self._IMG_KNOWN = None @@ -100,21 +102,21 @@ class This: self._IMG_NEW = None self._IMG_ERROR = None - self.thread: Optional[threading.Thread] = None + self.thread: threading.Thread | None = None - self.log: Optional[tk.IntVar] = None - self.log_button: Optional[ttk.Checkbutton] = None + self.log: tk.IntVar | None = None + self.log_button: ttk.Checkbutton | None = None - self.label: Optional[tk.Widget] = None + self.label: tk.Widget | None = None - self.cmdr_label: Optional[nb.Label] = None - self.cmdr_text: Optional[nb.Label] = None + self.cmdr_label: nb.Label | None = None + self.cmdr_text: nb.Label | None = None - self.user_label: Optional[nb.Label] = None - self.user: Optional[nb.Entry] = None + self.user_label: nb.Label | None = None + self.user: nb.Entry | None = None - self.apikey_label: Optional[nb.Label] = None - self.apikey: Optional[nb.Entry] = None + self.apikey_label: nb.Label | None = None + self.apikey: nb.Entry | None = None this = This() @@ -277,7 +279,7 @@ def toggle_password_visibility(): this.apikey.config(show="*") # type: ignore -def plugin_prefs(parent: ttk.Notebook, cmdr: Optional[str], is_beta: bool) -> tk.Frame: +def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Frame: """ Plugin preferences setup hook. @@ -361,7 +363,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: Optional[str], is_beta: bool) -> tk return frame -def prefs_cmdr_changed(cmdr: Optional[str], is_beta: bool) -> None: # noqa: CCR001 +def prefs_cmdr_changed(cmdr: str | None, is_beta: bool) -> None: # noqa: CCR001 """ Handle the Commander name changing whilst Settings was open. @@ -390,7 +392,7 @@ def prefs_cmdr_changed(cmdr: Optional[str], is_beta: bool) -> None: # noqa: CCR # LANG: We have no data on the current commander this.cmdr_text['text'] = _('None') - to_set: Union[Literal['normal'], Literal['disabled']] = tk.DISABLED + to_set: Literal['normal'] | Literal['disabled'] = tk.DISABLED if cmdr and not is_beta and this.log and this.log.get(): to_set = tk.NORMAL @@ -440,9 +442,9 @@ def prefs_changed(cmdr: str, is_beta: bool) -> None: config.set('edsm_out', this.log.get()) if cmdr and not is_beta: - cmdrs: List[str] = config.get_list('edsm_cmdrs', default=[]) - usernames: List[str] = config.get_list('edsm_usernames', default=[]) - apikeys: List[str] = config.get_list('edsm_apikeys', default=[]) + cmdrs: list[str] = config.get_list('edsm_cmdrs', default=[]) + usernames: list[str] = config.get_list('edsm_usernames', default=[]) + apikeys: list[str] = config.get_list('edsm_apikeys', default=[]) if this.user and this.apikey: if cmdr in cmdrs: @@ -460,7 +462,7 @@ def prefs_changed(cmdr: str, is_beta: bool) -> None: config.set('edsm_apikeys', apikeys) -def credentials(cmdr: str) -> Optional[Tuple[str, str]]: +def credentials(cmdr: str) -> tuple[str, str] | None: """ Get credentials for the given commander, if they exist. @@ -635,7 +637,7 @@ Queueing: {entry!r}''' # Update system data -def cmdr_data(data: CAPIData, is_beta: bool) -> Optional[str]: # noqa: CCR001 +def cmdr_data(data: CAPIData, is_beta: bool) -> str | None: # noqa: CCR001 """ Process new CAPI data. @@ -722,7 +724,7 @@ def worker() -> None: # noqa: CCR001 C901 :return: None """ logger.debug('Starting...') - pending: List[Mapping[str, Any]] = [] # Unsent events + pending: list[Mapping[str, Any]] = [] # Unsent events closing = False cmdr: str = "" last_game_version = "" @@ -744,7 +746,7 @@ def worker() -> None: # noqa: CCR001 C901 logger.debug(f'{this.shutting_down=}, so setting closing = True') closing = True - item: Optional[Tuple[str, str, str, Mapping[str, Any]]] = this.queue.get() + item: tuple[str, str, str, Mapping[str, Any]] | None = this.queue.get() if item: (cmdr, game_version, game_build, entry) = item logger.trace_if(CMDR_EVENTS, f'De-queued ({cmdr=}, {game_version=}, {game_build=}, {entry["event"]=})') @@ -756,7 +758,7 @@ def worker() -> None: # noqa: CCR001 C901 retrying = 0 while retrying < 3: if item is None: - item = cast(Tuple[str, str, str, Mapping[str, Any]], ("", {})) + item = cast(tuple[str, str, str, Mapping[str, Any]], ("", {})) should_skip, new_item = killswitch.check_killswitch( 'plugins.edsm.worker', item, @@ -909,7 +911,7 @@ def worker() -> None: # noqa: CCR001 C901 last_game_build = game_build -def should_send(entries: List[Mapping[str, Any]], event: str) -> bool: # noqa: CCR001 +def should_send(entries: list[Mapping[str, Any]], event: str) -> bool: # noqa: CCR001 """ Whether or not any of the given entries should be sent to EDSM. diff --git a/plugins/edsy.py b/plugins/edsy.py index 0c78a429..a02d3424 100644 --- a/plugins/edsy.py +++ b/plugins/edsy.py @@ -18,11 +18,13 @@ 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. """ +from __future__ import annotations + import base64 import gzip import io import json -from typing import Any, Mapping, Union +from typing import Any, Mapping def plugin_start3(plugin_dir: str) -> str: @@ -36,7 +38,7 @@ def plugin_start3(plugin_dir: str) -> str: # Return a URL for the current ship -def shipyard_url(loadout: Mapping[str, Any], is_beta: bool) -> Union[bool, str]: +def shipyard_url(loadout: Mapping[str, Any], is_beta: bool) -> bool | str: """ Construct a URL for ship loadout. diff --git a/plugins/inara.py b/plugins/inara.py index efe010df..2a124f54 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. """ +from __future__ import annotations import json import threading @@ -29,9 +30,8 @@ from datetime import datetime, timedelta, timezone from operator import itemgetter from threading import Lock, Thread from tkinter import ttk -from typing import TYPE_CHECKING, Any, Callable, Deque, Dict, List, Mapping, NamedTuple, Optional +from typing import TYPE_CHECKING, Any, Callable, Deque, Mapping, NamedTuple, Sequence, cast, Union from typing import OrderedDict as OrderedDictT -from typing import Sequence, Union, cast import requests import edmc_data import killswitch @@ -63,8 +63,8 @@ CREDITS_DELTA_MIN_ABSOLUTE = 10_000_000 # Absolute difference threshold class Credentials(NamedTuple): """Credentials holds the set of credentials required to identify an inara API payload to inara.""" - cmdr: Optional[str] - fid: Optional[str] + cmdr: str | None + fid: str | None api_key: str @@ -89,25 +89,25 @@ class This: self.parent: tk.Tk # Handle only sending Live galaxy data - self.legacy_galaxy_last_notified: Optional[datetime] = None + self.legacy_galaxy_last_notified: datetime | None = None self.lastlocation = None # eventData from the last Commander's Flight Log event self.lastship = None # eventData from the last addCommanderShip or setCommanderShip event # Cached Cmdr state - self.cmdr: Optional[str] = None - self.FID: Optional[str] = None # Frontier ID + self.cmdr: str | None = None + self.FID: str | None = None # Frontier ID self.multicrew: bool = False # don't send captain's ship info to Inara while on a crew self.newuser: bool = False # just entered API Key - send state immediately self.newsession: bool = True # starting a new session - wait for Cargo event self.undocked: bool = False # just undocked self.suppress_docked = False # Skip initial Docked event if started docked - self.cargo: Optional[List[OrderedDictT[str, Any]]] = None - self.materials: Optional[List[OrderedDictT[str, Any]]] = None + self.cargo: list[OrderedDictT[str, Any]] | None = None + self.materials: list[OrderedDictT[str, Any]] | None = None self.last_credits: int = 0 # Send credit update soon after Startup / new game - self.storedmodules: Optional[List[OrderedDictT[str, Any]]] = None - self.loadout: Optional[OrderedDictT[str, Any]] = None - self.fleet: Optional[List[OrderedDictT[str, Any]]] = None + self.storedmodules: list[OrderedDictT[str, Any]] | None = None + self.loadout: OrderedDictT[str, Any] | None = None + self.fleet: list[OrderedDictT[str, Any]] | None = None self.shipswap: bool = False # just swapped ship self.on_foot = False @@ -115,9 +115,9 @@ class This: # Main window clicks self.system_link: tk.Widget = None # type: ignore - self.system_name: Optional[str] = None # type: ignore - self.system_address: Optional[str] = None # type: ignore - self.system_population: Optional[int] = None + self.system_name: str | None = None # type: ignore + 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_marketid = None @@ -129,7 +129,7 @@ class This: self.apikey: nb.Entry self.apikey_label: tk.Label - self.events: Dict[Credentials, Deque[Event]] = defaultdict(deque) + self.events: dict[Credentials, Deque[Event]] = defaultdict(deque) self.event_lock: Lock = threading.Lock() # protects events, for use when rewriting events def filter_events(self, key: Credentials, predicate: Callable[[Event], bool]) -> None: @@ -361,7 +361,7 @@ def prefs_changed(cmdr: str, is_beta: bool) -> None: ) -def credentials(cmdr: Optional[str]) -> Optional[str]: +def credentials(cmdr: str | None) -> str | None: """ Get the credentials for the current commander. @@ -383,7 +383,7 @@ def credentials(cmdr: Optional[str]) -> Optional[str]: def journal_entry( # noqa: C901, CCR001 - cmdr: str, is_beta: bool, system: str, station: str, entry: Dict[str, Any], state: Dict[str, Any] + cmdr: str, is_beta: bool, system: str, station: str, entry: dict[str, Any], state: dict[str, Any] ) -> str: """ Journal entry hook. @@ -394,7 +394,7 @@ def journal_entry( # noqa: C901, CCR001 # causing users to spam Inara with 'URL provider' queries, and we want to # stop that. should_return: bool - new_entry: Dict[str, Any] = {} + new_entry: dict[str, Any] = {} should_return, new_entry = killswitch.check_killswitch('plugins.inara.journal', entry, logger) if should_return: @@ -813,7 +813,7 @@ def journal_entry( # noqa: C901, CCR001 # Fleet if event_name == 'StoredShips': - fleet: List[OrderedDictT[str, Any]] = sorted( + fleet: list[OrderedDictT[str, Any]] = sorted( [OrderedDict({ 'shipType': x['ShipType'], 'shipGameID': x['ShipID'], @@ -860,7 +860,7 @@ def journal_entry( # noqa: C901, CCR001 # Stored modules if event_name == 'StoredModules': items = {mod['StorageSlot']: mod for mod in entry['Items']} # Impose an order - modules: List[OrderedDictT[str, Any]] = [] + modules: list[OrderedDictT[str, Any]] = [] for slot in sorted(items): item = items[slot] module: OrderedDictT[str, Any] = OrderedDict([ @@ -1088,7 +1088,7 @@ def journal_entry( # noqa: C901, CCR001 # # So we're going to do a lot of checking here and bail out if we dont like the look of ANYTHING here - to_send_data: Optional[Dict[str, Any]] = {} # This is a glorified sentinel until lower down. + to_send_data: dict[str, Any] | None = {} # This is a glorified sentinel until lower down. # On Horizons, neither of these exist on TouchDown star_system_name = entry.get('StarSystem', this.system_name) body_name = entry.get('Body', state['Body'] if state['BodyType'] == 'Planet' else None) @@ -1370,7 +1370,7 @@ def cmdr_data(data: CAPIData, is_beta): # noqa: CCR001, reanalyze me later pass -def make_loadout(state: Dict[str, Any]) -> OrderedDictT[str, Any]: # noqa: CCR001 +def make_loadout(state: dict[str, Any]) -> OrderedDictT[str, Any]: # noqa: CCR001 """ Construct an inara loadout from an event. @@ -1440,8 +1440,8 @@ def new_add_event( name: str, timestamp: str, data: EVENT_DATA, - cmdr: Optional[str] = None, - fid: Optional[str] = None + cmdr: str | None = None, + fid: str | None = None ): """ Add a journal event to the queue, to be sent to inara at the next opportunity. @@ -1470,11 +1470,11 @@ def new_add_event( this.events[key].append(Event(name, timestamp, data)) -def clean_event_list(event_list: List[Event]) -> List[Event]: +def clean_event_list(event_list: list[Event]) -> list[Event]: """ Check for killswitched events and remove or modify them as requested. - :param event_list: List of events to clean + :param event_list: list of events to clean :return: Cleaned list of events """ cleaned_events = [] @@ -1533,14 +1533,14 @@ def new_worker(): logger.debug('Done.') -def get_events(clear: bool = True) -> Dict[Credentials, List[Event]]: +def get_events(clear: bool = True) -> dict[Credentials, list[Event]]: """ Fetch a copy of all events from the current queue. :param clear: whether to clear the queues as we go, defaults to True :return: a copy of the event dictionary """ - events_copy: Dict[Credentials, List[Event]] = {} + events_copy: dict[Credentials, list[Event]] = {} with this.event_lock: for key, events in this.events.items(): @@ -1590,7 +1590,7 @@ def send_data(url: str, data: Mapping[str, Any]) -> bool: return True # Regardless of errors above, we DID manage to send it, therefore inform our caller as such -def handle_api_error(data: Mapping[str, Any], status: int, reply: Dict[str, Any]) -> None: +def handle_api_error(data: Mapping[str, Any], status: int, reply: dict[str, Any]) -> None: """ Handle API error response. @@ -1604,7 +1604,7 @@ def handle_api_error(data: Mapping[str, Any], status: int, reply: Dict[str, Any] plug.show_error(_('Error: Inara {MSG}').format(MSG=error_message)) -def handle_success_reply(data: Mapping[str, Any], reply: Dict[str, Any]) -> None: +def handle_success_reply(data: Mapping[str, Any], reply: dict[str, Any]) -> None: """ Handle successful API response. @@ -1619,7 +1619,7 @@ def handle_success_reply(data: Mapping[str, Any], reply: Dict[str, Any]) -> None handle_special_events(data_event, reply_event) -def handle_individual_error(data_event: Dict[str, Any], reply_status: int, reply_text: str) -> None: +def handle_individual_error(data_event: dict[str, Any], reply_status: int, reply_text: str) -> None: """ Handle individual API error. @@ -1638,7 +1638,7 @@ def handle_individual_error(data_event: Dict[str, Any], reply_status: int, reply )) -def handle_special_events(data_event: Dict[str, Any], reply_event: Dict[str, Any]) -> None: +def handle_special_events(data_event: dict[str, Any], reply_event: dict[str, Any]) -> None: """ Handle special events in the API response. From 473bd1cdf6b59fad4b159c8eabd2f70116f06efc Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Thu, 16 Nov 2023 13:21:54 -0500 Subject: [PATCH 20/83] [2051] Replace More Old-Style Union/Opts And re-adds the missing but deprecated abstracts in config --- config/__init__.py | 13 ++++++++++- tests/config/_old_config.py | 26 ++++++++++++---------- tests/config/test_config.py | 12 +++++----- tests/journal_lock.py/test_journal_lock.py | 8 ++++--- tests/killswitch.py/test_apply.py | 6 +++-- tests/killswitch.py/test_killswitch.py | 8 +++---- 6 files changed, 45 insertions(+), 28 deletions(-) diff --git a/config/__init__.py b/config/__init__.py index e86a60d1..ca964274 100644 --- a/config/__init__.py +++ b/config/__init__.py @@ -162,12 +162,23 @@ def appversion_nobuild() -> semantic_version.Version: class AbstractConfig(abc.ABC): - """Abstract root class of all platform specific Config implementations.""" + """ + Abstract root class of all platform specific Config implementations. + + Commented lines are no longer supported or replaced. + """ OUT_EDDN_SEND_STATION_DATA = 1 + # OUT_MKT_BPC = 2 # No longer supported OUT_MKT_TD = 4 OUT_MKT_CSV = 8 OUT_SHIP = 16 + # OUT_SHIP_EDS = 16 # Replaced by OUT_SHIP + # OUT_SYS_FILE = 32 # No longer supported + # OUT_STAT = 64 # No longer available + # OUT_SHIP_CORIOLIS = 128 # Replaced by OUT_SHIP + # OUT_SYS_EDSM = 256 # Now a plugin + # OUT_SYS_AUTO = 512 # Now always automatic OUT_MKT_MANUAL = 1024 OUT_EDDN_SEND_NON_STATION = 2048 OUT_EDDN_DELAY = 4096 diff --git a/tests/config/_old_config.py b/tests/config/_old_config.py index 6eab451b..22f0b18f 100644 --- a/tests/config/_old_config.py +++ b/tests/config/_old_config.py @@ -1,11 +1,13 @@ """Old Configuration Test File.""" +from __future__ import annotations + import numbers import sys import warnings from configparser import NoOptionError from os import getenv, makedirs, mkdir, pardir from os.path import dirname, expanduser, isdir, join, normpath -from typing import TYPE_CHECKING, Optional, Union +from typing import TYPE_CHECKING from config import applongname, appname, update_interval from EDMCLogging import get_main_logger @@ -80,7 +82,7 @@ elif sys.platform == 'win32': RegDeleteValue.restype = LONG RegDeleteValue.argtypes = [HKEY, LPCWSTR] - def known_folder_path(guid: uuid.UUID) -> Optional[str]: + def known_folder_path(guid: uuid.UUID) -> str | None: """Look up a Windows GUID to actual folder path name.""" buf = ctypes.c_wchar_p() if SHGetKnownFolderPath(ctypes.create_string_buffer(guid.bytes_le), 0, 0, ctypes.byref(buf)): @@ -138,7 +140,7 @@ class OldConfig: self.identifier = f'uk.org.marginal.{appname.lower()}' NSBundle.mainBundle().infoDictionary()['CFBundleIdentifier'] = self.identifier - self.default_journal_dir: Optional[str] = join( + self.default_journal_dir: str | None = join( NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], 'Frontier Developments', 'Elite Dangerous' @@ -152,7 +154,7 @@ class OldConfig: if not self.get('outdir') or not isdir(str(self.get('outdir'))): self.set('outdir', NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, True)[0]) - def get(self, key: str, default: Union[None, list, str] = None) -> Union[None, list, str]: + def get(self, key: str, default: None | list | str = None) -> None | list | str: """Look up a string configuration value.""" val = self.settings.get(key) if val is None: @@ -179,7 +181,7 @@ class OldConfig: logger.debug('The exception type is ...', exc_info=e) return default - def set(self, key: str, val: Union[int, str, list]) -> None: + def set(self, key: str, val: int | str | list) -> None: """Set value on the specified configuration key.""" self.settings[key] = val @@ -221,13 +223,13 @@ class OldConfig: journaldir = known_folder_path(FOLDERID_SavedGames) if journaldir: - self.default_journal_dir: Optional[str] = join(journaldir, 'Frontier Developments', 'Elite Dangerous') + self.default_journal_dir: str | None = join(journaldir, 'Frontier Developments', 'Elite Dangerous') else: self.default_journal_dir = None self.identifier = applongname - self.hkey: Optional[ctypes.c_void_p] = HKEY() + self.hkey: ctypes.c_void_p | None = HKEY() disposition = DWORD() if RegCreateKeyEx( HKEY_CURRENT_USER, @@ -280,7 +282,7 @@ class OldConfig: if not self.get('outdir') or not isdir(self.get('outdir')): # type: ignore self.set('outdir', known_folder_path(FOLDERID_Documents) or self.home) - def get(self, key: str, default: Union[None, list, str] = None) -> Union[None, list, str]: + def get(self, key: str, default: None | list | str = None) -> None | list | str: """Look up a string configuration value.""" key_type = DWORD() key_size = DWORD() @@ -327,7 +329,7 @@ class OldConfig: return key_val.value - def set(self, key: str, val: Union[int, str, list]) -> None: + def set(self, key: str, val: int | str | list) -> None: """Set value on the specified configuration key.""" if isinstance(val, str): buf = ctypes.create_unicode_buffer(val) @@ -373,7 +375,7 @@ class OldConfig: mkdir(self.plugin_dir) self.internal_plugin_dir = join(dirname(__file__), 'plugins') - self.default_journal_dir: Optional[str] = None + self.default_journal_dir: str | None = None self.home = expanduser('~') self.respath = dirname(__file__) self.identifier = f'uk.org.marginal.{appname.lower()}' @@ -394,7 +396,7 @@ class OldConfig: if not self.get('outdir') or not isdir(self.get('outdir')): # type: ignore # Not going to change self.set('outdir', expanduser('~')) - def get(self, key: str, default: Union[None, list, str] = None) -> Union[None, list, str]: + def get(self, key: str, default: None | list | str = None) -> None | list | str: """Look up a string configuration value.""" try: val = self.config.get(self.SECTION, key) @@ -429,7 +431,7 @@ class OldConfig: return default - def set(self, key: str, val: Union[int, str, list]) -> None: + def set(self, key: str, val: int | str | list) -> None: """Set value on the specified configuration key.""" if isinstance(val, bool): self.config.set(self.SECTION, key, val and '1' or '0') diff --git a/tests/config/test_config.py b/tests/config/test_config.py index ae80701c..e839afc7 100644 --- a/tests/config/test_config.py +++ b/tests/config/test_config.py @@ -13,7 +13,7 @@ import pathlib import random import string import sys -from typing import Any, Iterable, List, cast +from typing import Any, Iterable, cast import pytest from pytest import mark @@ -28,12 +28,12 @@ from _old_config import old_config # noqa: E402 from config import config # noqa: E402 -def _fuzz_list(length: int) -> List[str]: +def _fuzz_list(length: int) -> list[str]: out = [] for _ in range(length): out.append(_fuzz_generators[str](random.randint(0, 1337))) - return cast(List[str], out) + return cast(list[str], out) _fuzz_generators = { # Type annotating this would be a nightmare. @@ -70,7 +70,7 @@ bool_tests = [True, False] big_int = int(0xFFFFFFFF) # 32 bit int -def _make_params(args: List[Any], id_name: str = 'random_test_{i}') -> list: +def _make_params(args: list[Any], id_name: str = 'random_test_{i}') -> list: return [pytest.param(x, id=id_name.format(i=i)) for i, x in enumerate(args)] @@ -115,7 +115,7 @@ class TestNewConfig: config.delete(name) @mark.parametrize("lst", _build_test_list(list_tests, _get_fuzz(list))) - def test_list(self, lst: List[str]) -> None: + def test_list(self, lst: list[str]) -> None: """Save a list and then ask for it back.""" name = f'list_test_{ hash("".join(lst)) }' config.set(name, lst) @@ -214,7 +214,7 @@ class TestOldNewConfig: assert res == string @mark.parametrize("lst", _build_test_list(list_tests, _get_fuzz(list))) - def test_list(self, lst: List[str]) -> None: + def test_list(self, lst: list[str]) -> None: """Save a list though the old config, recall it using the new config.""" lst = [x.replace("\r", "") for x in lst] # OldConfig on linux fails to store these correctly if sys.platform == 'win32': diff --git a/tests/journal_lock.py/test_journal_lock.py b/tests/journal_lock.py/test_journal_lock.py index 148c2cb5..649140c8 100644 --- a/tests/journal_lock.py/test_journal_lock.py +++ b/tests/journal_lock.py/test_journal_lock.py @@ -1,9 +1,11 @@ """Tests for journal_lock.py code.""" +from __future__ import annotations + import multiprocessing as mp import os import pathlib import sys -from typing import Generator, Optional +from typing import Generator import pytest from pytest import MonkeyPatch, TempdirFactory, TempPathFactory from config import config @@ -118,7 +120,7 @@ class TestJournalLock: tmp_path_factory: TempdirFactory ) -> Generator: """Fixture for mocking config.get_str('journaldir').""" - def get_str(key: str, *, default: Optional[str] = None) -> str: + def get_str(key: str, *, default: str | None = None) -> str: """Mock config.*Config get_str to provide fake journaldir.""" if key == 'journaldir': return str(tmp_path_factory.getbasetemp()) @@ -137,7 +139,7 @@ class TestJournalLock: tmp_path_factory: TempdirFactory ) -> Generator: """Fixture for mocking config.get_str('journaldir').""" - def get_str(key: str, *, default: Optional[str] = None) -> str: + def get_str(key: str, *, default: str | None = None) -> str: """Mock config.*Config get_str to provide fake journaldir.""" if key == 'journaldir': return tmp_path_factory.mktemp("changing") # type: ignore diff --git a/tests/killswitch.py/test_apply.py b/tests/killswitch.py/test_apply.py index 63657c69..ab9bb267 100644 --- a/tests/killswitch.py/test_apply.py +++ b/tests/killswitch.py/test_apply.py @@ -1,6 +1,8 @@ """Test the apply functions used by killswitch to modify data.""" +from __future__ import annotations + import copy -from typing import Any, Optional +from typing import Any import pytest @@ -61,7 +63,7 @@ def test_apply_no_error() -> None: (False, 0), (str((1 << 63)-1), (1 << 63)-1), (True, 1), (str(1 << 1337), 1 << 1337) ] ) -def test_get_int(input: str, expected: Optional[int]) -> None: +def test_get_int(input: str, expected: int | None) -> None: """Check that _get_int doesn't throw when handed bad data.""" assert expected == killswitch._get_int(input) diff --git a/tests/killswitch.py/test_killswitch.py b/tests/killswitch.py/test_killswitch.py index 3b004a48..3c681ded 100644 --- a/tests/killswitch.py/test_killswitch.py +++ b/tests/killswitch.py/test_killswitch.py @@ -1,7 +1,7 @@ """Tests of killswitch behaviour.""" -import copy -from typing import Optional, List +from __future__ import annotations +import copy import pytest import semantic_version @@ -34,7 +34,7 @@ TEST_SET = killswitch.KillSwitchSet([ ], ) def test_killswitch( - input: killswitch.UPDATABLE_DATA, kill: str, should_pass: bool, result: Optional[killswitch.UPDATABLE_DATA], + input: killswitch.UPDATABLE_DATA, kill: str, should_pass: bool, result: killswitch.UPDATABLE_DATA | None, version: str ) -> None: """Simple killswitch tests.""" @@ -85,7 +85,7 @@ def test_operator_precedence( ] ) def test_check_multiple( - names: List[str], input: killswitch.UPDATABLE_DATA, result: killswitch.UPDATABLE_DATA, expected_return: bool + names: list[str], input: killswitch.UPDATABLE_DATA, result: killswitch.UPDATABLE_DATA, expected_return: bool ) -> None: """Check that order is correct when checking multiple killswitches.""" should_return, data = TEST_SET.check_multiple_killswitches(input, *names, version='1.0.0') From 24aaea7ded16cce0b74159e417b15957881b75a9 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Thu, 16 Nov 2023 13:46:18 -0500 Subject: [PATCH 21/83] [Submodule] Manually Update Submodules The action isn't doing whatever it should be properly. I don't know why. But this will suppress it for now. --- FDevIDs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/FDevIDs b/FDevIDs index e8dbd99d..1f47f67d 160000 --- a/FDevIDs +++ b/FDevIDs @@ -1 +1 @@ -Subproject commit e8dbd99ddc00beabac140bf26f423a353bc98c5d +Subproject commit 1f47f67dfe0d3c8c43c9003e4f929e1cf1464352 From c8edce26e69cd8b14b4b84c203515b25a513b2d1 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Thu, 16 Nov 2023 16:11:14 -0500 Subject: [PATCH 22/83] [2051] Workflow and Requirement Update --- .github/workflows/windows-build.yml | 15 ++++----------- requirements-dev.txt | 10 +++++----- 2 files changed, 9 insertions(+), 16 deletions(-) diff --git a/.github/workflows/windows-build.yml b/.github/workflows/windows-build.yml index 7f465497..b50f868f 100644 --- a/.github/workflows/windows-build.yml +++ b/.github/workflows/windows-build.yml @@ -103,18 +103,11 @@ jobs: pip install wheel pip install -r requirements-dev.txt - - name: Download latest WinSparkle release + - name: Download winsparkle run: | - $url = "https://api.github.com/repos/vslavik/winsparkle/releases/latest" - $response = Invoke-RestMethod -Uri $url - $latestAsset = $response.assets | Where-Object { $_.name -match "WinSparkle.*\.zip" -and $_.name -notmatch "-src" } - - $downloadUrl = $latestAsset.browser_download_url - Invoke-WebRequest -Uri $downloadUrl -OutFile WinSparkle-Latest.zip - - Expand-Archive -Path WinSparkle-Latest.zip -DestinationPath . - $extractedFolder = Get-ChildItem -Filter "WinSparkle-*" -Directory - Move-Item -Path "$($extractedFolder.FullName)\Release\*" -Destination . + Invoke-Webrequest -UseBasicParsing https://github.com/vslavik/winsparkle/releases/download/v0.8.0/WinSparkle-0.8.0.zip -OutFile out.zip + Expand-Archive out.zip + Move-Item 'out\WinSparkle-0.8.0\Release\*' '.\' - name: Build EDMC run: | diff --git a/requirements-dev.txt b/requirements-dev.txt index a8b0815b..3ab5f9a3 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -18,24 +18,24 @@ flake8-noqa==1.3.2 flake8-polyfill==1.0.2 flake8-use-fstring==1.4 -mypy==1.6.1 +mypy==1.7.0 pep8-naming==0.13.3 safety==2.3.5 -types-requests==2.31.0.2 +types-requests==2.31.0.10 types-pkg-resources==0.1.3 # Code formatting tools autopep8==2.0.4 # Git pre-commit checking -pre-commit==3.3.3 +pre-commit==3.5.0 # HTML changelogs -grip==4.6.1 +grip==4.6.2 # Packaging # We only need py2exe on windows. -py2exe==0.13.0.0; sys_platform == 'win32' +py2exe==0.13.0.1; sys_platform == 'win32' # Testing pytest==7.4.3 From 62cf621b2049de0c966d98b60d0afff999147899 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Thu, 16 Nov 2023 16:11:37 -0500 Subject: [PATCH 23/83] [2051] Docfile Brief Pass --- docs/examples/click_counter/load.py | 4 ++-- docs/examples/plugintest/load.py | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/docs/examples/click_counter/load.py b/docs/examples/click_counter/load.py index 70c24f53..0c65fc29 100644 --- a/docs/examples/click_counter/load.py +++ b/docs/examples/click_counter/load.py @@ -79,7 +79,7 @@ class ClickCounter: """ # You need to cast to `int` here to store *as* an `int`, so that # `config.get_int()` will work for re-loading the value. - config.set('click_counter_count', int(self.click_count.get())) # type: ignore + config.set('click_counter_count', int(self.click_count.get())) def setup_main_ui(self, parent: tk.Frame) -> tk.Frame: """ @@ -95,7 +95,7 @@ class ClickCounter: button = tk.Button( frame, text="Count me", - command=lambda: self.click_count.set(str(int(self.click_count.get()) + 1)) # type: ignore + command=lambda: self.click_count.set(str(int(self.click_count.get()) + 1)) ) button.grid(row=current_row) current_row += 1 diff --git a/docs/examples/plugintest/load.py b/docs/examples/plugintest/load.py index 314eef19..4aca1689 100644 --- a/docs/examples/plugintest/load.py +++ b/docs/examples/plugintest/load.py @@ -44,7 +44,7 @@ class This: this = This() -class PluginTest(object): +class PluginTest: """Class that performs actual tests on bundled modules.""" def __init__(self, directory: str): @@ -83,7 +83,6 @@ class PluginTest(object): logger.debug(f'timestamp = "{timestamp}", cmdr = "{cmdrname}", system = "{system}", station = "{station}", event = "{event}"') # noqa: E501 self.sqlc.execute('INSERT INTO entries VALUES(?, ?, ?, ?, ?)', (timestamp, cmdrname, system, station, event)) self.sqlconn.commit() - return None def plugin_start3(plugin_dir: str) -> str: From c7c6d5eed7d9f4fa60ea1cd2b23c905b915f49ab Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Thu, 16 Nov 2023 16:13:14 -0500 Subject: [PATCH 24/83] [2051] Scripts Update --- scripts/find_localised_strings.py | 269 ++++++++++++++---------------- scripts/killswitch_test.py | 13 +- scripts/pip_rev_deps.py | 19 ++- 3 files changed, 152 insertions(+), 149 deletions(-) diff --git a/scripts/find_localised_strings.py b/scripts/find_localised_strings.py index 74cfe1b4..b9d8a8b5 100644 --- a/scripts/find_localised_strings.py +++ b/scripts/find_localised_strings.py @@ -1,4 +1,6 @@ """Search all given paths recursively for localised string calls.""" +from __future__ import annotations + import argparse import ast import dataclasses @@ -6,9 +8,6 @@ import json import pathlib import re import sys -from typing import Optional - -# spell-checker: words dedupe deduping deduped def get_func_name(thing: ast.AST) -> str: @@ -16,11 +15,9 @@ def get_func_name(thing: ast.AST) -> str: if isinstance(thing, ast.Name): return thing.id - elif isinstance(thing, ast.Attribute): + if isinstance(thing, ast.Attribute): return get_func_name(thing.value) - - else: - return '' + return '' def get_arg(call: ast.Call) -> str: @@ -31,10 +28,9 @@ def get_arg(call: ast.Call) -> str: arg = call.args[0] if isinstance(arg, ast.Constant): return arg.value - elif isinstance(arg, ast.Name): + if isinstance(arg, ast.Name): return f'VARIABLE! CHECK CODE! {arg.id}' - else: - return f'Unknown! {type(arg)=} {ast.dump(arg)} ||| {ast.unparse(arg)}' + return f'Unknown! {type(arg)=} {ast.dump(arg)} ||| {ast.unparse(arg)}' # type: ignore def find_calls_in_stmt(statement: ast.AST) -> list[ast.Call]: @@ -62,7 +58,7 @@ COMMENT_SAME_LINE_RE = re.compile(r'^.*?(#.*)$') COMMENT_OWN_LINE_RE = re.compile(r'^\s*?(#.*)$') -def extract_comments(call: ast.Call, lines: list[str], file: pathlib.Path) -> Optional[str]: # noqa: CCR001 +def extract_comments(call: ast.Call, lines: list[str], file: pathlib.Path) -> str | None: """ Extract comments from source code based on the given call. @@ -74,51 +70,32 @@ def extract_comments(call: ast.Call, lines: list[str], file: pathlib.Path) -> Op :param file: The path to the file this call node came from :return: The first comment that matches the rules, or None """ - out: Optional[str] = None - above = call.lineno - 2 - current = call.lineno - 1 + above_line_number = call.lineno - 2 + current_line_number = call.lineno - 1 - above_line = lines[above].strip() if len(lines) >= above else None - above_comment: Optional[str] = None - current_line = lines[current].strip() - current_comment: Optional[str] = None + def extract_lang_comment(line: str) -> str | None: + """ + Extract a language comment from a given line. - bad_comment: Optional[str] = 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 + :param line: The line to extract the language comment from. + :return: The extracted language comment, or None if no valid comment is found. + """ + match = COMMENT_OWN_LINE_RE.match(line) + if match and match.group(1).startswith('# LANG:'): + return match.group(1).replace('# LANG:', '').strip() + return None - else: - above_comment = above_comment.replace('# LANG:', '').strip() + above_comment = extract_lang_comment(lines[above_line_number]) if len(lines) >= above_line_number else None + current_comment = extract_lang_comment(lines[current_line_number]) - 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 + if current_comment is None: + current_comment = above_comment - else: - current_comment = current_comment.replace('# LANG:', '').strip() + if current_comment is None: + print(f'No comment for {file}:{call.lineno} {lines[current_line_number]}', file=sys.stderr) + return None - if current_comment is not None: - out = current_comment - - elif above_comment is not None: - out = above_comment - - elif bad_comment is not None: - print(bad_comment, file=sys.stderr) - - if out is None: - print(f'No comment for {file}:{call.lineno} {current_line}', file=sys.stderr) - - return out + return current_comment def scan_file(path: pathlib.Path) -> list[ast.Call]: @@ -126,17 +103,19 @@ def scan_file(path: pathlib.Path) -> list[ast.Call]: data = path.read_text(encoding='utf-8') lines = data.splitlines() parsed = ast.parse(data) - out: list[ast.Call] = [] + calls: list[ast.Call] = [] for statement in parsed.body: - out.extend(find_calls_in_stmt(statement)) + calls.extend(find_calls_in_stmt(statement)) - # see if we can extract any comments - for call in out: - setattr(call, 'comment', extract_comments(call, lines, path)) + # Extract and assign comments to each call + for call in calls: + call.comment = extract_comments(call, lines, path) # type: ignore - out.sort(key=lambda c: c.lineno) - return out + # Sort the calls by line number + calls.sort(key=lambda c: c.lineno) + + return calls def scan_directory(path: pathlib.Path, skip: list[pathlib.Path] | None = None) -> dict[pathlib.Path, list[ast.Call]]: @@ -150,40 +129,34 @@ def scan_directory(path: pathlib.Path, skip: list[pathlib.Path] | None = None) - for thing in path.iterdir(): if skip is not None and any(s.name == thing.name for s in skip): continue - if thing.is_file(): if not thing.name.endswith('.py'): continue - out[thing] = scan_file(thing) - elif thing.is_dir(): - out |= scan_directory(thing) - + out |= scan_directory(thing) # type: ignore else: raise ValueError(type(thing), thing) - return out -def parse_template(path) -> set[str]: +def parse_template(path: pathlib.Path) -> set[str]: """ Parse a lang.template file. - The regexp this uses was extracted from l10n.py. + The regular expression used here was extracted from l10n.py. :param path: The path to the lang file """ - lang_re = re.compile(r'\s*"((?:[^"]|(?:\"))+)"\s*=\s*"((?:[^"]|(?:\"))+)"\s*;\s*$') - out = set() + lang_re = re.compile(r'\s*"([^"]+)"\s*=\s*"([^"]+)"\s*;\s*$') + result = set() + for line in pathlib.Path(path).read_text(encoding='utf-8').splitlines(): match = lang_re.match(line) - if not match: - continue - if match.group(1) != '!Language': - out.add(match.group(1)) + if match and match.group(1) != '!Language': + result.add(match.group(1)) - return out + return result @dataclasses.dataclass @@ -193,8 +166,8 @@ class FileLocation: path: pathlib.Path line_start: int line_start_col: int - line_end: Optional[int] - line_end_col: Optional[int] + line_end: int | None + line_end_col: int | None @staticmethod def from_call(path: pathlib.Path, c: ast.Call) -> 'FileLocation': @@ -213,50 +186,46 @@ class LangEntry: locations: list[FileLocation] string: str - comments: list[Optional[str]] + comments: list[str | None] def files(self) -> str: """Return a string representation of all the files this LangEntry is in, and its location therein.""" - out = '' - for loc in self.locations: - start = loc.line_start - end = loc.line_end - end_str = f':{end}' if end is not None and end != start else '' - out += f'{loc.path.name}:{start}{end_str}; ' + file_locations = [ + f'{loc.path.name}:{loc.line_start}' + + (f':{loc.line_end}' if loc.line_end is not None and loc.line_end != loc.line_start else '') + for loc in self.locations + ] - return out + return '; '.join(file_locations) def dedupe_lang_entries(entries: list[LangEntry]) -> list[LangEntry]: """ Deduplicate a list of lang entries. - This will coalesce LangEntries that have that same string but differing files and comments into a single - LangEntry that cotains all comments and FileLocations + This will coalesce LangEntries that have the same string but differing files and comments into a single + LangEntry that contains all comments and FileLocations. :param entries: The list to deduplicate :return: The deduplicated list """ - deduped: list[LangEntry] = [] + deduped: dict[str, LangEntry] = {} + for e in entries: - cont = False - for d in deduped: - if d.string == e.string: - cont = True - d.locations.append(e.locations[0]) - d.comments.extend(e.comments) + existing = deduped.get(e.string) + if existing: + existing.locations.extend(e.locations) + existing.comments.extend(e.comments) + else: + deduped[e.string] = LangEntry(locations=e.locations[:], string=e.string, comments=e.comments[:]) - if cont: - continue - - deduped.append(e) - - return deduped + return list(deduped.values()) def generate_lang_template(data: dict[pathlib.Path, list[ast.Call]]) -> str: """Generate a full en.template from the given data.""" entries: list[LangEntry] = [] + for path, calls in data.items(): for c in calls: entries.append(LangEntry([FileLocation.from_call(path, c)], get_arg(c), [getattr(c, 'comment')])) @@ -267,30 +236,72 @@ 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) - comment = '' - files = 'In files: ' + entry.files() + comment_parts = [] string = f'"{entry.string}"' - for i in range(len(entry.comments)): - if entry.comments[i] is None: + for i, comment_text in enumerate(entry.comments): + if comment_text is None: continue loc = entry.locations[i] - to_append = f'{loc.path.name}: {entry.comments[i]}; ' - if to_append not in comment: - comment += to_append + comment_parts.append(f'{loc.path.name}: {comment_text};') - header = f'{comment.strip()} {files}'.strip() - out += f'/* {header} */\n' - out += f'{string} = {string};\n' - out += '\n' + if comment_parts: + header = ' '.join(comment_parts) + out += f'/* {header} */\n' + + out += f'{string} = {string};\n\n' return out -if __name__ == '__main__': +def compare_lang_with_template(template: set[str], res: dict[pathlib.Path, list[ast.Call]]) -> None: + """ + Compare language entries in source code with a given language template. + + :param template: A set of language entries from a language template. + :param res: A dictionary containing source code paths as keys and lists of ast.Call objects as values. + """ + seen = set() + + for file, calls in res.items(): + for c in calls: + arg = get_arg(c) + if arg in template: + seen.add(arg) + else: + print(f'NEW! {file}:{c.lineno}: {arg!r}') + + for old in set(template) ^ seen: + print(f'No longer used: {old}') + + +def print_json_output(res: dict[pathlib.Path, list[ast.Call]]) -> None: + """ + Print JSON output of extracted language entries. + + :param res: A dictionary containing source code paths as keys and lists of ast.Call objects as values. + """ + to_print_data = [ + { + 'path': str(path), + 'string': get_arg(c), + 'reconstructed': ast.unparse(c), # type: ignore + 'start_line': c.lineno, + 'start_offset': c.col_offset, + 'end_line': c.end_lineno, + 'end_offset': c.end_col_offset, + 'comment': getattr(c, 'comment', None) + } for (path, calls) in res.items() for c in calls + ] + + print(json.dumps(to_print_data, indent=2)) + + +if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--directory', help='Directory to search from', default='.') parser.add_argument('--ignore', action='append', help='directories to ignore', default=['venv', '.venv', '.git']) @@ -302,56 +313,32 @@ if __name__ == '__main__': args = parser.parse_args() directory = pathlib.Path(args.directory) - res = scan_directory(directory, [pathlib.Path(p) for p in args.ignore]) + skip = [pathlib.Path(p) for p in args.ignore] + res = scan_directory(directory, skip) - if args.compare_lang is not None and len(args.compare_lang) > 0: - seen = set() + if args.compare_lang: template = parse_template(args.compare_lang) - - for file, calls in res.items(): - for c in calls: - arg = get_arg(c) - if arg in template: - seen.add(arg) - else: - print(f'NEW! {file}:{c.lineno}: {arg!r}') - - for old in set(template) ^ seen: - print(f'No longer used: {old}') + compare_lang_with_template(template, res) elif args.json: - to_print_data = [ - { - 'path': str(path), - 'string': get_arg(c), - 'reconstructed': ast.unparse(c), - 'start_line': c.lineno, - 'start_offset': c.col_offset, - 'end_line': c.end_lineno, - 'end_offset': c.end_col_offset, - 'comment': getattr(c, 'comment', None) - } for (path, calls) in res.items() for c in calls - ] - - print(json.dumps(to_print_data, indent=2)) + print_json_output(res) elif args.lang: if args.lang == '-': print(generate_lang_template(res)) - else: with open(args.lang, mode='w+', newline='\n') as langfile: langfile.writelines(generate_lang_template(res)) else: for path, calls in res.items(): - if len(calls) == 0: + if not calls: continue print(path) for c in calls: print( - f' {c.lineno:4d}({c.col_offset:3d}):{c.end_lineno:4d}({c.end_col_offset:3d})\t', ast.unparse(c) + f' {c.lineno:4d}({c.col_offset:3d}):{c.end_lineno:4d}(' + f'{c.end_col_offset:3d})\t', ast.unparse(c) # type: ignore ) - print() diff --git a/scripts/killswitch_test.py b/scripts/killswitch_test.py index b85b341e..cef93c88 100644 --- a/scripts/killswitch_test.py +++ b/scripts/killswitch_test.py @@ -116,9 +116,14 @@ if __name__ == '__main__': if file_name == '-': file = sys.stdin else: - file = open(file_name) - - res = json.load(file) - file.close() + try: + with open(file_name) as file: + res = json.load(file) + except FileNotFoundError: + print(f"File '{file_name}' not found.") + sys.exit(1) + except json.JSONDecodeError: + print(f"Error decoding JSON in '{file_name}'.") + sys.exit(1) show_killswitch_set_info(KillSwitchSet(parse_kill_switches(res))) diff --git a/scripts/pip_rev_deps.py b/scripts/pip_rev_deps.py index b97757d5..8a187172 100644 --- a/scripts/pip_rev_deps.py +++ b/scripts/pip_rev_deps.py @@ -1,11 +1,10 @@ -#!/usr/bin/env python -"""Find the reverse dependencies of a package according to pip.""" +"""Search for dependencies given a package.""" import sys import pkg_resources -def find_reverse_deps(package_name: str): +def find_reverse_deps(package_name: str) -> list[str]: """ Find the packages that depend on the named one. @@ -19,4 +18,16 @@ def find_reverse_deps(package_name: str): if __name__ == '__main__': - print(find_reverse_deps(sys.argv[1])) + if len(sys.argv) != 2: + print("Usage: python reverse_deps.py ") + sys.exit(1) + + package_name = sys.argv[1] + reverse_deps = find_reverse_deps(package_name) + + if reverse_deps: + print(f"Reverse dependencies of '{package_name}':") + for dep in reverse_deps: + print(dep) + else: + print(f"No reverse dependencies found for '{package_name}'.") From 8693c1a66798d47700c0d05d4b9ba7b5e9cd3536 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Thu, 16 Nov 2023 16:14:59 -0500 Subject: [PATCH 25/83] [2051] Utilities Quick Pass --- util/text.py | 8 +++++++- util_ships.py | 12 +++++++++--- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/util/text.py b/util/text.py index 0755f0f3..84af758b 100644 --- a/util/text.py +++ b/util/text.py @@ -1,4 +1,10 @@ -"""Utilities for dealing with text (and byte representations thereof).""" +""" +text.py - Dealing with Text and Bytes. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" from __future__ import annotations from gzip import compress diff --git a/util_ships.py b/util_ships.py index bd3ae3df..8bbfd813 100644 --- a/util_ships.py +++ b/util_ships.py @@ -1,4 +1,10 @@ -"""Utility functions relating to ships.""" +""" +util_ships.py - Ship Utilities. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" from edmc_data import ship_name_map @@ -11,6 +17,6 @@ def ship_file_name(ship_name: str, ship_type: str) -> str: if name.lower() in ('con', 'prn', 'aux', 'nul', 'com0', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7', 'com8', 'com9', 'lpt0', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7', 'lpt8', 'lpt9'): - name = name + '_' + name += '_' - return name.translate({ord(x): u'_' for x in ('\0', '<', '>', ':', '"', '/', '\\', '|', '?', '*')}) + return name.translate({ord(x): '_' for x in ('\0', '<', '>', ':', '"', '/', '\\', '|', '?', '*')}) From 07ae14be5a0208fa1d1f127619825a3b027c1c32 Mon Sep 17 00:00:00 2001 From: Phoebe Date: Thu, 16 Nov 2023 22:21:57 +0100 Subject: [PATCH 26/83] [2088] fix UI bugs, introduce standard - Fixes #2088 and #2089. - Adds usage of ``row=`` for ``.grid()`` for all config entries in included plugins. - Changes all config pages to start at row 0. - Starts introducing a standard for config panel layouts. --- plugins/eddn.py | 12 ++++++++---- plugins/edsm.py | 17 +++++++++++------ plugins/inara.py | 20 +++++++++++++------- prefs.py | 45 ++++++++++++++++++++++----------------------- 4 files changed, 54 insertions(+), 40 deletions(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index ee70d6e9..c3d62014 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -2098,13 +2098,15 @@ def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: eddnframe = nb.Frame(parent) + cur_row = 0 HyperlinkLabel( eddnframe, text='Elite Dangerous Data Network', background=nb.Label().cget('background'), url='https://github.com/EDCD/EDDN#eddn---elite-dangerous-data-network', underline=True - ).grid(padx=PADX, sticky=tk.W) # Don't translate + ).grid(row=cur_row, padx=PADX, sticky=tk.W) # Don't translate + cur_row += 1 this.eddn_station = tk.IntVar(value=(output & config.OUT_EDDN_SEND_STATION_DATA) and 1) this.eddn_station_button = nb.Checkbutton( @@ -2114,8 +2116,9 @@ def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: variable=this.eddn_station, command=prefsvarchanged ) # Output setting + this.eddn_station_button.grid(row=cur_row, padx=BUTTONX, pady=(5, 0), sticky=tk.W) + cur_row += 1 - this.eddn_station_button.grid(padx=BUTTONX, pady=(5, 0), sticky=tk.W) this.eddn_system = tk.IntVar(value=(output & config.OUT_EDDN_SEND_NON_STATION) and 1) # Output setting new in E:D 2.2 this.eddn_system_button = nb.Checkbutton( @@ -2125,8 +2128,9 @@ def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: variable=this.eddn_system, command=prefsvarchanged ) + this.eddn_system_button.grid(row=cur_row, padx=BUTTONX, pady=(5, 0), sticky=tk.W) + cur_row += 1 - this.eddn_system_button.grid(padx=BUTTONX, pady=(5, 0), sticky=tk.W) this.eddn_delay = tk.IntVar(value=(output & config.OUT_EDDN_DELAY) and 1) # Output setting under 'Send system and scan data to the Elite Dangerous Data Network' new in E:D 2.2 this.eddn_delay_button = nb.Checkbutton( @@ -2135,7 +2139,7 @@ def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: text=_('Delay sending until docked'), variable=this.eddn_delay ) - this.eddn_delay_button.grid(padx=BUTTONX, sticky=tk.W) + this.eddn_delay_button.grid(row=cur_row, padx=BUTTONX, sticky=tk.W) return eddnframe diff --git a/plugins/edsm.py b/plugins/edsm.py index 33af692b..647cd2fd 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -298,13 +298,15 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr frame = nb.Frame(parent) frame.columnconfigure(1, weight=1) + cur_row = 0 HyperlinkLabel( frame, text='Elite Dangerous Star Map', background=nb.Label().cget('background'), url='https://www.edsm.net/', underline=True - ).grid(columnspan=2, padx=PADX, sticky=tk.W) + ).grid(row=cur_row, columnspan=2, padx=PADX, sticky=tk.W) + cur_row += 1 this.log = tk.IntVar(value=config.get_int('edsm_out') and 1) this.log_button = nb.Checkbutton( @@ -314,9 +316,11 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr command=prefsvarchanged ) if this.log_button: - this.log_button.grid(columnspan=2, padx=BUTTONX, pady=(5, 0), sticky=tk.W) + this.log_button.grid(row=cur_row, columnspan=2, padx=BUTTONX, pady=(5, 0), sticky=tk.W) + cur_row += 1 - nb.Label(frame).grid(sticky=tk.W) # big spacer + nb.Label(frame).grid(row=cur_row, sticky=tk.W) # big spacer + cur_row += 1 this.label = HyperlinkLabel( frame, @@ -325,10 +329,10 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr url='https://www.edsm.net/settings/api', underline=True ) - cur_row = 10 if this.label: - this.label.grid(columnspan=2, padx=PADX, sticky=tk.W) + this.label.grid(row=cur_row, columnspan=2, padx=PADX, sticky=tk.W) # LANG: Game Commander name label in EDSM settings + cur_row += 1 this.cmdr_label = nb.Label(frame, text=_('Cmdr')) this.cmdr_label.grid(row=cur_row, padx=PADX, sticky=tk.W) this.cmdr_text = nb.Label(frame) @@ -347,6 +351,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr this.apikey_label.grid(row=cur_row, padx=PADX, sticky=tk.W) this.apikey = nb.Entry(frame, show="*", width=50) this.apikey.grid(row=cur_row, column=1, padx=PADX, pady=PADY, sticky=tk.EW) + cur_row += 1 prefs_cmdr_changed(cmdr, is_beta) @@ -358,7 +363,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr variable=show_password_var, command=toggle_password_visibility ) - show_password_checkbox.grid(columnspan=2, padx=BUTTONX, pady=(5, 0), sticky=tk.W) + show_password_checkbox.grid(row=cur_row, columnspan=2, padx=BUTTONX, pady=(5, 0), sticky=tk.W) return frame diff --git a/plugins/inara.py b/plugins/inara.py index 2a124f54..9653bde5 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -250,13 +250,15 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> tk.Frame: x_padding = 10 x_button_padding = 12 # indent Checkbuttons and Radiobuttons y_padding = 2 # close spacing + cur_row = 0 frame = nb.Frame(parent) frame.columnconfigure(1, weight=1) HyperlinkLabel( frame, text='Inara', background=nb.Label().cget('background'), url='https://inara.cz/', underline=True - ).grid(columnspan=2, padx=x_padding, sticky=tk.W) # Don't translate + ).grid(row=cur_row, columnspan=2, padx=x_padding, sticky=tk.W) # Don't translate + cur_row += 1 this.log = tk.IntVar(value=config.get_int('inara_out') and 1) this.log_button = nb.Checkbutton( @@ -266,9 +268,11 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> tk.Frame: command=prefsvarchanged ) - this.log_button.grid(columnspan=2, padx=x_button_padding, pady=(5, 0), sticky=tk.W) + this.log_button.grid(row=cur_row, columnspan=2, padx=x_button_padding, pady=(5, 0), sticky=tk.W) + cur_row += 1 - nb.Label(frame).grid(sticky=tk.W) # big spacer + nb.Label(frame).grid(row=cur_row, sticky=tk.W) # big spacer + cur_row += 1 # Section heading in settings this.label = HyperlinkLabel( @@ -279,13 +283,15 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> tk.Frame: underline=True ) - this.label.grid(columnspan=2, padx=x_padding, sticky=tk.W) + this.label.grid(row=cur_row, columnspan=2, padx=x_padding, sticky=tk.W) + cur_row += 1 # LANG: Inara API key label this.apikey_label = nb.Label(frame, text=_('API Key')) # Inara setting - this.apikey_label.grid(row=12, padx=x_padding, sticky=tk.W) + this.apikey_label.grid(row=cur_row, padx=x_padding, sticky=tk.W) this.apikey = nb.Entry(frame, show="*", width=50) - this.apikey.grid(row=12, column=1, padx=x_padding, pady=y_padding, sticky=tk.EW) + this.apikey.grid(row=cur_row, column=1, padx=x_padding, pady=y_padding, sticky=tk.EW) + cur_row += 1 prefs_cmdr_changed(cmdr, is_beta) @@ -296,7 +302,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> tk.Frame: variable=show_password_var, command=toggle_password_visibility, ) - show_password_checkbox.grid(columnspan=2, padx=x_padding, pady=(5, 0), sticky=tk.W) + show_password_checkbox.grid(row=cur_row, columnspan=2, padx=x_padding, pady=(5, 0), sticky=tk.W) return frame diff --git a/prefs.py b/prefs.py index 034d451e..44437089 100644 --- a/prefs.py +++ b/prefs.py @@ -347,7 +347,7 @@ class PreferencesDialog(tk.Toplevel): else: output = config.get_int('output') - row = AutoInc(start=1) + row = AutoInc(start=0) # LANG: Settings > Output - choosing what data to save to files self.out_label = nb.Label(output_frame, text=_('Please choose what data to save')) @@ -396,7 +396,7 @@ class PreferencesDialog(tk.Toplevel): # LANG: Settings > Output - Label for "where files are located" self.outdir_label = nb.Label(output_frame, text=_('File location')+':') # Section heading in settings # Type ignored due to incorrect type annotation. a 2 tuple does padding for each side - self.outdir_label.grid(padx=self.PADX, pady=(5, 0), sticky=tk.W, row=row.get()) # type: ignore + self.outdir_label.grid(padx=self.PADX, pady=(0, self.PADY), sticky=tk.W, row=row.get()) # type: ignore self.outdir_entry = nb.Entry(output_frame, takefocus=False) self.outdir_entry.grid(columnspan=2, padx=self.PADX, pady=(0, self.PADY), sticky=tk.EW, row=row.get()) @@ -415,7 +415,7 @@ class PreferencesDialog(tk.Toplevel): # LANG: Settings > Output - Label for "where files are located" command=lambda: self.filebrowse(_('File location'), self.outdir) ) - self.outbutton.grid(column=1, padx=self.PADX, pady=self.PADY, sticky=tk.NSEW, row=row.get()) + self.outbutton.grid(column=1, padx=self.PADX, pady=self.PADY, sticky=tk.EW, row=row.get()) nb.Frame(output_frame).grid(row=row.get()) # bottom spacer # TODO: does nothing? @@ -431,7 +431,7 @@ class PreferencesDialog(tk.Toplevel): def __setup_config_tab(self, notebook: ttk.Notebook) -> None: # noqa: CCR001 config_frame = nb.Frame(notebook) config_frame.columnconfigure(1, weight=1) - row = AutoInc(start=1) + row = AutoInc(start=0) self.logdir = tk.StringVar() default = config.default_journal_dir if config.default_journal_dir_path is not None else '' @@ -709,21 +709,21 @@ class PreferencesDialog(tk.Toplevel): frame = nb.Frame(notebook) self.hide_multicrew_captain = tk.BooleanVar(value=config.get_bool('hide_multicrew_captain', default=False)) self.hide_private_group = tk.BooleanVar(value=config.get_bool('hide_private_group', default=False)) - row = AutoInc() + row = AutoInc(start=0) # LANG: UI elements privacy section header in privacy tab of preferences nb.Label(frame, text=_('Main UI privacy options')).grid( - row=row.get(), column=0, sticky=tk.W, padx=self.PADX, pady=self.PADY + row=row.get(), column=0, sticky=tk.W, padx=self.PADX ) nb.Checkbutton( frame, text=_('Hide private group name in UI'), # LANG: Hide private group owner name from UI checkbox variable=self.hide_private_group - ).grid(row=row.get(), column=0, padx=self.PADX, pady=self.PADY) + ).grid(row=row.get(), column=0, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W) nb.Checkbutton( frame, text=_('Hide multi-crew captain name'), # LANG: Hide multicrew captain name from main UI checkbox variable=self.hide_multicrew_captain - ).grid(row=row.get(), column=0, padx=self.PADX, pady=self.PADY) + ).grid(row=row.get(), column=0, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W) notebook.add(frame, text=_('Privacy')) # LANG: Preferences privacy tab title @@ -743,7 +743,7 @@ class PreferencesDialog(tk.Toplevel): _('Highlighted text'), # Dark theme color setting ] - row = AutoInc(start=1) + row = AutoInc(start=0) appearance_frame = nb.Frame(notebook) appearance_frame.columnconfigure(2, weight=1) @@ -923,30 +923,29 @@ class PreferencesDialog(tk.Toplevel): plugins_frame.columnconfigure(0, weight=1) plugdir = tk.StringVar() plugdir.set(config.plugin_dir) - row = AutoInc(1) + row = AutoInc(start=0) + + # Section heading in settings + # LANG: Label for location of third-party plugins folder + nb.Label(plugins_frame, text=_('Plugins folder') + ':').grid(padx=self.PADX, pady=(0, self.PADY), sticky=tk.W, row=row.get()) plugdirentry = nb.Entry(plugins_frame, justify=tk.LEFT) self.displaypath(plugdir, plugdirentry) - with row as cur_row: - # Section heading in settings - # LANG: Label for location of third-party plugins folder - nb.Label(plugins_frame, text=_('Plugins folder') + ':').grid(padx=self.PADX, sticky=tk.W, row=cur_row) + plugdirentry.grid(columnspan=2, padx=self.PADX, pady=(0, self.PADY), sticky=tk.EW, row=row.get()) - plugdirentry.grid(padx=self.PADX, sticky=tk.EW, row=cur_row) - - nb.Button( - plugins_frame, - # LANG: Label on button used to open a filesystem folder - text=_('Open'), # Button that opens a folder in Explorer/Finder - command=lambda: webbrowser.open(f'file:///{config.plugin_dir_path}') - ).grid(column=1, padx=(0, self.PADX), sticky=tk.NSEW, row=cur_row) + nb.Button( + plugins_frame, + # LANG: Label on button used to open a filesystem folder + text=_('Open'), # Button that opens a folder in Explorer/Finder + command=lambda: webbrowser.open(f'file:///{config.plugin_dir_path}') + ).grid(column=1, padx=self.PADX, pady=self.PADY, sticky=tk.EW, row=row.get()) nb.Label( plugins_frame, # Help text in settings # LANG: Tip/label about how to disable plugins text=_("Tip: You can disable a plugin by{CR}adding '{EXT}' to its folder name").format(EXT='.disabled') - ).grid(columnspan=2, padx=self.PADX, pady=10, sticky=tk.NSEW, row=row.get()) + ).grid(columnspan=2, padx=self.PADX, pady=10, sticky=tk.EW, row=row.get()) enabled_plugins = list(filter(lambda x: x.folder and x.module, plug.PLUGINS)) if len(enabled_plugins): From e878453ba0acea4b1ed50bbd2e12985a6f9cd0a2 Mon Sep 17 00:00:00 2001 From: Phoebe Date: Thu, 16 Nov 2023 22:28:45 +0100 Subject: [PATCH 27/83] [Minor] flake8 --- prefs.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/prefs.py b/prefs.py index 44437089..cc979d88 100644 --- a/prefs.py +++ b/prefs.py @@ -927,7 +927,9 @@ class PreferencesDialog(tk.Toplevel): # Section heading in settings # LANG: Label for location of third-party plugins folder - nb.Label(plugins_frame, text=_('Plugins folder') + ':').grid(padx=self.PADX, pady=(0, self.PADY), sticky=tk.W, row=row.get()) + nb.Label(plugins_frame, text=_('Plugins folder') + ':').grid( + padx=self.PADX, pady=(0, self.PADY), sticky=tk.W, row=row.get() + ) plugdirentry = nb.Entry(plugins_frame, justify=tk.LEFT) self.displaypath(plugdir, plugdirentry) From b741047fd589a1add15a2de4276dac1903dd0bee Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Thu, 16 Nov 2023 18:16:25 -0500 Subject: [PATCH 28/83] [2051] Fix Localized Strings --- plugins/edsm.py | 4 +- scripts/find_localised_strings.py | 235 ++++++++++++++---------------- 2 files changed, 113 insertions(+), 126 deletions(-) diff --git a/plugins/edsm.py b/plugins/edsm.py index 33af692b..4827dbf4 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -309,7 +309,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr this.log = tk.IntVar(value=config.get_int('edsm_out') and 1) this.log_button = nb.Checkbutton( frame, - text=_('Send flight log and Cmdr status to EDSM'), + text=_('Send flight log and CMDR status to EDSM'), # LANG: Send flight log and CMDR Status to EDSM variable=this.log, command=prefsvarchanged ) @@ -320,7 +320,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr this.label = HyperlinkLabel( frame, - text=_('Elite Dangerous Star Map credentials'), + text=_('Elite Dangerous Star Map credentials'), # LANG: Elite Dangerous Star Map credentials background=nb.Label().cget('background'), url='https://www.edsm.net/settings/api', underline=True diff --git a/scripts/find_localised_strings.py b/scripts/find_localised_strings.py index b9d8a8b5..cdc95686 100644 --- a/scripts/find_localised_strings.py +++ b/scripts/find_localised_strings.py @@ -30,7 +30,7 @@ def get_arg(call: ast.Call) -> str: return arg.value if isinstance(arg, ast.Name): return f'VARIABLE! CHECK CODE! {arg.id}' - return f'Unknown! {type(arg)=} {ast.dump(arg)} ||| {ast.unparse(arg)}' # type: ignore + return f'Unknown! {type(arg)=} {ast.dump(arg)} ||| {ast.unparse(arg)}' def find_calls_in_stmt(statement: ast.AST) -> list[ast.Call]: @@ -39,9 +39,7 @@ def find_calls_in_stmt(statement: ast.AST) -> list[ast.Call]: for n in ast.iter_child_nodes(statement): out.extend(find_calls_in_stmt(n)) if isinstance(statement, ast.Call) and get_func_name(statement.func) == '_': - out.append(statement) - return out @@ -70,32 +68,48 @@ def extract_comments(call: ast.Call, lines: list[str], file: pathlib.Path) -> st :param file: The path to the file this call node came from :return: The first comment that matches the rules, or None """ - above_line_number = call.lineno - 2 - current_line_number = call.lineno - 1 + out: str | None = None + above = call.lineno - 2 + current = call.lineno - 1 - def extract_lang_comment(line: str) -> str | None: - """ - Extract a language comment from a given line. + above_line = lines[above].strip() if len(lines) >= above else None + above_comment: str | None = None + current_line = lines[current].strip() + current_comment: str | None = None - :param line: The line to extract the language comment from. - :return: The extracted language comment, or None if no valid comment is found. - """ - match = COMMENT_OWN_LINE_RE.match(line) - if match and match.group(1).startswith('# LANG:'): - return match.group(1).replace('# LANG:', '').strip() - return 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 - above_comment = extract_lang_comment(lines[above_line_number]) if len(lines) >= above_line_number else None - current_comment = extract_lang_comment(lines[current_line_number]) + else: + above_comment = above_comment.replace('# LANG:', '').strip() - if current_comment is None: - current_comment = above_comment + 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 - if current_comment is None: - print(f'No comment for {file}:{call.lineno} {lines[current_line_number]}', file=sys.stderr) - return None + else: + current_comment = current_comment.replace('# LANG:', '').strip() - return current_comment + if current_comment is not None: + out = current_comment + elif above_comment is not None: + out = above_comment + elif bad_comment is not None: + print(bad_comment, file=sys.stderr) + + if out is None: + print(f'No comment for {file}:{call.lineno} {current_line}', file=sys.stderr) + return out def scan_file(path: pathlib.Path) -> list[ast.Call]: @@ -103,19 +117,17 @@ def scan_file(path: pathlib.Path) -> list[ast.Call]: data = path.read_text(encoding='utf-8') lines = data.splitlines() parsed = ast.parse(data) - calls: list[ast.Call] = [] + out: list[ast.Call] = [] for statement in parsed.body: - calls.extend(find_calls_in_stmt(statement)) + out.extend(find_calls_in_stmt(statement)) - # Extract and assign comments to each call - for call in calls: - call.comment = extract_comments(call, lines, path) # type: ignore + # see if we can extract any comments + for call in out: + setattr(call, 'comment', extract_comments(call, lines, path)) - # Sort the calls by line number - calls.sort(key=lambda c: c.lineno) - - return calls + out.sort(key=lambda c: c.lineno) + return out def scan_directory(path: pathlib.Path, skip: list[pathlib.Path] | None = None) -> dict[pathlib.Path, list[ast.Call]]: @@ -125,38 +137,38 @@ def scan_directory(path: pathlib.Path, skip: list[pathlib.Path] | None = None) - :param path: path to scan :param skip: paths to skip, if any, defaults to None """ + if skip is None: + skip = [] out = {} for thing in path.iterdir(): - if skip is not None and any(s.name == thing.name for s in skip): + if any(same_path.name == thing.name for same_path in skip): continue - if thing.is_file(): - if not thing.name.endswith('.py'): - continue + + if thing.is_file() and thing.suffix == '.py': out[thing] = scan_file(thing) elif thing.is_dir(): - out |= scan_directory(thing) # type: ignore - else: - raise ValueError(type(thing), thing) + out.update(scan_directory(thing, skip)) + return out -def parse_template(path: pathlib.Path) -> set[str]: +def parse_template(path) -> set[str]: """ Parse a lang.template file. - The regular expression used here was extracted from l10n.py. + The regexp this uses was extracted from l10n.py. :param path: The path to the lang file """ lang_re = re.compile(r'\s*"([^"]+)"\s*=\s*"([^"]+)"\s*;\s*$') - result = set() + out = set() + with open(path, encoding='utf-8') as file: + for line in file: + match = lang_re.match(line.strip()) + if match and match.group(1) != '!Language': + out.add(match.group(1)) - for line in pathlib.Path(path).read_text(encoding='utf-8').splitlines(): - match = lang_re.match(line) - if match and match.group(1) != '!Language': - result.add(match.group(1)) - - return result + return out @dataclasses.dataclass @@ -191,41 +203,38 @@ class LangEntry: def files(self) -> str: """Return a string representation of all the files this LangEntry is in, and its location therein.""" file_locations = [ - f'{loc.path.name}:{loc.line_start}' + - (f':{loc.line_end}' if loc.line_end is not None and loc.line_end != loc.line_start else '') + f"{loc.path.name}:{loc.line_start}:{loc.line_end or ''}" for loc in self.locations ] - - return '; '.join(file_locations) + return "; ".join(file_locations) def dedupe_lang_entries(entries: list[LangEntry]) -> list[LangEntry]: """ Deduplicate a list of lang entries. - This will coalesce LangEntries that have the same string but differing files and comments into a single - LangEntry that contains all comments and FileLocations. + This will coalesce LangEntries that have that same string but differing files and comments into a single + LangEntry that cotains all comments and FileLocations :param entries: The list to deduplicate :return: The deduplicated list """ deduped: dict[str, LangEntry] = {} - for e in entries: existing = deduped.get(e.string) if existing: existing.locations.extend(e.locations) existing.comments.extend(e.comments) else: - deduped[e.string] = LangEntry(locations=e.locations[:], string=e.string, comments=e.comments[:]) - + deduped[e.string] = LangEntry( + locations=e.locations[:], string=e.string, comments=e.comments[:] + ) return list(deduped.values()) def generate_lang_template(data: dict[pathlib.Path, list[ast.Call]]) -> str: """Generate a full en.template from the given data.""" entries: list[LangEntry] = [] - for path, calls in data.items(): for c in calls: entries.append(LangEntry([FileLocation.from_call(path, c)], get_arg(c), [getattr(c, 'comment')])) @@ -236,72 +245,26 @@ 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) - comment_parts = [] + + comment_set = set() + for comment, loc in zip(entry.comments, entry.locations): + if comment: + comment_set.add(f'{loc.path.name}: {comment};') + + files = 'In files: ' + entry.files() + comment = ' '.join(comment_set).strip() + + header = f'{comment} {files}'.strip() string = f'"{entry.string}"' - - for i, comment_text in enumerate(entry.comments): - if comment_text is None: - continue - - loc = entry.locations[i] - comment_parts.append(f'{loc.path.name}: {comment_text};') - - if comment_parts: - header = ' '.join(comment_parts) - out += f'/* {header} */\n' - + out += f'/* {header} */\n' out += f'{string} = {string};\n\n' return out -def compare_lang_with_template(template: set[str], res: dict[pathlib.Path, list[ast.Call]]) -> None: - """ - Compare language entries in source code with a given language template. - - :param template: A set of language entries from a language template. - :param res: A dictionary containing source code paths as keys and lists of ast.Call objects as values. - """ - seen = set() - - for file, calls in res.items(): - for c in calls: - arg = get_arg(c) - if arg in template: - seen.add(arg) - else: - print(f'NEW! {file}:{c.lineno}: {arg!r}') - - for old in set(template) ^ seen: - print(f'No longer used: {old}') - - -def print_json_output(res: dict[pathlib.Path, list[ast.Call]]) -> None: - """ - Print JSON output of extracted language entries. - - :param res: A dictionary containing source code paths as keys and lists of ast.Call objects as values. - """ - to_print_data = [ - { - 'path': str(path), - 'string': get_arg(c), - 'reconstructed': ast.unparse(c), # type: ignore - 'start_line': c.lineno, - 'start_offset': c.col_offset, - 'end_line': c.end_lineno, - 'end_offset': c.end_col_offset, - 'comment': getattr(c, 'comment', None) - } for (path, calls) in res.items() for c in calls - ] - - print(json.dumps(to_print_data, indent=2)) - - -if __name__ == "__main__": +if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--directory', help='Directory to search from', default='.') parser.add_argument('--ignore', action='append', help='directories to ignore', default=['venv', '.venv', '.git']) @@ -313,32 +276,56 @@ if __name__ == "__main__": args = parser.parse_args() directory = pathlib.Path(args.directory) - skip = [pathlib.Path(p) for p in args.ignore] - res = scan_directory(directory, skip) + res = scan_directory(directory, [pathlib.Path(p) for p in args.ignore]) - if args.compare_lang: + if args.compare_lang is not None and len(args.compare_lang) > 0: + seen = set() template = parse_template(args.compare_lang) - compare_lang_with_template(template, res) + + for file, calls in res.items(): + for c in calls: + arg = get_arg(c) + if arg in template: + seen.add(arg) + else: + print(f'NEW! {file}:{c.lineno}: {arg!r}') + + for old in set(template) ^ seen: + print(f'No longer used: {old}') elif args.json: - print_json_output(res) + to_print_data = [ + { + 'path': str(path), + 'string': get_arg(c), + 'reconstructed': ast.unparse(c), + 'start_line': c.lineno, + 'start_offset': c.col_offset, + 'end_line': c.end_lineno, + 'end_offset': c.end_col_offset, + 'comment': getattr(c, 'comment', None) + } for (path, calls) in res.items() for c in calls + ] + + print(json.dumps(to_print_data, indent=2)) elif args.lang: if args.lang == '-': print(generate_lang_template(res)) + else: with open(args.lang, mode='w+', newline='\n') as langfile: langfile.writelines(generate_lang_template(res)) else: for path, calls in res.items(): - if not calls: + if len(calls) == 0: continue print(path) for c in calls: print( - f' {c.lineno:4d}({c.col_offset:3d}):{c.end_lineno:4d}(' - f'{c.end_col_offset:3d})\t', ast.unparse(c) # type: ignore + f' {c.lineno:4d}({c.col_offset:3d}):{c.end_lineno:4d}({c.end_col_offset:3d})\t', ast.unparse(c) ) + print() From 93619e456560db5891aedf078bb0528345376c5b Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Thu, 16 Nov 2023 18:16:25 -0500 Subject: [PATCH 29/83] [2051] Fix Localized Strings --- plugins/edsm.py | 4 +- scripts/find_localised_strings.py | 237 ++++++++++++++---------------- 2 files changed, 114 insertions(+), 127 deletions(-) diff --git a/plugins/edsm.py b/plugins/edsm.py index 33af692b..4827dbf4 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -309,7 +309,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr this.log = tk.IntVar(value=config.get_int('edsm_out') and 1) this.log_button = nb.Checkbutton( frame, - text=_('Send flight log and Cmdr status to EDSM'), + text=_('Send flight log and CMDR status to EDSM'), # LANG: Send flight log and CMDR Status to EDSM variable=this.log, command=prefsvarchanged ) @@ -320,7 +320,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr this.label = HyperlinkLabel( frame, - text=_('Elite Dangerous Star Map credentials'), + text=_('Elite Dangerous Star Map credentials'), # LANG: Elite Dangerous Star Map credentials background=nb.Label().cget('background'), url='https://www.edsm.net/settings/api', underline=True diff --git a/scripts/find_localised_strings.py b/scripts/find_localised_strings.py index b9d8a8b5..1d1da826 100644 --- a/scripts/find_localised_strings.py +++ b/scripts/find_localised_strings.py @@ -30,7 +30,7 @@ def get_arg(call: ast.Call) -> str: return arg.value if isinstance(arg, ast.Name): return f'VARIABLE! CHECK CODE! {arg.id}' - return f'Unknown! {type(arg)=} {ast.dump(arg)} ||| {ast.unparse(arg)}' # type: ignore + return f'Unknown! {type(arg)=} {ast.dump(arg)} ||| {ast.unparse(arg)}' def find_calls_in_stmt(statement: ast.AST) -> list[ast.Call]: @@ -39,9 +39,7 @@ def find_calls_in_stmt(statement: ast.AST) -> list[ast.Call]: for n in ast.iter_child_nodes(statement): out.extend(find_calls_in_stmt(n)) if isinstance(statement, ast.Call) and get_func_name(statement.func) == '_': - out.append(statement) - return out @@ -58,7 +56,7 @@ COMMENT_SAME_LINE_RE = re.compile(r'^.*?(#.*)$') COMMENT_OWN_LINE_RE = re.compile(r'^\s*?(#.*)$') -def extract_comments(call: ast.Call, lines: list[str], file: pathlib.Path) -> str | None: +def extract_comments(call: ast.Call, lines: list[str], file: pathlib.Path) -> str | None: # noqa: CCR001 """ Extract comments from source code based on the given call. @@ -70,32 +68,48 @@ def extract_comments(call: ast.Call, lines: list[str], file: pathlib.Path) -> st :param file: The path to the file this call node came from :return: The first comment that matches the rules, or None """ - above_line_number = call.lineno - 2 - current_line_number = call.lineno - 1 + out: str | None = None + above = call.lineno - 2 + current = call.lineno - 1 - def extract_lang_comment(line: str) -> str | None: - """ - Extract a language comment from a given line. + above_line = lines[above].strip() if len(lines) >= above else None + above_comment: str | None = None + current_line = lines[current].strip() + current_comment: str | None = None - :param line: The line to extract the language comment from. - :return: The extracted language comment, or None if no valid comment is found. - """ - match = COMMENT_OWN_LINE_RE.match(line) - if match and match.group(1).startswith('# LANG:'): - return match.group(1).replace('# LANG:', '').strip() - return 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 - above_comment = extract_lang_comment(lines[above_line_number]) if len(lines) >= above_line_number else None - current_comment = extract_lang_comment(lines[current_line_number]) + else: + above_comment = above_comment.replace('# LANG:', '').strip() - if current_comment is None: - current_comment = above_comment + 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 - if current_comment is None: - print(f'No comment for {file}:{call.lineno} {lines[current_line_number]}', file=sys.stderr) - return None + else: + current_comment = current_comment.replace('# LANG:', '').strip() - return current_comment + if current_comment is not None: + out = current_comment + elif above_comment is not None: + out = above_comment + elif bad_comment is not None: + print(bad_comment, file=sys.stderr) + + if out is None: + print(f'No comment for {file}:{call.lineno} {current_line}', file=sys.stderr) + return out def scan_file(path: pathlib.Path) -> list[ast.Call]: @@ -103,19 +117,17 @@ def scan_file(path: pathlib.Path) -> list[ast.Call]: data = path.read_text(encoding='utf-8') lines = data.splitlines() parsed = ast.parse(data) - calls: list[ast.Call] = [] + out: list[ast.Call] = [] for statement in parsed.body: - calls.extend(find_calls_in_stmt(statement)) + out.extend(find_calls_in_stmt(statement)) - # Extract and assign comments to each call - for call in calls: - call.comment = extract_comments(call, lines, path) # type: ignore + # see if we can extract any comments + for call in out: + setattr(call, 'comment', extract_comments(call, lines, path)) - # Sort the calls by line number - calls.sort(key=lambda c: c.lineno) - - return calls + out.sort(key=lambda c: c.lineno) + return out def scan_directory(path: pathlib.Path, skip: list[pathlib.Path] | None = None) -> dict[pathlib.Path, list[ast.Call]]: @@ -125,38 +137,38 @@ def scan_directory(path: pathlib.Path, skip: list[pathlib.Path] | None = None) - :param path: path to scan :param skip: paths to skip, if any, defaults to None """ + if skip is None: + skip = [] out = {} for thing in path.iterdir(): - if skip is not None and any(s.name == thing.name for s in skip): + if any(same_path.name == thing.name for same_path in skip): continue - if thing.is_file(): - if not thing.name.endswith('.py'): - continue + + if thing.is_file() and thing.suffix == '.py': out[thing] = scan_file(thing) elif thing.is_dir(): - out |= scan_directory(thing) # type: ignore - else: - raise ValueError(type(thing), thing) + out.update(scan_directory(thing, skip)) + return out -def parse_template(path: pathlib.Path) -> set[str]: +def parse_template(path) -> set[str]: """ Parse a lang.template file. - The regular expression used here was extracted from l10n.py. + The regexp this uses was extracted from l10n.py. :param path: The path to the lang file """ lang_re = re.compile(r'\s*"([^"]+)"\s*=\s*"([^"]+)"\s*;\s*$') - result = set() + out = set() + with open(path, encoding='utf-8') as file: + for line in file: + match = lang_re.match(line.strip()) + if match and match.group(1) != '!Language': + out.add(match.group(1)) - for line in pathlib.Path(path).read_text(encoding='utf-8').splitlines(): - match = lang_re.match(line) - if match and match.group(1) != '!Language': - result.add(match.group(1)) - - return result + return out @dataclasses.dataclass @@ -191,41 +203,38 @@ class LangEntry: def files(self) -> str: """Return a string representation of all the files this LangEntry is in, and its location therein.""" file_locations = [ - f'{loc.path.name}:{loc.line_start}' + - (f':{loc.line_end}' if loc.line_end is not None and loc.line_end != loc.line_start else '') + f"{loc.path.name}:{loc.line_start}:{loc.line_end or ''}" for loc in self.locations ] - - return '; '.join(file_locations) + return "; ".join(file_locations) def dedupe_lang_entries(entries: list[LangEntry]) -> list[LangEntry]: """ Deduplicate a list of lang entries. - This will coalesce LangEntries that have the same string but differing files and comments into a single - LangEntry that contains all comments and FileLocations. + This will coalesce LangEntries that have that same string but differing files and comments into a single + LangEntry that cotains all comments and FileLocations :param entries: The list to deduplicate :return: The deduplicated list """ deduped: dict[str, LangEntry] = {} - for e in entries: existing = deduped.get(e.string) if existing: existing.locations.extend(e.locations) existing.comments.extend(e.comments) else: - deduped[e.string] = LangEntry(locations=e.locations[:], string=e.string, comments=e.comments[:]) - + deduped[e.string] = LangEntry( + locations=e.locations[:], string=e.string, comments=e.comments[:] + ) return list(deduped.values()) def generate_lang_template(data: dict[pathlib.Path, list[ast.Call]]) -> str: """Generate a full en.template from the given data.""" entries: list[LangEntry] = [] - for path, calls in data.items(): for c in calls: entries.append(LangEntry([FileLocation.from_call(path, c)], get_arg(c), [getattr(c, 'comment')])) @@ -236,72 +245,26 @@ 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) - comment_parts = [] + + comment_set = set() + for comment, loc in zip(entry.comments, entry.locations): + if comment: + comment_set.add(f'{loc.path.name}: {comment};') + + files = 'In files: ' + entry.files() + comment = ' '.join(comment_set).strip() + + header = f'{comment} {files}'.strip() string = f'"{entry.string}"' - - for i, comment_text in enumerate(entry.comments): - if comment_text is None: - continue - - loc = entry.locations[i] - comment_parts.append(f'{loc.path.name}: {comment_text};') - - if comment_parts: - header = ' '.join(comment_parts) - out += f'/* {header} */\n' - + out += f'/* {header} */\n' out += f'{string} = {string};\n\n' return out -def compare_lang_with_template(template: set[str], res: dict[pathlib.Path, list[ast.Call]]) -> None: - """ - Compare language entries in source code with a given language template. - - :param template: A set of language entries from a language template. - :param res: A dictionary containing source code paths as keys and lists of ast.Call objects as values. - """ - seen = set() - - for file, calls in res.items(): - for c in calls: - arg = get_arg(c) - if arg in template: - seen.add(arg) - else: - print(f'NEW! {file}:{c.lineno}: {arg!r}') - - for old in set(template) ^ seen: - print(f'No longer used: {old}') - - -def print_json_output(res: dict[pathlib.Path, list[ast.Call]]) -> None: - """ - Print JSON output of extracted language entries. - - :param res: A dictionary containing source code paths as keys and lists of ast.Call objects as values. - """ - to_print_data = [ - { - 'path': str(path), - 'string': get_arg(c), - 'reconstructed': ast.unparse(c), # type: ignore - 'start_line': c.lineno, - 'start_offset': c.col_offset, - 'end_line': c.end_lineno, - 'end_offset': c.end_col_offset, - 'comment': getattr(c, 'comment', None) - } for (path, calls) in res.items() for c in calls - ] - - print(json.dumps(to_print_data, indent=2)) - - -if __name__ == "__main__": +if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--directory', help='Directory to search from', default='.') parser.add_argument('--ignore', action='append', help='directories to ignore', default=['venv', '.venv', '.git']) @@ -313,32 +276,56 @@ if __name__ == "__main__": args = parser.parse_args() directory = pathlib.Path(args.directory) - skip = [pathlib.Path(p) for p in args.ignore] - res = scan_directory(directory, skip) + res = scan_directory(directory, [pathlib.Path(p) for p in args.ignore]) - if args.compare_lang: + if args.compare_lang is not None and len(args.compare_lang) > 0: + seen = set() template = parse_template(args.compare_lang) - compare_lang_with_template(template, res) + + for file, calls in res.items(): + for c in calls: + arg = get_arg(c) + if arg in template: + seen.add(arg) + else: + print(f'NEW! {file}:{c.lineno}: {arg!r}') + + for old in set(template) ^ seen: + print(f'No longer used: {old}') elif args.json: - print_json_output(res) + to_print_data = [ + { + 'path': str(path), + 'string': get_arg(c), + 'reconstructed': ast.unparse(c), + 'start_line': c.lineno, + 'start_offset': c.col_offset, + 'end_line': c.end_lineno, + 'end_offset': c.end_col_offset, + 'comment': getattr(c, 'comment', None) + } for (path, calls) in res.items() for c in calls + ] + + print(json.dumps(to_print_data, indent=2)) elif args.lang: if args.lang == '-': print(generate_lang_template(res)) + else: with open(args.lang, mode='w+', newline='\n') as langfile: langfile.writelines(generate_lang_template(res)) else: for path, calls in res.items(): - if not calls: + if len(calls) == 0: continue print(path) for c in calls: print( - f' {c.lineno:4d}({c.col_offset:3d}):{c.end_lineno:4d}(' - f'{c.end_col_offset:3d})\t', ast.unparse(c) # type: ignore + f' {c.lineno:4d}({c.col_offset:3d}):{c.end_lineno:4d}({c.end_col_offset:3d})\t', ast.unparse(c) ) + print() From 8063cf099b11e10fdd526ef8f7ee88d3e7d91a95 Mon Sep 17 00:00:00 2001 From: Phoebe Date: Fri, 17 Nov 2023 01:39:52 +0100 Subject: [PATCH 30/83] [2095] Standardize vertical Padding - Standardizes vertical Padding. - Fixes issues with the disabled and outdated Plugin list. - Part of #2095 --- plugins/coriolis.py | 2 +- plugins/eddn.py | 7 +- plugins/edsm.py | 5 +- plugins/inara.py | 23 +++--- prefs.py | 195 +++++++++++++++++++++++--------------------- 5 files changed, 124 insertions(+), 108 deletions(-) diff --git a/plugins/coriolis.py b/plugins/coriolis.py index 283b49d8..599e4d57 100644 --- a/plugins/coriolis.py +++ b/plugins/coriolis.py @@ -91,7 +91,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr # LANG: Settings>Coriolis: Help/hint for changing coriolis URLs nb.Label(conf_frame, text=_( "Set the URL to use with coriolis.io ship loadouts. Note that this MUST end with '/import?data='" - )).grid(sticky=tk.EW, row=cur_row, column=0, columnspan=3) + )).grid(sticky=tk.EW, row=cur_row, column=0, padx=PADX, columnspan=3) cur_row += 1 # LANG: Settings>Coriolis: Label for 'NOT alpha/beta game version' URL diff --git a/plugins/eddn.py b/plugins/eddn.py index c3d62014..c8bca92a 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -2089,6 +2089,7 @@ def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: """ PADX = 10 # noqa: N806 BUTTONX = 12 # noqa: N806 # indent Checkbuttons and Radiobuttons + PADY = 2 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 @@ -2116,7 +2117,7 @@ def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: variable=this.eddn_station, command=prefsvarchanged ) # Output setting - this.eddn_station_button.grid(row=cur_row, padx=BUTTONX, pady=(5, 0), sticky=tk.W) + this.eddn_station_button.grid(row=cur_row, padx=BUTTONX, pady=PADY, sticky=tk.W) cur_row += 1 this.eddn_system = tk.IntVar(value=(output & config.OUT_EDDN_SEND_NON_STATION) and 1) @@ -2128,7 +2129,7 @@ def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: variable=this.eddn_system, command=prefsvarchanged ) - this.eddn_system_button.grid(row=cur_row, padx=BUTTONX, pady=(5, 0), sticky=tk.W) + this.eddn_system_button.grid(row=cur_row, padx=BUTTONX, pady=PADY, sticky=tk.W) cur_row += 1 this.eddn_delay = tk.IntVar(value=(output & config.OUT_EDDN_DELAY) and 1) @@ -2139,7 +2140,7 @@ def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: text=_('Delay sending until docked'), variable=this.eddn_delay ) - this.eddn_delay_button.grid(row=cur_row, padx=BUTTONX, sticky=tk.W) + this.eddn_delay_button.grid(row=cur_row, padx=BUTTONX, pady=PADY, sticky=tk.W) return eddnframe diff --git a/plugins/edsm.py b/plugins/edsm.py index 647cd2fd..1e400c80 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -294,6 +294,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr PADX = 10 # noqa: N806 BUTTONX = 12 # noqa: N806 PADY = 2 # noqa: N806 + SEPY = 10 # noqa: N806 frame = nb.Frame(parent) frame.columnconfigure(1, weight=1) @@ -319,7 +320,9 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr this.log_button.grid(row=cur_row, columnspan=2, padx=BUTTONX, pady=(5, 0), sticky=tk.W) cur_row += 1 - nb.Label(frame).grid(row=cur_row, sticky=tk.W) # big spacer + ttk.Separator(frame, orient=tk.HORIZONTAL).grid( + columnspan=2, padx=PADX, pady=SEPY, sticky=tk.EW, row=cur_row + ) cur_row += 1 this.label = HyperlinkLabel( diff --git a/plugins/inara.py b/plugins/inara.py index 9653bde5..b3446b62 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -247,9 +247,10 @@ def toggle_password_visibility(): def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> tk.Frame: """Plugin Preferences UI hook.""" - x_padding = 10 - x_button_padding = 12 # indent Checkbuttons and Radiobuttons - y_padding = 2 # close spacing + PADX = 10 + BUTTONX = 12 # indent Checkbuttons and Radiobuttons + PADY = 2 # close spacing + SEPY = 10 # seperator line spacing cur_row = 0 frame = nb.Frame(parent) @@ -257,7 +258,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> tk.Frame: HyperlinkLabel( frame, text='Inara', background=nb.Label().cget('background'), url='https://inara.cz/', underline=True - ).grid(row=cur_row, columnspan=2, padx=x_padding, sticky=tk.W) # Don't translate + ).grid(row=cur_row, columnspan=2, padx=PADX, sticky=tk.W) # Don't translate cur_row += 1 this.log = tk.IntVar(value=config.get_int('inara_out') and 1) @@ -268,10 +269,12 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> tk.Frame: command=prefsvarchanged ) - this.log_button.grid(row=cur_row, columnspan=2, padx=x_button_padding, pady=(5, 0), sticky=tk.W) + this.log_button.grid(row=cur_row, columnspan=2, padx=BUTTONX, pady=(5, 0), sticky=tk.W) cur_row += 1 - nb.Label(frame).grid(row=cur_row, sticky=tk.W) # big spacer + ttk.Separator(frame, orient=tk.HORIZONTAL).grid( + columnspan=2, padx=PADX, pady=SEPY, sticky=tk.EW, row=cur_row + ) cur_row += 1 # Section heading in settings @@ -283,14 +286,14 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> tk.Frame: underline=True ) - this.label.grid(row=cur_row, columnspan=2, padx=x_padding, sticky=tk.W) + this.label.grid(row=cur_row, columnspan=2, padx=PADX, sticky=tk.W) cur_row += 1 # LANG: Inara API key label this.apikey_label = nb.Label(frame, text=_('API Key')) # Inara setting - this.apikey_label.grid(row=cur_row, padx=x_padding, sticky=tk.W) + this.apikey_label.grid(row=cur_row, padx=PADX, sticky=tk.W) this.apikey = nb.Entry(frame, show="*", width=50) - this.apikey.grid(row=cur_row, column=1, padx=x_padding, pady=y_padding, sticky=tk.EW) + this.apikey.grid(row=cur_row, column=1, padx=PADX, pady=PADY, sticky=tk.EW) cur_row += 1 prefs_cmdr_changed(cmdr, is_beta) @@ -302,7 +305,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> tk.Frame: variable=show_password_var, command=toggle_password_visibility, ) - show_password_checkbox.grid(row=cur_row, columnspan=2, padx=x_padding, pady=(5, 0), sticky=tk.W) + show_password_checkbox.grid(row=cur_row, columnspan=2, padx=BUTTONX, pady=(5, 0), sticky=tk.W) return frame diff --git a/prefs.py b/prefs.py index cc979d88..20cc3cef 100644 --- a/prefs.py +++ b/prefs.py @@ -288,7 +288,9 @@ class PreferencesDialog(tk.Toplevel): self.PADX = 10 self.BUTTONX = 12 # indent Checkbuttons and Radiobuttons + self.LISTX = 25 # indent listed items self.PADY = 2 # close spacing + self.SEPY = 10 # seperator line spacing # Set up different tabs self.__setup_output_tab(notebook) @@ -457,29 +459,30 @@ class PreferencesDialog(tk.Toplevel): else: text = (_('Browse...')) # LANG: NOT-macOS Setting - files location selection button - self.logbutton = nb.Button( - config_frame, - text=text, - # LANG: Settings > Configuration - Label for Journal files location - command=lambda: self.filebrowse(_('E:D journal file location'), self.logdir) - ) - self.logbutton.grid(column=3, padx=self.PADX, pady=self.PADY, sticky=tk.EW, row=row.get()) - - if config.default_journal_dir_path: - # Appearance theme and language setting - nb.Button( + with row as cur_row: + self.logbutton = nb.Button( config_frame, - # LANG: Settings > Configuration - Label on 'reset journal files location to default' button - text=_('Default'), - command=self.logdir_reset, - state=tk.NORMAL if config.get_str('journaldir') else tk.DISABLED - ).grid(column=2, pady=self.PADY, sticky=tk.EW, row=row.get()) + text=text, + # LANG: Settings > Configuration - Label for Journal files location + command=lambda: self.filebrowse(_('E:D journal file location'), self.logdir) + ) + self.logbutton.grid(column=3, padx=self.PADX, pady=self.PADY, sticky=tk.EW, row=cur_row) + + if config.default_journal_dir_path: + # Appearance theme and language setting + nb.Button( + config_frame, + # LANG: Settings > Configuration - Label on 'reset journal files location to default' button + text=_('Default'), + command=self.logdir_reset, + state=tk.NORMAL if config.get_str('journaldir') else tk.DISABLED + ).grid(column=2, padx=self.PADX, pady=self.PADY, sticky=tk.EW, row=cur_row) # CAPI settings self.capi_fleetcarrier = tk.BooleanVar(value=config.get_bool('capi_fleetcarrier')) ttk.Separator(config_frame, orient=tk.HORIZONTAL).grid( - columnspan=4, padx=self.PADX, pady=self.PADY*4, sticky=tk.EW, row=row.get() + columnspan=4, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get() ) nb.Label( @@ -492,62 +495,63 @@ class PreferencesDialog(tk.Toplevel): # LANG: Configuration - Enable or disable the Fleet Carrier CAPI calls text=_('Enable Fleetcarrier CAPI Queries'), variable=self.capi_fleetcarrier - ).grid(columnspan=4, padx=self.PADX, pady=(5, 0), sticky=tk.W, row=row.get()) + ).grid(columnspan=4, padx=self.BUTTONX, pady=(5, 0), sticky=tk.W, row=row.get()) if sys.platform in ('darwin', 'win32'): ttk.Separator(config_frame, orient=tk.HORIZONTAL).grid( - columnspan=4, padx=self.PADX, pady=self.PADY*4, sticky=tk.EW, row=row.get() + columnspan=4, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get() ) self.hotkey_code = config.get_int('hotkey_code') self.hotkey_mods = config.get_int('hotkey_mods') self.hotkey_only = tk.IntVar(value=not config.get_int('hotkey_always')) self.hotkey_play = tk.IntVar(value=not config.get_int('hotkey_mute')) - nb.Label( - config_frame, - text=_('Keyboard shortcut') if # LANG: Hotkey/Shortcut settings prompt on OSX - sys.platform == 'darwin' else - _('Hotkey') # LANG: Hotkey/Shortcut settings prompt on Windows - ).grid(padx=self.PADX, sticky=tk.W, row=row.get()) + with row as cur_row: + nb.Label( + config_frame, + text=_('Keyboard shortcut') if # LANG: Hotkey/Shortcut settings prompt on OSX + sys.platform == 'darwin' else + _('Hotkey') # LANG: Hotkey/Shortcut settings prompt on Windows + ).grid(padx=self.PADX, sticky=tk.W, row=cur_row) - if sys.platform == 'darwin' and not was_accessible_at_launch: - if AXIsProcessTrusted(): - # Shortcut settings prompt on OSX - nb.Label( - config_frame, - # LANG: macOS Preferences > Configuration - restart the app message - text=_('Re-start {APP} to use shortcuts').format(APP=applongname), - foreground='firebrick' - ).grid(padx=self.PADX, sticky=tk.W, row=row.get()) + if sys.platform == 'darwin' and not was_accessible_at_launch: + if AXIsProcessTrusted(): + # Shortcut settings prompt on OSX + nb.Label( + config_frame, + # LANG: macOS Preferences > Configuration - restart the app message + text=_('Re-start {APP} to use shortcuts').format(APP=applongname), + foreground='firebrick' + ).grid(padx=self.PADX, sticky=tk.W, row=cur_row) + + else: + # Shortcut settings prompt on OSX + nb.Label( + config_frame, + # LANG: macOS - Configuration - need to grant the app permission for keyboard shortcuts + text=_('{APP} needs permission to use shortcuts').format(APP=applongname), + foreground='firebrick' + ).grid(columnspan=4, padx=self.PADX, sticky=tk.W, row=cur_row) + + # LANG: Shortcut settings button on OSX + nb.Button(config_frame, text=_('Open System Preferences'), command=self.enableshortcuts).grid( + padx=self.PADX, sticky=tk.E, row=cur_row + ) else: - # Shortcut settings prompt on OSX - nb.Label( - config_frame, - # LANG: macOS - Configuration - need to grant the app permission for keyboard shortcuts - text=_('{APP} needs permission to use shortcuts').format(APP=applongname), - foreground='firebrick' - ).grid(columnspan=4, padx=self.PADX, sticky=tk.W, row=row.get()) - - # LANG: Shortcut settings button on OSX - nb.Button(config_frame, text=_('Open System Preferences'), command=self.enableshortcuts).grid( - padx=self.PADX, sticky=tk.E, row=row.get() + self.hotkey_text = nb.Entry(config_frame, width=( + 20 if sys.platform == 'darwin' else 30), justify=tk.CENTER) + self.hotkey_text.insert( + 0, + # No hotkey/shortcut currently defined + # TODO: display Only shows up on darwin or windows + # LANG: No hotkey/shortcut set + hotkeymgr.display(self.hotkey_code, self.hotkey_mods) if self.hotkey_code else _('None') ) - else: - self.hotkey_text = nb.Entry(config_frame, width=( - 20 if sys.platform == 'darwin' else 30), justify=tk.CENTER) - self.hotkey_text.insert( - 0, - # No hotkey/shortcut currently defined - # TODO: display Only shows up on darwin or windows - # LANG: No hotkey/shortcut set - hotkeymgr.display(self.hotkey_code, self.hotkey_mods) if self.hotkey_code else _('None') - ) - - self.hotkey_text.bind('', self.hotkeystart) - self.hotkey_text.bind('', self.hotkeyend) - self.hotkey_text.grid(column=1, columnspan=2, pady=(5, 0), sticky=tk.W, row=row.get()) + self.hotkey_text.bind('', self.hotkeystart) + self.hotkey_text.bind('', self.hotkeyend) + self.hotkey_text.grid(column=1, columnspan=2, pady=(5, 0), sticky=tk.W, row=cur_row) # Hotkey/Shortcut setting self.hotkey_only_btn = nb.Checkbutton( @@ -558,7 +562,7 @@ class PreferencesDialog(tk.Toplevel): state=tk.NORMAL if self.hotkey_code else tk.DISABLED ) - self.hotkey_only_btn.grid(columnspan=4, padx=self.PADX, pady=(5, 0), sticky=tk.W, row=row.get()) + self.hotkey_only_btn.grid(columnspan=4, padx=self.BUTTONX, pady=(5, 0), sticky=tk.W, row=row.get()) # Hotkey/Shortcut setting self.hotkey_play_btn = nb.Checkbutton( @@ -569,11 +573,11 @@ class PreferencesDialog(tk.Toplevel): state=tk.NORMAL if self.hotkey_code else tk.DISABLED ) - self.hotkey_play_btn.grid(columnspan=4, padx=self.PADX, sticky=tk.W, row=row.get()) + self.hotkey_play_btn.grid(columnspan=4, padx=self.BUTTONX, sticky=tk.W, row=row.get()) # Option to disabled Automatic Check For Updates whilst in-game ttk.Separator(config_frame, orient=tk.HORIZONTAL).grid( - columnspan=4, padx=self.PADX, pady=self.PADY*4, sticky=tk.EW, row=row.get() + columnspan=4, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get() ) self.disable_autoappupdatecheckingame = tk.IntVar(value=config.get_int('disable_autoappupdatecheckingame')) self.disable_autoappupdatecheckingame_btn = nb.Checkbutton( @@ -584,10 +588,10 @@ class PreferencesDialog(tk.Toplevel): command=self.disable_autoappupdatecheckingame_changed ) - self.disable_autoappupdatecheckingame_btn.grid(columnspan=4, padx=self.PADX, sticky=tk.W, row=row.get()) + self.disable_autoappupdatecheckingame_btn.grid(columnspan=4, padx=self.BUTTONX, sticky=tk.W, row=row.get()) ttk.Separator(config_frame, orient=tk.HORIZONTAL).grid( - columnspan=4, padx=self.PADX, pady=self.PADY*4, sticky=tk.EW, row=row.get() + columnspan=4, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get() ) # Settings prompt for preferred ship loadout, system and station info websites @@ -660,7 +664,7 @@ class PreferencesDialog(tk.Toplevel): # Set loglevel ttk.Separator(config_frame, orient=tk.HORIZONTAL).grid( - columnspan=4, padx=self.PADX, pady=self.PADY*4, sticky=tk.EW, row=row.get() + columnspan=4, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get() ) with row as cur_row: @@ -706,26 +710,26 @@ class PreferencesDialog(tk.Toplevel): notebook.add(config_frame, text=_('Configuration')) def __setup_privacy_tab(self, notebook: ttk.Notebook) -> None: - frame = nb.Frame(notebook) + privacy_frame = nb.Frame(notebook) self.hide_multicrew_captain = tk.BooleanVar(value=config.get_bool('hide_multicrew_captain', default=False)) self.hide_private_group = tk.BooleanVar(value=config.get_bool('hide_private_group', default=False)) row = AutoInc(start=0) # LANG: UI elements privacy section header in privacy tab of preferences - nb.Label(frame, text=_('Main UI privacy options')).grid( + nb.Label(privacy_frame, text=_('Main UI privacy options')).grid( row=row.get(), column=0, sticky=tk.W, padx=self.PADX ) nb.Checkbutton( - frame, text=_('Hide private group name in UI'), # LANG: Hide private group owner name from UI checkbox + privacy_frame, text=_('Hide private group name in UI'), # LANG: Hide private group owner name from UI checkbox variable=self.hide_private_group ).grid(row=row.get(), column=0, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W) nb.Checkbutton( - frame, text=_('Hide multi-crew captain name'), # LANG: Hide multicrew captain name from main UI checkbox + privacy_frame, text=_('Hide multi-crew captain name'), # LANG: Hide multicrew captain name from main UI checkbox variable=self.hide_multicrew_captain ).grid(row=row.get(), column=0, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W) - notebook.add(frame, text=_('Privacy')) # LANG: Preferences privacy tab title + notebook.add(privacy_frame, text=_('Privacy')) # LANG: Preferences privacy tab title def __setup_appearance_tab(self, notebook: ttk.Notebook) -> None: self.languages = Translations.available_names() @@ -751,10 +755,10 @@ class PreferencesDialog(tk.Toplevel): # LANG: Appearance - Label for selection of application display language nb.Label(appearance_frame, text=_('Language')).grid(padx=self.PADX, sticky=tk.W, row=cur_row) self.lang_button = nb.OptionMenu(appearance_frame, self.lang, self.lang.get(), *self.languages.values()) - self.lang_button.grid(column=1, columnspan=2, padx=self.PADX, sticky=tk.W, row=cur_row) + self.lang_button.grid(column=1, columnspan=2, padx=(0, self.PADX), sticky=tk.W, row=cur_row) ttk.Separator(appearance_frame, orient=tk.HORIZONTAL).grid( - columnspan=3, padx=self.PADX, pady=self.PADY*4, sticky=tk.EW, row=row.get() + columnspan=3, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get() ) # Appearance setting @@ -797,7 +801,7 @@ class PreferencesDialog(tk.Toplevel): command=lambda: self.themecolorbrowse(0) ) - self.theme_button_0.grid(column=1, padx=self.PADX, pady=self.PADY, sticky=tk.NSEW, row=cur_row) + self.theme_button_0.grid(column=1, padx=0, pady=self.PADY, sticky=tk.NSEW, row=cur_row) with row as cur_row: self.theme_label_1 = nb.Label(appearance_frame, text=self.theme_prompts[1]) @@ -809,7 +813,7 @@ class PreferencesDialog(tk.Toplevel): command=lambda: self.themecolorbrowse(1) ) - self.theme_button_1.grid(column=1, padx=self.PADX, pady=self.PADY, sticky=tk.NSEW, row=cur_row) + self.theme_button_1.grid(column=1, padx=0, pady=self.PADY, sticky=tk.NSEW, row=cur_row) # UI Scaling """ @@ -820,7 +824,7 @@ class PreferencesDialog(tk.Toplevel): of 200 we'll end up setting 2.66 as the tk-scaling value. """ ttk.Separator(appearance_frame, orient=tk.HORIZONTAL).grid( - columnspan=4, padx=self.PADX, pady=self.PADY*4, sticky=tk.EW, row=row.get() + columnspan=4, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get() ) with row as cur_row: # LANG: Appearance - Label for selection of UI scaling @@ -841,7 +845,7 @@ class PreferencesDialog(tk.Toplevel): resolution=10, ) - self.uiscale_bar.grid(column=1, sticky=tk.W, row=cur_row) + self.uiscale_bar.grid(column=1, padx=0, sticky=tk.W, row=cur_row) self.ui_scaling_defaultis = nb.Label( appearance_frame, # LANG: Appearance - Help/hint text for UI scaling selection @@ -850,7 +854,7 @@ class PreferencesDialog(tk.Toplevel): # Transparency slider ttk.Separator(appearance_frame, orient=tk.HORIZONTAL).grid( - columnspan=4, padx=self.PADX, pady=self.PADY*4, sticky=tk.EW, row=row.get() + columnspan=4, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get() ) with row as cur_row: @@ -887,11 +891,11 @@ class PreferencesDialog(tk.Toplevel): row=cur_row ) - self.transparency_bar.grid(column=1, sticky=tk.W, row=cur_row) + self.transparency_bar.grid(column=1, padx=0, sticky=tk.W, row=cur_row) # Always on top ttk.Separator(appearance_frame, orient=tk.HORIZONTAL).grid( - columnspan=4, padx=self.PADX, pady=self.PADY*4, sticky=tk.EW, row=row.get() + columnspan=4, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get() ) self.ontop_button = nb.Checkbutton( @@ -947,12 +951,12 @@ class PreferencesDialog(tk.Toplevel): # Help text in settings # LANG: Tip/label about how to disable plugins text=_("Tip: You can disable a plugin by{CR}adding '{EXT}' to its folder name").format(EXT='.disabled') - ).grid(columnspan=2, padx=self.PADX, pady=10, sticky=tk.EW, row=row.get()) + ).grid(columnspan=2, padx=self.PADX, pady=self.PADY, sticky=tk.EW, row=row.get()) enabled_plugins = list(filter(lambda x: x.folder and x.module, plug.PLUGINS)) if len(enabled_plugins): ttk.Separator(plugins_frame, orient=tk.HORIZONTAL).grid( - columnspan=3, padx=self.PADX, pady=self.PADY * 8, sticky=tk.EW + columnspan=3, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get() ) nb.Label( plugins_frame, @@ -967,21 +971,19 @@ class PreferencesDialog(tk.Toplevel): else: label = nb.Label(plugins_frame, text=f'{plugin.folder} ({plugin.name})') - label.grid(columnspan=2, padx=self.PADX*2, sticky=tk.W, row=row.get()) + label.grid(columnspan=2, padx=self.LISTX, sticky=tk.W, row=row.get()) ############################################################ # Show which plugins don't have Python 3.x support ############################################################ if len(plug.PLUGINS_not_py3): ttk.Separator(plugins_frame, orient=tk.HORIZONTAL).grid( - columnspan=3, padx=self.PADX, pady=self.PADY * 8, sticky=tk.EW, row=row.get() + columnspan=3, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get() ) # LANG: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x - nb.Label(plugins_frame, text=_('Plugins Without Python 3.x Support:')+':').grid(padx=self.PADX, sticky=tk.W) - - for plugin in plug.PLUGINS_not_py3: - if plugin.folder: # 'system' ones have this set to None to suppress listing in Plugins prefs tab - nb.Label(plugins_frame, text=plugin.name).grid(columnspan=2, padx=self.PADX*2, sticky=tk.W) + nb.Label(plugins_frame, text=_('Plugins Without Python 3.x Support')+':').grid( + padx=self.PADX, sticky=tk.W, row=row.get() + ) HyperlinkLabel( # LANG: Plugins - Label on URL to documentation about migrating plugins from Python 2.7 @@ -989,23 +991,30 @@ class PreferencesDialog(tk.Toplevel): background=nb.Label().cget('background'), url='https://github.com/EDCD/EDMarketConnector/blob/main/PLUGINS.md#migration-from-python-27', underline=True - ).grid(columnspan=2, padx=self.PADX, sticky=tk.W) - ############################################################ + ).grid(columnspan=2, padx=self.PADX, sticky=tk.W, row=row.get()) + for plugin in plug.PLUGINS_not_py3: + if plugin.folder: # 'system' ones have this set to None to suppress listing in Plugins prefs tab + nb.Label(plugins_frame, text=plugin.name).grid( + columnspan=2, padx=self.LISTX, sticky=tk.W, row=row.get() + ) + ############################################################ + # Show disabled plugins + ############################################################ disabled_plugins = list(filter(lambda x: x.folder and not x.module, plug.PLUGINS)) if len(disabled_plugins): ttk.Separator(plugins_frame, orient=tk.HORIZONTAL).grid( - columnspan=3, padx=self.PADX, pady=self.PADY * 8, sticky=tk.EW, row=row.get() + columnspan=3, padx=self.PADX*2, pady=self.SEPY, sticky=tk.EW, row=row.get() ) nb.Label( plugins_frame, - # LANG: Lable on list of user-disabled plugins + # LANG: Label on list of user-disabled plugins text=_('Disabled Plugins')+':' # List of plugins in settings ).grid(padx=self.PADX, sticky=tk.W, row=row.get()) for plugin in disabled_plugins: nb.Label(plugins_frame, text=plugin.name).grid( - columnspan=2, padx=self.PADX*2, sticky=tk.W, row=row.get() + columnspan=2, padx=self.LISTX, sticky=tk.W, row=row.get() ) # LANG: Label on Settings > Plugins tab From fc9775b9101aba570f4b9d7aa7fc8fca13568497 Mon Sep 17 00:00:00 2001 From: Phoebe Date: Fri, 17 Nov 2023 01:57:13 +0100 Subject: [PATCH 31/83] [Minor] flake8 --- plugins/eddn.py | 2 +- plugins/inara.py | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index c8bca92a..7ce79e83 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -2089,7 +2089,7 @@ def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: """ PADX = 10 # noqa: N806 BUTTONX = 12 # noqa: N806 # indent Checkbuttons and Radiobuttons - PADY = 2 + PADY = 2 # 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 diff --git a/plugins/inara.py b/plugins/inara.py index b3446b62..da9e47b4 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -247,11 +247,11 @@ def toggle_password_visibility(): def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> tk.Frame: """Plugin Preferences UI hook.""" - PADX = 10 - BUTTONX = 12 # indent Checkbuttons and Radiobuttons - PADY = 2 # close spacing - SEPY = 10 # seperator line spacing - cur_row = 0 + PADX = 10 # noqa: N806 + BUTTONX = 12 # noqa: N806 # indent Checkbuttons and Radiobuttons + PADY = 2 # noqa: N806 # close spacing + SEPY = 10 # noqa: N806 # seperator line spacing + cur_row = 0 # noqa: N806 frame = nb.Frame(parent) frame.columnconfigure(1, weight=1) From a3c1763f4a12888882f124f7441c484e64aa5f41 Mon Sep 17 00:00:00 2001 From: Phoebe Date: Fri, 17 Nov 2023 03:05:42 +0100 Subject: [PATCH 32/83] [2095] Standardize horizontal Padding - Standardizes horizontal Padding. - Fixes further padding issues. - Part of #2095 --- plugins/coriolis.py | 26 ++++--- plugins/eddn.py | 4 +- plugins/edsm.py | 25 +++---- plugins/inara.py | 17 ++--- prefs.py | 164 ++++++++++++++++++++++++-------------------- 5 files changed, 129 insertions(+), 107 deletions(-) diff --git a/plugins/coriolis.py b/plugins/coriolis.py index 599e4d57..9de635d0 100644 --- a/plugins/coriolis.py +++ b/plugins/coriolis.py @@ -84,6 +84,8 @@ def plugin_start3(path: str) -> str: def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Frame: """Set up plugin preferences.""" PADX = 10 # noqa: N806 + PADY = 1 # noqa: N806 + BOXY = 2 # noqa: N806 # box spacing conf_frame = nb.Frame(parent) conf_frame.columnconfigure(index=1, weight=1) @@ -91,33 +93,39 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr # LANG: Settings>Coriolis: Help/hint for changing coriolis URLs nb.Label(conf_frame, text=_( "Set the URL to use with coriolis.io ship loadouts. Note that this MUST end with '/import?data='" - )).grid(sticky=tk.EW, row=cur_row, column=0, padx=PADX, columnspan=3) + )).grid(sticky=tk.EW, row=cur_row, column=0, padx=PADX, pady=PADY, columnspan=3) cur_row += 1 # LANG: Settings>Coriolis: Label for 'NOT alpha/beta game version' URL - nb.Label(conf_frame, text=_('Normal URL')).grid(sticky=tk.W, row=cur_row, column=0, padx=PADX) + nb.Label(conf_frame, text=_('Normal URL')).grid(sticky=tk.W, row=cur_row, column=0, padx=PADX, pady=PADY) nb.Entry(conf_frame, - textvariable=coriolis_config.normal_textvar).grid(sticky=tk.EW, row=cur_row, column=1, padx=PADX) + textvariable=coriolis_config.normal_textvar).grid( + sticky=tk.EW, row=cur_row, column=1, padx=PADX, pady=BOXY + ) # LANG: Generic 'Reset' button label nb.Button(conf_frame, text=_("Reset"), command=lambda: coriolis_config.normal_textvar.set(value=DEFAULT_NORMAL_URL)).grid( - sticky=tk.W, row=cur_row, column=2, padx=PADX + sticky=tk.W, row=cur_row, column=2, padx=PADX, pady=0 ) cur_row += 1 # LANG: Settings>Coriolis: Label for 'alpha/beta game version' URL - nb.Label(conf_frame, text=_('Beta URL')).grid(sticky=tk.W, row=cur_row, column=0, padx=PADX) - nb.Entry(conf_frame, textvariable=coriolis_config.beta_textvar).grid(sticky=tk.EW, row=cur_row, column=1, padx=PADX) + nb.Label(conf_frame, text=_('Beta URL')).grid(sticky=tk.W, row=cur_row, column=0, padx=PADX, pady=PADY) + nb.Entry(conf_frame, textvariable=coriolis_config.beta_textvar).grid( + sticky=tk.EW, row=cur_row, column=1, padx=PADX, pady=BOXY + ) # LANG: Generic 'Reset' button label nb.Button(conf_frame, text=_('Reset'), command=lambda: coriolis_config.beta_textvar.set(value=DEFAULT_BETA_URL)).grid( - sticky=tk.W, row=cur_row, column=2, padx=PADX + sticky=tk.W, row=cur_row, column=2, padx=PADX, pady=0 ) cur_row += 1 # TODO: This needs a help/hint text to be sure users know what it's for. # LANG: Settings>Coriolis: Label for selection of using Normal, Beta or 'auto' Coriolis URL - nb.Label(conf_frame, text=_('Override Beta/Normal Selection')).grid(sticky=tk.W, row=cur_row, column=0, padx=PADX) + nb.Label(conf_frame, text=_('Override Beta/Normal Selection')).grid( + sticky=tk.W, row=cur_row, column=0, padx=PADX, pady=PADY + ) nb.OptionMenu( conf_frame, coriolis_config.override_textvar, @@ -125,7 +133,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr _('Normal'), # LANG: 'Normal' label for Coriolis site override selection _('Beta'), # LANG: 'Beta' label for Coriolis site override selection _('Auto') # LANG: 'Auto' label for Coriolis site override selection - ).grid(sticky=tk.W, row=cur_row, column=1, padx=PADX) + ).grid(sticky=tk.W, row=cur_row, column=1, padx=PADX, pady=BOXY) cur_row += 1 return conf_frame diff --git a/plugins/eddn.py b/plugins/eddn.py index 7ce79e83..a1f90610 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -2089,7 +2089,7 @@ def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: """ PADX = 10 # noqa: N806 BUTTONX = 12 # noqa: N806 # indent Checkbuttons and Radiobuttons - PADY = 2 # noqa: N806 + 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 @@ -2106,7 +2106,7 @@ def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: background=nb.Label().cget('background'), url='https://github.com/EDCD/EDDN#eddn---elite-dangerous-data-network', underline=True - ).grid(row=cur_row, padx=PADX, sticky=tk.W) # Don't translate + ).grid(row=cur_row, padx=PADX, pady=PADY, sticky=tk.W) # Don't translate cur_row += 1 this.eddn_station = tk.IntVar(value=(output & config.OUT_EDDN_SEND_STATION_DATA) and 1) diff --git a/plugins/edsm.py b/plugins/edsm.py index 1e400c80..93296f1b 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -293,8 +293,9 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr """ PADX = 10 # noqa: N806 BUTTONX = 12 # noqa: N806 - PADY = 2 # noqa: N806 - SEPY = 10 # noqa: N806 + PADY = 1 # noqa: N806 + BOXY = 2 # noqa: N806 + SEPY = 10 # noqa: N806 frame = nb.Frame(parent) frame.columnconfigure(1, weight=1) @@ -306,7 +307,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr background=nb.Label().cget('background'), url='https://www.edsm.net/', underline=True - ).grid(row=cur_row, columnspan=2, padx=PADX, sticky=tk.W) + ).grid(row=cur_row, columnspan=2, padx=PADX, pady=PADY, sticky=tk.W) cur_row += 1 this.log = tk.IntVar(value=config.get_int('edsm_out') and 1) @@ -317,7 +318,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr command=prefsvarchanged ) if this.log_button: - this.log_button.grid(row=cur_row, columnspan=2, padx=BUTTONX, pady=(5, 0), sticky=tk.W) + this.log_button.grid(row=cur_row, columnspan=2, padx=BUTTONX, pady=PADY, sticky=tk.W) cur_row += 1 ttk.Separator(frame, orient=tk.HORIZONTAL).grid( @@ -333,27 +334,27 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr underline=True ) if this.label: - this.label.grid(row=cur_row, columnspan=2, padx=PADX, sticky=tk.W) + this.label.grid(row=cur_row, columnspan=2, padx=PADX, pady=PADY, sticky=tk.W) # LANG: Game Commander name label in EDSM settings cur_row += 1 this.cmdr_label = nb.Label(frame, text=_('Cmdr')) - this.cmdr_label.grid(row=cur_row, padx=PADX, sticky=tk.W) + this.cmdr_label.grid(row=cur_row, padx=PADX, pady=PADY, sticky=tk.W) this.cmdr_text = nb.Label(frame) - this.cmdr_text.grid(row=cur_row, column=1, padx=PADX, pady=PADY, sticky=tk.W) + this.cmdr_text.grid(row=cur_row, column=1, padx=PADX, pady=BOXY, sticky=tk.W) cur_row += 1 # LANG: EDSM Commander name label in EDSM settings this.user_label = nb.Label(frame, text=_('Commander Name')) - this.user_label.grid(row=cur_row, padx=PADX, sticky=tk.W) + this.user_label.grid(row=cur_row, padx=PADX, pady=PADY, sticky=tk.W) this.user = nb.Entry(frame) - this.user.grid(row=cur_row, column=1, padx=PADX, pady=PADY, sticky=tk.EW) + this.user.grid(row=cur_row, column=1, padx=PADX, pady=BOXY, sticky=tk.EW) cur_row += 1 # LANG: EDSM API key label this.apikey_label = nb.Label(frame, text=_('API Key')) - this.apikey_label.grid(row=cur_row, padx=PADX, sticky=tk.W) + this.apikey_label.grid(row=cur_row, padx=PADX, pady=PADY, sticky=tk.W) this.apikey = nb.Entry(frame, show="*", width=50) - this.apikey.grid(row=cur_row, column=1, padx=PADX, pady=PADY, sticky=tk.EW) + this.apikey.grid(row=cur_row, column=1, padx=PADX, pady=BOXY, sticky=tk.EW) cur_row += 1 prefs_cmdr_changed(cmdr, is_beta) @@ -366,7 +367,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr variable=show_password_var, command=toggle_password_visibility ) - show_password_checkbox.grid(row=cur_row, columnspan=2, padx=BUTTONX, pady=(5, 0), sticky=tk.W) + show_password_checkbox.grid(row=cur_row, columnspan=2, padx=BUTTONX, pady=PADY, sticky=tk.W) return frame diff --git a/plugins/inara.py b/plugins/inara.py index da9e47b4..9bb50a87 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -249,16 +249,17 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> tk.Frame: """Plugin Preferences UI hook.""" PADX = 10 # noqa: N806 BUTTONX = 12 # noqa: N806 # indent Checkbuttons and Radiobuttons - PADY = 2 # noqa: N806 # close spacing + PADY = 1 # noqa: N806 # close spacing + BOXY = 2 # noqa: N806 # box spacing SEPY = 10 # noqa: N806 # seperator line spacing - cur_row = 0 # noqa: N806 + cur_row = 0 frame = nb.Frame(parent) frame.columnconfigure(1, weight=1) HyperlinkLabel( frame, text='Inara', background=nb.Label().cget('background'), url='https://inara.cz/', underline=True - ).grid(row=cur_row, columnspan=2, padx=PADX, sticky=tk.W) # Don't translate + ).grid(row=cur_row, columnspan=2, padx=PADX, pady=PADY, sticky=tk.W) # Don't translate cur_row += 1 this.log = tk.IntVar(value=config.get_int('inara_out') and 1) @@ -269,7 +270,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> tk.Frame: command=prefsvarchanged ) - this.log_button.grid(row=cur_row, columnspan=2, padx=BUTTONX, pady=(5, 0), sticky=tk.W) + this.log_button.grid(row=cur_row, columnspan=2, padx=BUTTONX, pady=PADY, sticky=tk.W) cur_row += 1 ttk.Separator(frame, orient=tk.HORIZONTAL).grid( @@ -286,14 +287,14 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> tk.Frame: underline=True ) - this.label.grid(row=cur_row, columnspan=2, padx=PADX, sticky=tk.W) + this.label.grid(row=cur_row, columnspan=2, padx=PADX, pady=PADY, sticky=tk.W) cur_row += 1 # LANG: Inara API key label this.apikey_label = nb.Label(frame, text=_('API Key')) # Inara setting - this.apikey_label.grid(row=cur_row, padx=PADX, sticky=tk.W) + this.apikey_label.grid(row=cur_row, padx=PADX, pady=PADY, sticky=tk.W) this.apikey = nb.Entry(frame, show="*", width=50) - this.apikey.grid(row=cur_row, column=1, padx=PADX, pady=PADY, sticky=tk.EW) + this.apikey.grid(row=cur_row, column=1, padx=PADX, pady=BOXY, sticky=tk.EW) cur_row += 1 prefs_cmdr_changed(cmdr, is_beta) @@ -305,7 +306,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> tk.Frame: variable=show_password_var, command=toggle_password_visibility, ) - show_password_checkbox.grid(row=cur_row, columnspan=2, padx=BUTTONX, pady=(5, 0), sticky=tk.W) + show_password_checkbox.grid(row=cur_row, columnspan=2, padx=BUTTONX, pady=PADY, sticky=tk.W) return frame diff --git a/prefs.py b/prefs.py index 20cc3cef..e1ab6ea2 100644 --- a/prefs.py +++ b/prefs.py @@ -289,8 +289,9 @@ class PreferencesDialog(tk.Toplevel): self.PADX = 10 self.BUTTONX = 12 # indent Checkbuttons and Radiobuttons self.LISTX = 25 # indent listed items - self.PADY = 2 # close spacing - self.SEPY = 10 # seperator line spacing + self.PADY = 1 # close spacing + self.BOXY = 2 # box spacing + self.SEPY = 10 # seperator line spacing # Set up different tabs self.__setup_output_tab(notebook) @@ -353,7 +354,7 @@ class PreferencesDialog(tk.Toplevel): # LANG: Settings > Output - choosing what data to save to files self.out_label = nb.Label(output_frame, text=_('Please choose what data to save')) - self.out_label.grid(columnspan=2, padx=self.PADX, sticky=tk.W, row=row.get()) + self.out_label.grid(columnspan=2, padx=self.PADX, pady=self.PADY, sticky=tk.W, row=row.get()) self.out_csv = tk.IntVar(value=1 if (output & config.OUT_MKT_CSV) else 0) self.out_csv_button = nb.Checkbutton( @@ -362,7 +363,7 @@ class PreferencesDialog(tk.Toplevel): variable=self.out_csv, command=self.outvarchanged ) - self.out_csv_button.grid(columnspan=2, padx=self.BUTTONX, sticky=tk.W, row=row.get()) + self.out_csv_button.grid(columnspan=2, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W, row=row.get()) self.out_td = tk.IntVar(value=1 if (output & config.OUT_MKT_TD) else 0) self.out_td_button = nb.Checkbutton( @@ -371,7 +372,7 @@ class PreferencesDialog(tk.Toplevel): variable=self.out_td, command=self.outvarchanged ) - self.out_td_button.grid(columnspan=2, padx=self.BUTTONX, sticky=tk.W, row=row.get()) + self.out_td_button.grid(columnspan=2, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W, row=row.get()) self.out_ship = tk.IntVar(value=1 if (output & config.OUT_SHIP) else 0) # Output setting @@ -381,7 +382,7 @@ class PreferencesDialog(tk.Toplevel): variable=self.out_ship, command=self.outvarchanged ) - self.out_ship_button.grid(columnspan=2, padx=self.BUTTONX, pady=(5, 0), sticky=tk.W, row=row.get()) + self.out_ship_button.grid(columnspan=2, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W, row=row.get()) self.out_auto = tk.IntVar(value=0 if output & config.OUT_MKT_MANUAL else 1) # inverted # Output setting @@ -391,17 +392,17 @@ class PreferencesDialog(tk.Toplevel): variable=self.out_auto, command=self.outvarchanged ) - self.out_auto_button.grid(columnspan=2, padx=self.BUTTONX, pady=(5, 0), sticky=tk.W, row=row.get()) + self.out_auto_button.grid(columnspan=2, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W, row=row.get()) self.outdir = tk.StringVar() self.outdir.set(str(config.get_str('outdir'))) # LANG: Settings > Output - Label for "where files are located" self.outdir_label = nb.Label(output_frame, text=_('File location')+':') # Section heading in settings # Type ignored due to incorrect type annotation. a 2 tuple does padding for each side - self.outdir_label.grid(padx=self.PADX, pady=(0, self.PADY), sticky=tk.W, row=row.get()) # type: ignore + self.outdir_label.grid(padx=self.PADX, pady=self.PADY, sticky=tk.W, row=row.get()) # type: ignore self.outdir_entry = nb.Entry(output_frame, takefocus=False) - self.outdir_entry.grid(columnspan=2, padx=self.PADX, pady=(0, self.PADY), sticky=tk.EW, row=row.get()) + self.outdir_entry.grid(columnspan=2, padx=self.PADX, pady=self.BOXY, sticky=tk.EW, row=row.get()) if sys.platform == 'darwin': text = (_('Change...')) # LANG: macOS Preferences - files location selection button @@ -449,9 +450,9 @@ class PreferencesDialog(tk.Toplevel): config_frame, # LANG: Settings > Configuration - Label for Journal files location text=_('E:D journal file location')+':' - ).grid(columnspan=4, padx=self.PADX, sticky=tk.W, row=row.get()) + ).grid(columnspan=4, padx=self.PADX, pady=self.PADY, sticky=tk.W, row=row.get()) - self.logdir_entry.grid(columnspan=4, padx=self.PADX, pady=(0, self.PADY), sticky=tk.EW, row=row.get()) + self.logdir_entry.grid(columnspan=4, padx=self.PADX, pady=self.BOXY, sticky=tk.EW, row=row.get()) if sys.platform == 'darwin': text = (_('Change...')) # LANG: macOS Preferences - files location selection button @@ -488,14 +489,14 @@ class PreferencesDialog(tk.Toplevel): nb.Label( config_frame, text=_('CAPI Settings') # LANG: Settings > Configuration - Label for CAPI section - ).grid(padx=self.PADX, sticky=tk.W, row=row.get()) + ).grid(padx=self.PADX, pady=self.PADY, sticky=tk.W, row=row.get()) nb.Checkbutton( config_frame, # LANG: Configuration - Enable or disable the Fleet Carrier CAPI calls text=_('Enable Fleetcarrier CAPI Queries'), variable=self.capi_fleetcarrier - ).grid(columnspan=4, padx=self.BUTTONX, pady=(5, 0), sticky=tk.W, row=row.get()) + ).grid(columnspan=4, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W, row=row.get()) if sys.platform in ('darwin', 'win32'): ttk.Separator(config_frame, orient=tk.HORIZONTAL).grid( @@ -512,7 +513,7 @@ class PreferencesDialog(tk.Toplevel): text=_('Keyboard shortcut') if # LANG: Hotkey/Shortcut settings prompt on OSX sys.platform == 'darwin' else _('Hotkey') # LANG: Hotkey/Shortcut settings prompt on Windows - ).grid(padx=self.PADX, sticky=tk.W, row=cur_row) + ).grid(padx=self.PADX, pady=self.PADY, sticky=tk.W, row=cur_row) if sys.platform == 'darwin' and not was_accessible_at_launch: if AXIsProcessTrusted(): @@ -522,7 +523,7 @@ class PreferencesDialog(tk.Toplevel): # LANG: macOS Preferences > Configuration - restart the app message text=_('Re-start {APP} to use shortcuts').format(APP=applongname), foreground='firebrick' - ).grid(padx=self.PADX, sticky=tk.W, row=cur_row) + ).grid(padx=self.PADX, pady=self.PADY, sticky=tk.W, row=cur_row) else: # Shortcut settings prompt on OSX @@ -531,11 +532,11 @@ class PreferencesDialog(tk.Toplevel): # LANG: macOS - Configuration - need to grant the app permission for keyboard shortcuts text=_('{APP} needs permission to use shortcuts').format(APP=applongname), foreground='firebrick' - ).grid(columnspan=4, padx=self.PADX, sticky=tk.W, row=cur_row) + ).grid(columnspan=4, padx=self.PADX, pady=self.PADY, sticky=tk.W, row=cur_row) # LANG: Shortcut settings button on OSX nb.Button(config_frame, text=_('Open System Preferences'), command=self.enableshortcuts).grid( - padx=self.PADX, sticky=tk.E, row=cur_row + padx=self.PADX, pady=self.BOXY, sticky=tk.E, row=cur_row ) else: @@ -551,7 +552,7 @@ class PreferencesDialog(tk.Toplevel): self.hotkey_text.bind('', self.hotkeystart) self.hotkey_text.bind('', self.hotkeyend) - self.hotkey_text.grid(column=1, columnspan=2, pady=(5, 0), sticky=tk.W, row=cur_row) + self.hotkey_text.grid(column=1, columnspan=2, pady=self.BOXY, sticky=tk.W, row=cur_row) # Hotkey/Shortcut setting self.hotkey_only_btn = nb.Checkbutton( @@ -562,7 +563,7 @@ class PreferencesDialog(tk.Toplevel): state=tk.NORMAL if self.hotkey_code else tk.DISABLED ) - self.hotkey_only_btn.grid(columnspan=4, padx=self.BUTTONX, pady=(5, 0), sticky=tk.W, row=row.get()) + self.hotkey_only_btn.grid(columnspan=4, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W, row=row.get()) # Hotkey/Shortcut setting self.hotkey_play_btn = nb.Checkbutton( @@ -573,7 +574,7 @@ class PreferencesDialog(tk.Toplevel): state=tk.NORMAL if self.hotkey_code else tk.DISABLED ) - self.hotkey_play_btn.grid(columnspan=4, padx=self.BUTTONX, sticky=tk.W, row=row.get()) + self.hotkey_play_btn.grid(columnspan=4, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W, row=row.get()) # Option to disabled Automatic Check For Updates whilst in-game ttk.Separator(config_frame, orient=tk.HORIZONTAL).grid( @@ -588,7 +589,9 @@ class PreferencesDialog(tk.Toplevel): command=self.disable_autoappupdatecheckingame_changed ) - self.disable_autoappupdatecheckingame_btn.grid(columnspan=4, padx=self.BUTTONX, sticky=tk.W, row=row.get()) + self.disable_autoappupdatecheckingame_btn.grid( + columnspan=4, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W, row=row.get() + ) ttk.Separator(config_frame, orient=tk.HORIZONTAL).grid( columnspan=4, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get() @@ -597,7 +600,7 @@ class PreferencesDialog(tk.Toplevel): # Settings prompt for preferred ship loadout, system and station info websites # LANG: Label for preferred shipyard, system and station 'providers' nb.Label(config_frame, text=_('Preferred websites')).grid( - columnspan=4, padx=self.PADX, sticky=tk.W, row=row.get() + columnspan=4, padx=self.PADX, pady=self.PADY, sticky=tk.W, row=row.get() ) with row as cur_row: @@ -607,13 +610,13 @@ class PreferencesDialog(tk.Toplevel): ) # Setting to decide which ship outfitting website to link to - either E:D Shipyard or Coriolis # LANG: Label for Shipyard provider selection - nb.Label(config_frame, text=_('Shipyard')).grid(padx=self.PADX, pady=2*self.PADY, sticky=tk.W, row=cur_row) + nb.Label(config_frame, text=_('Shipyard')).grid(padx=self.PADX, pady=self.PADY, sticky=tk.W, row=cur_row) self.shipyard_button = nb.OptionMenu( config_frame, self.shipyard_provider, self.shipyard_provider.get(), *plug.provides('shipyard_url') ) self.shipyard_button.configure(width=15) - self.shipyard_button.grid(column=1, sticky=tk.W, row=cur_row) + self.shipyard_button.grid(column=1, pady=self.BOXY, sticky=tk.W, row=cur_row) # Option for alternate URL opening self.alt_shipyard_open = tk.IntVar(value=config.get_int('use_alt_shipyard_open')) self.alt_shipyard_open_btn = nb.Checkbutton( @@ -624,7 +627,7 @@ class PreferencesDialog(tk.Toplevel): command=self.alt_shipyard_open_changed, ) - self.alt_shipyard_open_btn.grid(column=2, sticky=tk.W, row=cur_row) + self.alt_shipyard_open_btn.grid(column=2, padx=self.PADX, pady=self.PADY, sticky=tk.W, row=cur_row) with row as cur_row: system_provider = config.get_str('system_provider') @@ -633,7 +636,7 @@ class PreferencesDialog(tk.Toplevel): ) # LANG: Configuration - Label for selection of 'System' provider website - nb.Label(config_frame, text=_('System')).grid(padx=self.PADX, pady=2*self.PADY, sticky=tk.W, row=cur_row) + nb.Label(config_frame, text=_('System')).grid(padx=self.PADX, pady=self.PADY, sticky=tk.W, row=cur_row) self.system_button = nb.OptionMenu( config_frame, self.system_provider, @@ -642,7 +645,7 @@ class PreferencesDialog(tk.Toplevel): ) self.system_button.configure(width=15) - self.system_button.grid(column=1, sticky=tk.W, row=cur_row) + self.system_button.grid(column=1, pady=self.BOXY, sticky=tk.W, row=cur_row) with row as cur_row: station_provider = config.get_str('station_provider') @@ -651,7 +654,7 @@ class PreferencesDialog(tk.Toplevel): ) # LANG: Configuration - Label for selection of 'Station' provider website - nb.Label(config_frame, text=_('Station')).grid(padx=self.PADX, pady=2*self.PADY, sticky=tk.W, row=cur_row) + nb.Label(config_frame, text=_('Station')).grid(padx=self.PADX, pady=self.PADY, sticky=tk.W, row=cur_row) self.station_button = nb.OptionMenu( config_frame, self.station_provider, @@ -660,7 +663,7 @@ class PreferencesDialog(tk.Toplevel): ) self.station_button.configure(width=15) - self.station_button.grid(column=1, sticky=tk.W, row=cur_row) + self.station_button.grid(column=1, pady=self.BOXY, sticky=tk.W, row=cur_row) # Set loglevel ttk.Separator(config_frame, orient=tk.HORIZONTAL).grid( @@ -673,7 +676,7 @@ class PreferencesDialog(tk.Toplevel): config_frame, # LANG: Configuration - Label for selection of Log Level text=_('Log Level') - ).grid(padx=self.PADX, pady=2*self.PADY, sticky=tk.W, row=cur_row) + ).grid(padx=self.PADX, pady=self.PADY, sticky=tk.W, row=cur_row) current_loglevel = config.get_str('loglevel') if not current_loglevel: @@ -694,14 +697,14 @@ class PreferencesDialog(tk.Toplevel): ) self.loglevel_dropdown.configure(width=15) - self.loglevel_dropdown.grid(column=1, sticky=tk.W, row=cur_row) + self.loglevel_dropdown.grid(column=1, pady=self.BOXY, sticky=tk.W, row=cur_row) nb.Button( config_frame, # LANG: Label on button used to open a filesystem folder text=_('Open Log Folder'), # Button that opens a folder in Explorer/Finder command=lambda: help_open_log_folder() - ).grid(column=2, padx=(0, self.PADX), sticky=tk.NSEW, row=cur_row) + ).grid(column=2, padx=self.PADX, pady=0, sticky=tk.NSEW, row=cur_row) # Big spacer nb.Label(config_frame).grid(sticky=tk.W, row=row.get()) @@ -717,15 +720,17 @@ class PreferencesDialog(tk.Toplevel): # LANG: UI elements privacy section header in privacy tab of preferences nb.Label(privacy_frame, text=_('Main UI privacy options')).grid( - row=row.get(), column=0, sticky=tk.W, padx=self.PADX + row=row.get(), column=0, sticky=tk.W, padx=self.PADX, pady=self.PADY ) nb.Checkbutton( - privacy_frame, text=_('Hide private group name in UI'), # LANG: Hide private group owner name from UI checkbox + # LANG: Hide private group owner name from UI checkbox + privacy_frame, text=_('Hide private group name in UI'), variable=self.hide_private_group ).grid(row=row.get(), column=0, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W) nb.Checkbutton( - privacy_frame, text=_('Hide multi-crew captain name'), # LANG: Hide multicrew captain name from main UI checkbox + # LANG: Hide multicrew captain name from main UI checkbox + privacy_frame, text=_('Hide multi-crew captain name'), variable=self.hide_multicrew_captain ).grid(row=row.get(), column=0, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W) @@ -753,30 +758,34 @@ class PreferencesDialog(tk.Toplevel): appearance_frame.columnconfigure(2, weight=1) with row as cur_row: # LANG: Appearance - Label for selection of application display language - nb.Label(appearance_frame, text=_('Language')).grid(padx=self.PADX, sticky=tk.W, row=cur_row) + nb.Label(appearance_frame, text=_('Language')).grid( + padx=self.PADX, pady=self.PADY, sticky=tk.W, row=cur_row + ) self.lang_button = nb.OptionMenu(appearance_frame, self.lang, self.lang.get(), *self.languages.values()) - self.lang_button.grid(column=1, columnspan=2, padx=(0, self.PADX), sticky=tk.W, row=cur_row) + self.lang_button.grid(column=1, columnspan=2, padx=0, pady=self.BOXY, sticky=tk.W, row=cur_row) ttk.Separator(appearance_frame, orient=tk.HORIZONTAL).grid( - columnspan=3, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get() + columnspan=4, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get() ) # Appearance setting # LANG: Label for Settings > Appearance > Theme selection - nb.Label(appearance_frame, text=_('Theme')).grid(columnspan=3, padx=self.PADX, sticky=tk.W, row=row.get()) + nb.Label(appearance_frame, text=_('Theme')).grid( + columnspan=3, padx=self.PADX, pady=self.PADY, sticky=tk.W, row=row.get() + ) # Appearance theme and language setting nb.Radiobutton( # LANG: Label for 'Default' theme radio button appearance_frame, text=_('Default'), variable=self.theme, value=theme.THEME_DEFAULT, command=self.themevarchanged - ).grid(columnspan=3, padx=self.BUTTONX, sticky=tk.W, row=row.get()) + ).grid(columnspan=3, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W, row=row.get()) # Appearance theme setting nb.Radiobutton( # LANG: Label for 'Dark' theme radio button appearance_frame, text=_('Dark'), variable=self.theme, value=theme.THEME_DARK, command=self.themevarchanged - ).grid(columnspan=3, padx=self.BUTTONX, sticky=tk.W, row=row.get()) + ).grid(columnspan=3, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W, row=row.get()) if sys.platform == 'win32': nb.Radiobutton( @@ -786,11 +795,11 @@ class PreferencesDialog(tk.Toplevel): variable=self.theme, value=theme.THEME_TRANSPARENT, command=self.themevarchanged - ).grid(columnspan=3, padx=self.BUTTONX, sticky=tk.W, row=row.get()) + ).grid(columnspan=3, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W, row=row.get()) with row as cur_row: self.theme_label_0 = nb.Label(appearance_frame, text=self.theme_prompts[0]) - self.theme_label_0.grid(padx=self.PADX, sticky=tk.W, row=cur_row) + self.theme_label_0.grid(padx=self.PADX, pady=self.PADY, sticky=tk.W, row=cur_row) # Main window self.theme_button_0 = nb.ColoredButton( @@ -801,11 +810,11 @@ class PreferencesDialog(tk.Toplevel): command=lambda: self.themecolorbrowse(0) ) - self.theme_button_0.grid(column=1, padx=0, pady=self.PADY, sticky=tk.NSEW, row=cur_row) + self.theme_button_0.grid(column=1, padx=0, pady=self.BOXY, sticky=tk.NSEW, row=cur_row) with row as cur_row: self.theme_label_1 = nb.Label(appearance_frame, text=self.theme_prompts[1]) - self.theme_label_1.grid(padx=self.PADX, sticky=tk.W, row=cur_row) + self.theme_label_1.grid(padx=self.PADX, pady=self.PADY, sticky=tk.W, row=cur_row) self.theme_button_1 = nb.ColoredButton( appearance_frame, text=' Hutton Orbital ', # Do not translate @@ -813,7 +822,7 @@ class PreferencesDialog(tk.Toplevel): command=lambda: self.themecolorbrowse(1) ) - self.theme_button_1.grid(column=1, padx=0, pady=self.PADY, sticky=tk.NSEW, row=cur_row) + self.theme_button_1.grid(column=1, padx=0, pady=self.BOXY, sticky=tk.NSEW, row=cur_row) # UI Scaling """ @@ -829,7 +838,7 @@ class PreferencesDialog(tk.Toplevel): with row as cur_row: # LANG: Appearance - Label for selection of UI scaling nb.Label(appearance_frame, text=_('UI Scale Percentage')).grid( - padx=self.PADX, pady=2*self.PADY, sticky=tk.W, row=cur_row + padx=self.PADX, pady=self.PADY, sticky=tk.W, row=cur_row ) self.ui_scale = tk.IntVar() @@ -845,12 +854,12 @@ class PreferencesDialog(tk.Toplevel): resolution=10, ) - self.uiscale_bar.grid(column=1, padx=0, sticky=tk.W, row=cur_row) + self.uiscale_bar.grid(column=1, padx=0, pady=self.BOXY, sticky=tk.W, row=cur_row) self.ui_scaling_defaultis = nb.Label( appearance_frame, # LANG: Appearance - Help/hint text for UI scaling selection text=_('100 means Default{CR}Restart Required for{CR}changes to take effect!') - ).grid(column=3, padx=self.PADX, pady=2*self.PADY, sticky=tk.E, row=cur_row) + ).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( @@ -860,7 +869,7 @@ class PreferencesDialog(tk.Toplevel): with row as cur_row: # LANG: Appearance - Label for selection of main window transparency nb.Label(appearance_frame, text=_("Main window transparency")).grid( - padx=self.PADX, pady=self.PADY*2, sticky=tk.W, row=cur_row + padx=self.PADX, pady=self.PADY, sticky=tk.W, row=cur_row ) self.transparency = tk.IntVar() self.transparency.set(config.get_int('ui_transparency') or 100) # Default to 100 for users @@ -886,12 +895,12 @@ class PreferencesDialog(tk.Toplevel): ).grid( column=3, padx=self.PADX, - pady=self.PADY*2, + pady=self.PADY, sticky=tk.E, row=cur_row ) - self.transparency_bar.grid(column=1, padx=0, sticky=tk.W, row=cur_row) + self.transparency_bar.grid(column=1, padx=0, pady=self.BOXY, sticky=tk.W, row=cur_row) # Always on top ttk.Separator(appearance_frame, orient=tk.HORIZONTAL).grid( @@ -905,7 +914,9 @@ class PreferencesDialog(tk.Toplevel): variable=self.always_ontop, command=self.themevarchanged ) - self.ontop_button.grid(columnspan=3, padx=self.BUTTONX, sticky=tk.W, row=row.get()) # Appearance setting + self.ontop_button.grid( + columnspan=3, padx=self.BUTTONX, pady=self.PADY, sticky=tk.W, row=row.get() + ) # Appearance setting if sys.platform == 'win32': nb.Checkbutton( @@ -914,7 +925,7 @@ class PreferencesDialog(tk.Toplevel): text=_('Minimize to system tray'), variable=self.minimize_system_tray, command=self.themevarchanged - ).grid(columnspan=3, padx=self.BUTTONX, sticky=tk.W, row=row.get()) # Appearance setting + ).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 @@ -932,26 +943,27 @@ class PreferencesDialog(tk.Toplevel): # Section heading in settings # LANG: Label for location of third-party plugins folder nb.Label(plugins_frame, text=_('Plugins folder') + ':').grid( - padx=self.PADX, pady=(0, self.PADY), sticky=tk.W, row=row.get() + padx=self.PADX, pady=self.PADY, sticky=tk.W, row=row.get() ) plugdirentry = nb.Entry(plugins_frame, justify=tk.LEFT) self.displaypath(plugdir, plugdirentry) - plugdirentry.grid(columnspan=2, padx=self.PADX, pady=(0, self.PADY), sticky=tk.EW, row=row.get()) + plugdirentry.grid(columnspan=2, padx=self.PADX, pady=self.BOXY, sticky=tk.EW, row=row.get()) - nb.Button( - plugins_frame, - # LANG: Label on button used to open a filesystem folder - text=_('Open'), # Button that opens a folder in Explorer/Finder - command=lambda: webbrowser.open(f'file:///{config.plugin_dir_path}') - ).grid(column=1, padx=self.PADX, pady=self.PADY, sticky=tk.EW, row=row.get()) + with row as cur_row: + nb.Label( + plugins_frame, + # Help text in settings + # LANG: Tip/label about how to disable plugins + text=_("Tip: You can disable a plugin by{CR}adding '{EXT}' to its folder name").format(EXT='.disabled') + ).grid(columnspan=2, padx=self.PADX, pady=self.PADY, sticky=tk.EW, row=cur_row) - nb.Label( - plugins_frame, - # Help text in settings - # LANG: Tip/label about how to disable plugins - text=_("Tip: You can disable a plugin by{CR}adding '{EXT}' to its folder name").format(EXT='.disabled') - ).grid(columnspan=2, padx=self.PADX, pady=self.PADY, sticky=tk.EW, row=row.get()) + nb.Button( + plugins_frame, + # LANG: Label on button used to open a filesystem folder + text=_('Open'), # Button that opens a folder in Explorer/Finder + command=lambda: webbrowser.open(f'file:///{config.plugin_dir_path}') + ).grid(column=1, padx=self.PADX, pady=self.PADY, sticky=tk.N, row=cur_row) enabled_plugins = list(filter(lambda x: x.folder and x.module, plug.PLUGINS)) if len(enabled_plugins): @@ -962,7 +974,7 @@ class PreferencesDialog(tk.Toplevel): plugins_frame, # LANG: Label on list of enabled plugins text=_('Enabled Plugins')+':' # List of plugins in settings - ).grid(padx=self.PADX, sticky=tk.W, row=row.get()) + ).grid(padx=self.PADX, pady=self.PADY, sticky=tk.W, row=row.get()) for plugin in enabled_plugins: if plugin.name == plugin.folder: @@ -971,7 +983,7 @@ class PreferencesDialog(tk.Toplevel): else: label = nb.Label(plugins_frame, text=f'{plugin.folder} ({plugin.name})') - label.grid(columnspan=2, padx=self.LISTX, sticky=tk.W, row=row.get()) + label.grid(columnspan=2, padx=self.LISTX, pady=self.PADY, sticky=tk.W, row=row.get()) ############################################################ # Show which plugins don't have Python 3.x support @@ -982,7 +994,7 @@ class PreferencesDialog(tk.Toplevel): ) # LANG: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x nb.Label(plugins_frame, text=_('Plugins Without Python 3.x Support')+':').grid( - padx=self.PADX, sticky=tk.W, row=row.get() + padx=self.PADX, pady=self.PADY, sticky=tk.W, row=row.get() ) HyperlinkLabel( @@ -991,12 +1003,12 @@ class PreferencesDialog(tk.Toplevel): background=nb.Label().cget('background'), url='https://github.com/EDCD/EDMarketConnector/blob/main/PLUGINS.md#migration-from-python-27', underline=True - ).grid(columnspan=2, padx=self.PADX, sticky=tk.W, row=row.get()) + ).grid(columnspan=2, padx=self.PADX, pady=self.PADY, sticky=tk.W, row=row.get()) for plugin in plug.PLUGINS_not_py3: if plugin.folder: # 'system' ones have this set to None to suppress listing in Plugins prefs tab nb.Label(plugins_frame, text=plugin.name).grid( - columnspan=2, padx=self.LISTX, sticky=tk.W, row=row.get() + columnspan=2, padx=self.LISTX, pady=self.PADY, sticky=tk.W, row=row.get() ) ############################################################ # Show disabled plugins @@ -1004,17 +1016,17 @@ class PreferencesDialog(tk.Toplevel): disabled_plugins = list(filter(lambda x: x.folder and not x.module, plug.PLUGINS)) if len(disabled_plugins): ttk.Separator(plugins_frame, orient=tk.HORIZONTAL).grid( - columnspan=3, padx=self.PADX*2, pady=self.SEPY, sticky=tk.EW, row=row.get() + columnspan=3, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get() ) nb.Label( plugins_frame, # LANG: Label on list of user-disabled plugins text=_('Disabled Plugins')+':' # List of plugins in settings - ).grid(padx=self.PADX, sticky=tk.W, row=row.get()) + ).grid(padx=self.PADX, pady=self.PADY, sticky=tk.W, row=row.get()) for plugin in disabled_plugins: nb.Label(plugins_frame, text=plugin.name).grid( - columnspan=2, padx=self.LISTX, sticky=tk.W, row=row.get() + columnspan=2, padx=self.LISTX, pady=self.PADY, sticky=tk.W, row=row.get() ) # LANG: Label on Settings > Plugins tab From a169fb5a18c523cd4bae03b10201f21f7ed32025 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 17 Nov 2023 10:54:00 -0500 Subject: [PATCH 33/83] [Minor] Suppress Errant MyPy Error --- plugins/eddn.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index a1f90610..0ab06a83 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -428,13 +428,13 @@ class EDDNSender: r.raise_for_status() except requests.exceptions.HTTPError as e: - if unknown_schema := self.UNKNOWN_SCHEMA_RE.match(e.response.text): + if unknown_schema := self.UNKNOWN_SCHEMA_RE.match(e.response.text): # type: ignore logger.debug(f"EDDN doesn't (yet?) know about schema: {unknown_schema['schema_name']}" f"/{unknown_schema['schema_version']}") # This dropping is to cater for the time period when EDDN doesn't *yet* support a new schema. return True - if e.response.status_code == http.HTTPStatus.BAD_REQUEST: + if e.response.status_code == http.HTTPStatus.BAD_REQUEST: # type: ignore # EDDN straight up says no, so drop the message logger.debug(f"EDDN responded '400 Bad Request' to the message, dropping:\n{msg!r}") return True From b2d5e134655f857ee99be5ffb4f3538d663ee403 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 17 Nov 2023 11:33:26 -0500 Subject: [PATCH 34/83] [2051] Update Supporting Files Not touching any of the big ones, but some clarification updates to many of the supporting files. --- collate.py | 4 ++-- debug_webserver.py | 15 ++++++------- journal_lock.py | 18 +++++++++++----- myNotebook.py | 19 +++++++++-------- theme.py | 53 ++++++++++++++++++++++++---------------------- timeout_session.py | 26 ++++++++++++++--------- update.py | 41 ++++++++++++++++++++--------------- 7 files changed, 100 insertions(+), 76 deletions(-) diff --git a/collate.py b/collate.py index 48007527..caf5994f 100755 --- a/collate.py +++ b/collate.py @@ -79,7 +79,7 @@ def addcommodities(data) -> None: # noqa: CCR001 commodities[key] = new - if not len(commodities) > size_pre: + if len(commodities) <= size_pre: return if isfile(commodityfile): @@ -227,7 +227,7 @@ if __name__ == "__main__": print('Not docked!') continue - elif not data.get('lastStarport'): + if not data.get('lastStarport'): print('No starport!') continue diff --git a/debug_webserver.py b/debug_webserver.py index 48f473a4..87f7eaed 100644 --- a/debug_webserver.py +++ b/debug_webserver.py @@ -1,4 +1,6 @@ """Simple HTTP listener to be used with debugging various EDMC sends.""" +from __future__ import annotations + import gzip import json import pathlib @@ -6,7 +8,7 @@ import tempfile import threading import zlib from http import server -from typing import Any, Callable, Literal, Tuple, Union +from typing import Any, Callable, Literal from urllib.parse import parse_qs from config import appname @@ -22,9 +24,6 @@ SAFE_TRANSLATE = str.maketrans({x: '_' for x in "!@#$%^&*()./\\\r\n[]-+='\";:?<> class LoggingHandler(server.BaseHTTPRequestHandler): """HTTP Handler implementation that logs to EDMCs logger and writes data to files on disk.""" - def __init__(self, request, client_address: Tuple[str, int], server) -> None: - super().__init__(request, client_address, server) - def log_message(self, format: str, *args: Any) -> None: """Override default handler logger with EDMC logger.""" logger.info(format % args) @@ -45,7 +44,7 @@ class LoggingHandler(server.BaseHTTPRequestHandler): elif len(target_path) == 1 and target_path[0] == '/': target_path = 'WEB_ROOT' - response: Union[Callable[[str], str], str, None] = DEFAULT_RESPONSES.get(target_path) + response: Callable[[str], str] | str | None = DEFAULT_RESPONSES.get(target_path) if callable(response): response = response(to_save) @@ -69,11 +68,11 @@ class LoggingHandler(server.BaseHTTPRequestHandler): target_file = output_data_path / (safe_file_name(target_path) + '.log') if target_file.parent != output_data_path: logger.warning(f"REFUSING TO WRITE FILE THAT ISN'T IN THE RIGHT PLACE! {target_file=}") - logger.warning(f'DATA FOLLOWS\n{data}') # type: ignore # mypy thinks data is a byte string here + logger.warning(f'DATA FOLLOWS\n{data}') return - with output_lock, target_file.open('a') as f: - f.write(to_save + "\n\n") + with output_lock, target_file.open('a') as file: + file.write(to_save + "\n\n") @staticmethod def get_printable(data: bytes, compression: Literal['deflate'] | Literal['gzip'] | str | None = None) -> str: diff --git a/journal_lock.py b/journal_lock.py index 7945ef91..b6f816b9 100644 --- a/journal_lock.py +++ b/journal_lock.py @@ -1,4 +1,11 @@ -"""Implements locking of Journal directory.""" +""" +journal_lock.py - Locking of the Journal Directory. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" +from __future__ import annotations import pathlib import sys @@ -6,7 +13,7 @@ import tkinter as tk from enum import Enum from os import getpid as os_getpid from tkinter import ttk -from typing import TYPE_CHECKING, Callable, Optional +from typing import TYPE_CHECKING, Callable from config import config from EDMCLogging import get_main_logger @@ -34,9 +41,9 @@ class JournalLock: def __init__(self) -> None: """Initialise where the journal directory and lock file are.""" self.journal_dir: str | None = config.get_str('journaldir') or config.default_journal_dir - self.journal_dir_path: Optional[pathlib.Path] = None + self.journal_dir_path: pathlib.Path | None = None self.set_path_from_journaldir() - self.journal_dir_lockfile_name: Optional[pathlib.Path] = None + self.journal_dir_lockfile_name: pathlib.Path | None = None # We never test truthiness of this, so let it be defined when first assigned. Avoids type hint issues. # self.journal_dir_lockfile: Optional[IO] = None self.locked = False @@ -58,7 +65,8 @@ class JournalLock: self.journal_dir_lockfile_name = self.journal_dir_path / 'edmc-journal-lock.txt' # type: ignore logger.trace_if('journal-lock', f'journal_dir_lockfile_name = {self.journal_dir_lockfile_name!r}') try: - self.journal_dir_lockfile = open(self.journal_dir_lockfile_name, mode='w+', encoding='utf-8') + with open(self.journal_dir_lockfile_name, mode='w+', encoding='utf-8') as lockfile: + self.journal_dir_lockfile = lockfile # Linux CIFS read-only mount throws: OSError(30, 'Read-only file system') # Linux no-write-perm directory throws: PermissionError(13, 'Permission denied') diff --git a/myNotebook.py b/myNotebook.py index 30f95274..6fa35774 100644 --- a/myNotebook.py +++ b/myNotebook.py @@ -10,10 +10,11 @@ OSX and Windows. Entire file may be imported by plugins. """ +from __future__ import annotations + import sys import tkinter as tk from tkinter import ttk -from typing import Optional # Can't do this with styles on OSX - http://www.tkdocs.com/tutorial/styles.html#whydifficult if sys.platform == 'darwin': @@ -29,7 +30,7 @@ elif sys.platform == 'win32': class Notebook(ttk.Notebook): """Custom ttk.Notebook class to fix some display issues.""" - def __init__(self, master: Optional[ttk.Frame] = None, **kw): + def __init__(self, master: ttk.Frame | None = None, **kw): ttk.Notebook.__init__(self, master, **kw) style = ttk.Style() @@ -75,9 +76,9 @@ class Frame(sys.platform == 'darwin' and tk.Frame or ttk.Frame): # type: ignore class Label(tk.Label): """Custom tk.Label class to fix some display issues.""" - def __init__(self, master: Optional[ttk.Frame] = None, **kw): + def __init__(self, master: ttk.Frame | None = None, **kw): # This format chosen over `sys.platform in (...)` as mypy and friends dont understand that - if sys.platform == 'darwin' or sys.platform == 'win32': + if sys.platform in ('darwin', 'win32'): kw['foreground'] = kw.pop('foreground', PAGEFG) kw['background'] = kw.pop('background', PAGEBG) else: @@ -89,7 +90,7 @@ class Label(tk.Label): class Entry(sys.platform == 'darwin' and tk.Entry or ttk.Entry): # type: ignore """Custom t(t)k.Entry class to fix some display issues.""" - def __init__(self, master: Optional[ttk.Frame] = None, **kw): + def __init__(self, master: ttk.Frame | None = None, **kw): if sys.platform == 'darwin': kw['highlightbackground'] = kw.pop('highlightbackground', PAGEBG) tk.Entry.__init__(self, master, **kw) @@ -100,7 +101,7 @@ class Entry(sys.platform == 'darwin' and tk.Entry or ttk.Entry): # type: ignore class Button(sys.platform == 'darwin' and tk.Button or ttk.Button): # type: ignore """Custom t(t)k.Button class to fix some display issues.""" - def __init__(self, master: Optional[ttk.Frame] = None, **kw): + def __init__(self, master: ttk.Frame | None = None, **kw): if sys.platform == 'darwin': kw['highlightbackground'] = kw.pop('highlightbackground', PAGEBG) tk.Button.__init__(self, master, **kw) @@ -113,7 +114,7 @@ class Button(sys.platform == 'darwin' and tk.Button or ttk.Button): # type: ign class ColoredButton(sys.platform == 'darwin' and tk.Label or tk.Button): # type: ignore """Custom t(t)k.ColoredButton class to fix some display issues.""" - def __init__(self, master: Optional[ttk.Frame] = None, **kw): + def __init__(self, master: ttk.Frame | None = None, **kw): if sys.platform == 'darwin': # Can't set Button background on OSX, so use a Label instead kw['relief'] = kw.pop('relief', tk.RAISED) @@ -131,7 +132,7 @@ class ColoredButton(sys.platform == 'darwin' and tk.Label or tk.Button): # type class Checkbutton(sys.platform == 'darwin' and tk.Checkbutton or ttk.Checkbutton): # type: ignore """Custom t(t)k.Checkbutton class to fix some display issues.""" - def __init__(self, master: Optional[ttk.Frame] = None, **kw): + def __init__(self, master: ttk.Frame | None = None, **kw): if sys.platform == 'darwin': kw['foreground'] = kw.pop('foreground', PAGEFG) kw['background'] = kw.pop('background', PAGEBG) @@ -145,7 +146,7 @@ class Checkbutton(sys.platform == 'darwin' and tk.Checkbutton or ttk.Checkbutton class Radiobutton(sys.platform == 'darwin' and tk.Radiobutton or ttk.Radiobutton): # type: ignore """Custom t(t)k.Radiobutton class to fix some display issues.""" - def __init__(self, master: Optional[ttk.Frame] = None, **kw): + def __init__(self, master: ttk.Frame | None = None, **kw): if sys.platform == 'darwin': kw['foreground'] = kw.pop('foreground', PAGEFG) kw['background'] = kw.pop('background', PAGEBG) diff --git a/theme.py b/theme.py index b5d51484..bfb76c55 100644 --- a/theme.py +++ b/theme.py @@ -1,9 +1,14 @@ """ -Theme support. +theme.py - Theme support. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. Because of various ttk limitations this app is an unholy mix of Tk and ttk widgets. So can't use ttk's theme support. So have to change colors manually. """ +from __future__ import annotations import os import sys @@ -11,7 +16,7 @@ import tkinter as tk from os.path import join from tkinter import font as tk_font from tkinter import ttk -from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Set, Tuple +from typing import TYPE_CHECKING, Callable from config import config from EDMCLogging import get_main_logger @@ -36,7 +41,7 @@ if sys.platform == 'win32': AddFontResourceEx.restypes = [LPCWSTR, DWORD, LPCVOID] # type: ignore FR_PRIVATE = 0x10 FR_NOT_ENUM = 0x20 - AddFontResourceEx(join(config.respath, u'EUROCAPS.TTF'), FR_PRIVATE, 0) + AddFontResourceEx(join(config.respath, 'EUROCAPS.TTF'), FR_PRIVATE, 0) elif sys.platform == 'linux': # pyright: reportUnboundVariable=false @@ -121,7 +126,7 @@ elif sys.platform == 'linux': dpy = None -class _Theme(object): +class _Theme: # Enum ? Remember these are, probably, based on 'value' of a tk # RadioButton set. Looking in prefs.py, they *appear* to be hard-coded @@ -132,18 +137,18 @@ class _Theme(object): def __init__(self) -> None: self.active: int | None = None # Starts out with no theme - self.minwidth: Optional[int] = None - self.widgets: Dict[tk.Widget | tk.BitmapImage, Set] = {} - self.widgets_pair: List = [] - self.defaults: Dict = {} - self.current: Dict = {} + self.minwidth: int | None = None + self.widgets: dict[tk.Widget | tk.BitmapImage, set] = {} + self.widgets_pair: list = [] + self.defaults: dict = {} + self.current: dict = {} self.default_ui_scale: float | None = None # None == not yet known self.startup_ui_scale: int | None = None 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.Widget) or isinstance(widget, tk.BitmapImage), widget + assert isinstance(widget, (tk.BitmapImage, tk.Widget)), widget if not self.defaults: # Can't initialise this til window is created # Windows, MacOS self.defaults = { @@ -169,14 +174,14 @@ class _Theme(object): attribs.add('fg') if widget['background'] not in ['', self.defaults['bitmapbg']]: attribs.add('bg') - elif isinstance(widget, tk.Entry) or isinstance(widget, ttk.Entry): + elif isinstance(widget, (tk.Entry, ttk.Entry)): if widget['foreground'] not in ['', self.defaults['entryfg']]: attribs.add('fg') if widget['background'] not in ['', self.defaults['entrybg']]: attribs.add('bg') if 'font' in widget.keys() and str(widget['font']) not in ['', self.defaults['entryfont']]: attribs.add('font') - elif isinstance(widget, tk.Frame) or isinstance(widget, ttk.Frame) or isinstance(widget, tk.Canvas): + elif isinstance(widget, (tk.Canvas, tk.Frame, ttk.Frame)): if ( ('background' in widget.keys() or isinstance(widget, tk.Canvas)) and widget['background'] not in ['', self.defaults['frame']] @@ -200,21 +205,21 @@ class _Theme(object): attribs.add('font') self.widgets[widget] = attribs - if isinstance(widget, tk.Frame) or isinstance(widget, ttk.Frame): + if isinstance(widget, (tk.Frame, ttk.Frame)): for child in widget.winfo_children(): self.register(child) - def register_alternate(self, pair: Tuple, gridopts: Dict) -> None: + def register_alternate(self, pair: tuple, gridopts: dict) -> None: self.widgets_pair.append((pair, gridopts)) def button_bind( - self, widget: tk.Widget, command: Callable, image: Optional[tk.BitmapImage] = None + self, widget: tk.Widget, command: Callable, image: tk.BitmapImage | None = None ) -> None: widget.bind('', command) widget.bind('', lambda e: self._enter(e, image)) widget.bind('', lambda e: self._leave(e, image)) - def _enter(self, event: tk.Event, image: Optional[tk.BitmapImage]) -> None: + def _enter(self, event: tk.Event, image: tk.BitmapImage | None) -> None: widget = event.widget if widget and widget['state'] != tk.DISABLED: try: @@ -231,7 +236,7 @@ class _Theme(object): except Exception: logger.exception(f'Failure configuring image: {image=}') - def _leave(self, event: tk.Event, image: Optional[tk.BitmapImage]) -> None: + def _leave(self, event: tk.Event, image: tk.BitmapImage | None) -> None: widget = event.widget if widget and widget['state'] != tk.DISABLED: try: @@ -299,13 +304,13 @@ class _Theme(object): Also, register it for future updates. :param widget: Target widget. """ - assert isinstance(widget, tk.Widget) or isinstance(widget, tk.BitmapImage), widget + assert isinstance(widget, (tk.BitmapImage, tk.Widget)), widget if not self.current: return # No need to call this for widgets created in plugin_app() self.register(widget) self._update_widget(widget) - if isinstance(widget, tk.Frame) or isinstance(widget, ttk.Frame): + if isinstance(widget, (tk.Frame, ttk.Frame)): for child in widget.winfo_children(): self._update_widget(child) @@ -314,7 +319,7 @@ class _Theme(object): if widget not in self.widgets: if isinstance(widget, tk.Widget): w_class = widget.winfo_class() - w_keys: List[str] = widget.keys() + w_keys: list[str] = widget.keys() else: # There is no tk.BitmapImage.winfo_class() @@ -325,7 +330,7 @@ class _Theme(object): assert_str = f'{w_class} {widget} "{"text" in w_keys and widget["text"]}"' raise AssertionError(assert_str) - attribs: Set = self.widgets.get(widget, set()) + attribs: set = self.widgets.get(widget, set()) try: if isinstance(widget, tk.BitmapImage): @@ -355,7 +360,7 @@ class _Theme(object): # e.g. tk.Button, tk.Label, tk.Menu if 'fg' not in attribs: widget['foreground'] = self.current['foreground'] - widget['activeforeground'] = self.current['activeforeground'], + widget['activeforeground'] = self.current['activeforeground'] widget['disabledforeground'] = self.current['disabledforeground'] if 'bg' not in attribs: @@ -419,9 +424,7 @@ class _Theme(object): if self.active == theme: return # Don't need to mess with the window manager - - else: - self.active = theme + self.active = theme if sys.platform == 'darwin': from AppKit import NSAppearance, NSApplication, NSMiniaturizableWindowMask, NSResizableWindowMask diff --git a/timeout_session.py b/timeout_session.py index 8a4656ce..2d0d395f 100644 --- a/timeout_session.py +++ b/timeout_session.py @@ -1,7 +1,15 @@ -"""A requests.session with a TimeoutAdapter.""" -import requests -from requests.adapters import HTTPAdapter +""" +timeout_session.py - requests session with timeout adapter. +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" +from __future__ import annotations + +import requests +from requests import Session +from requests.adapters import HTTPAdapter from config import user_agent REQUEST_TIMEOUT = 10 # reasonable timeout that all HTTP requests should use @@ -35,11 +43,9 @@ def new_session( :param session: the Session object to attach the Adapter to, defaults to a new session :return: The created Session """ - if session is None: - session = requests.Session() + with Session() as session: session.headers['User-Agent'] = user_agent - - adapter = TimeoutAdapter(timeout) - session.mount("http://", adapter) - session.mount("https://", adapter) - return session + adapter = TimeoutAdapter(timeout) + session.mount("http://", adapter) + session.mount("https://", adapter) + return session diff --git a/update.py b/update.py index 272d217d..f88daa38 100644 --- a/update.py +++ b/update.py @@ -1,25 +1,32 @@ -"""Checking for updates to this application.""" +""" +update.py - Checking for Program Updates. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" +from __future__ import annotations + import os import sys import threading from os.path import dirname, join from traceback import print_exc -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING from xml.etree import ElementTree - import requests import semantic_version +from config import appname, appversion_nobuild, config, update_feed +from EDMCLogging import get_main_logger if TYPE_CHECKING: import tkinter as tk -from config import appname, appversion_nobuild, config, update_feed -from EDMCLogging import get_main_logger logger = get_main_logger() -class EDMCVersion(object): +class EDMCVersion: """ Hold all the information about an EDMC version. @@ -39,7 +46,7 @@ class EDMCVersion(object): self.sv: semantic_version.base.Version = sv -class Updater(object): +class Updater: """ Handle checking for updates. @@ -63,16 +70,16 @@ class Updater(object): return False - def __init__(self, tkroot: Optional['tk.Tk'] = None, provider: str = 'internal'): + def __init__(self, tkroot: tk.Tk | None = None, provider: str = 'internal'): """ Initialise an Updater instance. :param tkroot: reference to the root window of the GUI :param provider: 'internal' or other string if not """ - self.root: Optional['tk.Tk'] = tkroot + self.root: tk.Tk | None = tkroot self.provider: str = provider - self.thread: Optional[threading.Thread] = None + self.thread: threading.Thread | None = None if self.use_internal(): return @@ -81,7 +88,7 @@ class Updater(object): import ctypes try: - self.updater: Optional[ctypes.CDLL] = ctypes.cdll.WinSparkle + self.updater: ctypes.CDLL | None = ctypes.cdll.WinSparkle # Set the appcast URL self.updater.win_sparkle_set_appcast_url(update_feed.encode()) @@ -150,7 +157,7 @@ class Updater(object): elif sys.platform == 'darwin' and self.updater: self.updater.checkForUpdates_(None) - def check_appcast(self) -> Optional[EDMCVersion]: + def check_appcast(self) -> EDMCVersion | None: """ Manually (no Sparkle or WinSparkle) check the update_feed appcast file. @@ -161,7 +168,7 @@ class Updater(object): newversion = None items = {} try: - r = requests.get(update_feed, timeout=10) + request = requests.get(update_feed, timeout=10) except requests.RequestException as ex: logger.exception(f'Error retrieving update_feed file: {ex}') @@ -169,7 +176,7 @@ class Updater(object): return None try: - feed = ElementTree.fromstring(r.text) + feed = ElementTree.fromstring(request.text) except SyntaxError as ex: logger.exception(f'Syntax error in update_feed file: {ex}') @@ -196,12 +203,12 @@ class Updater(object): continue # This will change A.B.C.D to A.B.C+D - sv = semantic_version.Version.coerce(ver) + semver = semantic_version.Version.coerce(ver) - items[sv] = EDMCVersion( + items[semver] = EDMCVersion( version=str(ver), # sv might have mangled version title=item.find('title').text, # type: ignore - sv=sv + sv=semver ) # Look for any remaining version greater than appversion From ebd1813612dd6e66c82d3894306199145c65d793 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 17 Nov 2023 11:37:36 -0500 Subject: [PATCH 35/83] [2051] Revert Breaking Change --- journal_lock.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/journal_lock.py b/journal_lock.py index b6f816b9..4d04992f 100644 --- a/journal_lock.py +++ b/journal_lock.py @@ -65,8 +65,7 @@ class JournalLock: self.journal_dir_lockfile_name = self.journal_dir_path / 'edmc-journal-lock.txt' # type: ignore logger.trace_if('journal-lock', f'journal_dir_lockfile_name = {self.journal_dir_lockfile_name!r}') try: - with open(self.journal_dir_lockfile_name, mode='w+', encoding='utf-8') as lockfile: - self.journal_dir_lockfile = lockfile + self.journal_dir_lockfile = open(self.journal_dir_lockfile_name, mode='w+', encoding='utf-8') # Linux CIFS read-only mount throws: OSError(30, 'Read-only file system') # Linux no-write-perm directory throws: PermissionError(13, 'Permission denied') From b41dfaa594c1805886bdc1c4457df6584f9d073e Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 17 Nov 2023 11:51:41 -0500 Subject: [PATCH 36/83] [2051] Don't Overwrite Every Session Whoops. Only fetch a new session if it's None. Co-Authored-By: Phoebe <40956085+C1701D@users.noreply.github.com> --- timeout_session.py | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/timeout_session.py b/timeout_session.py index 2d0d395f..55fc4dc0 100644 --- a/timeout_session.py +++ b/timeout_session.py @@ -7,8 +7,7 @@ See LICENSE file. """ from __future__ import annotations -import requests -from requests import Session +from requests import Session, Response from requests.adapters import HTTPAdapter from config import user_agent @@ -25,7 +24,7 @@ class TimeoutAdapter(HTTPAdapter): super().__init__(*args, **kwargs) - def send(self, *args, **kwargs) -> requests.Response: + def send(self, *args, **kwargs) -> Response: """Send, but with a timeout always set.""" if kwargs["timeout"] is None: kwargs["timeout"] = self.default_timeout @@ -33,9 +32,7 @@ class TimeoutAdapter(HTTPAdapter): return super().send(*args, **kwargs) -def new_session( - timeout: int = REQUEST_TIMEOUT, session: requests.Session | None = None -) -> requests.Session: +def new_session(timeout: int = REQUEST_TIMEOUT, session: Session | None = None) -> Session: """ Create a new requests.Session and override the default HTTPAdapter with a TimeoutAdapter. @@ -43,9 +40,11 @@ def new_session( :param session: the Session object to attach the Adapter to, defaults to a new session :return: The created Session """ - with Session() as session: - session.headers['User-Agent'] = user_agent - adapter = TimeoutAdapter(timeout) - session.mount("http://", adapter) - session.mount("https://", adapter) - return session + session = session or Session() + session.headers.setdefault("User-Agent", user_agent) + + adapter = TimeoutAdapter(timeout) + for prefix in ("http://", "https://"): + session.mount(prefix, adapter) + + return session From e268c248d1090edc9a47b47411b8424fd5e074ff Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 17 Nov 2023 13:19:06 -0500 Subject: [PATCH 37/83] [2051] Convert Pickle to Json --- build.py | 6 +- coriolis-update-files.py | 28 +- docs/Releasing.md | 2 +- edshipyard.py | 24 +- outfitting.py | 85 +- resources/modules.json | 3306 ++++++++++++++++++++++++++++++++++++++ resources/ships.json | 116 ++ 7 files changed, 3502 insertions(+), 65 deletions(-) create mode 100644 resources/modules.json create mode 100644 resources/ships.json diff --git a/build.py b/build.py index 4ee99758..1cdb239a 100644 --- a/build.py +++ b/build.py @@ -73,8 +73,10 @@ def generate_data_files( "ChangeLog.md", "snd_good.wav", "snd_bad.wav", - "modules.p", - "ships.p", + "modules.p", # TODO: Remove in 6.0 + "resources/modules.json", + "resources/ships.json", + "ships.p", # TODO: Remove in 6.0 f"{app_name}.VisualElementsManifest.xml", f"{app_name}.ico", "EDMarketConnector - TRACE.bat", diff --git a/coriolis-update-files.py b/coriolis-update-files.py index 62cef658..09592cfe 100755 --- a/coriolis-update-files.py +++ b/coriolis-update-files.py @@ -1,16 +1,18 @@ -#!/usr/bin/env python3 """ -Build ship and module databases from https://github.com/EDCD/coriolis-data/ . +coriolis-update-files.py - Build ship and module databases from https://github.com/EDCD/coriolis-data/. -This script also utilise the file outfitting.csv. Due to how collate.py -both reads and writes to this file a local copy is used, in the root of the -project structure, is used for this purpose. If you want to utilise the +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. + +This script also utilizes the file outfitting.csv. Due to how collate.py +both reads and writes to this file, a local copy in the root of the +project structure is used for this purpose. If you want to utilize the FDevIDs/ version of the file, copy it over the local one. """ import json -import pickle import subprocess import sys from collections import OrderedDict @@ -29,7 +31,9 @@ if __name__ == "__main__": # Regenerate coriolis-data distribution subprocess.check_call('npm install', cwd='coriolis-data', shell=True, stdout=sys.stdout, stderr=sys.stderr) - data = json.load(open('coriolis-data/dist/index.json')) + file_path = 'coriolis-data/dist/index.json' + with open(file_path) as file: + data = json.load(file) # Symbolic name from in-game name reverse_ship_map = {v: k for k, v in list(ship_name_map.items())} @@ -44,11 +48,12 @@ if __name__ == "__main__": name = coriolis_ship_map.get(m['properties']['name'], str(m['properties']['name'])) assert name in reverse_ship_map, name ships[name] = {'hullMass': m['properties']['hullMass']} - for i in range(len(bulkheads)): - modules['_'.join([reverse_ship_map[name], 'armour', bulkheads[i]])] = {'mass': m['bulkheads'][i]['mass']} + for i, bulkhead in enumerate(bulkheads): + modules['_'.join([reverse_ship_map[name], 'armour', bulkhead])] = {'mass': m['bulkheads'][i]['mass']} ships = OrderedDict([(k, ships[k]) for k in sorted(ships)]) # sort for easier diffing - pickle.dump(ships, open('ships.p', 'wb')) + with open("resources/ships.json", "w") as ships_file: + json.dump(ships, ships_file, indent=4) # Module masses for cat in list(data['Modules'].values()): @@ -82,4 +87,5 @@ if __name__ == "__main__": add(modules, 'hpt_multicannon_fixed_medium_advanced', {'mass': 4}) modules = OrderedDict([(k, modules[k]) for k in sorted(modules)]) # sort for easier diffing - pickle.dump(modules, open('modules.p', 'wb')) + with open("resources/modules.json", "w") as modules_file: + json.dump(modules, modules_file, indent=4) diff --git a/docs/Releasing.md b/docs/Releasing.md index f4c71483..74151752 100644 --- a/docs/Releasing.md +++ b/docs/Releasing.md @@ -156,7 +156,7 @@ Before you create a new install each time you should: 1. `cd coriolis-data` 2. `git pull` 3. `npm install` - to check it's worked. -3. Run `coriolis-update-files.py` to update `modules.p` and `ships.p`. **NB: +3. Run `coriolis-update-files.py` to update `modules.json` and `ships.json`. **NB: The submodule might have been updated by a GitHub workflow/PR/merge, so be sure to perform this step for every build.** 4. XXX: Test ? diff --git a/edshipyard.py b/edshipyard.py index 1bfa77e6..5d14009c 100644 --- a/edshipyard.py +++ b/edshipyard.py @@ -1,12 +1,13 @@ """Export ship loadout in ED Shipyard plain text format.""" +from __future__ import annotations +import json import os import pathlib -import pickle import re import time from collections import defaultdict -from typing import Dict, List, Union +from typing import Union import outfitting import util_ships @@ -17,14 +18,15 @@ from EDMCLogging import get_main_logger logger = get_main_logger() -__Module = Dict[str, Union[str, List[str]]] +__Module = dict[str, Union[str, list[str]]] # Have to keep old-style here for compatibility # Map API ship names to ED Shipyard names ship_map = ship_name_map.copy() # Ship masses -# TODO: prefer something other than pickle for this storage (dev readability, security) -ships = pickle.load(open(pathlib.Path(config.respath_path) / 'ships.p', 'rb')) +ships_file = config.respath_path / "resources" / "ships.json" +with open(ships_file, encoding="utf-8") as ships_file_handle: + ships = json.load(ships_file_handle) def export(data, filename=None) -> None: # noqa: C901, CCR001 @@ -75,7 +77,6 @@ def export(data, filename=None) -> None: # noqa: C901, CCR001 jumpboost = 0 for slot in sorted(data['ship']['modules']): - v = data['ship']['modules'][slot] try: if not v: @@ -116,15 +117,14 @@ def export(data, filename=None) -> None: # noqa: C901, CCR001 jumpboost += module.get('jumpboost', 0) # type: ignore - for s in slot_map: - if slot.lower().startswith(s): - loadout[slot_map[s]].append(cr + name) + for slot_prefix, index in slot_map.items(): + if slot.lower().startswith(slot_prefix): + loadout[index].append(cr + name) break else: if slot.lower().startswith('slot'): loadout[slot[-1]].append(cr + name) - elif not slot.lower().startswith('planetaryapproachsuite'): logger.debug(f'EDShipyard: Unknown slot {slot}') @@ -138,7 +138,6 @@ def export(data, filename=None) -> None: # noqa: C901, CCR001 # Construct description ship = ship_map.get(data['ship']['name'].lower(), data['ship']['name']) - if data['ship'].get('shipName') is not None: _ships = f'{ship}, {data["ship"]["shipName"]}' @@ -185,7 +184,6 @@ def export(data, filename=None) -> None: # noqa: C901, CCR001 if filename: with open(filename, 'wt') as h: h.write(string) - return # Look for last ship of this type @@ -193,7 +191,7 @@ def export(data, filename=None) -> None: # noqa: C901, CCR001 regexp = re.compile(re.escape(ship) + r'\.\d{4}-\d\d-\d\dT\d\d\.\d\d\.\d\d\.txt') oldfiles = sorted([x for x in os.listdir(config.get_str('outdir')) if regexp.match(x)]) if oldfiles: - with (pathlib.Path(config.get_str('outdir')) / oldfiles[-1]).open('r') as h: + with (pathlib.Path(config.get_str('outdir')) / oldfiles[-1]).open() as h: if h.read() == string: return # same as last time - don't write diff --git a/outfitting.py b/outfitting.py index 174e24b8..99d841f1 100644 --- a/outfitting.py +++ b/outfitting.py @@ -1,30 +1,37 @@ -"""Code dealing with ship outfitting.""" +""" +outfitting.py - Code dealing with ship outfitting. -import pickle +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" +from __future__ import annotations + +import json from collections import OrderedDict -from os.path import join -from typing import Optional from typing import OrderedDict as OrderedDictT from config import config -from edmc_data import outfitting_armour_map as armour_map -from edmc_data import outfitting_cabin_map as cabin_map -from edmc_data import outfitting_corrosion_rating_map as corrosion_rating_map -from edmc_data import outfitting_countermeasure_map as countermeasure_map -from edmc_data import outfitting_fighter_rating_map as fighter_rating_map -from edmc_data import outfitting_internal_map as internal_map -from edmc_data import outfitting_misc_internal_map as misc_internal_map -from edmc_data import outfitting_missiletype_map as missiletype_map -from edmc_data import outfitting_planet_rating_map as planet_rating_map -from edmc_data import outfitting_rating_map as rating_map -from edmc_data import outfitting_standard_map as standard_map -from edmc_data import outfitting_utility_map as utility_map -from edmc_data import outfitting_weapon_map as weapon_map -from edmc_data import outfitting_weaponclass_map as weaponclass_map -from edmc_data import outfitting_weaponmount_map as weaponmount_map -from edmc_data import outfitting_weaponoldvariant_map as weaponoldvariant_map -from edmc_data import outfitting_weaponrating_map as weaponrating_map -from edmc_data import ship_name_map +from edmc_data import ( + outfitting_armour_map as armour_map, + outfitting_cabin_map as cabin_map, + outfitting_corrosion_rating_map as corrosion_rating_map, + outfitting_countermeasure_map as countermeasure_map, + outfitting_fighter_rating_map as fighter_rating_map, + outfitting_internal_map as internal_map, + outfitting_misc_internal_map as misc_internal_map, + outfitting_missiletype_map as missiletype_map, + outfitting_planet_rating_map as planet_rating_map, + outfitting_rating_map as rating_map, + outfitting_standard_map as standard_map, + outfitting_utility_map as utility_map, + outfitting_weapon_map as weapon_map, + outfitting_weaponclass_map as weaponclass_map, + outfitting_weaponmount_map as weaponmount_map, + outfitting_weaponoldvariant_map as weaponoldvariant_map, + outfitting_weaponrating_map as weaponrating_map, + ship_name_map, +) from EDMCLogging import get_main_logger logger = get_main_logger() @@ -33,7 +40,7 @@ logger = get_main_logger() moduledata: OrderedDictT = OrderedDict() -def lookup(module, ship_map, entitled=False) -> Optional[dict]: # noqa: C901, CCR001 +def lookup(module, ship_map, entitled=False) -> dict | None: # noqa: C901, CCR001 """ Produce a standard dict description of the given module. @@ -51,7 +58,8 @@ def lookup(module, ship_map, entitled=False) -> Optional[dict]: # noqa: C901, C """ # Lazily populate if not moduledata: - moduledata.update(pickle.load(open(join(config.respath_path, 'modules.p'), 'rb'))) + modules_path = config.respath_path / "resources" / "modules.json" + moduledata.update(json.loads(modules_path.read_text())) if not module.get('name'): raise AssertionError(f'{module["id"]}') @@ -61,10 +69,13 @@ def lookup(module, ship_map, entitled=False) -> Optional[dict]: # noqa: C901, C # Armour - e.g. Federation_Dropship_Armour_Grade2 if name[-2] == 'armour': - name = module['name'].lower().rsplit('_', 2) # Armour is ship-specific, and ship names can have underscores + # Armour is ship-specific, and ship names can have underscores + ship_name, armour_grade = module["name"].lower().rsplit("_", 2)[0:2] + if ship_name not in ship_map: + raise AssertionError(f"Unknown ship: {ship_name}") new['category'] = 'standard' - new['name'] = armour_map[name[2]] - new['ship'] = ship_map[name[0]] # Generate error on unknown ship + new["name"] = armour_map[armour_grade] + new["ship"] = ship_map[ship_name] new['class'] = '1' new['rating'] = 'I' @@ -219,10 +230,7 @@ def lookup(module, ship_map, entitled=False) -> Optional[dict]: # noqa: C901, C new['enabled'], new['priority'] = module['on'], module['priority'] # priority is zero-based # Entitlements - if not module.get('sku'): - pass - - else: + if module.get('sku'): new['entitlement'] = module['sku'] # Extra module data @@ -245,10 +253,11 @@ def lookup(module, ship_map, entitled=False) -> Optional[dict]: # noqa: C901, C new.update(moduledata.get(module['name'].lower(), {})) - # check we've filled out mandatory fields - for thing in ['id', 'symbol', 'category', 'name', 'class', 'rating']: # Don't consider mass etc as mandatory - if not new.get(thing): - raise AssertionError(f'{module["id"]}: failed to set {thing}') + # Check we've filled out mandatory fields + 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}') if new['category'] == 'hardpoint' and not new.get('mount'): raise AssertionError(f'{module["id"]}: failed to set mount') @@ -263,15 +272,15 @@ def export(data, filename) -> None: :param data: CAPI data to export. :param filename: Filename to export into. """ - assert data['lastSystem'].get('name') - assert data['lastStarport'].get('name') + assert "name" in data["lastSystem"] + assert "name" in data["lastStarport"] header = 'System,Station,Category,Name,Mount,Guidance,Ship,Class,Rating,FDevID,Date\n' rowheader = f'{data["lastSystem"]["name"]},{data["lastStarport"]["name"]}' with open(filename, 'wt') as h: h.write(header) - for v in list(data['lastStarport'].get('modules', {}).values()): + for v in data["lastStarport"].get("modules", {}).values(): try: m = lookup(v, ship_name_map) if m: diff --git a/resources/modules.json b/resources/modules.json new file mode 100644 index 00000000..27e54626 --- /dev/null +++ b/resources/modules.json @@ -0,0 +1,3306 @@ +{ + "adder_armour_grade1": { + "mass": 0 + }, + "adder_armour_grade2": { + "mass": 3 + }, + "adder_armour_grade3": { + "mass": 5 + }, + "adder_armour_mirrored": { + "mass": 5 + }, + "adder_armour_reactive": { + "mass": 5 + }, + "anaconda_armour_grade1": { + "mass": 0 + }, + "anaconda_armour_grade2": { + "mass": 30 + }, + "anaconda_armour_grade3": { + "mass": 60 + }, + "anaconda_armour_mirrored": { + "mass": 60 + }, + "anaconda_armour_reactive": { + "mass": 60 + }, + "asp_armour_grade1": { + "mass": 0 + }, + "asp_armour_grade2": { + "mass": 21 + }, + "asp_armour_grade3": { + "mass": 42 + }, + "asp_armour_mirrored": { + "mass": 42 + }, + "asp_armour_reactive": { + "mass": 42 + }, + "asp_scout_armour_grade1": { + "mass": 0 + }, + "asp_scout_armour_grade2": { + "mass": 21 + }, + "asp_scout_armour_grade3": { + "mass": 42 + }, + "asp_scout_armour_mirrored": { + "mass": 42 + }, + "asp_scout_armour_reactive": { + "mass": 42 + }, + "belugaliner_armour_grade1": { + "mass": 0 + }, + "belugaliner_armour_grade2": { + "mass": 83 + }, + "belugaliner_armour_grade3": { + "mass": 165 + }, + "belugaliner_armour_mirrored": { + "mass": 165 + }, + "belugaliner_armour_reactive": { + "mass": 165 + }, + "cobramkiii_armour_grade1": { + "mass": 0 + }, + "cobramkiii_armour_grade2": { + "mass": 14 + }, + "cobramkiii_armour_grade3": { + "mass": 27 + }, + "cobramkiii_armour_mirrored": { + "mass": 27 + }, + "cobramkiii_armour_reactive": { + "mass": 27 + }, + "cobramkiv_armour_grade1": { + "mass": 0 + }, + "cobramkiv_armour_grade2": { + "mass": 14 + }, + "cobramkiv_armour_grade3": { + "mass": 27 + }, + "cobramkiv_armour_mirrored": { + "mass": 27 + }, + "cobramkiv_armour_reactive": { + "mass": 27 + }, + "cutter_armour_grade1": { + "mass": 0 + }, + "cutter_armour_grade2": { + "mass": 30 + }, + "cutter_armour_grade3": { + "mass": 60 + }, + "cutter_armour_mirrored": { + "mass": 60 + }, + "cutter_armour_reactive": { + "mass": 60 + }, + "diamondback_armour_grade1": { + "mass": 0 + }, + "diamondback_armour_grade2": { + "mass": 13 + }, + "diamondback_armour_grade3": { + "mass": 26 + }, + "diamondback_armour_mirrored": { + "mass": 26 + }, + "diamondback_armour_reactive": { + "mass": 26 + }, + "diamondbackxl_armour_grade1": { + "mass": 0 + }, + "diamondbackxl_armour_grade2": { + "mass": 23 + }, + "diamondbackxl_armour_grade3": { + "mass": 47 + }, + "diamondbackxl_armour_mirrored": { + "mass": 26 + }, + "diamondbackxl_armour_reactive": { + "mass": 47 + }, + "dolphin_armour_grade1": { + "mass": 0 + }, + "dolphin_armour_grade2": { + "mass": 32 + }, + "dolphin_armour_grade3": { + "mass": 63 + }, + "dolphin_armour_mirrored": { + "mass": 63 + }, + "dolphin_armour_reactive": { + "mass": 63 + }, + "eagle_armour_grade1": { + "mass": 0 + }, + "eagle_armour_grade2": { + "mass": 4 + }, + "eagle_armour_grade3": { + "mass": 8 + }, + "eagle_armour_mirrored": { + "mass": 8 + }, + "eagle_armour_reactive": { + "mass": 8 + }, + "empire_courier_armour_grade1": { + "mass": 0 + }, + "empire_courier_armour_grade2": { + "mass": 4 + }, + "empire_courier_armour_grade3": { + "mass": 8 + }, + "empire_courier_armour_mirrored": { + "mass": 8 + }, + "empire_courier_armour_reactive": { + "mass": 8 + }, + "empire_eagle_armour_grade1": { + "mass": 0 + }, + "empire_eagle_armour_grade2": { + "mass": 4 + }, + "empire_eagle_armour_grade3": { + "mass": 8 + }, + "empire_eagle_armour_mirrored": { + "mass": 8 + }, + "empire_eagle_armour_reactive": { + "mass": 8 + }, + "empire_trader_armour_grade1": { + "mass": 0 + }, + "empire_trader_armour_grade2": { + "mass": 30 + }, + "empire_trader_armour_grade3": { + "mass": 60 + }, + "empire_trader_armour_mirrored": { + "mass": 60 + }, + "empire_trader_armour_reactive": { + "mass": 60 + }, + "federation_corvette_armour_grade1": { + "mass": 0 + }, + "federation_corvette_armour_grade2": { + "mass": 30 + }, + "federation_corvette_armour_grade3": { + "mass": 60 + }, + "federation_corvette_armour_mirrored": { + "mass": 60 + }, + "federation_corvette_armour_reactive": { + "mass": 60 + }, + "federation_dropship_armour_grade1": { + "mass": 0 + }, + "federation_dropship_armour_grade2": { + "mass": 44 + }, + "federation_dropship_armour_grade3": { + "mass": 87 + }, + "federation_dropship_armour_mirrored": { + "mass": 87 + }, + "federation_dropship_armour_reactive": { + "mass": 87 + }, + "federation_dropship_mkii_armour_grade1": { + "mass": 0 + }, + "federation_dropship_mkii_armour_grade2": { + "mass": 44 + }, + "federation_dropship_mkii_armour_grade3": { + "mass": 87 + }, + "federation_dropship_mkii_armour_mirrored": { + "mass": 87 + }, + "federation_dropship_mkii_armour_reactive": { + "mass": 87 + }, + "federation_gunship_armour_grade1": { + "mass": 0 + }, + "federation_gunship_armour_grade2": { + "mass": 44 + }, + "federation_gunship_armour_grade3": { + "mass": 87 + }, + "federation_gunship_armour_mirrored": { + "mass": 87 + }, + "federation_gunship_armour_reactive": { + "mass": 87 + }, + "ferdelance_armour_grade1": { + "mass": 0 + }, + "ferdelance_armour_grade2": { + "mass": 19 + }, + "ferdelance_armour_grade3": { + "mass": 38 + }, + "ferdelance_armour_mirrored": { + "mass": 38 + }, + "ferdelance_armour_reactive": { + "mass": 38 + }, + "hauler_armour_grade1": { + "mass": 0 + }, + "hauler_armour_grade2": { + "mass": 1 + }, + "hauler_armour_grade3": { + "mass": 2 + }, + "hauler_armour_mirrored": { + "mass": 2 + }, + "hauler_armour_reactive": { + "mass": 2 + }, + "hpt_advancedtorppylon_fixed_large": { + "mass": 8 + }, + "hpt_advancedtorppylon_fixed_medium": { + "mass": 4 + }, + "hpt_advancedtorppylon_fixed_small": { + "mass": 2 + }, + "hpt_antiunknownshutdown_tiny": { + "mass": 1.3 + }, + "hpt_atdumbfiremissile_fixed_large": { + "mass": 8 + }, + "hpt_atdumbfiremissile_fixed_medium": { + "mass": 4 + }, + "hpt_atdumbfiremissile_turret_large": { + "mass": 8 + }, + "hpt_atdumbfiremissile_turret_medium": { + "mass": 4 + }, + "hpt_atmulticannon_fixed_large": { + "mass": 8 + }, + "hpt_atmulticannon_fixed_medium": { + "mass": 4 + }, + "hpt_atmulticannon_turret_large": { + "mass": 8 + }, + "hpt_atmulticannon_turret_medium": { + "mass": 4 + }, + "hpt_basicmissilerack_fixed_large": { + "mass": 8 + }, + "hpt_basicmissilerack_fixed_medium": { + "mass": 4 + }, + "hpt_basicmissilerack_fixed_small": { + "mass": 2 + }, + "hpt_beamlaser_fixed_huge": { + "mass": 16 + }, + "hpt_beamlaser_fixed_large": { + "mass": 8 + }, + "hpt_beamlaser_fixed_medium": { + "mass": 4 + }, + "hpt_beamlaser_fixed_small": { + "mass": 2 + }, + "hpt_beamlaser_fixed_small_heat": { + "mass": 2 + }, + "hpt_beamlaser_gimbal_huge": { + "mass": 16 + }, + "hpt_beamlaser_gimbal_large": { + "mass": 8 + }, + "hpt_beamlaser_gimbal_medium": { + "mass": 4 + }, + "hpt_beamlaser_gimbal_small": { + "mass": 2 + }, + "hpt_beamlaser_turret_large": { + "mass": 8 + }, + "hpt_beamlaser_turret_medium": { + "mass": 4 + }, + "hpt_beamlaser_turret_small": { + "mass": 2 + }, + "hpt_cannon_fixed_huge": { + "mass": 16 + }, + "hpt_cannon_fixed_large": { + "mass": 8 + }, + "hpt_cannon_fixed_medium": { + "mass": 4 + }, + "hpt_cannon_fixed_small": { + "mass": 2 + }, + "hpt_cannon_gimbal_huge": { + "mass": 16 + }, + "hpt_cannon_gimbal_large": { + "mass": 8 + }, + "hpt_cannon_gimbal_medium": { + "mass": 4 + }, + "hpt_cannon_gimbal_small": { + "mass": 2 + }, + "hpt_cannon_turret_large": { + "mass": 8 + }, + "hpt_cannon_turret_medium": { + "mass": 4 + }, + "hpt_cannon_turret_small": { + "mass": 2 + }, + "hpt_cargoscanner_size0_class1": { + "mass": 1.3 + }, + "hpt_cargoscanner_size0_class2": { + "mass": 1.3 + }, + "hpt_cargoscanner_size0_class3": { + "mass": 1.3 + }, + "hpt_cargoscanner_size0_class4": { + "mass": 1.3 + }, + "hpt_cargoscanner_size0_class5": { + "mass": 1.3 + }, + "hpt_causticmissile_fixed_medium": { + "mass": 4 + }, + "hpt_chafflauncher_tiny": { + "mass": 1.3 + }, + "hpt_cloudscanner_size0_class1": { + "mass": 1.3 + }, + "hpt_cloudscanner_size0_class2": { + "mass": 1.3 + }, + "hpt_cloudscanner_size0_class3": { + "mass": 1.3 + }, + "hpt_cloudscanner_size0_class4": { + "mass": 1.3 + }, + "hpt_cloudscanner_size0_class5": { + "mass": 1.3 + }, + "hpt_crimescanner_size0_class1": { + "mass": 1.3 + }, + "hpt_crimescanner_size0_class2": { + "mass": 1.3 + }, + "hpt_crimescanner_size0_class3": { + "mass": 1.3 + }, + "hpt_crimescanner_size0_class4": { + "mass": 1.3 + }, + "hpt_crimescanner_size0_class5": { + "mass": 1.3 + }, + "hpt_drunkmissilerack_fixed_medium": { + "mass": 4 + }, + "hpt_dumbfiremissilerack_fixed_large": { + "mass": 8 + }, + "hpt_dumbfiremissilerack_fixed_medium": { + "mass": 4 + }, + "hpt_dumbfiremissilerack_fixed_medium_advanced": { + "mass": 4 + }, + "hpt_dumbfiremissilerack_fixed_medium_lasso": { + "mass": 4 + }, + "hpt_dumbfiremissilerack_fixed_small": { + "mass": 2 + }, + "hpt_dumbfiremissilerack_fixed_small_advanced": { + "mass": 2 + }, + "hpt_electroniccountermeasure_tiny": { + "mass": 1.3 + }, + "hpt_flakmortar_fixed_medium": { + "mass": 4 + }, + "hpt_flakmortar_turret_medium": { + "mass": 4 + }, + "hpt_flechettelauncher_fixed_medium": { + "mass": 4 + }, + "hpt_flechettelauncher_turret_medium": { + "mass": 4 + }, + "hpt_guardian_gausscannon_fixed_medium": { + "mass": 4 + }, + "hpt_guardian_gausscannon_fixed_small": { + "mass": 2 + }, + "hpt_guardian_plasmalauncher_fixed_large": { + "mass": 8 + }, + "hpt_guardian_plasmalauncher_fixed_medium": { + "mass": 4 + }, + "hpt_guardian_plasmalauncher_fixed_small": { + "mass": 2 + }, + "hpt_guardian_plasmalauncher_turret_large": { + "mass": 8 + }, + "hpt_guardian_plasmalauncher_turret_medium": { + "mass": 4 + }, + "hpt_guardian_plasmalauncher_turret_small": { + "mass": 2 + }, + "hpt_guardian_shardcannon_fixed_large": { + "mass": 8 + }, + "hpt_guardian_shardcannon_fixed_medium": { + "mass": 4 + }, + "hpt_guardian_shardcannon_fixed_small": { + "mass": 2 + }, + "hpt_guardian_shardcannon_turret_large": { + "mass": 8 + }, + "hpt_guardian_shardcannon_turret_medium": { + "mass": 4 + }, + "hpt_guardian_shardcannon_turret_small": { + "mass": 2 + }, + "hpt_heatsinklauncher_turret_tiny": { + "mass": 1.3 + }, + "hpt_minelauncher_fixed_medium": { + "mass": 4 + }, + "hpt_minelauncher_fixed_small": { + "mass": 2 + }, + "hpt_minelauncher_fixed_small_impulse": { + "mass": 2 + }, + "hpt_mining_abrblstr_fixed_small": { + "mass": 2 + }, + "hpt_mining_abrblstr_turret_small": { + "mass": 2 + }, + "hpt_mining_seismchrgwarhd_fixed_medium": { + "mass": 4 + }, + "hpt_mining_seismchrgwarhd_turret_medium": { + "mass": 4 + }, + "hpt_mining_subsurfdispmisle_fixed_medium": { + "mass": 4 + }, + "hpt_mining_subsurfdispmisle_fixed_small": { + "mass": 2 + }, + "hpt_mining_subsurfdispmisle_turret_medium": { + "mass": 4 + }, + "hpt_mining_subsurfdispmisle_turret_small": { + "mass": 2 + }, + "hpt_mininglaser_fixed_medium": { + "mass": 2 + }, + "hpt_mininglaser_fixed_small": { + "mass": 2 + }, + "hpt_mininglaser_fixed_small_advanced": { + "mass": 2 + }, + "hpt_mininglaser_turret_medium": { + "mass": 2 + }, + "hpt_mininglaser_turret_small": { + "mass": 2 + }, + "hpt_mrascanner_size0_class1": { + "mass": 1.3 + }, + "hpt_mrascanner_size0_class2": { + "mass": 1.3 + }, + "hpt_mrascanner_size0_class3": { + "mass": 1.3 + }, + "hpt_mrascanner_size0_class4": { + "mass": 1.3 + }, + "hpt_mrascanner_size0_class5": { + "mass": 1.3 + }, + "hpt_multicannon_fixed_huge": { + "mass": 16 + }, + "hpt_multicannon_fixed_large": { + "mass": 8 + }, + "hpt_multicannon_fixed_medium": { + "mass": 4 + }, + "hpt_multicannon_fixed_medium_advanced": { + "mass": 4 + }, + "hpt_multicannon_fixed_small": { + "mass": 2 + }, + "hpt_multicannon_fixed_small_advanced": { + "mass": 2 + }, + "hpt_multicannon_fixed_small_strong": { + "mass": 2 + }, + "hpt_multicannon_gimbal_huge": { + "mass": 16 + }, + "hpt_multicannon_gimbal_large": { + "mass": 8 + }, + "hpt_multicannon_gimbal_medium": { + "mass": 4 + }, + "hpt_multicannon_gimbal_small": { + "mass": 2 + }, + "hpt_multicannon_turret_large": { + "mass": 8 + }, + "hpt_multicannon_turret_medium": { + "mass": 4 + }, + "hpt_multicannon_turret_small": { + "mass": 2 + }, + "hpt_plasmaaccelerator_fixed_huge": { + "mass": 16 + }, + "hpt_plasmaaccelerator_fixed_large": { + "mass": 8 + }, + "hpt_plasmaaccelerator_fixed_large_advanced": { + "mass": 8 + }, + "hpt_plasmaaccelerator_fixed_medium": { + "mass": 4 + }, + "hpt_plasmapointdefence_turret_tiny": { + "mass": 0.5 + }, + "hpt_plasmashockcannon_fixed_large": { + "mass": 8 + }, + "hpt_plasmashockcannon_fixed_medium": { + "mass": 4 + }, + "hpt_plasmashockcannon_fixed_small": { + "mass": 2 + }, + "hpt_plasmashockcannon_gimbal_large": { + "mass": 8 + }, + "hpt_plasmashockcannon_gimbal_medium": { + "mass": 4 + }, + "hpt_plasmashockcannon_gimbal_small": { + "mass": 2 + }, + "hpt_plasmashockcannon_turret_large": { + "mass": 8 + }, + "hpt_plasmashockcannon_turret_medium": { + "mass": 4 + }, + "hpt_plasmashockcannon_turret_small": { + "mass": 2 + }, + "hpt_pulselaser_fixed_huge": { + "mass": 16 + }, + "hpt_pulselaser_fixed_large": { + "mass": 8 + }, + "hpt_pulselaser_fixed_medium": { + "mass": 4 + }, + "hpt_pulselaser_fixed_medium_disruptor": { + "mass": 4 + }, + "hpt_pulselaser_fixed_small": { + "mass": 2 + }, + "hpt_pulselaser_gimbal_huge": { + "mass": 16 + }, + "hpt_pulselaser_gimbal_large": { + "mass": 8 + }, + "hpt_pulselaser_gimbal_medium": { + "mass": 4 + }, + "hpt_pulselaser_gimbal_small": { + "mass": 2 + }, + "hpt_pulselaser_turret_large": { + "mass": 8 + }, + "hpt_pulselaser_turret_medium": { + "mass": 4 + }, + "hpt_pulselaser_turret_small": { + "mass": 2 + }, + "hpt_pulselaserburst_fixed_huge": { + "mass": 16 + }, + "hpt_pulselaserburst_fixed_large": { + "mass": 8 + }, + "hpt_pulselaserburst_fixed_medium": { + "mass": 4 + }, + "hpt_pulselaserburst_fixed_small": { + "mass": 2 + }, + "hpt_pulselaserburst_fixed_small_scatter": { + "mass": 2 + }, + "hpt_pulselaserburst_gimbal_huge": { + "mass": 16 + }, + "hpt_pulselaserburst_gimbal_large": { + "mass": 8 + }, + "hpt_pulselaserburst_gimbal_medium": { + "mass": 4 + }, + "hpt_pulselaserburst_gimbal_small": { + "mass": 2 + }, + "hpt_pulselaserburst_turret_large": { + "mass": 8 + }, + "hpt_pulselaserburst_turret_medium": { + "mass": 4 + }, + "hpt_pulselaserburst_turret_small": { + "mass": 2 + }, + "hpt_railgun_fixed_medium": { + "mass": 4 + }, + "hpt_railgun_fixed_medium_burst": { + "mass": 4 + }, + "hpt_railgun_fixed_small": { + "mass": 2 + }, + "hpt_shieldbooster_size0_class1": { + "mass": 0.5 + }, + "hpt_shieldbooster_size0_class2": { + "mass": 1 + }, + "hpt_shieldbooster_size0_class3": { + "mass": 2 + }, + "hpt_shieldbooster_size0_class4": { + "mass": 3 + }, + "hpt_shieldbooster_size0_class5": { + "mass": 3.5 + }, + "hpt_slugshot_fixed_large": { + "mass": 8 + }, + "hpt_slugshot_fixed_large_range": { + "mass": 8 + }, + "hpt_slugshot_fixed_medium": { + "mass": 4 + }, + "hpt_slugshot_fixed_small": { + "mass": 2 + }, + "hpt_slugshot_gimbal_large": { + "mass": 8 + }, + "hpt_slugshot_gimbal_medium": { + "mass": 4 + }, + "hpt_slugshot_gimbal_small": { + "mass": 2 + }, + "hpt_slugshot_turret_large": { + "mass": 8 + }, + "hpt_slugshot_turret_medium": { + "mass": 4 + }, + "hpt_slugshot_turret_small": { + "mass": 2 + }, + "hpt_xenoscanner_basic_tiny": { + "mass": 1.3 + }, + "hpt_xenoscannermk2_basic_tiny": { + "mass": 1.3 + }, + "independant_trader_armour_grade1": { + "mass": 0 + }, + "independant_trader_armour_grade2": { + "mass": 12 + }, + "independant_trader_armour_grade3": { + "mass": 23 + }, + "independant_trader_armour_mirrored": { + "mass": 23 + }, + "independant_trader_armour_reactive": { + "mass": 23 + }, + "int_buggybay_size2_class1": { + "mass": 12 + }, + "int_buggybay_size2_class2": { + "mass": 6 + }, + "int_buggybay_size4_class1": { + "mass": 20 + }, + "int_buggybay_size4_class2": { + "mass": 10 + }, + "int_buggybay_size6_class1": { + "mass": 34 + }, + "int_buggybay_size6_class2": { + "mass": 17 + }, + "int_cargorack_size1_class1": { + "mass": 0 + }, + "int_cargorack_size2_class1": { + "mass": 0 + }, + "int_cargorack_size3_class1": { + "mass": 0 + }, + "int_cargorack_size4_class1": { + "mass": 0 + }, + "int_cargorack_size5_class1": { + "mass": 0 + }, + "int_cargorack_size6_class1": { + "mass": 0 + }, + "int_cargorack_size7_class1": { + "mass": 0 + }, + "int_cargorack_size8_class1": { + "mass": 0 + }, + "int_corrosionproofcargorack_size1_class1": { + "mass": 0 + }, + "int_corrosionproofcargorack_size1_class2": { + "mass": 0 + }, + "int_corrosionproofcargorack_size4_class1": { + "mass": 0 + }, + "int_detailedsurfacescanner_tiny": { + "mass": 0 + }, + "int_dockingcomputer_advanced": { + "mass": 0 + }, + "int_dockingcomputer_standard": { + "mass": 0 + }, + "int_dronecontrol_collection_size1_class1": { + "mass": 0.5 + }, + "int_dronecontrol_collection_size1_class2": { + "mass": 0.5 + }, + "int_dronecontrol_collection_size1_class3": { + "mass": 1.3 + }, + "int_dronecontrol_collection_size1_class4": { + "mass": 2 + }, + "int_dronecontrol_collection_size1_class5": { + "mass": 2 + }, + "int_dronecontrol_collection_size3_class1": { + "mass": 2 + }, + "int_dronecontrol_collection_size3_class2": { + "mass": 2 + }, + "int_dronecontrol_collection_size3_class3": { + "mass": 5 + }, + "int_dronecontrol_collection_size3_class4": { + "mass": 8 + }, + "int_dronecontrol_collection_size3_class5": { + "mass": 8 + }, + "int_dronecontrol_collection_size5_class1": { + "mass": 8 + }, + "int_dronecontrol_collection_size5_class2": { + "mass": 8 + }, + "int_dronecontrol_collection_size5_class3": { + "mass": 20 + }, + "int_dronecontrol_collection_size5_class4": { + "mass": 32 + }, + "int_dronecontrol_collection_size5_class5": { + "mass": 32 + }, + "int_dronecontrol_collection_size7_class1": { + "mass": 32 + }, + "int_dronecontrol_collection_size7_class2": { + "mass": 32 + }, + "int_dronecontrol_collection_size7_class3": { + "mass": 80 + }, + "int_dronecontrol_collection_size7_class4": { + "mass": 128 + }, + "int_dronecontrol_collection_size7_class5": { + "mass": 128 + }, + "int_dronecontrol_decontamination_size1_class1": { + "mass": 1.3 + }, + "int_dronecontrol_decontamination_size3_class1": { + "mass": 2 + }, + "int_dronecontrol_decontamination_size5_class1": { + "mass": 20 + }, + "int_dronecontrol_decontamination_size7_class1": { + "mass": 128 + }, + "int_dronecontrol_fueltransfer_size1_class1": { + "mass": 1.3 + }, + "int_dronecontrol_fueltransfer_size1_class2": { + "mass": 0.5 + }, + "int_dronecontrol_fueltransfer_size1_class3": { + "mass": 1.3 + }, + "int_dronecontrol_fueltransfer_size1_class4": { + "mass": 2 + }, + "int_dronecontrol_fueltransfer_size1_class5": { + "mass": 1.3 + }, + "int_dronecontrol_fueltransfer_size3_class1": { + "mass": 5 + }, + "int_dronecontrol_fueltransfer_size3_class2": { + "mass": 2 + }, + "int_dronecontrol_fueltransfer_size3_class3": { + "mass": 5 + }, + "int_dronecontrol_fueltransfer_size3_class4": { + "mass": 8 + }, + "int_dronecontrol_fueltransfer_size3_class5": { + "mass": 5 + }, + "int_dronecontrol_fueltransfer_size5_class1": { + "mass": 20 + }, + "int_dronecontrol_fueltransfer_size5_class2": { + "mass": 8 + }, + "int_dronecontrol_fueltransfer_size5_class3": { + "mass": 20 + }, + "int_dronecontrol_fueltransfer_size5_class4": { + "mass": 32 + }, + "int_dronecontrol_fueltransfer_size5_class5": { + "mass": 20 + }, + "int_dronecontrol_fueltransfer_size7_class1": { + "mass": 80 + }, + "int_dronecontrol_fueltransfer_size7_class2": { + "mass": 32 + }, + "int_dronecontrol_fueltransfer_size7_class3": { + "mass": 80 + }, + "int_dronecontrol_fueltransfer_size7_class4": { + "mass": 128 + }, + "int_dronecontrol_fueltransfer_size7_class5": { + "mass": 80 + }, + "int_dronecontrol_prospector_size1_class1": { + "mass": 1.3 + }, + "int_dronecontrol_prospector_size1_class2": { + "mass": 0.5 + }, + "int_dronecontrol_prospector_size1_class3": { + "mass": 1.3 + }, + "int_dronecontrol_prospector_size1_class4": { + "mass": 2 + }, + "int_dronecontrol_prospector_size1_class5": { + "mass": 1.3 + }, + "int_dronecontrol_prospector_size3_class1": { + "mass": 5 + }, + "int_dronecontrol_prospector_size3_class2": { + "mass": 2 + }, + "int_dronecontrol_prospector_size3_class3": { + "mass": 5 + }, + "int_dronecontrol_prospector_size3_class4": { + "mass": 8 + }, + "int_dronecontrol_prospector_size3_class5": { + "mass": 5 + }, + "int_dronecontrol_prospector_size5_class1": { + "mass": 20 + }, + "int_dronecontrol_prospector_size5_class2": { + "mass": 8 + }, + "int_dronecontrol_prospector_size5_class3": { + "mass": 20 + }, + "int_dronecontrol_prospector_size5_class4": { + "mass": 32 + }, + "int_dronecontrol_prospector_size5_class5": { + "mass": 20 + }, + "int_dronecontrol_prospector_size7_class1": { + "mass": 80 + }, + "int_dronecontrol_prospector_size7_class2": { + "mass": 32 + }, + "int_dronecontrol_prospector_size7_class3": { + "mass": 80 + }, + "int_dronecontrol_prospector_size7_class4": { + "mass": 128 + }, + "int_dronecontrol_prospector_size7_class5": { + "mass": 80 + }, + "int_dronecontrol_recon_size1_class1": { + "mass": 1.3 + }, + "int_dronecontrol_recon_size3_class1": { + "mass": 2 + }, + "int_dronecontrol_recon_size5_class1": { + "mass": 20 + }, + "int_dronecontrol_recon_size7_class1": { + "mass": 128 + }, + "int_dronecontrol_repair_size1_class1": { + "mass": 1.3 + }, + "int_dronecontrol_repair_size1_class2": { + "mass": 0.5 + }, + "int_dronecontrol_repair_size1_class3": { + "mass": 1.3 + }, + "int_dronecontrol_repair_size1_class4": { + "mass": 2 + }, + "int_dronecontrol_repair_size1_class5": { + "mass": 1.3 + }, + "int_dronecontrol_repair_size3_class1": { + "mass": 5 + }, + "int_dronecontrol_repair_size3_class2": { + "mass": 2 + }, + "int_dronecontrol_repair_size3_class3": { + "mass": 5 + }, + "int_dronecontrol_repair_size3_class4": { + "mass": 8 + }, + "int_dronecontrol_repair_size3_class5": { + "mass": 5 + }, + "int_dronecontrol_repair_size5_class1": { + "mass": 20 + }, + "int_dronecontrol_repair_size5_class2": { + "mass": 8 + }, + "int_dronecontrol_repair_size5_class3": { + "mass": 20 + }, + "int_dronecontrol_repair_size5_class4": { + "mass": 32 + }, + "int_dronecontrol_repair_size5_class5": { + "mass": 20 + }, + "int_dronecontrol_repair_size7_class1": { + "mass": 80 + }, + "int_dronecontrol_repair_size7_class2": { + "mass": 32 + }, + "int_dronecontrol_repair_size7_class3": { + "mass": 80 + }, + "int_dronecontrol_repair_size7_class4": { + "mass": 128 + }, + "int_dronecontrol_repair_size7_class5": { + "mass": 80 + }, + "int_dronecontrol_resourcesiphon_size1_class1": { + "mass": 1.3 + }, + "int_dronecontrol_resourcesiphon_size1_class2": { + "mass": 0.5 + }, + "int_dronecontrol_resourcesiphon_size1_class3": { + "mass": 1.3 + }, + "int_dronecontrol_resourcesiphon_size1_class4": { + "mass": 2 + }, + "int_dronecontrol_resourcesiphon_size1_class5": { + "mass": 1.3 + }, + "int_dronecontrol_resourcesiphon_size3_class1": { + "mass": 5 + }, + "int_dronecontrol_resourcesiphon_size3_class2": { + "mass": 2 + }, + "int_dronecontrol_resourcesiphon_size3_class3": { + "mass": 5 + }, + "int_dronecontrol_resourcesiphon_size3_class4": { + "mass": 8 + }, + "int_dronecontrol_resourcesiphon_size3_class5": { + "mass": 5 + }, + "int_dronecontrol_resourcesiphon_size5_class1": { + "mass": 20 + }, + "int_dronecontrol_resourcesiphon_size5_class2": { + "mass": 8 + }, + "int_dronecontrol_resourcesiphon_size5_class3": { + "mass": 20 + }, + "int_dronecontrol_resourcesiphon_size5_class4": { + "mass": 32 + }, + "int_dronecontrol_resourcesiphon_size5_class5": { + "mass": 20 + }, + "int_dronecontrol_resourcesiphon_size7_class1": { + "mass": 80 + }, + "int_dronecontrol_resourcesiphon_size7_class2": { + "mass": 32 + }, + "int_dronecontrol_resourcesiphon_size7_class3": { + "mass": 80 + }, + "int_dronecontrol_resourcesiphon_size7_class4": { + "mass": 128 + }, + "int_dronecontrol_resourcesiphon_size7_class5": { + "mass": 80 + }, + "int_dronecontrol_unkvesselresearch": { + "mass": 1.3 + }, + "int_engine_size2_class1": { + "mass": 2.5 + }, + "int_engine_size2_class2": { + "mass": 1 + }, + "int_engine_size2_class3": { + "mass": 2.5 + }, + "int_engine_size2_class4": { + "mass": 4 + }, + "int_engine_size2_class5": { + "mass": 2.5 + }, + "int_engine_size2_class5_fast": { + "mass": 2.5 + }, + "int_engine_size3_class1": { + "mass": 5 + }, + "int_engine_size3_class2": { + "mass": 2 + }, + "int_engine_size3_class3": { + "mass": 5 + }, + "int_engine_size3_class4": { + "mass": 8 + }, + "int_engine_size3_class5": { + "mass": 5 + }, + "int_engine_size3_class5_fast": { + "mass": 5 + }, + "int_engine_size4_class1": { + "mass": 10 + }, + "int_engine_size4_class2": { + "mass": 4 + }, + "int_engine_size4_class3": { + "mass": 10 + }, + "int_engine_size4_class4": { + "mass": 16 + }, + "int_engine_size4_class5": { + "mass": 10 + }, + "int_engine_size5_class1": { + "mass": 20 + }, + "int_engine_size5_class2": { + "mass": 8 + }, + "int_engine_size5_class3": { + "mass": 20 + }, + "int_engine_size5_class4": { + "mass": 32 + }, + "int_engine_size5_class5": { + "mass": 20 + }, + "int_engine_size6_class1": { + "mass": 40 + }, + "int_engine_size6_class2": { + "mass": 16 + }, + "int_engine_size6_class3": { + "mass": 40 + }, + "int_engine_size6_class4": { + "mass": 64 + }, + "int_engine_size6_class5": { + "mass": 40 + }, + "int_engine_size7_class1": { + "mass": 80 + }, + "int_engine_size7_class2": { + "mass": 32 + }, + "int_engine_size7_class3": { + "mass": 80 + }, + "int_engine_size7_class4": { + "mass": 128 + }, + "int_engine_size7_class5": { + "mass": 80 + }, + "int_engine_size8_class1": { + "mass": 160 + }, + "int_engine_size8_class2": { + "mass": 64 + }, + "int_engine_size8_class3": { + "mass": 160 + }, + "int_engine_size8_class4": { + "mass": 256 + }, + "int_engine_size8_class5": { + "mass": 160 + }, + "int_fighterbay_size5_class1": { + "mass": 20 + }, + "int_fighterbay_size6_class1": { + "mass": 40 + }, + "int_fighterbay_size7_class1": { + "mass": 60 + }, + "int_fsdinterdictor_size1_class1": { + "mass": 1.3 + }, + "int_fsdinterdictor_size1_class2": { + "mass": 0.5 + }, + "int_fsdinterdictor_size1_class3": { + "mass": 1.3 + }, + "int_fsdinterdictor_size1_class4": { + "mass": 2 + }, + "int_fsdinterdictor_size1_class5": { + "mass": 1.3 + }, + "int_fsdinterdictor_size2_class1": { + "mass": 2.5 + }, + "int_fsdinterdictor_size2_class2": { + "mass": 1 + }, + "int_fsdinterdictor_size2_class3": { + "mass": 2.5 + }, + "int_fsdinterdictor_size2_class4": { + "mass": 4 + }, + "int_fsdinterdictor_size2_class5": { + "mass": 2.5 + }, + "int_fsdinterdictor_size3_class1": { + "mass": 5 + }, + "int_fsdinterdictor_size3_class2": { + "mass": 2 + }, + "int_fsdinterdictor_size3_class3": { + "mass": 5 + }, + "int_fsdinterdictor_size3_class4": { + "mass": 8 + }, + "int_fsdinterdictor_size3_class5": { + "mass": 5 + }, + "int_fsdinterdictor_size4_class1": { + "mass": 10 + }, + "int_fsdinterdictor_size4_class2": { + "mass": 4 + }, + "int_fsdinterdictor_size4_class3": { + "mass": 10 + }, + "int_fsdinterdictor_size4_class4": { + "mass": 16 + }, + "int_fsdinterdictor_size4_class5": { + "mass": 10 + }, + "int_fuelscoop_size1_class1": { + "mass": 0 + }, + "int_fuelscoop_size1_class2": { + "mass": 0 + }, + "int_fuelscoop_size1_class3": { + "mass": 0 + }, + "int_fuelscoop_size1_class4": { + "mass": 0 + }, + "int_fuelscoop_size1_class5": { + "mass": 0 + }, + "int_fuelscoop_size2_class1": { + "mass": 0 + }, + "int_fuelscoop_size2_class2": { + "mass": 0 + }, + "int_fuelscoop_size2_class3": { + "mass": 0 + }, + "int_fuelscoop_size2_class4": { + "mass": 0 + }, + "int_fuelscoop_size2_class5": { + "mass": 0 + }, + "int_fuelscoop_size3_class1": { + "mass": 0 + }, + "int_fuelscoop_size3_class2": { + "mass": 0 + }, + "int_fuelscoop_size3_class3": { + "mass": 0 + }, + "int_fuelscoop_size3_class4": { + "mass": 0 + }, + "int_fuelscoop_size3_class5": { + "mass": 0 + }, + "int_fuelscoop_size4_class1": { + "mass": 0 + }, + "int_fuelscoop_size4_class2": { + "mass": 0 + }, + "int_fuelscoop_size4_class3": { + "mass": 0 + }, + "int_fuelscoop_size4_class4": { + "mass": 0 + }, + "int_fuelscoop_size4_class5": { + "mass": 0 + }, + "int_fuelscoop_size5_class1": { + "mass": 0 + }, + "int_fuelscoop_size5_class2": { + "mass": 0 + }, + "int_fuelscoop_size5_class3": { + "mass": 0 + }, + "int_fuelscoop_size5_class4": { + "mass": 0 + }, + "int_fuelscoop_size5_class5": { + "mass": 0 + }, + "int_fuelscoop_size6_class1": { + "mass": 0 + }, + "int_fuelscoop_size6_class2": { + "mass": 0 + }, + "int_fuelscoop_size6_class3": { + "mass": 0 + }, + "int_fuelscoop_size6_class4": { + "mass": 0 + }, + "int_fuelscoop_size6_class5": { + "mass": 0 + }, + "int_fuelscoop_size7_class1": { + "mass": 0 + }, + "int_fuelscoop_size7_class2": { + "mass": 0 + }, + "int_fuelscoop_size7_class3": { + "mass": 0 + }, + "int_fuelscoop_size7_class4": { + "mass": 0 + }, + "int_fuelscoop_size7_class5": { + "mass": 0 + }, + "int_fuelscoop_size8_class1": { + "mass": 0 + }, + "int_fuelscoop_size8_class2": { + "mass": 0 + }, + "int_fuelscoop_size8_class3": { + "mass": 0 + }, + "int_fuelscoop_size8_class4": { + "mass": 0 + }, + "int_fuelscoop_size8_class5": { + "mass": 0 + }, + "int_fueltank_size1_class3": { + "mass": 0 + }, + "int_fueltank_size2_class3": { + "mass": 0 + }, + "int_fueltank_size3_class3": { + "mass": 0 + }, + "int_fueltank_size4_class3": { + "mass": 0 + }, + "int_fueltank_size5_class3": { + "mass": 0 + }, + "int_fueltank_size6_class3": { + "mass": 0 + }, + "int_fueltank_size7_class3": { + "mass": 0 + }, + "int_fueltank_size8_class3": { + "mass": 0 + }, + "int_guardianfsdbooster_size1": { + "mass": 1.3, + "jumpboost": 4 + }, + "int_guardianfsdbooster_size2": { + "mass": 1.3, + "jumpboost": 6 + }, + "int_guardianfsdbooster_size3": { + "mass": 1.3, + "jumpboost": 7.75 + }, + "int_guardianfsdbooster_size4": { + "mass": 1.3, + "jumpboost": 9.25 + }, + "int_guardianfsdbooster_size5": { + "mass": 1.3, + "jumpboost": 10.5 + }, + "int_guardianhullreinforcement_size1_class1": { + "mass": 2 + }, + "int_guardianhullreinforcement_size1_class2": { + "mass": 1 + }, + "int_guardianhullreinforcement_size2_class1": { + "mass": 4 + }, + "int_guardianhullreinforcement_size2_class2": { + "mass": 2 + }, + "int_guardianhullreinforcement_size3_class1": { + "mass": 8 + }, + "int_guardianhullreinforcement_size3_class2": { + "mass": 4 + }, + "int_guardianhullreinforcement_size4_class1": { + "mass": 16 + }, + "int_guardianhullreinforcement_size4_class2": { + "mass": 8 + }, + "int_guardianhullreinforcement_size5_class1": { + "mass": 32 + }, + "int_guardianhullreinforcement_size5_class2": { + "mass": 16 + }, + "int_guardianmodulereinforcement_size1_class1": { + "mass": 2 + }, + "int_guardianmodulereinforcement_size1_class2": { + "mass": 1 + }, + "int_guardianmodulereinforcement_size2_class1": { + "mass": 4 + }, + "int_guardianmodulereinforcement_size2_class2": { + "mass": 2 + }, + "int_guardianmodulereinforcement_size3_class1": { + "mass": 8 + }, + "int_guardianmodulereinforcement_size3_class2": { + "mass": 4 + }, + "int_guardianmodulereinforcement_size4_class1": { + "mass": 16 + }, + "int_guardianmodulereinforcement_size4_class2": { + "mass": 8 + }, + "int_guardianmodulereinforcement_size5_class1": { + "mass": 32 + }, + "int_guardianmodulereinforcement_size5_class2": { + "mass": 16 + }, + "int_guardianpowerdistributor_size1": { + "mass": 1.4 + }, + "int_guardianpowerdistributor_size2": { + "mass": 2.6 + }, + "int_guardianpowerdistributor_size3": { + "mass": 5.25 + }, + "int_guardianpowerdistributor_size4": { + "mass": 10.5 + }, + "int_guardianpowerdistributor_size5": { + "mass": 21 + }, + "int_guardianpowerdistributor_size6": { + "mass": 42 + }, + "int_guardianpowerdistributor_size7": { + "mass": 84 + }, + "int_guardianpowerdistributor_size8": { + "mass": 168 + }, + "int_guardianpowerplant_size2": { + "mass": 1.5 + }, + "int_guardianpowerplant_size3": { + "mass": 2.9 + }, + "int_guardianpowerplant_size4": { + "mass": 5.9 + }, + "int_guardianpowerplant_size5": { + "mass": 11.7 + }, + "int_guardianpowerplant_size6": { + "mass": 23.4 + }, + "int_guardianpowerplant_size7": { + "mass": 46.8 + }, + "int_guardianpowerplant_size8": { + "mass": 93.6 + }, + "int_guardianshieldreinforcement_size1_class1": { + "mass": 2 + }, + "int_guardianshieldreinforcement_size1_class2": { + "mass": 1 + }, + "int_guardianshieldreinforcement_size2_class1": { + "mass": 4 + }, + "int_guardianshieldreinforcement_size2_class2": { + "mass": 2 + }, + "int_guardianshieldreinforcement_size3_class1": { + "mass": 8 + }, + "int_guardianshieldreinforcement_size3_class2": { + "mass": 4 + }, + "int_guardianshieldreinforcement_size4_class1": { + "mass": 16 + }, + "int_guardianshieldreinforcement_size4_class2": { + "mass": 8 + }, + "int_guardianshieldreinforcement_size5_class1": { + "mass": 32 + }, + "int_guardianshieldreinforcement_size5_class2": { + "mass": 16 + }, + "int_hullreinforcement_size1_class1": { + "mass": 2 + }, + "int_hullreinforcement_size1_class2": { + "mass": 1 + }, + "int_hullreinforcement_size2_class1": { + "mass": 4 + }, + "int_hullreinforcement_size2_class2": { + "mass": 2 + }, + "int_hullreinforcement_size3_class1": { + "mass": 8 + }, + "int_hullreinforcement_size3_class2": { + "mass": 4 + }, + "int_hullreinforcement_size4_class1": { + "mass": 16 + }, + "int_hullreinforcement_size4_class2": { + "mass": 8 + }, + "int_hullreinforcement_size5_class1": { + "mass": 32 + }, + "int_hullreinforcement_size5_class2": { + "mass": 16 + }, + "int_hyperdrive_size2_class1": { + "mass": 2.5, + "optmass": 48, + "maxfuel": 0.6, + "fuelmul": 0.011, + "fuelpower": 2 + }, + "int_hyperdrive_size2_class2": { + "mass": 1, + "optmass": 54, + "maxfuel": 0.6, + "fuelmul": 0.01, + "fuelpower": 2 + }, + "int_hyperdrive_size2_class3": { + "mass": 2.5, + "optmass": 60, + "maxfuel": 0.6, + "fuelmul": 0.008, + "fuelpower": 2 + }, + "int_hyperdrive_size2_class4": { + "mass": 4, + "optmass": 75, + "maxfuel": 0.8, + "fuelmul": 0.01, + "fuelpower": 2 + }, + "int_hyperdrive_size2_class5": { + "mass": 2.5, + "optmass": 90, + "maxfuel": 0.9, + "fuelmul": 0.012, + "fuelpower": 2 + }, + "int_hyperdrive_size3_class1": { + "mass": 5, + "optmass": 80, + "maxfuel": 1.2, + "fuelmul": 0.011, + "fuelpower": 2.15 + }, + "int_hyperdrive_size3_class2": { + "mass": 2, + "optmass": 90, + "maxfuel": 1.2, + "fuelmul": 0.01, + "fuelpower": 2.15 + }, + "int_hyperdrive_size3_class3": { + "mass": 5, + "optmass": 100, + "maxfuel": 1.2, + "fuelmul": 0.008, + "fuelpower": 2.15 + }, + "int_hyperdrive_size3_class4": { + "mass": 8, + "optmass": 125, + "maxfuel": 1.5, + "fuelmul": 0.01, + "fuelpower": 2.15 + }, + "int_hyperdrive_size3_class5": { + "mass": 5, + "optmass": 150, + "maxfuel": 1.8, + "fuelmul": 0.012, + "fuelpower": 2.15 + }, + "int_hyperdrive_size4_class1": { + "mass": 10, + "optmass": 280, + "maxfuel": 2, + "fuelmul": 0.011, + "fuelpower": 2.3 + }, + "int_hyperdrive_size4_class2": { + "mass": 4, + "optmass": 315, + "maxfuel": 2, + "fuelmul": 0.01, + "fuelpower": 2.3 + }, + "int_hyperdrive_size4_class3": { + "mass": 10, + "optmass": 350, + "maxfuel": 2, + "fuelmul": 0.008, + "fuelpower": 2.3 + }, + "int_hyperdrive_size4_class4": { + "mass": 16, + "optmass": 437.5, + "maxfuel": 2.5, + "fuelmul": 0.01, + "fuelpower": 2.3 + }, + "int_hyperdrive_size4_class5": { + "mass": 10, + "optmass": 525, + "maxfuel": 3, + "fuelmul": 0.012, + "fuelpower": 2.3 + }, + "int_hyperdrive_size5_class1": { + "mass": 20, + "optmass": 560, + "maxfuel": 3.3, + "fuelmul": 0.011, + "fuelpower": 2.45 + }, + "int_hyperdrive_size5_class2": { + "mass": 8, + "optmass": 630, + "maxfuel": 3.3, + "fuelmul": 0.01, + "fuelpower": 2.45 + }, + "int_hyperdrive_size5_class3": { + "mass": 20, + "optmass": 700, + "maxfuel": 3.3, + "fuelmul": 0.008, + "fuelpower": 2.45 + }, + "int_hyperdrive_size5_class4": { + "mass": 32, + "optmass": 875, + "maxfuel": 4.1, + "fuelmul": 0.01, + "fuelpower": 2.45 + }, + "int_hyperdrive_size5_class5": { + "mass": 20, + "optmass": 1050, + "maxfuel": 5, + "fuelmul": 0.012, + "fuelpower": 2.45 + }, + "int_hyperdrive_size6_class1": { + "mass": 40, + "optmass": 960, + "maxfuel": 5.3, + "fuelmul": 0.011, + "fuelpower": 2.6 + }, + "int_hyperdrive_size6_class2": { + "mass": 16, + "optmass": 1080, + "maxfuel": 5.3, + "fuelmul": 0.01, + "fuelpower": 2.6 + }, + "int_hyperdrive_size6_class3": { + "mass": 40, + "optmass": 1200, + "maxfuel": 5.3, + "fuelmul": 0.008, + "fuelpower": 2.6 + }, + "int_hyperdrive_size6_class4": { + "mass": 64, + "optmass": 1500, + "maxfuel": 6.6, + "fuelmul": 0.01, + "fuelpower": 2.6 + }, + "int_hyperdrive_size6_class5": { + "mass": 40, + "optmass": 1800, + "maxfuel": 8, + "fuelmul": 0.012, + "fuelpower": 2.6 + }, + "int_hyperdrive_size7_class1": { + "mass": 80, + "optmass": 1440, + "maxfuel": 8.5, + "fuelmul": 0.011, + "fuelpower": 2.75 + }, + "int_hyperdrive_size7_class2": { + "mass": 32, + "optmass": 1620, + "maxfuel": 8.5, + "fuelmul": 0.01, + "fuelpower": 2.75 + }, + "int_hyperdrive_size7_class3": { + "mass": 80, + "optmass": 1800, + "maxfuel": 8.5, + "fuelmul": 0.008, + "fuelpower": 2.75 + }, + "int_hyperdrive_size7_class4": { + "mass": 128, + "optmass": 2250, + "maxfuel": 10.6, + "fuelmul": 0.01, + "fuelpower": 2.75 + }, + "int_hyperdrive_size7_class5": { + "mass": 80, + "optmass": 2700, + "maxfuel": 12.8, + "fuelmul": 0.012, + "fuelpower": 2.75 + }, + "int_hyperdrive_size8_class1": { + "mass": 160, + "optmass": 0, + "maxfuel": 0, + "fuelmul": 0.011, + "fuelpower": 2.9 + }, + "int_hyperdrive_size8_class2": { + "mass": 64, + "optmass": 0, + "maxfuel": 0, + "fuelmul": 0.01, + "fuelpower": 2.9 + }, + "int_hyperdrive_size8_class3": { + "mass": 160, + "optmass": 0, + "maxfuel": 0, + "fuelmul": 0.008, + "fuelpower": 2.9 + }, + "int_hyperdrive_size8_class4": { + "mass": 256, + "optmass": 0, + "maxfuel": 0, + "fuelmul": 0.01, + "fuelpower": 2.9 + }, + "int_hyperdrive_size8_class5": { + "mass": 160, + "optmass": 0, + "maxfuel": 0, + "fuelmul": 0.012, + "fuelpower": 2.9 + }, + "int_lifesupport_size1_class1": { + "mass": 1.3 + }, + "int_lifesupport_size1_class2": { + "mass": 0.5 + }, + "int_lifesupport_size1_class3": { + "mass": 1.3 + }, + "int_lifesupport_size1_class4": { + "mass": 2 + }, + "int_lifesupport_size1_class5": { + "mass": 1.3 + }, + "int_lifesupport_size2_class1": { + "mass": 2.5 + }, + "int_lifesupport_size2_class2": { + "mass": 1 + }, + "int_lifesupport_size2_class3": { + "mass": 2.5 + }, + "int_lifesupport_size2_class4": { + "mass": 4 + }, + "int_lifesupport_size2_class5": { + "mass": 2.5 + }, + "int_lifesupport_size3_class1": { + "mass": 5 + }, + "int_lifesupport_size3_class2": { + "mass": 2 + }, + "int_lifesupport_size3_class3": { + "mass": 5 + }, + "int_lifesupport_size3_class4": { + "mass": 8 + }, + "int_lifesupport_size3_class5": { + "mass": 5 + }, + "int_lifesupport_size4_class1": { + "mass": 10 + }, + "int_lifesupport_size4_class2": { + "mass": 4 + }, + "int_lifesupport_size4_class3": { + "mass": 10 + }, + "int_lifesupport_size4_class4": { + "mass": 16 + }, + "int_lifesupport_size4_class5": { + "mass": 10 + }, + "int_lifesupport_size5_class1": { + "mass": 20 + }, + "int_lifesupport_size5_class2": { + "mass": 8 + }, + "int_lifesupport_size5_class3": { + "mass": 20 + }, + "int_lifesupport_size5_class4": { + "mass": 32 + }, + "int_lifesupport_size5_class5": { + "mass": 20 + }, + "int_lifesupport_size6_class1": { + "mass": 40 + }, + "int_lifesupport_size6_class2": { + "mass": 16 + }, + "int_lifesupport_size6_class3": { + "mass": 40 + }, + "int_lifesupport_size6_class4": { + "mass": 64 + }, + "int_lifesupport_size6_class5": { + "mass": 40 + }, + "int_lifesupport_size7_class1": { + "mass": 80 + }, + "int_lifesupport_size7_class2": { + "mass": 32 + }, + "int_lifesupport_size7_class3": { + "mass": 80 + }, + "int_lifesupport_size7_class4": { + "mass": 128 + }, + "int_lifesupport_size7_class5": { + "mass": 80 + }, + "int_lifesupport_size8_class1": { + "mass": 160 + }, + "int_lifesupport_size8_class2": { + "mass": 64 + }, + "int_lifesupport_size8_class3": { + "mass": 160 + }, + "int_lifesupport_size8_class4": { + "mass": 256 + }, + "int_lifesupport_size8_class5": { + "mass": 160 + }, + "int_metaalloyhullreinforcement_size1_class1": { + "mass": 2 + }, + "int_metaalloyhullreinforcement_size1_class2": { + "mass": 2 + }, + "int_metaalloyhullreinforcement_size2_class1": { + "mass": 4 + }, + "int_metaalloyhullreinforcement_size2_class2": { + "mass": 2 + }, + "int_metaalloyhullreinforcement_size3_class1": { + "mass": 8 + }, + "int_metaalloyhullreinforcement_size3_class2": { + "mass": 4 + }, + "int_metaalloyhullreinforcement_size4_class1": { + "mass": 16 + }, + "int_metaalloyhullreinforcement_size4_class2": { + "mass": 8 + }, + "int_metaalloyhullreinforcement_size5_class1": { + "mass": 32 + }, + "int_metaalloyhullreinforcement_size5_class2": { + "mass": 16 + }, + "int_modulereinforcement_size1_class1": { + "mass": 2 + }, + "int_modulereinforcement_size1_class2": { + "mass": 1 + }, + "int_modulereinforcement_size2_class1": { + "mass": 4 + }, + "int_modulereinforcement_size2_class2": { + "mass": 2 + }, + "int_modulereinforcement_size3_class1": { + "mass": 8 + }, + "int_modulereinforcement_size3_class2": { + "mass": 4 + }, + "int_modulereinforcement_size4_class1": { + "mass": 16 + }, + "int_modulereinforcement_size4_class2": { + "mass": 8 + }, + "int_modulereinforcement_size5_class1": { + "mass": 32 + }, + "int_modulereinforcement_size5_class2": { + "mass": 16 + }, + "int_multidronecontrol_mining_size3_class1": { + "mass": 12 + }, + "int_multidronecontrol_mining_size3_class3": { + "mass": 10 + }, + "int_multidronecontrol_operations_size3_class3": { + "mass": 10 + }, + "int_multidronecontrol_operations_size3_class4": { + "mass": 15 + }, + "int_multidronecontrol_rescue_size3_class2": { + "mass": 8 + }, + "int_multidronecontrol_rescue_size3_class3": { + "mass": 10 + }, + "int_multidronecontrol_universal_size7_class3": { + "mass": 125 + }, + "int_multidronecontrol_universal_size7_class5": { + "mass": 140 + }, + "int_multidronecontrol_xeno_size3_class3": { + "mass": 10 + }, + "int_multidronecontrol_xeno_size3_class4": { + "mass": 15 + }, + "int_passengercabin_size2_class1": { + "mass": 2.5 + }, + "int_passengercabin_size3_class1": { + "mass": 5 + }, + "int_passengercabin_size3_class2": { + "mass": 5 + }, + "int_passengercabin_size4_class1": { + "mass": 10 + }, + "int_passengercabin_size4_class2": { + "mass": 10 + }, + "int_passengercabin_size4_class3": { + "mass": 10 + }, + "int_passengercabin_size5_class1": { + "mass": 20 + }, + "int_passengercabin_size5_class2": { + "mass": 20 + }, + "int_passengercabin_size5_class3": { + "mass": 20 + }, + "int_passengercabin_size5_class4": { + "mass": 20 + }, + "int_passengercabin_size6_class1": { + "mass": 40 + }, + "int_passengercabin_size6_class2": { + "mass": 40 + }, + "int_passengercabin_size6_class3": { + "mass": 40 + }, + "int_passengercabin_size6_class4": { + "mass": 40 + }, + "int_planetapproachsuite": { + "mass": 0 + }, + "int_powerdistributor_size1_class1": { + "mass": 1.3 + }, + "int_powerdistributor_size1_class2": { + "mass": 0.5 + }, + "int_powerdistributor_size1_class3": { + "mass": 1.3 + }, + "int_powerdistributor_size1_class4": { + "mass": 2 + }, + "int_powerdistributor_size1_class5": { + "mass": 1.3 + }, + "int_powerdistributor_size2_class1": { + "mass": 2.5 + }, + "int_powerdistributor_size2_class2": { + "mass": 1 + }, + "int_powerdistributor_size2_class3": { + "mass": 2.5 + }, + "int_powerdistributor_size2_class4": { + "mass": 4 + }, + "int_powerdistributor_size2_class5": { + "mass": 2.5 + }, + "int_powerdistributor_size3_class1": { + "mass": 5 + }, + "int_powerdistributor_size3_class2": { + "mass": 2 + }, + "int_powerdistributor_size3_class3": { + "mass": 5 + }, + "int_powerdistributor_size3_class4": { + "mass": 8 + }, + "int_powerdistributor_size3_class5": { + "mass": 5 + }, + "int_powerdistributor_size4_class1": { + "mass": 10 + }, + "int_powerdistributor_size4_class2": { + "mass": 4 + }, + "int_powerdistributor_size4_class3": { + "mass": 10 + }, + "int_powerdistributor_size4_class4": { + "mass": 16 + }, + "int_powerdistributor_size4_class5": { + "mass": 10 + }, + "int_powerdistributor_size5_class1": { + "mass": 20 + }, + "int_powerdistributor_size5_class2": { + "mass": 8 + }, + "int_powerdistributor_size5_class3": { + "mass": 20 + }, + "int_powerdistributor_size5_class4": { + "mass": 32 + }, + "int_powerdistributor_size5_class5": { + "mass": 20 + }, + "int_powerdistributor_size6_class1": { + "mass": 40 + }, + "int_powerdistributor_size6_class2": { + "mass": 16 + }, + "int_powerdistributor_size6_class3": { + "mass": 40 + }, + "int_powerdistributor_size6_class4": { + "mass": 64 + }, + "int_powerdistributor_size6_class5": { + "mass": 40 + }, + "int_powerdistributor_size7_class1": { + "mass": 80 + }, + "int_powerdistributor_size7_class2": { + "mass": 32 + }, + "int_powerdistributor_size7_class3": { + "mass": 80 + }, + "int_powerdistributor_size7_class4": { + "mass": 128 + }, + "int_powerdistributor_size7_class5": { + "mass": 80 + }, + "int_powerdistributor_size8_class1": { + "mass": 160 + }, + "int_powerdistributor_size8_class2": { + "mass": 64 + }, + "int_powerdistributor_size8_class3": { + "mass": 160 + }, + "int_powerdistributor_size8_class4": { + "mass": 256 + }, + "int_powerdistributor_size8_class5": { + "mass": 160 + }, + "int_powerplant_size2_class1": { + "mass": 2.5 + }, + "int_powerplant_size2_class2": { + "mass": 1 + }, + "int_powerplant_size2_class3": { + "mass": 1.3 + }, + "int_powerplant_size2_class4": { + "mass": 2 + }, + "int_powerplant_size2_class5": { + "mass": 1.3 + }, + "int_powerplant_size3_class1": { + "mass": 5 + }, + "int_powerplant_size3_class2": { + "mass": 2 + }, + "int_powerplant_size3_class3": { + "mass": 2.5 + }, + "int_powerplant_size3_class4": { + "mass": 4 + }, + "int_powerplant_size3_class5": { + "mass": 2.5 + }, + "int_powerplant_size4_class1": { + "mass": 10 + }, + "int_powerplant_size4_class2": { + "mass": 4 + }, + "int_powerplant_size4_class3": { + "mass": 5 + }, + "int_powerplant_size4_class4": { + "mass": 8 + }, + "int_powerplant_size4_class5": { + "mass": 5 + }, + "int_powerplant_size5_class1": { + "mass": 20 + }, + "int_powerplant_size5_class2": { + "mass": 8 + }, + "int_powerplant_size5_class3": { + "mass": 10 + }, + "int_powerplant_size5_class4": { + "mass": 16 + }, + "int_powerplant_size5_class5": { + "mass": 10 + }, + "int_powerplant_size6_class1": { + "mass": 40 + }, + "int_powerplant_size6_class2": { + "mass": 16 + }, + "int_powerplant_size6_class3": { + "mass": 20 + }, + "int_powerplant_size6_class4": { + "mass": 32 + }, + "int_powerplant_size6_class5": { + "mass": 20 + }, + "int_powerplant_size7_class1": { + "mass": 80 + }, + "int_powerplant_size7_class2": { + "mass": 32 + }, + "int_powerplant_size7_class3": { + "mass": 40 + }, + "int_powerplant_size7_class4": { + "mass": 64 + }, + "int_powerplant_size7_class5": { + "mass": 40 + }, + "int_powerplant_size8_class1": { + "mass": 160 + }, + "int_powerplant_size8_class2": { + "mass": 64 + }, + "int_powerplant_size8_class3": { + "mass": 80 + }, + "int_powerplant_size8_class4": { + "mass": 128 + }, + "int_powerplant_size8_class5": { + "mass": 80 + }, + "int_refinery_size1_class1": { + "mass": 0 + }, + "int_refinery_size1_class2": { + "mass": 0 + }, + "int_refinery_size1_class3": { + "mass": 0 + }, + "int_refinery_size1_class4": { + "mass": 0 + }, + "int_refinery_size1_class5": { + "mass": 0 + }, + "int_refinery_size2_class1": { + "mass": 0 + }, + "int_refinery_size2_class2": { + "mass": 0 + }, + "int_refinery_size2_class3": { + "mass": 0 + }, + "int_refinery_size2_class4": { + "mass": 0 + }, + "int_refinery_size2_class5": { + "mass": 0 + }, + "int_refinery_size3_class1": { + "mass": 0 + }, + "int_refinery_size3_class2": { + "mass": 0 + }, + "int_refinery_size3_class3": { + "mass": 0 + }, + "int_refinery_size3_class4": { + "mass": 0 + }, + "int_refinery_size3_class5": { + "mass": 0 + }, + "int_refinery_size4_class1": { + "mass": 0 + }, + "int_refinery_size4_class2": { + "mass": 0 + }, + "int_refinery_size4_class3": { + "mass": 0 + }, + "int_refinery_size4_class4": { + "mass": 0 + }, + "int_refinery_size4_class5": { + "mass": 0 + }, + "int_repairer_size1_class1": { + "mass": 0 + }, + "int_repairer_size1_class2": { + "mass": 0 + }, + "int_repairer_size1_class3": { + "mass": 0 + }, + "int_repairer_size1_class4": { + "mass": 0 + }, + "int_repairer_size1_class5": { + "mass": 0 + }, + "int_repairer_size2_class1": { + "mass": 0 + }, + "int_repairer_size2_class2": { + "mass": 0 + }, + "int_repairer_size2_class3": { + "mass": 0 + }, + "int_repairer_size2_class4": { + "mass": 0 + }, + "int_repairer_size2_class5": { + "mass": 0 + }, + "int_repairer_size3_class1": { + "mass": 0 + }, + "int_repairer_size3_class2": { + "mass": 0 + }, + "int_repairer_size3_class3": { + "mass": 0 + }, + "int_repairer_size3_class4": { + "mass": 0 + }, + "int_repairer_size3_class5": { + "mass": 0 + }, + "int_repairer_size4_class1": { + "mass": 0 + }, + "int_repairer_size4_class2": { + "mass": 0 + }, + "int_repairer_size4_class3": { + "mass": 0 + }, + "int_repairer_size4_class4": { + "mass": 0 + }, + "int_repairer_size4_class5": { + "mass": 0 + }, + "int_repairer_size5_class1": { + "mass": 0 + }, + "int_repairer_size5_class2": { + "mass": 0 + }, + "int_repairer_size5_class3": { + "mass": 0 + }, + "int_repairer_size5_class4": { + "mass": 0 + }, + "int_repairer_size5_class5": { + "mass": 0 + }, + "int_repairer_size6_class1": { + "mass": 0 + }, + "int_repairer_size6_class2": { + "mass": 0 + }, + "int_repairer_size6_class3": { + "mass": 0 + }, + "int_repairer_size6_class4": { + "mass": 0 + }, + "int_repairer_size6_class5": { + "mass": 0 + }, + "int_repairer_size7_class1": { + "mass": 0 + }, + "int_repairer_size7_class2": { + "mass": 0 + }, + "int_repairer_size7_class3": { + "mass": 0 + }, + "int_repairer_size7_class4": { + "mass": 0 + }, + "int_repairer_size7_class5": { + "mass": 0 + }, + "int_repairer_size8_class1": { + "mass": 0 + }, + "int_repairer_size8_class2": { + "mass": 0 + }, + "int_repairer_size8_class3": { + "mass": 0 + }, + "int_repairer_size8_class4": { + "mass": 0 + }, + "int_repairer_size8_class5": { + "mass": 0 + }, + "int_sensors_size1_class1": { + "mass": 1.3 + }, + "int_sensors_size1_class2": { + "mass": 0.5 + }, + "int_sensors_size1_class3": { + "mass": 1.3 + }, + "int_sensors_size1_class4": { + "mass": 2 + }, + "int_sensors_size1_class5": { + "mass": 1.3 + }, + "int_sensors_size2_class1": { + "mass": 2.5 + }, + "int_sensors_size2_class2": { + "mass": 1 + }, + "int_sensors_size2_class3": { + "mass": 2.5 + }, + "int_sensors_size2_class4": { + "mass": 4 + }, + "int_sensors_size2_class5": { + "mass": 2.5 + }, + "int_sensors_size3_class1": { + "mass": 5 + }, + "int_sensors_size3_class2": { + "mass": 2 + }, + "int_sensors_size3_class3": { + "mass": 5 + }, + "int_sensors_size3_class4": { + "mass": 8 + }, + "int_sensors_size3_class5": { + "mass": 5 + }, + "int_sensors_size4_class1": { + "mass": 10 + }, + "int_sensors_size4_class2": { + "mass": 4 + }, + "int_sensors_size4_class3": { + "mass": 10 + }, + "int_sensors_size4_class4": { + "mass": 16 + }, + "int_sensors_size4_class5": { + "mass": 10 + }, + "int_sensors_size5_class1": { + "mass": 20 + }, + "int_sensors_size5_class2": { + "mass": 8 + }, + "int_sensors_size5_class3": { + "mass": 20 + }, + "int_sensors_size5_class4": { + "mass": 32 + }, + "int_sensors_size5_class5": { + "mass": 20 + }, + "int_sensors_size6_class1": { + "mass": 40 + }, + "int_sensors_size6_class2": { + "mass": 16 + }, + "int_sensors_size6_class3": { + "mass": 40 + }, + "int_sensors_size6_class4": { + "mass": 64 + }, + "int_sensors_size6_class5": { + "mass": 40 + }, + "int_sensors_size7_class1": { + "mass": 80 + }, + "int_sensors_size7_class2": { + "mass": 32 + }, + "int_sensors_size7_class3": { + "mass": 80 + }, + "int_sensors_size7_class4": { + "mass": 128 + }, + "int_sensors_size7_class5": { + "mass": 80 + }, + "int_sensors_size8_class1": { + "mass": 160 + }, + "int_sensors_size8_class2": { + "mass": 64 + }, + "int_sensors_size8_class3": { + "mass": 160 + }, + "int_sensors_size8_class4": { + "mass": 256 + }, + "int_sensors_size8_class5": { + "mass": 160 + }, + "int_shieldcellbank_size1_class1": { + "mass": 1.3 + }, + "int_shieldcellbank_size1_class2": { + "mass": 0.5 + }, + "int_shieldcellbank_size1_class3": { + "mass": 1.3 + }, + "int_shieldcellbank_size1_class4": { + "mass": 2 + }, + "int_shieldcellbank_size1_class5": { + "mass": 1.3 + }, + "int_shieldcellbank_size2_class1": { + "mass": 2.5 + }, + "int_shieldcellbank_size2_class2": { + "mass": 1 + }, + "int_shieldcellbank_size2_class3": { + "mass": 2.5 + }, + "int_shieldcellbank_size2_class4": { + "mass": 4 + }, + "int_shieldcellbank_size2_class5": { + "mass": 2.5 + }, + "int_shieldcellbank_size3_class1": { + "mass": 5 + }, + "int_shieldcellbank_size3_class2": { + "mass": 2 + }, + "int_shieldcellbank_size3_class3": { + "mass": 5 + }, + "int_shieldcellbank_size3_class4": { + "mass": 8 + }, + "int_shieldcellbank_size3_class5": { + "mass": 5 + }, + "int_shieldcellbank_size4_class1": { + "mass": 10 + }, + "int_shieldcellbank_size4_class2": { + "mass": 4 + }, + "int_shieldcellbank_size4_class3": { + "mass": 10 + }, + "int_shieldcellbank_size4_class4": { + "mass": 16 + }, + "int_shieldcellbank_size4_class5": { + "mass": 10 + }, + "int_shieldcellbank_size5_class1": { + "mass": 20 + }, + "int_shieldcellbank_size5_class2": { + "mass": 8 + }, + "int_shieldcellbank_size5_class3": { + "mass": 20 + }, + "int_shieldcellbank_size5_class4": { + "mass": 32 + }, + "int_shieldcellbank_size5_class5": { + "mass": 20 + }, + "int_shieldcellbank_size6_class1": { + "mass": 40 + }, + "int_shieldcellbank_size6_class2": { + "mass": 16 + }, + "int_shieldcellbank_size6_class3": { + "mass": 40 + }, + "int_shieldcellbank_size6_class4": { + "mass": 64 + }, + "int_shieldcellbank_size6_class5": { + "mass": 40 + }, + "int_shieldcellbank_size7_class1": { + "mass": 80 + }, + "int_shieldcellbank_size7_class2": { + "mass": 32 + }, + "int_shieldcellbank_size7_class3": { + "mass": 80 + }, + "int_shieldcellbank_size7_class4": { + "mass": 128 + }, + "int_shieldcellbank_size7_class5": { + "mass": 80 + }, + "int_shieldcellbank_size8_class1": { + "mass": 160 + }, + "int_shieldcellbank_size8_class2": { + "mass": 64 + }, + "int_shieldcellbank_size8_class3": { + "mass": 160 + }, + "int_shieldcellbank_size8_class4": { + "mass": 256 + }, + "int_shieldcellbank_size8_class5": { + "mass": 160 + }, + "int_shieldgenerator_size1_class3_fast": { + "mass": 1.3 + }, + "int_shieldgenerator_size1_class5": { + "mass": 1.3 + }, + "int_shieldgenerator_size1_class5_strong": { + "mass": 2.5 + }, + "int_shieldgenerator_size2_class1": { + "mass": 2.5 + }, + "int_shieldgenerator_size2_class2": { + "mass": 1 + }, + "int_shieldgenerator_size2_class3": { + "mass": 2.5 + }, + "int_shieldgenerator_size2_class3_fast": { + "mass": 2.5 + }, + "int_shieldgenerator_size2_class4": { + "mass": 4 + }, + "int_shieldgenerator_size2_class5": { + "mass": 2.5 + }, + "int_shieldgenerator_size2_class5_strong": { + "mass": 5 + }, + "int_shieldgenerator_size3_class1": { + "mass": 5 + }, + "int_shieldgenerator_size3_class2": { + "mass": 2 + }, + "int_shieldgenerator_size3_class3": { + "mass": 5 + }, + "int_shieldgenerator_size3_class3_fast": { + "mass": 5 + }, + "int_shieldgenerator_size3_class4": { + "mass": 8 + }, + "int_shieldgenerator_size3_class5": { + "mass": 5 + }, + "int_shieldgenerator_size3_class5_strong": { + "mass": 10 + }, + "int_shieldgenerator_size4_class1": { + "mass": 10 + }, + "int_shieldgenerator_size4_class2": { + "mass": 4 + }, + "int_shieldgenerator_size4_class3": { + "mass": 10 + }, + "int_shieldgenerator_size4_class3_fast": { + "mass": 10 + }, + "int_shieldgenerator_size4_class4": { + "mass": 16 + }, + "int_shieldgenerator_size4_class5": { + "mass": 10 + }, + "int_shieldgenerator_size4_class5_strong": { + "mass": 20 + }, + "int_shieldgenerator_size5_class1": { + "mass": 20 + }, + "int_shieldgenerator_size5_class2": { + "mass": 8 + }, + "int_shieldgenerator_size5_class3": { + "mass": 20 + }, + "int_shieldgenerator_size5_class3_fast": { + "mass": 20 + }, + "int_shieldgenerator_size5_class4": { + "mass": 32 + }, + "int_shieldgenerator_size5_class5": { + "mass": 20 + }, + "int_shieldgenerator_size5_class5_strong": { + "mass": 40 + }, + "int_shieldgenerator_size6_class1": { + "mass": 40 + }, + "int_shieldgenerator_size6_class2": { + "mass": 16 + }, + "int_shieldgenerator_size6_class3": { + "mass": 40 + }, + "int_shieldgenerator_size6_class3_fast": { + "mass": 40 + }, + "int_shieldgenerator_size6_class4": { + "mass": 64 + }, + "int_shieldgenerator_size6_class5": { + "mass": 40 + }, + "int_shieldgenerator_size6_class5_strong": { + "mass": 80 + }, + "int_shieldgenerator_size7_class1": { + "mass": 80 + }, + "int_shieldgenerator_size7_class2": { + "mass": 32 + }, + "int_shieldgenerator_size7_class3": { + "mass": 80 + }, + "int_shieldgenerator_size7_class3_fast": { + "mass": 80 + }, + "int_shieldgenerator_size7_class4": { + "mass": 128 + }, + "int_shieldgenerator_size7_class5": { + "mass": 80 + }, + "int_shieldgenerator_size7_class5_strong": { + "mass": 160 + }, + "int_shieldgenerator_size8_class1": { + "mass": 160 + }, + "int_shieldgenerator_size8_class2": { + "mass": 64 + }, + "int_shieldgenerator_size8_class3": { + "mass": 160 + }, + "int_shieldgenerator_size8_class3_fast": { + "mass": 160 + }, + "int_shieldgenerator_size8_class4": { + "mass": 256 + }, + "int_shieldgenerator_size8_class5": { + "mass": 160 + }, + "int_shieldgenerator_size8_class5_strong": { + "mass": 320 + }, + "int_stellarbodydiscoveryscanner_advanced": { + "mass": 2 + }, + "int_stellarbodydiscoveryscanner_intermediate": { + "mass": 2 + }, + "int_stellarbodydiscoveryscanner_standard": { + "mass": 2 + }, + "int_supercruiseassist": { + "mass": 0 + }, + "krait_light_armour_grade1": { + "mass": 0 + }, + "krait_light_armour_grade2": { + "mass": 26 + }, + "krait_light_armour_grade3": { + "mass": 53 + }, + "krait_light_armour_mirrored": { + "mass": 53 + }, + "krait_light_armour_reactive": { + "mass": 53 + }, + "krait_mkii_armour_grade1": { + "mass": 0 + }, + "krait_mkii_armour_grade2": { + "mass": 36 + }, + "krait_mkii_armour_grade3": { + "mass": 67 + }, + "krait_mkii_armour_mirrored": { + "mass": 67 + }, + "krait_mkii_armour_reactive": { + "mass": 67 + }, + "mamba_armour_grade1": { + "mass": 0 + }, + "mamba_armour_grade2": { + "mass": 19 + }, + "mamba_armour_grade3": { + "mass": 38 + }, + "mamba_armour_mirrored": { + "mass": 38 + }, + "mamba_armour_reactive": { + "mass": 38 + }, + "orca_armour_grade1": { + "mass": 0 + }, + "orca_armour_grade2": { + "mass": 21 + }, + "orca_armour_grade3": { + "mass": 87 + }, + "orca_armour_mirrored": { + "mass": 87 + }, + "orca_armour_reactive": { + "mass": 87 + }, + "python_armour_grade1": { + "mass": 0 + }, + "python_armour_grade2": { + "mass": 26 + }, + "python_armour_grade3": { + "mass": 53 + }, + "python_armour_mirrored": { + "mass": 53 + }, + "python_armour_reactive": { + "mass": 53 + }, + "sidewinder_armour_grade1": { + "mass": 0 + }, + "sidewinder_armour_grade2": { + "mass": 2 + }, + "sidewinder_armour_grade3": { + "mass": 4 + }, + "sidewinder_armour_mirrored": { + "mass": 4 + }, + "sidewinder_armour_reactive": { + "mass": 4 + }, + "type6_armour_grade1": { + "mass": 0 + }, + "type6_armour_grade2": { + "mass": 12 + }, + "type6_armour_grade3": { + "mass": 23 + }, + "type6_armour_mirrored": { + "mass": 23 + }, + "type6_armour_reactive": { + "mass": 23 + }, + "type7_armour_grade1": { + "mass": 0 + }, + "type7_armour_grade2": { + "mass": 32 + }, + "type7_armour_grade3": { + "mass": 63 + }, + "type7_armour_mirrored": { + "mass": 63 + }, + "type7_armour_reactive": { + "mass": 63 + }, + "type9_armour_grade1": { + "mass": 0 + }, + "type9_armour_grade2": { + "mass": 75 + }, + "type9_armour_grade3": { + "mass": 150 + }, + "type9_armour_mirrored": { + "mass": 150 + }, + "type9_armour_reactive": { + "mass": 150 + }, + "type9_military_armour_grade1": { + "mass": 0 + }, + "type9_military_armour_grade2": { + "mass": 75 + }, + "type9_military_armour_grade3": { + "mass": 150 + }, + "type9_military_armour_mirrored": { + "mass": 150 + }, + "type9_military_armour_reactive": { + "mass": 150 + }, + "typex_2_armour_grade1": { + "mass": 0 + }, + "typex_2_armour_grade2": { + "mass": 40 + }, + "typex_2_armour_grade3": { + "mass": 78 + }, + "typex_2_armour_mirrored": { + "mass": 78 + }, + "typex_2_armour_reactive": { + "mass": 78 + }, + "typex_3_armour_grade1": { + "mass": 0 + }, + "typex_3_armour_grade2": { + "mass": 40 + }, + "typex_3_armour_grade3": { + "mass": 78 + }, + "typex_3_armour_mirrored": { + "mass": 78 + }, + "typex_3_armour_reactive": { + "mass": 78 + }, + "typex_armour_grade1": { + "mass": 0 + }, + "typex_armour_grade2": { + "mass": 40 + }, + "typex_armour_grade3": { + "mass": 78 + }, + "typex_armour_mirrored": { + "mass": 78 + }, + "typex_armour_reactive": { + "mass": 78 + }, + "viper_armour_grade1": { + "mass": 0 + }, + "viper_armour_grade2": { + "mass": 5 + }, + "viper_armour_grade3": { + "mass": 9 + }, + "viper_armour_mirrored": { + "mass": 9 + }, + "viper_armour_reactive": { + "mass": 9 + }, + "viper_mkiv_armour_grade1": { + "mass": 0 + }, + "viper_mkiv_armour_grade2": { + "mass": 5 + }, + "viper_mkiv_armour_grade3": { + "mass": 9 + }, + "viper_mkiv_armour_mirrored": { + "mass": 9 + }, + "viper_mkiv_armour_reactive": { + "mass": 9 + }, + "vulture_armour_grade1": { + "mass": 0 + }, + "vulture_armour_grade2": { + "mass": 17 + }, + "vulture_armour_grade3": { + "mass": 35 + }, + "vulture_armour_mirrored": { + "mass": 35 + }, + "vulture_armour_reactive": { + "mass": 35 + } +} \ No newline at end of file diff --git a/resources/ships.json b/resources/ships.json new file mode 100644 index 00000000..4a40ba4f --- /dev/null +++ b/resources/ships.json @@ -0,0 +1,116 @@ +{ + "Adder": { + "hullMass": 35 + }, + "Alliance Challenger": { + "hullMass": 450 + }, + "Alliance Chieftain": { + "hullMass": 400 + }, + "Alliance Crusader": { + "hullMass": 500 + }, + "Anaconda": { + "hullMass": 400 + }, + "Asp Explorer": { + "hullMass": 280 + }, + "Asp Scout": { + "hullMass": 150 + }, + "Beluga Liner": { + "hullMass": 950 + }, + "Cobra MkIII": { + "hullMass": 180 + }, + "Cobra MkIV": { + "hullMass": 210 + }, + "Diamondback Explorer": { + "hullMass": 260 + }, + "Diamondback Scout": { + "hullMass": 170 + }, + "Dolphin": { + "hullMass": 140 + }, + "Eagle": { + "hullMass": 50 + }, + "Federal Assault Ship": { + "hullMass": 480 + }, + "Federal Corvette": { + "hullMass": 900 + }, + "Federal Dropship": { + "hullMass": 580 + }, + "Federal Gunship": { + "hullMass": 580 + }, + "Fer-de-Lance": { + "hullMass": 250 + }, + "Hauler": { + "hullMass": 14 + }, + "Imperial Clipper": { + "hullMass": 400 + }, + "Imperial Courier": { + "hullMass": 35 + }, + "Imperial Cutter": { + "hullMass": 1100 + }, + "Imperial Eagle": { + "hullMass": 50 + }, + "Keelback": { + "hullMass": 180 + }, + "Krait MkII": { + "hullMass": 320 + }, + "Krait Phantom": { + "hullMass": 270 + }, + "Mamba": { + "hullMass": 250 + }, + "Orca": { + "hullMass": 290 + }, + "Python": { + "hullMass": 350 + }, + "Sidewinder": { + "hullMass": 25 + }, + "Type-10 Defender": { + "hullMass": 1200 + }, + "Type-6 Transporter": { + "hullMass": 155 + }, + "Type-7 Transporter": { + "hullMass": 350 + }, + "Type-9 Heavy": { + "hullMass": 850 + }, + "Viper MkIII": { + "hullMass": 50 + }, + "Viper MkIV": { + "hullMass": 190 + }, + "Vulture": { + "hullMass": 230 + } +} \ No newline at end of file From 71ff00ce5894d2c2f63a1bcc380b5f05e35ddc79 Mon Sep 17 00:00:00 2001 From: Phoebe Date: Fri, 17 Nov 2023 22:03:23 +0100 Subject: [PATCH 38/83] [1490] Adds spansh as a URL provider - Adds a spansh plugin as a URL provider for systems and stations. - Adds plugin path to build.py. - Updates a comment in the EDSM plugin. --- build.py | 1 + plugins/edsm.py | 2 +- plugins/spansh_core.py | 195 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 197 insertions(+), 1 deletion(-) create mode 100644 plugins/spansh_core.py diff --git a/build.py b/build.py index 4ee99758..cf35f7c5 100644 --- a/build.py +++ b/build.py @@ -110,6 +110,7 @@ def build() -> None: "plugins/edsm.py", "plugins/edsy.py", "plugins/inara.py", + "plugins/spansh_core.py", ] options: dict = { "py2exe": { diff --git a/plugins/edsm.py b/plugins/edsm.py index 2ed31ab3..ba292ca6 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -205,7 +205,7 @@ def plugin_start3(plugin_dir: str) -> str: # Can't be earlier since can only call PhotoImage after window is created this._IMG_KNOWN = tk.PhotoImage(data=IMG_KNOWN_B64) # green circle this._IMG_UNKNOWN = tk.PhotoImage(data=IMG_UNKNOWN_B64) # red circle - this._IMG_NEW = tk.PhotoImage(data=IMG_NEW_B64) + this._IMG_NEW = tk.PhotoImage(data=IMG_NEW_B64) # yellow star this._IMG_ERROR = tk.PhotoImage(data=IMG_ERR_B64) # BBC Mode 5 '?' # Migrate old settings diff --git a/plugins/spansh_core.py b/plugins/spansh_core.py new file mode 100644 index 00000000..18a51846 --- /dev/null +++ b/plugins/spansh_core.py @@ -0,0 +1,195 @@ +""" +spansh_core.py - Spansh URL provider. + +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. +""" +from __future__ import annotations + +import tkinter as tk +from typing import Any, cast +import requests +from companion import CAPIData +from config import appname, config +from EDMCLogging import get_main_logger + +logger = get_main_logger() + + +class This: + """Holds module globals.""" + + def __init__(self): + self.parent: tk.Tk + self.shutting_down = False # Plugin is shutting down. + self.system_link: tk.Widget = None # type: ignore + self.system_name: str | None = None # type: ignore + self.system_address: str | None = None # type: ignore + self.system_population: int | None = None + self.station_link: tk.Widget = None # type: ignore + self.station_name = None + self.station_marketid = None + self.on_foot = False + + +this = This() +STATION_UNDOCKED: str = '×' # "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 'spansh' + + +def plugin_app(parent: tk.Tk) -> None: + """ + Construct this plugin's main UI, if any. + + :param parent: The tk parent to place our widgets into. + :return: See PLUGINS.md#display + """ + this.parent = parent + this.system_link = parent.nametowidget(f".{appname.lower()}.system") + this.station_link = parent.nametowidget(f".{appname.lower()}.station") + + +def plugin_stop() -> None: + """Plugin shutdown hook.""" + this.shutting_down = True + + +def journal_entry( + cmdr: str, is_beta: bool, system: str, station: str, entry: dict[str, Any], state: dict[str, Any] +) -> str: + """ + Handle a new Journal event. + + :param cmdr: Name of Commander. + :param is_beta: Whether game beta was detected. + :param system: Name of current tracked system. + :param station: Name of current tracked station location. + :param entry: The journal event. + :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'] + + # Only actually change URLs if we are current provider. + if config.get_str('system_provider') == 'spansh': + this.system_link['text'] = this.system_name + # 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.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 + # 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() + + return '' + + +def cmdr_data(data: CAPIData, is_beta: bool) -> str | None: + """ + Process new CAPI data. + + :param data: The latest merged CAPI data. + :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'] + + # Override standard URL functions + if config.get_str('system_provider') == 'spansh': + this.system_link['text'] = this.system_name + # 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.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'] = '' + # 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() + + return '' + + +def system_url(system_name: str) -> str: + """ + Construct an appropriate spansh URL for the provided system. + + :param system_name: Will be overridden with `this.system_address` if that + is set. + :return: The URL, empty if no data was available to construct it. + """ + if this.system_address: + return requests.utils.requote_uri(f'https://www.spansh.co.uk/system/{this.system_address}') + + if system_name: + return requests.utils.requote_uri(f'https://www.spansh.co.uk/search/{system_name}') + + return '' + + +def station_url(system_name: str, station_name: str) -> str: + """ + Construct an appropriate spansh URL for a station. + + Ignores `station_name` in favour of `this.station_marketid`. + + :param system_name: Name of the system the station is in. + :param station_name: **NOT USED** + :return: The URL, empty if no data was available to construct it. + """ + if this.station_marketid: + return requests.utils.requote_uri(f'https://www.spansh.co.uk/station/{this.station_marketid}') + + if system_name: + return system_url(system_name) + + return '' From ed163ddb611cb782252146d274919f0118442ddd Mon Sep 17 00:00:00 2001 From: Phoebe Date: Fri, 17 Nov 2023 22:40:08 +0100 Subject: [PATCH 39/83] [Minor] Typos and mypy --- plugins/edsm.py | 2 +- plugins/spansh_core.py | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/plugins/edsm.py b/plugins/edsm.py index ba292ca6..48dc80e8 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -199,7 +199,7 @@ def plugin_start3(plugin_dir: str) -> str: """ Start the plugin. - :param plugin_dir: NAme of directory this was loaded from. + :param plugin_dir: Name of directory this was loaded from. :return: Identifier string for this plugin. """ # Can't be earlier since can only call PhotoImage after window is created diff --git a/plugins/spansh_core.py b/plugins/spansh_core.py index 18a51846..8a7d87be 100644 --- a/plugins/spansh_core.py +++ b/plugins/spansh_core.py @@ -37,8 +37,8 @@ class This: self.parent: tk.Tk self.shutting_down = False # Plugin is shutting down. self.system_link: tk.Widget = None # type: ignore - self.system_name: str | None = None # type: ignore - self.system_address: str | None = None # type: ignore + self.system_name: str | None = None + self.system_address: str | None = None self.system_population: int | None = None self.station_link: tk.Widget = None # type: ignore self.station_name = None @@ -54,7 +54,7 @@ def plugin_start3(plugin_dir: str) -> str: """ Start the plugin. - :param plugin_dir: NAme of directory this was loaded from. + :param plugin_dir: Name of directory this was loaded from. :return: Identifier string for this plugin. """ return 'spansh' From 724dd2ce6af07c8be10a4a7eabb72b91d2d2fe2d Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 17 Nov 2023 17:46:32 -0500 Subject: [PATCH 40/83] [2051] Main GUI File --- EDMarketConnector.py | 383 +++++++++++++++++++++---------------------- 1 file changed, 184 insertions(+), 199 deletions(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 0b457c9c..411eefce 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -1,6 +1,10 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -"""Entry point for the main GUI application.""" +""" +EDMarketConnector.py - Entry point for the GUI. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" from __future__ import annotations import argparse @@ -9,14 +13,14 @@ import locale import pathlib import queue import re +import subprocess import sys import threading import webbrowser -from builtins import object, str -from os import chdir, environ -from os.path import dirname, join +from os import chdir, environ, path from time import localtime, strftime, time -from typing import TYPE_CHECKING, Any, Literal, Optional, Tuple, Union +from typing import TYPE_CHECKING, Any, Literal +from constants import applongname, appname, protocolhandler_redirect # Have this as early as possible for people running EDMarketConnector.exe # from cmd.exe or a bat file or similar. Else they might not be in the correct @@ -24,17 +28,16 @@ from typing import TYPE_CHECKING, Any, Literal, Optional, Tuple, Union if getattr(sys, 'frozen', False): # Under py2exe sys.path[0] is the executable name if sys.platform == 'win32': - chdir(dirname(sys.path[0])) + chdir(path.dirname(sys.path[0])) # Allow executable to be invoked from any cwd - environ['TCL_LIBRARY'] = join(dirname(sys.path[0]), 'lib', 'tcl') - environ['TK_LIBRARY'] = join(dirname(sys.path[0]), 'lib', 'tk') + environ['TCL_LIBRARY'] = path.join(path.dirname(sys.path[0]), 'lib', 'tcl') + environ['TK_LIBRARY'] = path.join(path.dirname(sys.path[0]), 'lib', 'tk') else: # We still want to *try* to have CWD be where the main script is, even if # not frozen. chdir(pathlib.Path(__file__).parent) -from constants import applongname, appname, protocolhandler_redirect # config will now cause an appname logger to be set up, so we need the # console redirect before this @@ -46,7 +49,9 @@ if __name__ == '__main__': import tempfile # unbuffered not allowed for text in python3, so use `1 for line buffering - sys.stdout = sys.stderr = open(join(tempfile.gettempdir(), f'{appname}.log'), mode='wt', buffering=1) + log_file_path = path.join(tempfile.gettempdir(), f'{appname}.log') + with open(log_file_path, mode='wt', buffering=1) as log_file: + sys.stdout = sys.stderr = log_file # TODO: Test: Make *sure* this redirect is working, else py2exe is going to cause an exit popup @@ -87,6 +92,11 @@ if __name__ == '__main__': # noqa: C901 help='Suppress the popup from when the application detects another instance already running', action='store_true' ) + + parser.add_argument('--start_min', + help="Start the application minimized", + action="store_true" + ) ########################################################################### ########################################################################### @@ -175,7 +185,7 @@ if __name__ == '__main__': # noqa: C901 ) ########################################################################### - args = parser.parse_args() + args: argparse.Namespace = parser.parse_args() if args.capi_pretend_down: import config as conf_module @@ -187,7 +197,7 @@ if __name__ == '__main__': # noqa: C901 with open(conf_module.config.app_dir_path / 'access_token.txt', 'r') as at: conf_module.capi_debug_access_token = at.readline().strip() - level_to_set: Optional[int] = None + level_to_set: int | None = None if args.trace or args.trace_on: level_to_set = logging.TRACE # type: ignore # it exists logger.info('Setting TRACE level debugging due to either --trace or a --trace-on') @@ -216,7 +226,7 @@ if __name__ == '__main__': # noqa: C901 else: print("--force-edmc-protocol is only valid on Windows") parser.print_help() - exit(1) + sys.exit(1) if args.debug_sender and len(args.debug_sender) > 0: import config as conf_module @@ -237,7 +247,7 @@ if __name__ == '__main__': # noqa: C901 logger.info(f'marked {d} for TRACE') def handle_edmc_callback_or_foregrounding() -> None: # noqa: CCR001 - """Handle any edmc:// auth callback, else foreground existing window.""" + """Handle any edmc:// auth callback, else foreground an existing window.""" logger.trace_if('frontier-auth.windows', 'Begin...') if sys.platform == 'win32': @@ -245,40 +255,40 @@ 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: - import ctypes + from ctypes import windll, c_int, create_unicode_buffer, WINFUNCTYPE from ctypes.wintypes import BOOL, HWND, INT, LPARAM, LPCWSTR, LPWSTR - EnumWindows = ctypes.windll.user32.EnumWindows # noqa: N806 - GetClassName = ctypes.windll.user32.GetClassNameW # noqa: N806 - GetClassName.argtypes = [HWND, LPWSTR, ctypes.c_int] - GetWindowText = ctypes.windll.user32.GetWindowTextW # noqa: N806 - GetWindowText.argtypes = [HWND, LPWSTR, ctypes.c_int] - GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW # noqa: N806 - GetProcessHandleFromHwnd = ctypes.windll.oleacc.GetProcessHandleFromHwnd # noqa: N806 + EnumWindows = windll.user32.EnumWindows # noqa: N806 + GetClassName = windll.user32.GetClassNameW # noqa: N806 + GetClassName.argtypes = [HWND, LPWSTR, c_int] + GetWindowText = windll.user32.GetWindowTextW # noqa: N806 + GetWindowText.argtypes = [HWND, LPWSTR, c_int] + GetWindowTextLength = windll.user32.GetWindowTextLengthW # noqa: N806 + GetProcessHandleFromHwnd = windll.oleacc.GetProcessHandleFromHwnd # noqa: N806 SW_RESTORE = 9 # noqa: N806 - SetForegroundWindow = ctypes.windll.user32.SetForegroundWindow # noqa: N806 - ShowWindow = ctypes.windll.user32.ShowWindow # noqa: N806 - ShowWindowAsync = ctypes.windll.user32.ShowWindowAsync # noqa: N806 + SetForegroundWindow = windll.user32.SetForegroundWindow # noqa: N806 + ShowWindow = windll.user32.ShowWindow # noqa: N806 + ShowWindowAsync = windll.user32.ShowWindowAsync # noqa: N806 COINIT_MULTITHREADED = 0 # noqa: N806,F841 COINIT_APARTMENTTHREADED = 0x2 # noqa: N806 COINIT_DISABLE_OLE1DDE = 0x4 # noqa: N806 - CoInitializeEx = ctypes.windll.ole32.CoInitializeEx # noqa: N806 + CoInitializeEx = windll.ole32.CoInitializeEx # noqa: N806 - ShellExecute = ctypes.windll.shell32.ShellExecuteW # noqa: N806 + ShellExecute = windll.shell32.ShellExecuteW # noqa: N806 ShellExecute.argtypes = [HWND, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR, INT] - def window_title(h: int) -> Optional[str]: + def window_title(h: int) -> str | None: if h: text_length = GetWindowTextLength(h) + 1 - buf = ctypes.create_unicode_buffer(text_length) + buf = create_unicode_buffer(text_length) if GetWindowText(h, buf, text_length): return buf.value return None - @ctypes.WINFUNCTYPE(BOOL, HWND, LPARAM) + @WINFUNCTYPE(BOOL, HWND, LPARAM) def enumwindowsproc(window_handle, l_param): # noqa: CCR001 """ Determine if any window for the Application exists. @@ -286,15 +296,16 @@ if __name__ == '__main__': # noqa: C901 Called for each found window by EnumWindows(). When a match is found we check if we're being invoked as the - edmc://auth handler. If so we send the message to the existing - process/window. If not we'll raise that existing window to the + edmc://auth handler. If so we send the message to the existing + process/window. If not we'll raise that existing window to the foreground. + :param window_handle: Window to check. :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 = ctypes.create_unicode_buffer(257) + cls = create_unicode_buffer(257) # This conditional is exploded to make debugging slightly easier if GetClassName(window_handle, cls, 257): if cls.value == 'TkTopLevel': @@ -323,13 +334,8 @@ if __name__ == '__main__': # noqa: C901 # Ref: EnumWindows(enumwindowsproc, 0) - return - def already_running_popup(): """Create the "already running" popup.""" - import tkinter as tk - from tkinter import ttk - # Check for CL arg that suppresses this popup. if args.suppress_dupe_process_popup: sys.exit(0) @@ -339,8 +345,7 @@ if __name__ == '__main__': # noqa: C901 frame = tk.Frame(root) frame.grid(row=1, column=0, sticky=tk.NSEW) - label = tk.Label(frame) - label['text'] = 'An EDMarketConnector.exe process was already running, exiting.' + label = tk.Label(frame, text='An EDMarketConnector.exe process was already running, exiting.') label.grid(row=1, column=0, sticky=tk.NSEW) button = ttk.Button(frame, text='OK', command=lambda: sys.exit(0)) @@ -373,41 +378,23 @@ if __name__ == '__main__': # noqa: C901 git_branch = "" try: - import subprocess git_cmd = subprocess.Popen('git branch --show-current'.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) out, err = git_cmd.communicate() - git_branch = out.decode().rstrip('\n') + git_branch = out.decode().strip() except Exception: pass if ( - ( - git_branch == 'develop' - or ( - git_branch == '' and '-alpha0' in str(appversion()) - ) - ) and ( - ( - sys.platform == 'linux' - and environ.get('USER') is not None - and environ['USER'] not in ['ad', 'athan'] - ) - or ( - sys.platform == 'win32' - and environ.get('USERNAME') is not None - and environ['USERNAME'] not in ['Athan'] - ) + git_branch == 'develop' + or ( + git_branch == '' and '-alpha0' in str(appversion()) ) ): - print("Why are you running the develop branch if you're not a developer?") - print("Please check https://github.com/EDCD/EDMarketConnector/wiki/Running-from-source#running-from-source") - print("You probably want the 'stable' branch.") - print("\n\rIf Athanasius or A_D asked you to run this, tell them about this message.") - sys.exit(-1) + print("You're running in a DEVELOPMENT branch build. You might encounter bugs!") # See EDMCLogging.py docs. @@ -427,8 +414,7 @@ import tkinter as tk import tkinter.filedialog import tkinter.font import tkinter.messagebox -from tkinter import ttk, constants as tkc - +from tkinter import ttk import commodity import plug import prefs @@ -462,7 +448,7 @@ SHIPYARD_HTML_TEMPLATE = """ """ -class AppWindow(object): +class AppWindow: """Define the main application window.""" _CAPI_RESPONSE_TK_EVENT_NAME = '<>' @@ -509,7 +495,7 @@ class AppWindow(object): else: self.w.tk.call('wm', 'iconphoto', self.w, '-default', - tk.PhotoImage(file=join(config.respath_path, 'io.edcd.EDMarketConnector.png'))) + tk.PhotoImage(file=path.join(config.respath_path, 'io.edcd.EDMarketConnector.png'))) # TODO: Export to files and merge from them in future ? self.theme_icon = tk.PhotoImage( @@ -637,7 +623,7 @@ class AppWindow(object): self.updater = update.Updater(tkroot=self.w, provider='external') else: - self.updater = update.Updater(tkroot=self.w, provider='internal') + self.updater = update.Updater(tkroot=self.w) self.updater.check_for_updates() # Sparkle / WinSparkle does this automatically for packaged apps if sys.platform == 'darwin': @@ -680,14 +666,14 @@ class AppWindow(object): self.w.protocol("WM_DELETE_WINDOW", self.w.withdraw) # close button shouldn't quit app self.w.resizable(tk.FALSE, tk.FALSE) # Can't be only resizable on one axis else: - self.file_menu = self.view_menu = tk.Menu(self.menubar, tearoff=tk.FALSE) # type: ignore + self.file_menu = self.view_menu = tk.Menu(self.menubar, tearoff=tk.FALSE) self.file_menu.add_command(command=lambda: stats.StatsDialog(self.w, self.status)) self.file_menu.add_command(command=self.save_raw) self.file_menu.add_command(command=lambda: prefs.PreferencesDialog(self.w, self.postprefs)) self.file_menu.add_separator() self.file_menu.add_command(command=self.onexit) self.menubar.add_cascade(menu=self.file_menu) - self.edit_menu = tk.Menu(self.menubar, tearoff=tk.FALSE) # type: ignore + self.edit_menu = tk.Menu(self.menubar, tearoff=tk.FALSE) self.edit_menu.add_command(accelerator='Ctrl+C', state=tk.DISABLED, command=self.copy) self.menubar.add_cascade(menu=self.edit_menu) self.help_menu = tk.Menu(self.menubar, tearoff=tk.FALSE) # type: ignore @@ -734,7 +720,7 @@ class AppWindow(object): anchor=tk.W, compound=tk.LEFT ) theme_titlebar.grid(columnspan=3, padx=2, sticky=tk.NSEW) - self.drag_offset: Tuple[Optional[int], Optional[int]] = (None, None) + self.drag_offset: tuple[int | None, int | None] = (None, None) theme_titlebar.bind('', self.drag_start) theme_titlebar.bind('', self.drag_continue) theme_titlebar.bind('', self.drag_end) @@ -808,7 +794,7 @@ class AppWindow(object): self.w.bind('', self.capi_request_data) self.w.bind_all('<>', self.capi_request_data) # Ask for CAPI queries to be performed self.w.bind_all(self._CAPI_RESPONSE_TK_EVENT_NAME, self.capi_handle_response) - self.w.bind_all('<>', self.journal_event) # Journal monitoring + self.w.bind_all('<>', self.journal_event) # type: ignore # Journal monitoring self.w.bind_all('<>', self.dashboard_event) # Dashboard monitoring self.w.bind_all('<>', self.plugin_error) # Statusbar self.w.bind_all('<>', self.auth) # cAPI auth @@ -826,6 +812,12 @@ class AppWindow(object): config.delete('logdir', suppress=True) self.postprefs(False) # Companion login happens in callback from monitor 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() def update_suit_text(self) -> None: """Update the suit text for current type and loadout.""" @@ -834,13 +826,14 @@ class AppWindow(object): self.suit['text'] = '' return - if (suit := monitor.state.get('SuitCurrent')) is None: + suit = monitor.state.get('SuitCurrent') + if suit is None: self.suit['text'] = f'<{_("Unknown")}>' # LANG: Unknown suit return suitname = suit['edmcName'] - - if (suitloadout := monitor.state.get('SuitLoadoutCurrent')) is None: + suitloadout = monitor.state.get('SuitLoadoutCurrent') + if suitloadout is None: self.suit['text'] = '' return @@ -849,31 +842,18 @@ class AppWindow(object): def suit_show_if_set(self) -> None: """Show UI Suit row if we have data, else hide.""" - if self.suit['text'] != '': - self.toggle_suit_row(visible=True) + self.toggle_suit_row(self.suit['text'] != '') - else: - self.toggle_suit_row(visible=False) - - def toggle_suit_row(self, visible: Optional[bool] = None) -> None: + def toggle_suit_row(self, visible: bool | None = None) -> None: """ Toggle the visibility of the 'Suit' row. :param visible: Force visibility to this. """ - if visible is True: - self.suit_shown = False - - elif visible is False: - self.suit_shown = True + self.suit_shown = not visible if not self.suit_shown: - if sys.platform != 'win32': - pady = 2 - - else: - - pady = 0 + pady = 2 if sys.platform != 'win32' else 0 self.suit_label.grid(row=self.suit_grid_row, column=0, sticky=tk.W, padx=self.PADX, pady=pady) self.suit.grid(row=self.suit_grid_row, column=1, sticky=tk.EW, padx=self.PADX, pady=pady) @@ -1020,38 +1000,44 @@ class AppWindow(object): :return: True if all OK, else False to trigger play_bad in caller. """ - if config.get_int('output') & (config.OUT_STATION_ANY): - if not data['commander'].get('docked') and not monitor.state['OnFoot']: - if not self.status['text']: - # Signal as error because the user might actually be docked - # but the server hosting the Companion API hasn't caught up - # LANG: Player is not docked at a station, when we expect them to be - self.status['text'] = _("You're not docked at a station!") - return False + output_flags = config.get_int('output') + is_docked = data['commander'].get('docked') + has_commodities = data['lastStarport'].get('commodities') + has_modules = data['lastStarport'].get('modules') + commodities_flag = config.OUT_MKT_CSV | config.OUT_MKT_TD - # Ignore possibly missing shipyard info - elif (config.get_int('output') & config.OUT_EDDN_SEND_STATION_DATA) \ - and not (data['lastStarport'].get('commodities') or data['lastStarport'].get('modules')): - if not self.status['text']: - # LANG: Status - Either no market or no modules data for station from Frontier CAPI - self.status['text'] = _("Station doesn't have anything!") + if output_flags & config.OUT_STATION_ANY: + if not is_docked and not monitor.state['OnFoot']: + # Signal as error because the user might actually be docked + # but the server hosting the Companion API hasn't caught up + self._handle_status(_("You're not docked at a station!")) + return False - elif not data['lastStarport'].get('commodities'): - if not self.status['text']: - # LANG: Status - No station market data from Frontier CAPI - self.status['text'] = _("Station doesn't have a market!") + if output_flags & config.OUT_EDDN_SEND_STATION_DATA and not (has_commodities or has_modules): + self._handle_status(_("Station doesn't have anything!")) - elif config.get_int('output') & (config.OUT_MKT_CSV | config.OUT_MKT_TD): - # Fixup anomalies in the commodity data + elif not has_commodities: + self._handle_status(_("Station doesn't have a market!")) + + elif output_flags & commodities_flag: fixed = companion.fixup(data) - if config.get_int('output') & config.OUT_MKT_CSV: + if output_flags & config.OUT_MKT_CSV: commodity.export(fixed, COMMODITY_CSV) - if config.get_int('output') & config.OUT_MKT_TD: + if output_flags & config.OUT_MKT_TD: td.export(fixed) return True + def _handle_status(self, message: str) -> None: + """ + Set the status label text if it's not already set. + + :param message: Status message to display. + """ + if not self.status['text']: + self.status['text'] = message + def capi_request_data(self, event=None) -> None: # noqa: CCR001 """ Perform CAPI data retrieval and associated actions. @@ -1117,30 +1103,28 @@ class AppWindow(object): self.login() return - if not companion.session.retrying: - if time() < self.capi_query_holdoff_time: # Was invoked by key while in cooldown - if play_sound and (self.capi_query_holdoff_time - time()) < companion.capi_query_cooldown * 0.75: - self.status['text'] = '' - hotkeymgr.play_bad() # Don't play sound in first few seconds to prevent repeats + if not companion.session.retrying and time() >= self.capi_query_holdoff_time: + if play_sound: + if time() < self.capi_query_holdoff_time: # Was invoked by key while in cooldown + if (self.capi_query_holdoff_time - time()) < companion.capi_query_cooldown * 0.75: + self.status['text'] = '' + hotkeymgr.play_bad() # Don't play sound in first few seconds to prevent repeats + else: + hotkeymgr.play_good() - return + # LANG: Status - Attempting to retrieve data from Frontier CAPI + self.status['text'] = _('Fetching data...') + self.button['state'] = self.theme_button['state'] = tk.DISABLED + self.w.update_idletasks() - elif play_sound: - hotkeymgr.play_good() - - # LANG: Status - Attempting to retrieve data from Frontier CAPI - self.status['text'] = _('Fetching data...') - self.button['state'] = self.theme_button['state'] = tk.DISABLED - self.w.update_idletasks() - - query_time = int(time()) - logger.trace_if('capi.worker', 'Requesting full station data') - config.set('querytime', query_time) - logger.trace_if('capi.worker', 'Calling companion.session.station') - companion.session.station( - query_time=query_time, tk_response_event=self._CAPI_RESPONSE_TK_EVENT_NAME, - play_sound=play_sound - ) + query_time = int(time()) + logger.trace_if('capi.worker', 'Requesting full station data') + config.set('querytime', query_time) + logger.trace_if('capi.worker', 'Calling companion.session.station') + companion.session.station( + query_time=query_time, tk_response_event=self._CAPI_RESPONSE_TK_EVENT_NAME, + play_sound=play_sound + ) def capi_request_fleetcarrier_data(self, event=None) -> None: """ @@ -1174,30 +1158,31 @@ class AppWindow(object): self.status['text'] = _('CAPI query aborted: GameVersion unknown') return - if not companion.session.retrying: - if time() < self.capi_fleetcarrier_query_holdoff_time: # Was invoked while in cooldown - logger.debug('CAPI fleetcarrier query aborted, too soon since last request') - return + if not companion.session.retrying and time() >= self.capi_fleetcarrier_query_holdoff_time: # LANG: Status - Attempting to retrieve data from Frontier CAPI self.status['text'] = _('Fetching data...') self.w.update_idletasks() - query_time = int(time()) - logger.trace_if('capi.worker', 'Requesting fleetcarrier data') - config.set('fleetcarrierquerytime', query_time) - logger.trace_if('capi.worker', 'Calling companion.session.fleetcarrier') - companion.session.fleetcarrier( - query_time=query_time, tk_response_event=self._CAPI_RESPONSE_TK_EVENT_NAME - ) + query_time = int(time()) + logger.trace_if('capi.worker', 'Requesting fleetcarrier data') + config.set('fleetcarrierquerytime', query_time) + logger.trace_if('capi.worker', 'Calling companion.session.fleetcarrier') + companion.session.fleetcarrier( + query_time=query_time, tk_response_event=self._CAPI_RESPONSE_TK_EVENT_NAME + ) def capi_handle_response(self, event=None): # noqa: C901, CCR001 - """Handle the resulting data from a CAPI query.""" + """ + Handle the resulting data from a CAPI query. + + :param event: generated event details. + """ logger.trace_if('capi.worker', 'Handling response') play_bad: bool = False - err: Optional[str] = None + err: str | None = None - capi_response: Union[companion.EDMCCAPIFailedRequest, companion.EDMCCAPIResponse] + capi_response: companion.EDMCCAPIFailedRequest | companion.EDMCCAPIResponse try: logger.trace_if('capi.worker', 'Pulling answer off queue') capi_response = companion.session.capi_response_queue.get(block=False) @@ -1206,8 +1191,7 @@ class AppWindow(object): if capi_response.exception: raise capi_response.exception - else: - raise ValueError(capi_response.message) + raise ValueError(capi_response.message) logger.trace_if('capi.worker', 'Answer is not a Failure') if not isinstance(capi_response, companion.EDMCCAPIResponse): @@ -1256,8 +1240,8 @@ class AppWindow(object): err = self.status['text'] = _("Where are you?!") # Shouldn't happen elif ( - not capi_response.capi_data.get('ship', {}).get('name') - or not capi_response.capi_data.get('ship', {}).get('modules') + not capi_response.capi_data.get('ship', {}).get('name') + or not capi_response.capi_data.get('ship', {}).get('modules') ): # LANG: We don't know what ship the commander is in, when we should err = self.status['text'] = _("What are you flying?!") # Shouldn't happen @@ -1268,8 +1252,8 @@ class AppWindow(object): raise companion.CmdrError() elif ( - capi_response.auto_update and not monitor.state['OnFoot'] - and not capi_response.capi_data['commander'].get('docked') + capi_response.auto_update and not monitor.state['OnFoot'] + and not capi_response.capi_data['commander'].get('docked') ): # auto update is only when just docked logger.warning(f"{capi_response.auto_update!r} and not {monitor.state['OnFoot']!r} and " @@ -1282,14 +1266,14 @@ class AppWindow(object): f"{monitor.state['SystemName']!r}") raise companion.ServerLagging() - elif capi_response.capi_data['lastStarport']['name'] != monitor.state['StationName']: + if capi_response.capi_data['lastStarport']['name'] != monitor.state['StationName']: if monitor.state['OnFoot'] and monitor.state['StationName']: logger.warning(f"({capi_response.capi_data['lastStarport']['name']!r} != " f"{monitor.state['StationName']!r}) AND " f"{monitor.state['OnFoot']!r} and {monitor.state['StationName']!r}") raise companion.ServerLagging() - elif capi_response.capi_data['commander']['docked'] and monitor.state['StationName'] is None: + if capi_response.capi_data['commander']['docked'] and monitor.state['StationName'] is None: # Likely (re-)Embarked on ship docked at an EDO settlement. # Both Disembark and Embark have `"Onstation": false` in Journal. # So there's nothing to tell us which settlement we're (still, @@ -1311,8 +1295,8 @@ class AppWindow(object): raise companion.ServerLagging() elif ( - not monitor.state['OnFoot'] - and capi_response.capi_data['ship']['name'].lower() != monitor.state['ShipType'] + not monitor.state['OnFoot'] + and capi_response.capi_data['ship']['name'].lower() != monitor.state['ShipType'] ): # CAPI ship type must match logger.warning(f"not {monitor.state['OnFoot']!r} and " @@ -1385,9 +1369,12 @@ class AppWindow(object): # TODO: Set status text return - except companion.ServerConnectionError: + except companion.ServerConnectionError as comp_err: # LANG: Frontier CAPI server error when fetching data self.status['text'] = _('Frontier CAPI server error') + logger.warning(f'Exception while contacting server: {comp_err}') + err = self.status['text'] = str(comp_err) + play_bad = True except companion.CredentialsRequireRefresh: # We need to 'close' the auth else it'll see STATE_OK and think login() isn't needed @@ -1425,11 +1412,6 @@ class AppWindow(object): companion.session.invalidate() self.login() - except companion.ServerConnectionError as e: # TODO: unreachable (subclass of ServerLagging -- move to above) - logger.warning(f'Exception while contacting server: {e}') - err = self.status['text'] = str(e) - play_bad = True - except Exception as e: # Including CredentialsError, ServerError logger.debug('"other" exception', exc_info=e) err = self.status['text'] = str(e) @@ -1448,7 +1430,7 @@ class AppWindow(object): self.cooldown() logger.trace_if('capi.worker', '...done') - def journal_event(self, event): # noqa: C901, CCR001 # Currently not easily broken up. + def journal_event(self, event: str): # noqa: C901, CCR001 # Currently not easily broken up. """ Handle a Journal event passed through event queue from monitor.py. @@ -1576,7 +1558,7 @@ class AppWindow(object): logger.info('StartUp or LoadGame event') # Disable WinSparkle automatic update checks, IFF configured to do so when in-game - if config.get_int('disable_autoappupdatecheckingame') and 1: + if config.get_int('disable_autoappupdatecheckingame'): if self.updater is not None: self.updater.set_automatic_updates_check(False) @@ -1721,21 +1703,21 @@ class AppWindow(object): # Avoid file length limits if possible provider = config.get_str('shipyard_provider', default='EDSY') target = plug.invoke(provider, 'EDSY', 'shipyard_url', loadout, monitor.is_beta) - file_name = join(config.app_dir_path, "last_shipyard.html") + file_name = path.join(config.app_dir_path, "last_shipyard.html") with open(file_name, 'w') as f: - print(SHIPYARD_HTML_TEMPLATE.format( + f.write(SHIPYARD_HTML_TEMPLATE.format( link=html.escape(str(target)), provider_name=html.escape(str(provider)), ship_name=html.escape(str(shipname)) - ), file=f) + )) return f'file://localhost/{file_name}' def system_url(self, system: str) -> str | None: """Despatch a system URL to the configured handler.""" return plug.invoke( - config.get_str('system_provider'), 'EDSM', 'system_url', monitor.state['SystemName'] + config.get_str('system_provider', default='EDSM'), 'EDSM', 'system_url', monitor.state['SystemName'] ) def station_url(self, station: str) -> str | None: @@ -1749,12 +1731,9 @@ class AppWindow(object): """Display and update the cooldown timer for 'Update' button.""" if time() < self.capi_query_holdoff_time: # Update button in main window - self.button['text'] = self.theme_button['text'] \ - = _('cooldown {SS}s').format( # LANG: Cooldown on 'Update' button - SS=int(self.capi_query_holdoff_time - time()) - ) + cooldown_time = int(self.capi_query_holdoff_time - time()) + self.button['text'] = self.theme_button['text'] = _('cooldown {SS}s').format(SS=cooldown_time) self.w.after(1000, self.cooldown) - else: self.button['text'] = self.theme_button['text'] = _('Update') # LANG: Update button in main window self.button['state'] = self.theme_button['state'] = ( @@ -1775,11 +1754,10 @@ class AppWindow(object): def copy(self, event=None) -> None: """Copy system, and possible station, name to clipboard.""" if monitor.state['SystemName']: + clipboard_text = f"{monitor.state['SystemName']},{monitor.state['StationName']}" if monitor.state[ + 'StationName'] else monitor.state['SystemName'] self.w.clipboard_clear() - self.w.clipboard_append( - f"{monitor.state['SystemName']},{monitor.state['StationName']}" if monitor.state['StationName'] - else monitor.state['SystemName'] - ) + self.w.clipboard_append(clipboard_text) def help_general(self, event=None) -> None: """Open Wiki Help page in browser.""" @@ -1805,9 +1783,14 @@ class AppWindow(object): class HelpAbout(tk.Toplevel): """The applications Help > About popup.""" - showing = False + showing: bool = False - def __init__(self, parent: tk.Tk): + def __init__(self, parent: tk.Tk) -> None: + """ + Initialize the HelpAbout popup. + + :param parent: The parent Tk window. + """ if self.__class__.showing: return @@ -1848,11 +1831,11 @@ class AppWindow(object): # version tk.Label(frame).grid(row=row, column=0) # spacer row += 1 - self.appversion_label = tk.Text(frame, height=1, width=len(str(appversion())), wrap=tkc.NONE, bd=0) + self.appversion_label = tk.Text(frame, height=1, width=len(str(appversion())), wrap=tk.NONE, bd=0) self.appversion_label.insert("1.0", str(appversion())) self.appversion_label.tag_configure("center", justify="center") self.appversion_label.tag_add("center", "1.0", "end") - self.appversion_label.config(state=tkc.DISABLED, bg=frame.cget("background"), font="TkDefaultFont") + self.appversion_label.config(state=tk.DISABLED, bg=frame.cget("background"), font="TkDefaultFont") self.appversion_label.grid(row=row, column=0, sticky=tk.E) # LANG: Help > Release Notes self.appversion = HyperlinkLabel(frame, compound=tk.RIGHT, text=_('Release Notes'), @@ -2068,7 +2051,7 @@ Locale LC_TIME: {locale.getlocale(locale.LC_TIME)}''' ) -def setup_killswitches(filename: Optional[str]): +def setup_killswitches(filename: str | None): """Download and setup the main killswitch list.""" logger.debug('fetching killswitches...') if filename is not None: @@ -2130,7 +2113,7 @@ sys.path: {sys.path}''' config.delete('font_size', suppress=True) config.set('ui_scale', 100) # 100% is the default here - config.delete('geometry', suppress=True) # unset is recreated by other code + config.delete('geometry', suppress=True) # unset is recreated by other code logger.info('reset theme, transparency, font, font size, ui scale, and ui geometry to default.') @@ -2167,12 +2150,12 @@ sys.path: {sys.path}''' # # Windows 19, 1903 was build 18362 if ( - sys.platform != 'win32' - or ( - windows_ver.major == 10 - and windows_ver.build >= 18362 - ) - or windows_ver.major > 10 # Paranoid future check + sys.platform != 'win32' + or ( + windows_ver.major == 10 + and windows_ver.build >= 18362 + ) + or windows_ver.major > 10 # Paranoid future check ): # Set that same language, but utf8 encoding (it was probably cp1252 # or equivalent for other languages). @@ -2209,10 +2192,10 @@ sys.path: {sys.path}''' # logger.debug('Test from __main__') # test_logging() - class A(object): + class A: """Simple top-level class.""" - class B(object): + class B: """Simple second-level class.""" def __init__(self): @@ -2268,7 +2251,7 @@ sys.path: {sys.path}''' def messagebox_not_py3(): """Display message about plugins not updated for Python 3.x.""" plugins_not_py3_last = config.get_int('plugins_not_py3_last', default=0) - if (plugins_not_py3_last + 86400) < int(time()) and len(plug.PLUGINS_not_py3): + if (plugins_not_py3_last + 86400) < int(time()) and plug.PLUGINS_not_py3: # LANG: Popup-text about 'active' plugins without Python 3.x support popup_text = _( "One or more of your enabled plugins do not yet have support for Python 3.x. Please see the " @@ -2302,9 +2285,11 @@ sys.path: {sys.path}''' ui_transparency = 100 root.wm_attributes('-alpha', ui_transparency / 100) - + # Display message box about plugins without Python 3.x support root.after(0, messagebox_not_py3) + # Show warning popup for killswitches matching current version root.after(1, show_killswitch_poppup, root) + # Start the main event loop root.mainloop() logger.info('Exiting') From ff1f931afdd79d5b1be0a93f46ee731aacec8350 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 17 Nov 2023 18:07:37 -0500 Subject: [PATCH 41/83] [2051] EDMC Pass + Readd LANG --- EDMC.py | 74 +++++++++++++++++++++----------------------- EDMarketConnector.py | 11 +++++-- 2 files changed, 44 insertions(+), 41 deletions(-) diff --git a/EDMC.py b/EDMC.py index f56f7ead..20ad9ec8 100755 --- a/EDMC.py +++ b/EDMC.py @@ -1,6 +1,11 @@ -#!/usr/bin/env python3 -"""Command-line interface. Requires prior setup through the GUI.""" +""" +EDMC.py - Command-line interface. Requires prior setup through the GUI. +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" +from __future__ import annotations import argparse import json @@ -8,24 +13,22 @@ import locale import os import queue import sys -from os.path import getmtime from time import sleep, time -from typing import TYPE_CHECKING, Any, List, Optional +from typing import TYPE_CHECKING, Any # isort: off - os.environ["EDMC_NO_UI"] = "1" # See EDMCLogging.py docs. # workaround for https://github.com/EDCD/EDMarketConnector/issues/568 from EDMCLogging import edmclogger, logger, logging + if TYPE_CHECKING: from logging import TRACE # type: ignore # noqa: F401 # needed to make mypy happy edmclogger.set_channels_loglevel(logging.INFO) # isort: on - import collate import commodity import companion @@ -45,6 +48,8 @@ sys.path.append(config.internal_plugin_dir) # The sys.path.append has to be after `import sys` and `from config import config` # isort: off import eddn # noqa: E402 + + # isort: on @@ -66,7 +71,7 @@ EXIT_SUCCESS, EXIT_SERVER, EXIT_CREDENTIALS, EXIT_VERIFICATION, EXIT_LAGGING, EX EXIT_JOURNAL_READ_ERR, EXIT_COMMANDER_UNKNOWN = range(9) -def versioncmp(versionstring) -> List: +def versioncmp(versionstring) -> list: """Quick and dirty version comparison assuming "strict" numeric only version numbers.""" return list(map(int, versionstring.split('.'))) @@ -98,9 +103,7 @@ def deep_get(target: dict | companion.CAPIData, *args: str, default=None) -> Any res = current.get(arg) if res is None: return default - current = res - return current @@ -155,16 +158,15 @@ def main(): # noqa: C901, CCR001 args = parser.parse_args() if args.version: - updater = Updater(provider='internal') - newversion: Optional[EDMCVersion] = updater.check_appcast() + updater = Updater() + newversion: EDMCVersion | None = updater.check_appcast() if newversion: print(f'{appversion()} ({newversion.title!r} is available)') else: print(appversion()) - return - level_to_set: Optional[int] = None + level_to_set: int | None = None if args.trace or args.trace_on: level_to_set = logging.TRACE # type: ignore # it exists logger.info('Setting TRACE level debugging due to either --trace or a --trace-on') @@ -185,10 +187,10 @@ def main(): # noqa: C901, CCR001 logger.debug(f'Startup v{appversion()} : Running on Python v{sys.version}') logger.debug(f'''Platform: {sys.platform} -argv[0]: {sys.argv[0]} -exec_prefix: {sys.exec_prefix} -executable: {sys.executable} -sys.path: {sys.path}''' + argv[0]: {sys.argv[0]} + exec_prefix: {sys.exec_prefix} + executable: {sys.executable} + sys.path: {sys.path}''' ) if args.trace_on and len(args.trace_on) > 0: import config as conf_module @@ -207,12 +209,14 @@ sys.path: {sys.path}''' # system, chances are its the current locale, and not utf-8. Otherwise if it was copied, its probably # utf8. Either way, try the system FIRST because reading something like cp1251 in UTF-8 results in garbage # but the reverse results in an exception. + json_file = os.path.abspath(args.j) try: - data = json.load(open(args.j)) + with open(json_file) as file_handle: + data = json.load(file_handle) except UnicodeDecodeError: - data = json.load(open(args.j, encoding='utf-8')) - - config.set('querytime', int(getmtime(args.j))) + with open(json_file, encoding='utf-8') as file_handle: + data = json.load(file_handle) + config.set('querytime', int(os.path.getmtime(args.j))) else: # Get state from latest Journal file @@ -255,10 +259,7 @@ sys.path: {sys.path}''' for idx, cmdr in enumerate(cmdrs): if cmdr.lower() == args.p.lower(): break - - else: - raise companion.CredentialsError() - + raise companion.CredentialsError() companion.session.login(cmdrs[idx], monitor.is_beta) else: @@ -292,9 +293,7 @@ sys.path: {sys.path}''' logger.trace_if('capi.worker', f'Failed Request: {capi_response.message}') if capi_response.exception: raise capi_response.exception - - else: - raise ValueError(capi_response.message) + raise ValueError(capi_response.message) logger.trace_if('capi.worker', 'Answer is not a Failure') if not isinstance(capi_response, companion.EDMCCAPIResponse): @@ -366,20 +365,19 @@ sys.path: {sys.path}''' else: print(deep_get(data, 'lastSystem', 'name', default='Unknown')) - if (args.m or args.o or args.s or args.n or args.j): + if args.m or args.o or args.s or args.n or args.j: if not data['commander'].get('docked'): logger.error("Can't use -m, -o, -s, -n or -j because you're not currently docked!") return - elif not deep_get(data, 'lastStarport', 'name'): + if not deep_get(data, 'lastStarport', 'name'): logger.error("No data['lastStarport']['name'] from CAPI") sys.exit(EXIT_LAGGING) # Ignore possibly missing shipyard info - elif not (data['lastStarport'].get('commodities') or data['lastStarport'].get('modules')): + if not (data['lastStarport'].get('commodities') or data['lastStarport'].get('modules')): logger.error("No commodities or outfitting (modules) in CAPI data") return - else: return @@ -410,8 +408,8 @@ sys.path: {sys.path}''' else: logger.error("Station doesn't supply outfitting") - if (args.s or args.n) and not args.j and not \ - data['lastStarport'].get('ships') and data['lastStarport']['services'].get('shipyard'): + if ((args.s or args.n) and not args.j and not data['lastStarport'].get('ships') + and data['lastStarport']['services'].get('shipyard')): # Retry for shipyard sleep(SERVER_RETRY) @@ -462,14 +460,14 @@ sys.path: {sys.path}''' except Exception: logger.exception('Failed to send data to EDDN') - except companion.ServerError: - logger.exception('Frontier CAPI Server returned an error') - sys.exit(EXIT_SERVER) - except companion.ServerConnectionError: logger.exception('Exception while contacting server') sys.exit(EXIT_SERVER) + except companion.ServerError: + logger.exception('Frontier CAPI Server returned an error') + sys.exit(EXIT_SERVER) + except companion.CredentialsError: logger.error('Frontier CAPI Server: Invalid Credentials') sys.exit(EXIT_CREDENTIALS) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 411eefce..21f9708c 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -1007,19 +1007,24 @@ class AppWindow: commodities_flag = config.OUT_MKT_CSV | config.OUT_MKT_TD if output_flags & config.OUT_STATION_ANY: - if not is_docked and not monitor.state['OnFoot']: + if not is_docked and not monitor.state['OnFoot'] and not self.status['text']: # Signal as error because the user might actually be docked # but the server hosting the Companion API hasn't caught up + # LANG: Player is not docked at a station, when we expect them to be self._handle_status(_("You're not docked at a station!")) return False - if output_flags & config.OUT_EDDN_SEND_STATION_DATA and not (has_commodities or has_modules): + # Ignore possibly missing shipyard info + if output_flags & config.OUT_EDDN_SEND_STATION_DATA and not (has_commodities or has_modules) and not self.status['text']: + # LANG: Status - Either no market or no modules data for station from Frontier CAPI self._handle_status(_("Station doesn't have anything!")) - elif not has_commodities: + elif not has_commodities and not self.status['text']: + # LANG: Status - No station market data from Frontier CAPI self._handle_status(_("Station doesn't have a market!")) elif output_flags & commodities_flag: + # Fixup anomalies in the comodity data fixed = companion.fixup(data) if output_flags & config.OUT_MKT_CSV: commodity.export(fixed, COMMODITY_CSV) From acfe9f2717e54d39d478beaedc1d3324daf03ba0 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 17 Nov 2023 18:09:09 -0500 Subject: [PATCH 42/83] [2051] Wait we did account for that --- EDMarketConnector.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 21f9708c..00c42a69 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -1007,7 +1007,7 @@ class AppWindow: commodities_flag = config.OUT_MKT_CSV | config.OUT_MKT_TD if output_flags & config.OUT_STATION_ANY: - if not is_docked and not monitor.state['OnFoot'] and not self.status['text']: + if not is_docked and not monitor.state['OnFoot']: # Signal as error because the user might actually be docked # but the server hosting the Companion API hasn't caught up # LANG: Player is not docked at a station, when we expect them to be @@ -1015,11 +1015,11 @@ class AppWindow: return False # Ignore possibly missing shipyard info - if output_flags & config.OUT_EDDN_SEND_STATION_DATA and not (has_commodities or has_modules) and not self.status['text']: + if output_flags & config.OUT_EDDN_SEND_STATION_DATA and not (has_commodities or has_modules): # LANG: Status - Either no market or no modules data for station from Frontier CAPI self._handle_status(_("Station doesn't have anything!")) - elif not has_commodities and not self.status['text']: + elif not has_commodities: # LANG: Status - No station market data from Frontier CAPI self._handle_status(_("Station doesn't have a market!")) From 32cba245cd7d0c5b6b2ee7b887f9e194a92ac909 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 17 Nov 2023 18:14:25 -0500 Subject: [PATCH 43/83] [2051] Redo the Time Block --- EDMarketConnector.py | 43 +++++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 00c42a69..d5df29a0 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -1108,28 +1108,31 @@ class AppWindow: self.login() return - if not companion.session.retrying and time() >= self.capi_query_holdoff_time: - if play_sound: - if time() < self.capi_query_holdoff_time: # Was invoked by key while in cooldown - if (self.capi_query_holdoff_time - time()) < companion.capi_query_cooldown * 0.75: - self.status['text'] = '' - hotkeymgr.play_bad() # Don't play sound in first few seconds to prevent repeats - else: - hotkeymgr.play_good() + if not companion.session.retrying: + if time() < self.capi_query_holdoff_time: + # Invoked by key while in cooldown + time_remaining = self.capi_query_holdoff_time - time() + if play_sound and time_remaining < companion.capi_query_cooldown * 0.75: + self.status['text'] = '' + hotkeymgr.play_bad() + return + elif play_sound: + hotkeymgr.play_good() - # LANG: Status - Attempting to retrieve data from Frontier CAPI - self.status['text'] = _('Fetching data...') - self.button['state'] = self.theme_button['state'] = tk.DISABLED - self.w.update_idletasks() + # LANG: Status - Attempting to retrieve data from Frontier CAPI + self.status['text'] = _('Fetching data...') + self.button['state'] = self.theme_button['state'] = tk.DISABLED + self.w.update_idletasks() - query_time = int(time()) - logger.trace_if('capi.worker', 'Requesting full station data') - config.set('querytime', query_time) - logger.trace_if('capi.worker', 'Calling companion.session.station') - companion.session.station( - query_time=query_time, tk_response_event=self._CAPI_RESPONSE_TK_EVENT_NAME, - play_sound=play_sound - ) + query_time = int(time()) + logger.trace_if('capi.worker', 'Requesting full station data') + config.set('querytime', query_time) + logger.trace_if('capi.worker', 'Calling companion.session.station') + + companion.session.station( + query_time=query_time, tk_response_event=self._CAPI_RESPONSE_TK_EVENT_NAME, + play_sound=play_sound + ) def capi_request_fleetcarrier_data(self, event=None) -> None: """ From c47552d6781b0fe35252d5f408060297f43650e8 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 17 Nov 2023 18:28:11 -0500 Subject: [PATCH 44/83] [2051] Revert Bool Check --- EDMarketConnector.py | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index d5df29a0..6bab851a 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -1166,19 +1166,22 @@ class AppWindow: self.status['text'] = _('CAPI query aborted: GameVersion unknown') return - if not companion.session.retrying and time() >= self.capi_fleetcarrier_query_holdoff_time: + if not companion.session.retrying: + if time() < self.capi_fleetcarrier_query_holdoff_time: # Was invoked while in cooldown + logger.debug('CAPI fleetcarrier query aborted, too soon since last request') + return # LANG: Status - Attempting to retrieve data from Frontier CAPI self.status['text'] = _('Fetching data...') self.w.update_idletasks() - query_time = int(time()) - logger.trace_if('capi.worker', 'Requesting fleetcarrier data') - config.set('fleetcarrierquerytime', query_time) - logger.trace_if('capi.worker', 'Calling companion.session.fleetcarrier') - companion.session.fleetcarrier( - query_time=query_time, tk_response_event=self._CAPI_RESPONSE_TK_EVENT_NAME - ) + query_time = int(time()) + logger.trace_if('capi.worker', 'Requesting fleetcarrier data') + config.set('fleetcarrierquerytime', query_time) + logger.trace_if('capi.worker', 'Calling companion.session.fleetcarrier') + companion.session.fleetcarrier( + query_time=query_time, tk_response_event=self._CAPI_RESPONSE_TK_EVENT_NAME + ) def capi_handle_response(self, event=None): # noqa: C901, CCR001 """ @@ -1274,7 +1277,7 @@ class AppWindow: f"{monitor.state['SystemName']!r}") raise companion.ServerLagging() - if capi_response.capi_data['lastStarport']['name'] != monitor.state['StationName']: + elif capi_response.capi_data['lastStarport']['name'] != monitor.state['StationName']: if monitor.state['OnFoot'] and monitor.state['StationName']: logger.warning(f"({capi_response.capi_data['lastStarport']['name']!r} != " f"{monitor.state['StationName']!r}) AND " From 960b00efbc64508d47bc70c5b7f60734d7b5b1d7 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 17 Nov 2023 18:35:32 -0500 Subject: [PATCH 45/83] [2051] We need that else --- EDMC.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/EDMC.py b/EDMC.py index 20ad9ec8..df203008 100755 --- a/EDMC.py +++ b/EDMC.py @@ -259,7 +259,8 @@ def main(): # noqa: C901, CCR001 for idx, cmdr in enumerate(cmdrs): if cmdr.lower() == args.p.lower(): break - raise companion.CredentialsError() + else: + raise companion.CredentialsError() companion.session.login(cmdrs[idx], monitor.is_beta) else: From 95c73179c650d6956408098a24bb273079853600 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 17 Nov 2023 18:39:47 -0500 Subject: [PATCH 46/83] [2051] Logging File Check --- EDMCLogging.py | 26 +++++++++----------------- 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/EDMCLogging.py b/EDMCLogging.py index e698b35b..74b439f9 100644 --- a/EDMCLogging.py +++ b/EDMCLogging.py @@ -34,6 +34,7 @@ To utilise logging in a 'found' (third-party) plugin, include this: # See, plug.py:load_plugins() logger = logging.getLogger(f'{appname}.{plugin_name}') """ +from __future__ import annotations import inspect import logging @@ -48,7 +49,7 @@ from sys import _getframe as getframe from threading import get_native_id as thread_native_id from time import gmtime from traceback import print_exc -from typing import TYPE_CHECKING, Tuple, cast +from typing import TYPE_CHECKING, cast import config as config_mod from config import appcmdname, appname, config @@ -122,7 +123,6 @@ if TYPE_CHECKING: def trace(self, message, *args, **kwargs) -> None: """See implementation above.""" - ... def trace_if(self, condition: str, message, *args, **kwargs) -> None: """ @@ -130,7 +130,6 @@ if TYPE_CHECKING: See implementation above. """ - ... class Logger: @@ -183,18 +182,12 @@ class Logger: # rotated versions. # This is {logger_name} so that EDMC.py logs to a different file. logfile_rotating = pathlib.Path(tempfile.gettempdir()) - logfile_rotating = logfile_rotating / f'{appname}' + logfile_rotating /= f'{appname}' logfile_rotating.mkdir(exist_ok=True) - logfile_rotating = logfile_rotating / f'{logger_name}-debug.log' + logfile_rotating /= f'{logger_name}-debug.log' - self.logger_channel_rotating = logging.handlers.RotatingFileHandler( - logfile_rotating, - mode='a', - maxBytes=1024 * 1024, # 1MiB - backupCount=10, - encoding='utf-8', - delay=False - ) + self.logger_channel_rotating = logging.handlers.RotatingFileHandler(logfile_rotating, maxBytes=1024 * 1024, + backupCount=10, encoding='utf-8') # Yes, we always want these rotated files to be at TRACE level self.logger_channel_rotating.setLevel(logging.TRACE) # type: ignore self.logger_channel_rotating.setFormatter(self.logger_formatter) @@ -325,7 +318,7 @@ class EDMCContextFilter(logging.Filter): return True @classmethod - def caller_attributes(cls, module_name: str = '') -> Tuple[str, str, str]: # noqa: CCR001, E501, C901 # this is as refactored as is sensible + def caller_attributes(cls, module_name: str = '') -> tuple[str, str, str]: # noqa: CCR001, E501, C901 # this is as refactored as is sensible """ Determine extra or changed fields for the caller. @@ -535,9 +528,8 @@ def get_main_logger(sublogger_name: str = '') -> 'LoggerMixin': if not os.getenv("EDMC_NO_UI"): # GUI app being run return cast('LoggerMixin', logging.getLogger(appname)) - else: - # Must be the CLI - return cast('LoggerMixin', logging.getLogger(appcmdname)) + # Must be the CLI + return cast('LoggerMixin', logging.getLogger(appcmdname)) # Singleton From 45a38ccdaab18ed81a9af72216a67d456dde0788 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 17 Nov 2023 19:21:48 -0500 Subject: [PATCH 47/83] [2051] Dashboard, Killswitch, l10n --- dashboard.py | 56 +++++++++------------ killswitch.py | 78 +++++++++++++++-------------- l10n.py | 136 +++++++++++++++++++++++++------------------------- 3 files changed, 133 insertions(+), 137 deletions(-) diff --git a/dashboard.py b/dashboard.py index 715fd230..3c1c7e5f 100644 --- a/dashboard.py +++ b/dashboard.py @@ -1,32 +1,31 @@ -"""Handle the game Status.json file.""" +""" +dashboard.py - Handle the game Status.json file. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" +from __future__ import annotations import json -import pathlib import sys import time import tkinter as tk -from calendar import timegm -from os.path import getsize, isdir, isfile -from typing import Any, Dict, Optional, cast - +from os.path import getsize, isdir, isfile, join +from typing import Any, cast from watchdog.observers.api import BaseObserver - from config import config from EDMCLogging import get_main_logger logger = get_main_logger() -if sys.platform == 'darwin': +if sys.platform in ('darwin', 'win32'): from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer - -elif sys.platform == 'win32': - from watchdog.events import FileSystemEventHandler - from watchdog.observers import Observer - else: # Linux's inotify doesn't work over CIFS or NFS, so poll - FileSystemEventHandler = object # dummy + class FileSystemEventHandler: # type: ignore + """Dummy class to represent a file system event handler on platforms other than macOS and Windows.""" class Dashboard(FileSystemEventHandler): @@ -39,9 +38,9 @@ class Dashboard(FileSystemEventHandler): self.session_start: int = int(time.time()) self.root: tk.Tk = None # type: ignore self.currentdir: str = None # type: ignore # The actual logdir that we're monitoring - self.observer: Optional[Observer] = None # type: ignore + self.observer: Observer | None = None # type: ignore self.observed = None # a watchdog ObservedWatch, or None if polling - self.status: Dict[str, Any] = {} # Current status for communicating status back to main thread + self.status: dict[str, Any] = {} # Current status for communicating status back to main thread def start(self, root: tk.Tk, started: int) -> bool: """ @@ -56,10 +55,8 @@ class Dashboard(FileSystemEventHandler): self.session_start = started logdir = config.get_str('journaldir', default=config.default_journal_dir) - if logdir == '': - logdir = config.default_journal_dir - - if not logdir or not isdir(logdir): + logdir = logdir or config.default_journal_dir + if not isdir(logdir): logger.info(f"No logdir, or it isn't a directory: {logdir=}") self.stop() return False @@ -74,7 +71,7 @@ class Dashboard(FileSystemEventHandler): # File system events are unreliable/non-existent over network drives on Linux. # We can't easily tell whether a path points to a network drive, so assume # any non-standard logdir might be on a network drive and poll instead. - if not (sys.platform != 'win32') and not self.observer: + if sys.platform == 'win32' and not self.observer: logger.debug('Setting up observer...') self.observer = Observer() self.observer.daemon = True @@ -87,7 +84,7 @@ class Dashboard(FileSystemEventHandler): self.observer = None # type: ignore logger.debug('Done') - if not self.observed and not (sys.platform != 'win32'): + if not self.observed and sys.platform == 'win32': logger.debug('Starting observer...') self.observed = cast(BaseObserver, self.observer).schedule(self, self.currentdir) logger.debug('Done') @@ -178,22 +175,17 @@ class Dashboard(FileSystemEventHandler): """ if config.shutting_down: return - try: - with (pathlib.Path(self.currentdir) / 'Status.json').open('rb') as h: + status_json_path = join(self.currentdir, 'Status.json') + with open(status_json_path, 'rb') as h: data = h.read().strip() - if data: # Can be empty if polling while the file is being re-written entry = json.loads(data) - - # Status file is shared between beta and live. So filter out status not in this game session. - if ( - timegm(time.strptime(entry['timestamp'], '%Y-%m-%dT%H:%M:%SZ')) >= self.session_start - and self.status != entry - ): + # Status file is shared between beta and live. Filter out status not in this game session. + entry_timestamp = time.mktime(time.strptime(entry['timestamp'], '%Y-%m-%dT%H:%M:%SZ')) + if entry_timestamp >= self.session_start and self.status != entry: self.status = entry self.root.event_generate('<>', when="tail") - except Exception: logger.exception('Processing Status.json') diff --git a/killswitch.py b/killswitch.py index 42d02844..9cc407a6 100644 --- a/killswitch.py +++ b/killswitch.py @@ -1,18 +1,22 @@ -"""Fetch kill switches from EDMC Repo.""" +""" +killswitch.py - Fetch kill switches from EDMC Repo. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" from __future__ import annotations import json import threading from copy import deepcopy from typing import ( - TYPE_CHECKING, Any, Callable, Dict, List, Mapping, MutableMapping, MutableSequence, NamedTuple, Optional, Sequence, - Tuple, TypedDict, TypeVar, Union, cast + TYPE_CHECKING, Any, Callable, Mapping, MutableMapping, MutableSequence, NamedTuple, Sequence, + TypedDict, TypeVar, cast, Union ) - import requests import semantic_version from semantic_version.base import Version - import config import EDMCLogging @@ -21,7 +25,7 @@ logger = EDMCLogging.get_main_logger() OLD_KILLSWITCH_URL = 'https://raw.githubusercontent.com/EDCD/EDMarketConnector/releases/killswitches.json' DEFAULT_KILLSWITCH_URL = 'https://raw.githubusercontent.com/EDCD/EDMarketConnector/releases/killswitches_v2.json' CURRENT_KILLSWITCH_VERSION = 2 -UPDATABLE_DATA = Union[Mapping, Sequence] +UPDATABLE_DATA = Union[Mapping, Sequence] # Have to keep old-style _current_version: semantic_version.Version = config.appversion_nobuild() T = TypeVar('T', bound=UPDATABLE_DATA) @@ -32,13 +36,13 @@ class SingleKill(NamedTuple): match: str reason: str - redact_fields: Optional[List[str]] = None - delete_fields: Optional[List[str]] = None - set_fields: Optional[Dict[str, Any]] = None + redact_fields: list[str] | None = None + delete_fields: list[str] | None = None + set_fields: dict[str, Any] | None = None @property def has_rules(self) -> bool: - """Return whether or not this SingleKill can apply rules to a dict to make it safe to use.""" + """Return whether this SingleKill can apply rules to a dict to make it safe to use.""" return any(x is not None for x in (self.redact_fields, self.delete_fields, self.set_fields)) def apply_rules(self, target: T) -> T: @@ -119,9 +123,9 @@ def _deep_apply(target: UPDATABLE_DATA, path: str, to_set=None, delete=False): # it exists on this level, dont go further break - elif isinstance(current, Mapping) and any('.' in k and path.startswith(k) for k in current.keys()): + if isinstance(current, Mapping) and any('.' in k and path.startswith(k) for k in current.keys()): # there is a dotted key in here that can be used for this - # if theres a dotted key in here (must be a mapping), use that if we can + # if there's a dotted key in here (must be a mapping), use that if we can keys = current.keys() for k in filter(lambda x: '.' in x, keys): @@ -140,7 +144,7 @@ def _deep_apply(target: UPDATABLE_DATA, path: str, to_set=None, delete=False): key, _, path = path.partition('.') if isinstance(current, Mapping): - current = current[key] # type: ignore # I really dont know at this point what you want from me mypy. + current = current[key] # type: ignore # I really don't know at this point what you want from me mypy. elif isinstance(current, Sequence): target_idx = _get_int(key) # mypy is broken. doesn't like := here. @@ -155,7 +159,7 @@ def _deep_apply(target: UPDATABLE_DATA, path: str, to_set=None, delete=False): _apply(current, path, to_set, delete) -def _get_int(s: str) -> Optional[int]: +def _get_int(s: str) -> int | None: try: return int(s) except ValueError: @@ -166,7 +170,7 @@ class KillSwitches(NamedTuple): """One version's set of kill switches.""" version: semantic_version.SimpleSpec - kills: Dict[str, SingleKill] + kills: dict[str, SingleKill] @staticmethod def from_dict(data: KillSwitchSetJSON) -> KillSwitches: @@ -189,7 +193,7 @@ class DisabledResult(NamedTuple): """DisabledResult is the result returned from various is_disabled calls.""" disabled: bool - kill: Optional[SingleKill] + kill: SingleKill | None @property def reason(self) -> str: @@ -197,11 +201,11 @@ class DisabledResult(NamedTuple): return self.kill.reason if self.kill is not None else "" def has_kill(self) -> bool: - """Return whether or not this DisabledResult has a Kill associated with it.""" + """Return whether this DisabledResult has a Kill associated with it.""" return self.kill is not None def has_rules(self) -> bool: - """Return whether or not the kill on this Result contains rules.""" + """Return whether the kill on this Result contains rules.""" # HACK: 2021-07-09 # Python/mypy/pyright does not support type guards like this yet. self.kill will always # be non-None at the point it is evaluated return self.has_kill() and self.kill.has_rules # type: ignore @@ -210,12 +214,12 @@ class DisabledResult(NamedTuple): class KillSwitchSet: """Queryable set of kill switches.""" - def __init__(self, kill_switches: List[KillSwitches]) -> None: + def __init__(self, kill_switches: list[KillSwitches]) -> None: self.kill_switches = kill_switches def get_disabled(self, id: str, *, version: Union[Version, str] = _current_version) -> DisabledResult: """ - Return whether or not the given feature ID is disabled by a killswitch for the given version. + Return whether the given feature ID is disabled by a killswitch for the given version. :param id: The feature ID to check :param version: The version to check killswitches for, defaults to the @@ -234,14 +238,14 @@ class KillSwitchSet: return DisabledResult(False, None) def is_disabled(self, id: str, *, version: semantic_version.Version = _current_version) -> bool: - """Return whether or not a given feature ID is disabled for the given version.""" + """Return whether a given feature ID is disabled for the given version.""" return self.get_disabled(id, version=version).disabled def get_reason(self, id: str, version: semantic_version.Version = _current_version) -> str: """Return a reason for why the given id is disabled for the given version, if any.""" return self.get_disabled(id, version=version).reason - def kills_for_version(self, version: semantic_version.Version = _current_version) -> List[KillSwitches]: + def kills_for_version(self, version: semantic_version.Version = _current_version) -> list[KillSwitches]: """ Get all killswitch entries that apply to the given version. @@ -252,9 +256,9 @@ class KillSwitchSet: def check_killswitch( self, name: str, data: T, log=logger, version=_current_version - ) -> Tuple[bool, T]: + ) -> tuple[bool, T]: """ - Check whether or not a killswitch is enabled. If it is, apply rules if any. + Check whether a killswitch is enabled. If it is, apply rules if any. :param name: The killswitch to check :param data: The data to modify if needed @@ -283,7 +287,7 @@ class KillSwitchSet: log.info('Rules applied successfully, allowing execution to continue') return False, new_data - def check_multiple_killswitches(self, data: T, *names: str, log=logger, version=_current_version) -> Tuple[bool, T]: + def check_multiple_killswitches(self, data: T, *names: str, log=logger, version=_current_version) -> tuple[bool, T]: """ Check multiple killswitches in order. @@ -323,16 +327,16 @@ class SingleKillSwitchJSON(BaseSingleKillSwitch, total=False): # noqa: D101 class KillSwitchSetJSON(TypedDict): # noqa: D101 version: str - kills: Dict[str, SingleKillSwitchJSON] + kills: dict[str, SingleKillSwitchJSON] class KillSwitchJSONFile(TypedDict): # noqa: D101 version: int last_updated: str - kill_switches: List[KillSwitchSetJSON] + kill_switches: list[KillSwitchSetJSON] -def fetch_kill_switches(target=DEFAULT_KILLSWITCH_URL) -> Optional[KillSwitchJSONFile]: +def fetch_kill_switches(target=DEFAULT_KILLSWITCH_URL) -> KillSwitchJSONFile | None: """ Fetch the JSON representation of our kill switches. @@ -343,7 +347,7 @@ def fetch_kill_switches(target=DEFAULT_KILLSWITCH_URL) -> Optional[KillSwitchJSO if target.startswith('file:'): target = target.replace('file:', '') try: - with open(target, 'r') as t: + with open(target) as t: return json.load(t) except FileNotFoundError: @@ -366,13 +370,13 @@ def fetch_kill_switches(target=DEFAULT_KILLSWITCH_URL) -> Optional[KillSwitchJSO class _KillSwitchV1(TypedDict): version: str - kills: Dict[str, str] + kills: dict[str, str] class _KillSwitchJSONFileV1(TypedDict): version: int last_updated: str - kill_switches: List[_KillSwitchV1] + kill_switches: list[_KillSwitchV1] def _upgrade_kill_switch_dict(data: KillSwitchJSONFile) -> KillSwitchJSONFile: @@ -402,7 +406,7 @@ def _upgrade_kill_switch_dict(data: KillSwitchJSONFile) -> KillSwitchJSONFile: raise ValueError(f'Unknown Killswitch version {data["version"]}') -def parse_kill_switches(data: KillSwitchJSONFile) -> List[KillSwitches]: +def parse_kill_switches(data: KillSwitchJSONFile) -> list[KillSwitches]: """ Parse kill switch dict to List of KillSwitches. @@ -431,7 +435,7 @@ def parse_kill_switches(data: KillSwitchJSONFile) -> List[KillSwitches]: return out -def get_kill_switches(target=DEFAULT_KILLSWITCH_URL, fallback: Optional[str] = None) -> Optional[KillSwitchSet]: +def get_kill_switches(target=DEFAULT_KILLSWITCH_URL, fallback: str | None = None) -> KillSwitchSet | None: """ Get a kill switch set object. @@ -451,7 +455,7 @@ def get_kill_switches(target=DEFAULT_KILLSWITCH_URL, fallback: Optional[str] = N def get_kill_switches_thread( - target, callback: Callable[[Optional[KillSwitchSet]], None], fallback: Optional[str] = None, + target, callback: Callable[[KillSwitchSet | None], None], fallback: str | None = None, ) -> None: """ Threaded version of get_kill_switches. Request is performed off thread, and callback is called when it is available. @@ -469,7 +473,7 @@ def get_kill_switches_thread( active: KillSwitchSet = KillSwitchSet([]) -def setup_main_list(filename: Optional[str]): +def setup_main_list(filename: str | None): """ Set up the global set of kill switches for querying. @@ -498,7 +502,7 @@ def get_disabled(id: str, *, version: semantic_version.Version = _current_versio return active.get_disabled(id, version=version) -def check_killswitch(name: str, data: T, log=logger) -> Tuple[bool, T]: +def check_killswitch(name: str, data: T, log=logger) -> tuple[bool, T]: """Query the global KillSwitchSet#check_killswitch method.""" return active.check_killswitch(name, data, log) @@ -518,6 +522,6 @@ def get_reason(id: str, *, version: semantic_version.Version = _current_version) return active.get_reason(id, version=version) -def kills_for_version(version: semantic_version.Version = _current_version) -> List[KillSwitches]: +def kills_for_version(version: semantic_version.Version = _current_version) -> list[KillSwitches]: """Query the global KillSwitchSet for kills matching a particular version.""" return active.kills_for_version(version) diff --git a/l10n.py b/l10n.py index e2c1143f..fc144b77 100755 --- a/l10n.py +++ b/l10n.py @@ -1,18 +1,27 @@ -#!/usr/bin/env python3 -"""Localization with gettext is a pain on non-Unix systems. Use OSX-style strings files instead.""" +""" +l10n.py - Localize using OSX-Style Strings. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. + +Localization with gettext is a pain on non-Unix systems. +""" +from __future__ import annotations import builtins import locale import numbers -import os -import pathlib import re import sys import warnings from collections import OrderedDict from contextlib import suppress -from os.path import basename, dirname, isdir, isfile, join -from typing import TYPE_CHECKING, Dict, Iterable, Optional, Set, TextIO, Union, cast +from os import pardir, listdir, sep, makedirs +from os.path import basename, dirname, isdir, isfile, join, abspath, exists +from typing import TYPE_CHECKING, Iterable, TextIO, cast +from config import config +from EDMCLogging import get_main_logger if TYPE_CHECKING: def _(x: str) -> str: ... @@ -20,22 +29,16 @@ if TYPE_CHECKING: # Note that this is also done in EDMarketConnector.py, and thus removing this here may not have a desired effect try: locale.setlocale(locale.LC_ALL, '') - except Exception: # Locale env variables incorrect or locale package not installed/configured on Linux, mysterious reasons on Windows print("Can't set locale!") -from config import config -from EDMCLogging import get_main_logger - logger = get_main_logger() - # Language name LANGUAGE_ID = '!Language' LOCALISATION_DIR = 'L10n' - if sys.platform == 'darwin': from Foundation import ( # type: ignore # exists on Darwin NSLocale, NSNumberFormatter, NSNumberFormatterDecimalStyle @@ -68,11 +71,11 @@ class _Translations: FALLBACK = 'en' # strings in this code are in English FALLBACK_NAME = 'English' - TRANS_RE = re.compile(r'\s*"((?:[^"]|(?:\"))+)"\s*=\s*"((?:[^"]|(?:\"))+)"\s*;\s*$') + TRANS_RE = re.compile(r'\s*"((?:[^"]|\")+)"\s*=\s*"((?:[^"]|\")+)"\s*;\s*$') COMMENT_RE = re.compile(r'\s*/\*.*\*/\s*$') def __init__(self) -> None: - self.translations: Dict[Optional[str], Dict[str, str]] = {None: {}} + self.translations: dict[str | None, dict[str, str]] = {None: {}} def install_dummy(self) -> None: """ @@ -112,7 +115,7 @@ class _Translations: return self.translations = {None: self.contents(cast(str, lang))} - for plugin in os.listdir(config.plugin_dir_path): + for plugin in listdir(config.plugin_dir_path): plugin_path = join(config.plugin_dir_path, plugin, LOCALISATION_DIR) if isdir(plugin_path): try: @@ -126,7 +129,7 @@ class _Translations: builtins.__dict__['_'] = self.translate - def contents(self, lang: str, plugin_path: Optional[str] = None) -> Dict[str, str]: + def contents(self, lang: str, plugin_path: str | None = None) -> dict[str, str]: """Load all the translations from a translation file.""" assert lang in self.available() translations = {} @@ -151,7 +154,7 @@ class _Translations: return translations - def translate(self, x: str, context: Optional[str] = None) -> str: + def translate(self, x: str, context: str | None = None) -> str: """ Translate the given string to the current lang. @@ -161,7 +164,7 @@ class _Translations: """ if context: # TODO: There is probably a better way to go about this now. - context = context[len(config.plugin_dir)+1:].split(os.sep)[0] + context = context[len(config.plugin_dir)+1:].split(sep)[0] if self.translations[None] and context not in self.translations: logger.debug(f'No translations for {context!r}') @@ -172,23 +175,23 @@ class _Translations: return self.translations[None].get(x) or str(x).replace(r'\"', '"').replace('{CR}', '\n') - def available(self) -> Set[str]: + def available(self) -> set[str]: """Return a list of available language codes.""" path = self.respath() if getattr(sys, 'frozen', False) and sys.platform == 'darwin': available = { - x[:-len('.lproj')] for x in os.listdir(path) + x[:-len('.lproj')] for x in listdir(path) if x.endswith('.lproj') and isfile(join(x, 'Localizable.strings')) } else: - available = {x[:-len('.strings')] for x in os.listdir(path) if x.endswith('.strings')} + available = {x[:-len('.strings')] for x in listdir(path) if x.endswith('.strings')} return available - def available_names(self) -> Dict[Optional[str], str]: + def available_names(self) -> dict[str | None, str]: """Available language names by code.""" - names: Dict[Optional[str], str] = OrderedDict([ + names: dict[str | None, str] = OrderedDict([ # LANG: The system default language choice in Settings > Appearance (None, _('Default')), # Appearance theme and language setting ]) @@ -200,20 +203,20 @@ class _Translations: return names - def respath(self) -> pathlib.Path: + def respath(self) -> str: """Path to localisation files.""" if getattr(sys, 'frozen', False): if sys.platform == 'darwin': - return (pathlib.Path(sys.executable).parents[0] / os.pardir / 'Resources').resolve() + return abspath(join(dirname(sys.executable), pardir, 'Resources')) - return pathlib.Path(dirname(sys.executable)) / LOCALISATION_DIR + return abspath(join(dirname(sys.executable), LOCALISATION_DIR)) - elif __file__: - return pathlib.Path(__file__).parents[0] / LOCALISATION_DIR + if __file__: + return abspath(join(dirname(__file__), LOCALISATION_DIR)) - return pathlib.Path(LOCALISATION_DIR) + return abspath(LOCALISATION_DIR) - def file(self, lang: str, plugin_path: Optional[str] = None) -> Optional[TextIO]: + def file(self, lang: str, plugin_path: str | None = None) -> TextIO | None: """ Open the given lang file for reading. @@ -222,20 +225,21 @@ class _Translations: :return: the opened file (Note: This should be closed when done) """ if plugin_path: - f = pathlib.Path(plugin_path) / f'{lang}.strings' - if not f.exists(): + file_path = join(plugin_path, f'{lang}.strings') + if not exists(file_path): return None try: - return f.open('r', encoding='utf-8') - + return open(file_path, encoding='utf-8') except OSError: - logger.exception(f'could not open {f}') + logger.exception(f'could not open {file_path}') elif getattr(sys, 'frozen', False) and sys.platform == 'darwin': - return (self.respath() / f'{lang}.lproj' / 'Localizable.strings').open('r', encoding='utf-16') + res_path = join(self.respath(), f'{lang}.lproj', 'Localizable.strings') + return open(res_path, encoding='utf-16') - return (self.respath() / f'{lang}.strings').open('r', encoding='utf-8') + res_path = join(self.respath(), f'{lang}.strings') + return open(res_path, encoding='utf-8') class _Locale: @@ -250,11 +254,11 @@ class _Locale: self.float_formatter.setMinimumFractionDigits_(5) self.float_formatter.setMaximumFractionDigits_(5) - def stringFromNumber(self, number: Union[float, int], decimals: int | None = None) -> str: # noqa: N802 + def stringFromNumber(self, number: float | int, decimals: int | None = None) -> str: # noqa: N802 warnings.warn(DeprecationWarning('use _Locale.string_from_number instead.')) return self.string_from_number(number, decimals) # type: ignore - def numberFromString(self, string: str) -> Union[int, float, None]: # noqa: N802 + def numberFromString(self, string: str) -> int | float | None: # noqa: N802 warnings.warn(DeprecationWarning('use _Locale.number_from_string instead.')) return self.number_from_string(string) @@ -262,7 +266,7 @@ class _Locale: warnings.warn(DeprecationWarning('use _Locale.preferred_languages instead.')) return self.preferred_languages() - def string_from_number(self, number: Union[float, int], decimals: int = 5) -> str: + def string_from_number(self, number: float | int, decimals: int = 5) -> str: """ Convert a number to a string. @@ -285,11 +289,9 @@ class _Locale: if not decimals and isinstance(number, numbers.Integral): return locale.format_string('%d', number, True) + return locale.format_string('%.*f', (decimals, number), True) - else: - return locale.format_string('%.*f', (decimals, number), True) - - def number_from_string(self, string: str) -> Union[int, float, None]: + def number_from_string(self, string: str) -> int | float | None: """ Convert a string to a number using the system locale. @@ -308,7 +310,17 @@ class _Locale: return None - def preferred_languages(self) -> Iterable[str]: # noqa: CCR001 + 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. @@ -326,32 +338,21 @@ class _Locale: elif sys.platform != 'win32': # POSIX lang = locale.getlocale()[0] - languages = lang and [lang.replace('_', '-')] or [] + languages = [lang.replace('_', '-')] if lang else [] else: - def wszarray_to_list(array): - offset = 0 - while offset < len(array): - sz = ctypes.wstring_at(ctypes.addressof(array) + offset*2) - if sz: - yield sz - offset += len(sz)+1 - - else: - break - num = ctypes.c_ulong() size = ctypes.c_ulong(0) languages = [] if GetUserPreferredUILanguages( - MUI_LANGUAGE_NAME, ctypes.byref(num), None, ctypes.byref(size) + 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) + MUI_LANGUAGE_NAME, ctypes.byref(num), ctypes.byref(buf), ctypes.byref(size) ): - languages = wszarray_to_list(buf) + languages = self.wszarray_to_list(buf) # 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 @@ -369,14 +370,13 @@ Translations = _Translations() # generate template strings file - like xgettext # parsing is limited - only single ' or " delimited strings, and only one string per line if __name__ == "__main__": - import re regexp = re.compile(r'''_\([ur]?(['"])(((? Date: Fri, 17 Nov 2023 19:44:36 -0500 Subject: [PATCH 48/83] [2051] And a few more, with timezones --- dashboard.py | 3 +- loadout.py | 34 ++++++++++--------- protocol.py | 79 ++++++++++++++++++++++++++++---------------- ttkHyperlinkLabel.py | 53 ++++++++++++++++++----------- 4 files changed, 105 insertions(+), 64 deletions(-) diff --git a/dashboard.py b/dashboard.py index 3c1c7e5f..1f95a943 100644 --- a/dashboard.py +++ b/dashboard.py @@ -11,6 +11,7 @@ import json import sys import time import tkinter as tk +from calendar import timegm from os.path import getsize, isdir, isfile, join from typing import Any, cast from watchdog.observers.api import BaseObserver @@ -182,7 +183,7 @@ class Dashboard(FileSystemEventHandler): if data: # Can be empty if polling while the file is being re-written entry = json.loads(data) # Status file is shared between beta and live. Filter out status not in this game session. - entry_timestamp = time.mktime(time.strptime(entry['timestamp'], '%Y-%m-%dT%H:%M:%SZ')) + entry_timestamp = timegm(time.strptime(entry['timestamp'], '%Y-%m-%dT%H:%M:%SZ')) if entry_timestamp >= self.session_start and self.status != entry: self.status = entry self.root.event_generate('<>', when="tail") diff --git a/loadout.py b/loadout.py index 2e2061a2..11e0f895 100644 --- a/loadout.py +++ b/loadout.py @@ -1,13 +1,17 @@ -"""Export ship loadout in Companion API json format.""" +""" +loadout.py - Export ship loadout in Companion API json format. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" +from __future__ import annotations import json -import os -import pathlib import re import time +from os import listdir from os.path import join -from typing import Optional - import companion import util_ships from config import config @@ -16,7 +20,7 @@ from EDMCLogging import get_main_logger logger = get_main_logger() -def export(data: companion.CAPIData, requested_filename: Optional[str] = None) -> None: +def export(data: companion.CAPIData, requested_filename: str | None = None) -> None: """ Write Ship Loadout in Companion API JSON format. @@ -32,15 +36,14 @@ def export(data: companion.CAPIData, requested_filename: Optional[str] = None) - with open(requested_filename, 'wt') as h: h.write(string) return - - elif not requested_filename: + if not requested_filename: logger.error(f"{requested_filename=} is not valid") return # Look for last ship of this type ship = util_ships.ship_file_name(data['ship'].get('shipName'), data['ship']['name']) - regexp = re.compile(re.escape(ship) + r'\.\d\d\d\d\-\d\d\-\d\dT\d\d\.\d\d\.\d\d\.txt') - oldfiles = sorted([x for x in os.listdir(config.get_str('outdir')) if regexp.match(x)]) + regexp = re.compile(re.escape(ship) + r'\.\d\d\d\d-\d\d-\d\dT\d\d\.\d\d\.\d\d\.txt') + oldfiles = sorted([x for x in listdir(config.get_str('outdir')) if regexp.match(x)]) if oldfiles: with open(join(config.get_str('outdir'), oldfiles[-1]), 'rU') as h: if h.read() == string: @@ -50,10 +53,9 @@ def export(data: companion.CAPIData, requested_filename: Optional[str] = None) - # Write - with open( - pathlib.Path(config.get_str('outdir')) / pathlib.Path( - ship + '.' + time.strftime('%Y-%m-%dT%H.%M.%S', time.localtime(query_time)) + '.txt' - ), - 'wt' - ) as h: + output_directory = config.get_str('outdir') + ship_time = time.strftime('%Y-%m-%dT%H.%M.%S', time.localtime(query_time)) + file_path = join(output_directory, f"{ship}.{ship_time}.txt") + + with open(file_path, 'wt') as h: h.write(string) diff --git a/protocol.py b/protocol.py index cf3a9f75..f3b956d2 100644 --- a/protocol.py +++ b/protocol.py @@ -1,12 +1,17 @@ -"""protocol handler for cAPI authorisation.""" -# spell-checker: words ntdll GURL alloc wfile instantiatable pyright +""" +protocol.py - Protocol Handler for cAPI Auth. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" +from __future__ import annotations + import os import sys import threading -import urllib.error -import urllib.parse -import urllib.request -from typing import TYPE_CHECKING, Optional, Type +from urllib import parse +from typing import TYPE_CHECKING, Type from config import config from constants import appname, protocolhandler_redirect @@ -34,7 +39,7 @@ class GenericProtocolHandler: def __init__(self) -> None: self.redirect = protocolhandler_redirect # Base redirection URL self.master: 'tkinter.Tk' = None # type: ignore - self.lastpayload: Optional[str] = None + self.lastpayload: str | None = None def start(self, master: 'tkinter.Tk') -> None: """Start Protocol Handler.""" @@ -42,7 +47,6 @@ class GenericProtocolHandler: def close(self) -> None: """Stop / Close Protocol Handler.""" - pass def event(self, url: str) -> None: """Generate an auth event.""" @@ -75,7 +79,7 @@ if sys.platform == 'darwin' and getattr(sys, 'frozen', False): # noqa: C901 # i def start(self, master: 'tkinter.Tk') -> None: """Start Protocol Handler.""" GenericProtocolHandler.start(self, master) - self.lasturl: Optional[str] = None + self.lasturl: str | None = None self.eventhandler = EventHandler.alloc().init() def poll(self) -> None: @@ -106,12 +110,11 @@ if sys.platform == 'darwin' and getattr(sys, 'frozen', False): # noqa: C901 # i def handleEvent_withReplyEvent_(self, event, replyEvent) -> None: # noqa: N802 N803 # Required to override """Actual event handling from NSAppleEventManager.""" - protocolhandler.lasturl = urllib.parse.unquote( # noqa: F821: type: ignore # It's going to be a DPH in - # this code + protocolhandler.lasturl = parse.unquote( event.paramDescriptorForKeyword_(keyDirectObject).stringValue() ).strip() - protocolhandler.master.after(DarwinProtocolHandler.POLL, protocolhandler.poll) # noqa: F821 # type: ignore + protocolhandler.master.after(DarwinProtocolHandler.POLL, protocolhandler.poll) elif (config.auth_force_edmc_protocol @@ -124,9 +127,8 @@ elif (config.auth_force_edmc_protocol # This could be false if you use auth_force_edmc_protocol, but then you get to keep the pieces assert sys.platform == 'win32' # spell-checker: words HBRUSH HICON WPARAM wstring WNDCLASS HMENU HGLOBAL - from ctypes import windll # type: ignore from ctypes import ( # type: ignore - POINTER, WINFUNCTYPE, Structure, byref, c_long, c_void_p, create_unicode_buffer, wstring_at + 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, @@ -271,7 +273,7 @@ elif (config.auth_force_edmc_protocol def __init__(self) -> None: super().__init__() - self.thread: Optional[threading.Thread] = None + self.thread: threading.Thread | None = None def start(self, master: 'tkinter.Tk') -> None: """Start the DDE thread.""" @@ -342,7 +344,7 @@ elif (config.auth_force_edmc_protocol if args.lower().startswith('open("') and args.endswith('")'): logger.trace_if('frontier-auth.windows', f'args are: {args}') - url = urllib.parse.unquote(args[6:-2]).strip() + url = parse.unquote(args[6:-2]).strip() if url.startswith(self.redirect): logger.debug(f'Message starts with {self.redirect}') self.event(url) @@ -381,7 +383,7 @@ else: # Linux / Run from source if not os.getenv("EDMC_NO_UI"): logger.info(f'Web server listening on {self.redirect}') - self.thread: Optional[threading.Thread] = None + self.thread: threading.Thread | None = None def start(self, master: 'tkinter.Tk') -> None: """Start the HTTP server thread.""" @@ -420,15 +422,14 @@ else: # Linux / Run from source def parse(self) -> bool: """Parse a request.""" logger.trace_if('frontier-auth.http', f'Got message on path: {self.path}') - url = urllib.parse.unquote(self.path) + url = parse.unquote(self.path) if url.startswith('/auth'): logger.debug('Request starts with /auth, sending to protocolhandler.event()') - protocolhandler.event(url) # noqa: F821 + protocolhandler.event(url) self.send_response(200) return True - else: - self.send_response(404) # Not found - return False + self.send_response(404) # Not found + return False def do_HEAD(self) -> None: # noqa: N802 # Required to override """Handle HEAD Request.""" @@ -440,14 +441,37 @@ else: # Linux / Run from source if self.parse(): self.send_header('Content-Type', 'text/html') self.end_headers() - self.wfile.write('Authentication successful'.encode('utf-8')) - self.wfile.write('

Authentication successful

'.encode('utf-8')) + self.wfile.write(self._generate_auth_response().encode('utf-8')) else: + self.send_response(404) self.end_headers() def log_request(self, code: int | str = '-', size: int | str = '-') -> None: """Override to prevent logging.""" - pass + + def _generate_auth_response(self) -> str: + """ + Generate the authentication response HTML. + + :return: The HTML content of the authentication response. + """ + return ( + '' + '' + 'Authentication successful - Elite: Dangerous' + '' + '' + '' + '

Authentication successful

' + '

Thank you for authenticating.

' + '

Please close this browser tab now.

' + '' + '' + ) def get_handler_impl() -> Type[GenericProtocolHandler]: @@ -459,14 +483,13 @@ def get_handler_impl() -> Type[GenericProtocolHandler]: if sys.platform == 'darwin' and getattr(sys, 'frozen', False): return DarwinProtocolHandler # pyright: reportUnboundVariable=false - elif ( + if ( (sys.platform == 'win32' and config.auth_force_edmc_protocol) or (getattr(sys, 'frozen', False) and not is_wine and not config.auth_force_localserver) ): return WindowsProtocolHandler - else: - return LinuxProtocolHandler + return LinuxProtocolHandler # *late init* singleton diff --git a/ttkHyperlinkLabel.py b/ttkHyperlinkLabel.py index 1d9749ac..24470a93 100644 --- a/ttkHyperlinkLabel.py +++ b/ttkHyperlinkLabel.py @@ -1,5 +1,9 @@ """ -A clickable ttk label for HTTP links. +ttkHyperlinkLabel.py - Clickable ttk labels. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. In addition to standard ttk.Label arguments, takes the following arguments: url: The URL as a string that the user will be sent to on clicking on @@ -14,6 +18,8 @@ In addition to standard ttk.Label arguments, takes the following arguments: May be imported by plugins """ +from __future__ import annotations + import sys import tkinter as tk import webbrowser @@ -26,14 +32,22 @@ if TYPE_CHECKING: # FIXME: Split this into multi-file module to separate the platforms -class HyperlinkLabel(sys.platform == 'darwin' and tk.Label or ttk.Label, object): # type: ignore +class HyperlinkLabel(sys.platform == 'darwin' and tk.Label or ttk.Label): # type: ignore """Clickable label for HTTP links.""" def __init__(self, master: tk.Frame | None = None, **kw: Any) -> None: - self.url = 'url' in kw and kw.pop('url') or None + """ + Initialize the HyperlinkLabel. + + :param master: The master widget. + :param kw: Additional keyword arguments. + """ + self.font_u: tk_font.Font + self.font_n = None + self.url = kw.pop('url', None) self.popup_copy = kw.pop('popup_copy', False) self.underline = kw.pop('underline', None) # override ttk.Label's underline - self.foreground = kw.get('foreground') or 'blue' + self.foreground = kw.get('foreground', 'blue') self.disabledforeground = kw.pop('disabledforeground', ttk.Style().lookup( 'TLabel', 'foreground', ('disabled',))) # ttk.Label doesn't support disabledforeground option @@ -44,11 +58,11 @@ class HyperlinkLabel(sys.platform == 'darwin' and tk.Label or ttk.Label, object) tk.Label.__init__(self, master, **kw) else: - ttk.Label.__init__(self, master, **kw) # type: ignore + ttk.Label.__init__(self, master, **kw) self.bind('', self._click) - self.menu = tk.Menu(None, tearoff=tk.FALSE) + self.menu = tk.Menu(tearoff=tk.FALSE) # LANG: Label for 'Copy' as in 'Copy and Paste' self.menu.add_command(label=_('Copy'), command=self.copy) # As in Copy and Paste self.bind(sys.platform == 'darwin' and '' or '', self._contextmenu) @@ -74,29 +88,30 @@ class HyperlinkLabel(sys.platform == 'darwin' and tk.Label or ttk.Label, object) setattr(self, thing, kw[thing]) # Emulate disabledforeground option for ttk.Label - if kw.get('state') == tk.DISABLED: - if 'foreground' not in kw: + if 'state' in kw: + state = kw['state'] + if state == tk.DISABLED and 'foreground' not in kw: kw['foreground'] = self.disabledforeground - elif 'state' in kw: - if 'foreground' not in kw: + elif state != tk.DISABLED and 'foreground' not in kw: kw['foreground'] = self.foreground if 'font' in kw: self.font_n = kw['font'] self.font_u = tk_font.Font(font=self.font_n) self.font_u.configure(underline=True) - kw['font'] = self.underline is True and self.font_u or self.font_n + kw['font'] = self.font_u if self.underline is True else self.font_n if 'cursor' not in kw: - if (kw['state'] if 'state' in kw else str(self['state'])) == tk.DISABLED: + state = kw.get('state', str(self['state'])) + if state == tk.DISABLED: kw['cursor'] = 'arrow' # System default elif self.url and (kw['text'] if 'text' in kw else self['text']): - kw['cursor'] = sys.platform == 'darwin' and 'pointinghand' or 'hand2' + kw['cursor'] = 'pointinghand' if sys.platform == 'darwin' else 'hand2' else: - kw['cursor'] = (sys.platform == 'darwin' and 'notallowed') or ( - sys.platform == 'win32' and 'no') or 'circle' + kw['cursor'] = 'notallowed' if sys.platform == 'darwin' else ( + 'no' if sys.platform == 'win32' else 'circle') - return super(HyperlinkLabel, self).configure(cnf, **kw) + return super().configure(cnf, **kw) def __setitem__(self, key: str, value: Any) -> None: """ @@ -105,15 +120,15 @@ class HyperlinkLabel(sys.platform == 'darwin' and tk.Label or ttk.Label, object) :param key: option name :param value: option value """ - self.configure(None, **{key: value}) + self.configure(**{key: value}) def _enter(self, event: tk.Event) -> None: if self.url and self.underline is not False and str(self['state']) != tk.DISABLED: - super(HyperlinkLabel, self).configure(font=self.font_u) + super().configure(font=self.font_u) def _leave(self, event: tk.Event) -> None: if not self.underline: - super(HyperlinkLabel, self).configure(font=self.font_n) + super().configure(font=self.font_n) def _click(self, event: tk.Event) -> None: if self.url and self['text'] and str(self['state']) != tk.DISABLED: From 169cfbfc56550a9500da7b0e4d40c9452328d84a Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 17 Nov 2023 21:09:42 -0500 Subject: [PATCH 49/83] [2051] Alter Open Logic --- EDMarketConnector.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 6bab851a..7f08a9f2 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -50,8 +50,7 @@ if __name__ == '__main__': # unbuffered not allowed for text in python3, so use `1 for line buffering log_file_path = path.join(tempfile.gettempdir(), f'{appname}.log') - with open(log_file_path, mode='wt', buffering=1) as log_file: - sys.stdout = sys.stderr = log_file + sys.stdout = sys.stderr = open(log_file_path, mode='wt', buffering=1) # Do NOT use WITH here. # TODO: Test: Make *sure* this redirect is working, else py2exe is going to cause an exit popup From 955d72ead20e21322610c42e9871c34320d64635 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Tue, 21 Nov 2023 20:44:53 -0500 Subject: [PATCH 50/83] Re-Add Missing LANG comment I gotta stop doing that. Co-authored-by: Phoebe <40956085+C1701D@users.noreply.github.com> --- EDMarketConnector.py | 1 + 1 file changed, 1 insertion(+) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 7f08a9f2..dab375d3 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -1742,6 +1742,7 @@ class AppWindow: if time() < self.capi_query_holdoff_time: # Update button in main window cooldown_time = int(self.capi_query_holdoff_time - time()) + # LANG: Cooldown on 'Update' button self.button['text'] = self.theme_button['text'] = _('cooldown {SS}s').format(SS=cooldown_time) self.w.after(1000, self.cooldown) else: From 501e8da2685995d8f5031b7b283a98d8282d0df6 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Tue, 21 Nov 2023 20:48:04 -0500 Subject: [PATCH 51/83] [2051] Add Default Fallback --- EDMarketConnector.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index dab375d3..8be745f2 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -1733,7 +1733,7 @@ class AppWindow: def station_url(self, station: str) -> str | None: """Despatch a station URL to the configured handler.""" return plug.invoke( - config.get_str('station_provider'), 'EDSM', 'station_url', + config.get_str('station_provider', default='EDSM'), 'EDSM', 'station_url', monitor.state['SystemName'], monitor.state['StationName'] ) From fc3b92faf7e327f59686576e6d69d89db9f8b1fc Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 30 Nov 2023 18:31:24 +0000 Subject: [PATCH 52/83] updating submodules --- FDevIDs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/FDevIDs b/FDevIDs index 1f47f67d..069b09b1 160000 --- a/FDevIDs +++ b/FDevIDs @@ -1 +1 @@ -Subproject commit 1f47f67dfe0d3c8c43c9003e4f929e1cf1464352 +Subproject commit 069b09b1afbd2001248ad93b1481d6f6a309c6f5 From cb2a18025c929b5842c790e3a20b2841c3e73592 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Thu, 30 Nov 2023 21:30:18 -0500 Subject: [PATCH 53/83] [2051] First Pass Remaining Files --- companion.py | 182 ++++++++++++++++++++++----------------------- hotkey/__init__.py | 7 +- hotkey/darwin.py | 14 ++-- hotkey/linux.py | 3 +- hotkey/windows.py | 25 +++---- monitor.py | 120 +++++++++++++++--------------- plug.py | 134 +++++++++++++++++---------------- stats.py | 20 +++-- 8 files changed, 255 insertions(+), 250 deletions(-) diff --git a/companion.py b/companion.py index 60322231..4f729479 100644 --- a/companion.py +++ b/companion.py @@ -1,10 +1,15 @@ """ -Handle use of Frontier's Companion API (CAPI) service. +companion.py - Handle use of Frontier's Companion API (CAPI) service. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. Deals with initiating authentication for, and use of, CAPI. Some associated code is in protocol.py which creates and handles the edmc:// protocol used for the callback. """ +from __future__ import annotations import base64 import collections @@ -21,13 +26,10 @@ import time import tkinter as tk import urllib.parse import webbrowser -from builtins import object, range, str from email.utils import parsedate from queue import Queue -from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, OrderedDict, TypeVar, Union - +from typing import TYPE_CHECKING, Any, Mapping, OrderedDict, TypeVar import requests - import config as conf_module import killswitch import protocol @@ -43,7 +45,7 @@ if TYPE_CHECKING: UserDict = collections.UserDict[str, Any] # indicate to our type checkers what this generic class holds normally else: - UserDict = collections.UserDict # type: ignore # Otherwise simply use the actual class + UserDict = collections.UserDict # Otherwise simply use the actual class capi_query_cooldown = 60 # Minimum time between (sets of) CAPI queries @@ -59,7 +61,7 @@ SERVER_LIVE = 'https://companion.orerve.net' SERVER_LEGACY = 'https://legacy-companion.orerve.net' SERVER_BETA = 'https://pts-companion.orerve.net' -commodity_map: Dict = {} +commodity_map: dict = {} class CAPIData(UserDict): @@ -67,10 +69,10 @@ class CAPIData(UserDict): def __init__( self, - data: Union[str, Dict[str, Any], 'CAPIData', None] = None, - source_host: Optional[str] = None, - source_endpoint: Optional[str] = None, - request_cmdr: Optional[str] = None + data: str | dict[str, Any] | 'CAPIData' | None = None, + source_host: str | None = None, + source_endpoint: str | None = None, + request_cmdr: str | None = None ) -> None: if data is None: super().__init__() @@ -102,13 +104,13 @@ class CAPIData(UserDict): This has side-effects of fixing `data` to be as expected in terms of types of those elements. """ - modules: Dict[str, Any] = self.data['lastStarport'].get('modules') + modules: dict[str, Any] = self.data['lastStarport'].get('modules') if modules is None or not isinstance(modules, dict): if modules is None: logger.debug('modules was None. FC or Damaged Station?') elif isinstance(modules, list): - if len(modules) == 0: + if not modules: logger.debug('modules is empty list. Damaged Station?') else: @@ -120,13 +122,13 @@ class CAPIData(UserDict): # Set a safe value self.data['lastStarport']['modules'] = modules = {} - ships: Dict[str, Any] = self.data['lastStarport'].get('ships') + ships: dict[str, Any] = self.data['lastStarport'].get('ships') if ships is None or not isinstance(ships, dict): if ships is None: logger.debug('ships was None') else: - logger.error(f'ships was neither None nor a Dict! type: {type(ships)}, content: {ships}') + logger.error(f'ships was neither None nor a dict! type: {type(ships)}, content: {ships}') # Set a safe value self.data['lastStarport']['ships'] = {'shipyard_list': {}, 'unavailable_list': []} @@ -152,7 +154,7 @@ class CAPIDataRawEndpoint: class CAPIDataRaw: """The last obtained raw CAPI response for each endpoint.""" - raw_data: Dict[str, CAPIDataRawEndpoint] = {} + raw_data: dict[str, CAPIDataRawEndpoint] = {} def record_endpoint( self, endpoint: str, @@ -176,14 +178,14 @@ class CAPIDataRaw: def __iter__(self): """Make this iterable on its raw_data dict.""" - yield from self.raw_data + yield from self.raw_data.keys() def __getitem__(self, item): """Make the raw_data dict's items get'able.""" - return self.raw_data.__getitem__(item) + return self.raw_data[item] -def listify(thing: Union[List, Dict]) -> List: +def listify(thing: list | dict) -> list: """ Convert actual JSON array or int-indexed dict into a Python list. @@ -196,11 +198,11 @@ def listify(thing: Union[List, Dict]) -> List: if thing is None: return [] # data is not present - elif isinstance(thing, list): + if isinstance(thing, list): return list(thing) # array is not sparse - elif isinstance(thing, dict): - retval: List[Any] = [] + if isinstance(thing, dict): + retval: list[Any] = [] for k, v in thing.items(): idx = int(k) @@ -211,9 +213,7 @@ def listify(thing: Union[List, Dict]) -> List: retval[idx] = v return retval - - else: - raise ValueError(f"expected an array or sparse array, got {thing!r}") + raise ValueError(f"expected an array or sparse array, got {thing!r}") class ServerError(Exception): @@ -297,7 +297,7 @@ class CmdrError(Exception): self.args = (_('Error: Wrong Cmdr'),) -class Auth(object): +class Auth: """Handles authentication with the Frontier CAPI service via oAuth2.""" # Currently the "Elite Dangerous Market Connector (EDCD/Athanasius)" one in @@ -313,15 +313,15 @@ class Auth(object): self.cmdr: str = cmdr self.requests_session = requests.Session() self.requests_session.headers['User-Agent'] = user_agent - self.verifier: Union[bytes, None] = None - self.state: Union[str, None] = None + self.verifier: bytes | None = None + self.state: str | None = None def __del__(self) -> None: """Ensure our Session is closed if we're being deleted.""" if self.requests_session: self.requests_session.close() - def refresh(self) -> Optional[str]: + def refresh(self) -> str | None: """ Attempt use of Refresh Token to get a valid Access Token. @@ -347,7 +347,7 @@ class Auth(object): logger.debug(f'idx = {idx}') tokens = config.get_list('fdev_apikeys', default=[]) - tokens = tokens + [''] * (len(cmdrs) - len(tokens)) + tokens += [''] * (len(cmdrs) - len(tokens)) if tokens[idx]: logger.debug('We have a refresh token for that idx') data = { @@ -358,7 +358,7 @@ class Auth(object): logger.debug('Attempting refresh with Frontier...') try: - r: Optional[requests.Response] = None + r: requests.Response | None = None r = self.requests_session.post( FRONTIER_AUTH_SERVER + self.FRONTIER_AUTH_PATH_TOKEN, data=data, @@ -372,11 +372,10 @@ class Auth(object): return data.get('access_token') - else: - logger.error(f"Frontier CAPI Auth: Can't refresh token for \"{self.cmdr}\"") - self.dump(r) + logger.error(f"Frontier CAPI Auth: Can't refresh token for \"{self.cmdr}\"") + self.dump(r) - except (ValueError, requests.RequestException, ) as e: + except (ValueError, requests.RequestException) as e: logger.exception(f"Frontier CAPI Auth: Can't refresh token for \"{self.cmdr}\"\n{e!r}") if r is not None: self.dump(r) @@ -490,7 +489,7 @@ class Auth(object): cmdrs = config.get_list('cmdrs', default=[]) idx = cmdrs.index(self.cmdr) tokens = config.get_list('fdev_apikeys', default=[]) - tokens = tokens + [''] * (len(cmdrs) - len(tokens)) + tokens += [''] * (len(cmdrs) - len(tokens)) tokens[idx] = data_token.get('refresh_token', '') config.set('fdev_apikeys', tokens) config.save() # Save settings now for use by command-line app @@ -518,9 +517,9 @@ class Auth(object): raise CredentialsError(f'{_("Error")}: {error!r}') @staticmethod - def invalidate(cmdr: Optional[str]) -> None: + def invalidate(cmdr: str | None) -> None: """Invalidate Refresh Token for specified Commander.""" - to_set: Optional[list] = None + to_set: list | None = None if cmdr is None: logger.info('Frontier CAPI Auth: Invalidating ALL tokens!') cmdrs = config.get_list('cmdrs', default=[]) @@ -531,7 +530,7 @@ class Auth(object): cmdrs = config.get_list('cmdrs', default=[]) idx = cmdrs.index(cmdr) to_set = config.get_list('fdev_apikeys', default=[]) - to_set = to_set + [''] * (len(cmdrs) - len(to_set)) # type: ignore + to_set += [''] * (len(cmdrs) - len(to_set)) to_set[idx] = '' if to_set is None: @@ -560,7 +559,7 @@ class EDMCCAPIReturn: """Base class for Request, Failure or Response.""" def __init__( - self, query_time: int, tk_response_event: Optional[str] = None, + self, query_time: int, tk_response_event: str | None = None, play_sound: bool = False, auto_update: bool = False ): self.tk_response_event = tk_response_event # Name of tk event to generate when response queued. @@ -577,7 +576,7 @@ class EDMCCAPIRequest(EDMCCAPIReturn): def __init__( self, capi_host: str, endpoint: str, query_time: int, - tk_response_event: Optional[str] = None, + tk_response_event: str | None = None, play_sound: bool = False, auto_update: bool = False ): super().__init__( @@ -612,7 +611,7 @@ class EDMCCAPIFailedRequest(EDMCCAPIReturn): self.exception: Exception = exception # Exception that recipient should raise. -class Session(object): +class Session: """Methods for handling Frontier Auth and CAPI queries.""" STATE_INIT, STATE_AUTH, STATE_OK = list(range(3)) @@ -628,11 +627,11 @@ class Session(object): def __init__(self) -> None: self.state = Session.STATE_INIT - self.credentials: Optional[Dict[str, Any]] = None + self.credentials: dict[str, Any] | None = None self.requests_session = requests.Session() - self.auth: Optional[Auth] = None + self.auth: Auth | None = None self.retrying = False # Avoid infinite loop when successful auth / unsuccessful query - self.tk_master: Optional[tk.Tk] = None + self.tk_master: tk.Tk | None = None self.capi_raw_data = CAPIDataRaw() # Cache of raw replies from CAPI service # Queue that holds requests for CAPI queries, the items should always @@ -642,7 +641,7 @@ class Session(object): # queries back to the requesting code (technically anything checking # this queue, but it should be either EDMarketConnector.AppWindow or # EDMC.py). Items may be EDMCCAPIResponse or EDMCCAPIFailedRequest. - self.capi_response_queue: Queue[Union[EDMCCAPIResponse, EDMCCAPIFailedRequest]] = Queue() + self.capi_response_queue: Queue[EDMCCAPIResponse | EDMCCAPIFailedRequest] = Queue() logger.debug('Starting CAPI queries thread...') self.capi_query_thread = threading.Thread( target=self.capi_query_worker, @@ -667,7 +666,7 @@ class Session(object): self.state = Session.STATE_OK - def login(self, cmdr: Optional[str] = None, is_beta: Optional[bool] = None) -> bool: + def login(self, cmdr: str | None = None, is_beta: bool | None = None) -> bool: """ Attempt oAuth2 login. @@ -694,7 +693,7 @@ class Session(object): logger.error('self.credentials is None') raise CredentialsError('Missing credentials') # Shouldn't happen - elif self.state == Session.STATE_OK: + if self.state == Session.STATE_OK: logger.debug('already logged in (state == STATE_OK)') return True # already logged in @@ -704,10 +703,9 @@ class Session(object): logger.debug(f'already logged in (is_beta = {is_beta})') return True # already logged in - else: - logger.debug('changed account or retrying login during auth') - self.reinit_session() - self.credentials = credentials + logger.debug('changed account or retrying login during auth') + self.reinit_session() + self.credentials = credentials self.state = Session.STATE_INIT self.auth = Auth(self.credentials['cmdr']) @@ -719,11 +717,10 @@ class Session(object): self.start_frontier_auth(access_token) return True - else: - logger.debug('We do NOT have an access_token') - self.state = Session.STATE_AUTH - return False - # Wait for callback + logger.debug('We do NOT have an access_token') + self.state = Session.STATE_AUTH + return False + # Wait for callback # Callback from protocol handler def auth_callback(self) -> None: @@ -745,7 +742,7 @@ class Session(object): self.auth = None raise # Bad thing happened if getattr(sys, 'frozen', False): - tk.messagebox.showinfo(title="Authentication Successful", + tk.messagebox.showinfo(title="Authentication Successful", # type: ignore message="Authentication with cAPI Successful.\n" "You may now close the Frontier login tab if it is still open.") @@ -812,11 +809,11 @@ class Session(object): raise ServerConnectionError(f'Pretending CAPI down: {capi_endpoint}') if conf_module.capi_debug_access_token is not None: - self.requests_session.headers['Authorization'] = f'Bearer {conf_module.capi_debug_access_token}' # type: ignore # noqa: E501 + self.requests_session.headers['Authorization'] = f'Bearer {conf_module.capi_debug_access_token}' # This is one-shot conf_module.capi_debug_access_token = None - r = self.requests_session.get(capi_host + capi_endpoint, timeout=timeout) # type: ignore + r = self.requests_session.get(capi_host + capi_endpoint, timeout=timeout) logger.trace_if('capi.worker', '... got result...') r.raise_for_status() # Typically 403 "Forbidden" on token expiry @@ -835,21 +832,7 @@ class Session(object): raise ServerConnectionError(f'Unable to connect to endpoint: {capi_endpoint}') from e except requests.HTTPError as e: # In response to raise_for_status() - logger.exception(f'Frontier CAPI Auth: GET {capi_endpoint}') - self.dump(r) - - if r.status_code == 401: # CAPI doesn't think we're Auth'd - # TODO: This needs to try a REFRESH, not a full re-auth - # No need for translation, we'll go straight into trying new Auth - # and thus any message would be overwritten. - raise CredentialsRequireRefresh('Frontier CAPI said "unauthorized"') from e - - if r.status_code == 418: # "I'm a teapot" - used to signal maintenance - # LANG: Frontier CAPI returned 418, meaning down for maintenance - raise ServerError(_("Frontier CAPI down for maintenance")) from e - - logger.exception('Frontier CAPI: Misc. Error') - raise ServerError('Frontier CAPI: Misc. Error') from e + handle_http_error(e.response, capi_endpoint) # type: ignore # Handle various HTTP errors except ValueError as e: logger.exception(f'decoding CAPI response content:\n{r.content.decode(encoding="utf-8")}\n') @@ -870,6 +853,28 @@ class Session(object): return capi_data + def handle_http_error(response: requests.Response, endpoint: str): + """ + Handle different types of HTTP errors raised during CAPI requests. + + :param response: The HTTP response object. + :param endpoint: The CAPI endpoint that was queried. + :raises: Various exceptions based on the error scenarios. + """ + logger.exception(f'Frontier CAPI Auth: GET {endpoint}') + self.dump(response) + + if response.status_code == 401: + # CAPI doesn't think we're Auth'd + raise CredentialsRequireRefresh('Frontier CAPI said "unauthorized"') + + if response.status_code == 418: + # "I'm a teapot" - used to signal maintenance + raise ServerError(_("Frontier CAPI down for maintenance")) + + logger.exception('Frontier CAPI: Misc. Error') + raise ServerError('Frontier CAPI: Misc. Error') + def capi_station_queries( # noqa: CCR001 capi_host: str, timeout: int = capi_default_requests_timeout ) -> CAPIData: @@ -939,9 +944,8 @@ class Session(object): logger.warning(f"{last_starport_id!r} != {int(market_data['id'])!r}") raise ServerLagging() - else: - market_data['name'] = last_starport_name - station_data['lastStarport'].update(market_data) + market_data['name'] = last_starport_name + station_data['lastStarport'].update(market_data) if services.get('outfitting') or services.get('shipyard'): shipyard_data = capi_single_query(capi_host, self.FRONTIER_CAPI_PATH_SHIPYARD, timeout=timeout) @@ -953,9 +957,8 @@ class Session(object): logger.warning(f"{last_starport_id!r} != {int(shipyard_data['id'])!r}") raise ServerLagging() - else: - shipyard_data['name'] = last_starport_name - station_data['lastStarport'].update(shipyard_data) + shipyard_data['name'] = last_starport_name + station_data['lastStarport'].update(shipyard_data) # WORKAROUND END return station_data @@ -1024,7 +1027,7 @@ class Session(object): ) def station( - self, query_time: int, tk_response_event: Optional[str] = None, + self, query_time: int, tk_response_event: str | None = None, play_sound: bool = False, auto_update: bool = False ) -> None: """ @@ -1178,11 +1181,9 @@ class Session(object): logger.debug(f"Using {SERVER_LIVE} because monitor.is_live_galaxy() was True") return SERVER_LIVE - else: - logger.debug(f"Using {SERVER_LEGACY} because monitor.is_live_galaxy() was False") - return SERVER_LEGACY + logger.debug(f"Using {SERVER_LEGACY} because monitor.is_live_galaxy() was False") + return SERVER_LEGACY - return '' ###################################################################### @@ -1300,11 +1301,11 @@ def ship(data: CAPIData) -> CAPIData: V = TypeVar('V') -def index_possibly_sparse_list(data: Union[Mapping[str, V], List[V]], key: int) -> V: +def index_possibly_sparse_list(data: Mapping[str, V] | list[V], key: int) -> V: """ Index into a "list" that may or may not be sparseified into a dict. - :param data: List or Dict to index + :param data: list or dict to index :param key: Key to use to index :raises ValueError: When data is of an unexpected type :return: The value at the key @@ -1320,11 +1321,10 @@ def index_possibly_sparse_list(data: Union[Mapping[str, V], List[V]], key: int) if isinstance(data, list): return data[key] - elif isinstance(data, (dict, OrderedDict)): + if isinstance(data, (dict, OrderedDict)): return data[str(key)] - else: - raise ValueError(f'Unexpected data type {type(data)}') + raise ValueError(f'Unexpected data type {type(data)}') ###################################################################### diff --git a/hotkey/__init__.py b/hotkey/__init__.py index 5162621c..52f8d684 100644 --- a/hotkey/__init__.py +++ b/hotkey/__init__.py @@ -79,16 +79,15 @@ def get_hotkeymgr() -> AbstractHotkeyMgr: from hotkey.darwin import MacHotkeyMgr return MacHotkeyMgr() - elif sys.platform == 'win32': + if sys.platform == 'win32': from hotkey.windows import WindowsHotkeyMgr return WindowsHotkeyMgr() - elif sys.platform == 'linux': + if sys.platform == 'linux': from hotkey.linux import LinuxHotKeyMgr return LinuxHotKeyMgr() - else: - raise ValueError(f'Unknown platform: {sys.platform}') + raise ValueError(f'Unknown platform: {sys.platform}') # singleton diff --git a/hotkey/darwin.py b/hotkey/darwin.py index cbf9d260..63f9d132 100644 --- a/hotkey/darwin.py +++ b/hotkey/darwin.py @@ -1,8 +1,10 @@ """darwin/macOS implementation of hotkey.AbstractHotkeyMgr.""" +from __future__ import annotations + import pathlib import sys import tkinter as tk -from typing import Callable, Optional, Tuple, Union +from typing import Callable assert sys.platform == 'darwin' import objc @@ -107,7 +109,7 @@ class MacHotkeyMgr(AbstractHotkeyMgr): # suppress the event by not chaining the old function return the_event - elif the_event.type() in (NSKeyDown, NSKeyUp): + if the_event.type() in (NSKeyDown, NSKeyUp): c = the_event.charactersIgnoringModifiers() self.acquire_key = (c and ord(c[0]) or 0) | \ (the_event.modifierFlags() & NSDeviceIndependentModifierFlagsMask) @@ -192,7 +194,7 @@ class MacHotkeyMgr(AbstractHotkeyMgr): self.acquire_state = MacHotkeyMgr.ACQUIRE_ACTIVE self.root.after(50, self._acquire_poll) - def fromevent(self, event) -> Optional[Union[bool, Tuple]]: + def fromevent(self, event) -> bool | tuple | None: """ Return configuration (keycode, modifiers) or None=clear or False=retain previous. @@ -209,17 +211,17 @@ class MacHotkeyMgr(AbstractHotkeyMgr): return False # BkSp, Del, Clear = clear hotkey - elif keycode in [0x7f, ord(NSDeleteFunctionKey), ord(NSClearLineFunctionKey)]: + if keycode in [0x7f, ord(NSDeleteFunctionKey), ord(NSClearLineFunctionKey)]: self.acquire_state = MacHotkeyMgr.ACQUIRE_INACTIVE return None # don't allow keys needed for typing in System Map - elif keycode in [0x13, 0x20, 0x2d] or 0x61 <= keycode <= 0x7a: + if keycode in [0x13, 0x20, 0x2d] or 0x61 <= keycode <= 0x7a: NSBeep() self.acquire_state = MacHotkeyMgr.ACQUIRE_INACTIVE return None - return (keycode, modifiers) + return keycode, modifiers def display(self, keycode, modifiers) -> str: """ diff --git a/hotkey/linux.py b/hotkey/linux.py index 927c4d26..11d95a62 100644 --- a/hotkey/linux.py +++ b/hotkey/linux.py @@ -1,6 +1,7 @@ """Linux implementation of hotkey.AbstractHotkeyMgr.""" -import sys +from __future__ import annotations +import sys from EDMCLogging import get_main_logger from hotkey import AbstractHotkeyMgr diff --git a/hotkey/windows.py b/hotkey/windows.py index 8a1c7acd..f21a24b2 100644 --- a/hotkey/windows.py +++ b/hotkey/windows.py @@ -1,4 +1,6 @@ """Windows implementation of hotkey.AbstractHotkeyMgr.""" +from __future__ import annotations + import atexit import ctypes import pathlib @@ -7,8 +9,6 @@ import threading import tkinter as tk import winsound from ctypes.wintypes import DWORD, HWND, LONG, LPWSTR, MSG, ULONG, WORD -from typing import Optional, Tuple, Union - from config import config from EDMCLogging import get_main_logger from hotkey import AbstractHotkeyMgr @@ -266,7 +266,7 @@ class WindowsHotkeyMgr(AbstractHotkeyMgr): """Stop acquiring hotkey state.""" pass - def fromevent(self, event) -> Optional[Union[bool, Tuple]]: # noqa: CCR001 + def fromevent(self, event) -> bool | tuple | None: # noqa: CCR001 """ Return configuration (keycode, modifiers) or None=clear or False=retain previous. @@ -285,33 +285,32 @@ class WindowsHotkeyMgr(AbstractHotkeyMgr): keycode = event.keycode if keycode in [VK_SHIFT, VK_CONTROL, VK_MENU, VK_LWIN, VK_RWIN]: - return (0, modifiers) + return 0, modifiers if not modifiers: if keycode == VK_ESCAPE: # Esc = retain previous return False - elif keycode in [VK_BACK, VK_DELETE, VK_CLEAR, VK_OEM_CLEAR]: # BkSp, Del, Clear = clear hotkey + if keycode in [VK_BACK, VK_DELETE, VK_CLEAR, VK_OEM_CLEAR]: # BkSp, Del, Clear = clear hotkey return None - elif ( + if ( keycode in [VK_RETURN, 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 - elif (keycode in [VK_NUMLOCK, VK_SCROLL, VK_PROCESSKEY] - or VK_CAPITAL <= keycode <= VK_MODECHANGE): # ignore unmodified mode switch keys - return (0, modifiers) + if (keycode in [VK_NUMLOCK, VK_SCROLL, VK_PROCESSKEY] + or VK_CAPITAL <= keycode <= VK_MODECHANGE): # ignore unmodified mode switch keys + return 0, modifiers # See if the keycode is usable and available if RegisterHotKey(None, 2, modifiers | MOD_NOREPEAT, keycode): UnregisterHotKey(None, 2) - return (keycode, modifiers) + return keycode, modifiers - else: - winsound.MessageBeep() - return None + winsound.MessageBeep() + return None def display(self, keycode, modifiers) -> str: """ diff --git a/monitor.py b/monitor.py index bbbfc190..17a6fa16 100644 --- a/monitor.py +++ b/monitor.py @@ -1,7 +1,11 @@ -"""Monitor for new Journal files and contents of latest.""" -# v [sic] -# spell-checker: words onfoot unforseen relog fsdjump suitloadoutid slotid suitid loadoutid fauto Intimidator -# spell-checker: words joinacrew quitacrew sellshiponrebuy newbal navroute npccrewpaidwage sauto +""" +monitor.py - Monitor for new Journal files and contents of latest. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" +from __future__ import annotations import json import pathlib @@ -14,19 +18,16 @@ from collections import OrderedDict, defaultdict from os import SEEK_END, SEEK_SET, listdir from os.path import basename, expanduser, getctime, isdir, join from time import gmtime, localtime, mktime, sleep, strftime, strptime, time -from typing import TYPE_CHECKING, Any, BinaryIO, MutableMapping, Tuple - -if TYPE_CHECKING: - import tkinter - +from typing import TYPE_CHECKING, Any, BinaryIO, MutableMapping import semantic_version - import util_ships from config import config from edmc_data import edmc_suit_shortnames, edmc_suit_symbol_localised from EDMCLogging import get_main_logger -# spell-checker: words navroute +if TYPE_CHECKING: + import tkinter + logger = get_main_logger() STARTUP = 'journal.startup' @@ -76,11 +77,10 @@ else: # Journal handler -class EDLogs(FileSystemEventHandler): # type: ignore # See below +class EDLogs(FileSystemEventHandler): """Monitoring of Journal files.""" # Magic with FileSystemEventHandler can confuse type checkers when they do not have access to every import - _POLL = 1 # Polling is cheap, so do it often _RE_CANONICALISE = re.compile(r'\$(.+)_name;') _RE_CATEGORY = re.compile(r'\$MICRORESOURCE_CATEGORY_(.+);') @@ -207,7 +207,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below :return: bool - False if we couldn't access/find latest Journal file. """ logger.debug('Begin...') - self.root = root # type: ignore + self.root = root journal_dir = config.get_str('journaldir') if journal_dir == '' or journal_dir is None: @@ -515,8 +515,6 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below else: self.game_was_running = self.game_running() - logger.debug('Done.') - def synthesize_startup_event(self) -> dict[str, Any]: """ Synthesize a 'StartUp' event to notify plugins of initial state. @@ -570,7 +568,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below try: # Preserve property order because why not? entry: MutableMapping[str, Any] = json.loads(line, object_pairs_hook=OrderedDict) - entry['timestamp'] # we expect this to exist # TODO: replace with assert? or an if key in check + assert 'timestamp' in entry, "Timestamp does not exist in the entry" self.__navroute_retry() @@ -933,7 +931,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below ############################################################### if 'StarPos' in entry: # Plugins need this as well, so copy in state - self.state['StarPos'] = tuple(entry['StarPos']) # type: ignore + self.state['StarPos'] = tuple(entry['StarPos']) else: logger.warning(f"'{event_type}' event without 'StarPos' !!!:\n{entry}\n") @@ -1109,7 +1107,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below while attempts < shiplocker_max_attempts: attempts += 1 try: - with open(shiplocker_filename, 'rb') as h: # type: ignore + with open(shiplocker_filename, 'rb') as h: entry = json.load(h, object_pairs_hook=OrderedDict) self.state['ShipLockerJSON'] = entry break @@ -1551,7 +1549,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below entry = json.load(mf) except json.JSONDecodeError: - logger.exception('Failed decoding ModulesInfo.json', exc_info=True) + logger.exception('Failed decoding ModulesInfo.json') else: self.state['ModuleInfo'] = entry @@ -1812,7 +1810,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below self.state['Credits'] -= entry.get('Price', 0) elif event_type == 'carrierbanktransfer': - if (newbal := entry.get('PlayerBalance')): + if newbal := entry.get('PlayerBalance'): self.state['Credits'] = newbal elif event_type == 'carrierdecommission': @@ -1911,7 +1909,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below return name - def suitloadout_store_from_event(self, entry) -> Tuple[int, int]: + def suitloadout_store_from_event(self, entry) -> tuple[int, int]: """ Store Suit and SuitLoadout data from a journal event. @@ -1990,64 +1988,64 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below # TODO: *This* will need refactoring and a proper validation infrastructure # designed for this in the future. This is a bandaid for a known issue. - def event_valid_engineerprogress(self, entry) -> bool: # noqa: CCR001 C901 + def event_valid_engineerprogress(self, entry) -> bool: # noqa: CCR001 """ Check an `EngineerProgress` Journal event for validity. :param entry: Journal event dict :return: True if passes validation, else False. """ - # The event should have at least one of these - if 'Engineers' not in entry and 'Progress' not in entry: + engineers_present = 'Engineers' in entry + progress_present = 'Progress' in entry + + if not (engineers_present or progress_present): logger.warning(f"EngineerProgress has neither 'Engineers' nor 'Progress': {entry=}") return False - # But not both of them - if 'Engineers' in entry and 'Progress' in entry: + if engineers_present and progress_present: logger.warning(f"EngineerProgress has BOTH 'Engineers' and 'Progress': {entry=}") return False - if 'Engineers' in entry: + if engineers_present: + engineers = entry['Engineers'] # 'Engineers' version should have a list as value - if not isinstance(entry['Engineers'], list): + if not isinstance(engineers, list): logger.warning(f"EngineerProgress 'Engineers' is not a list: {entry=}") return False # It should have at least one entry? This might still be valid ? - if len(entry['Engineers']) < 1: + if len(engineers) < 1: logger.warning(f"EngineerProgress 'Engineers' list is empty ?: {entry=}") # TODO: As this might be valid, we might want to only log return False # And that list should have all of these keys - for e in entry['Engineers']: - for f in ('Engineer', 'EngineerID', 'Rank', 'Progress', 'RankProgress'): - if f not in e: - # For some Progress there's no Rank/RankProgress yet - if f in ('Rank', 'RankProgress'): - if (progress := e.get('Progress', None)) is not None: - if progress in ('Invited', 'Known'): - continue + # For some Progress there's no Rank/RankProgress yet + required_keys = ('Engineer', 'EngineerID', 'Rank', 'Progress', 'RankProgress') + for e in engineers: + missing_keys = [key for key in required_keys if key not in e] + if any(key in ('Rank', 'RankProgress') and e.get('Progress') in ('Invited', 'Known') for key in + missing_keys): + continue - logger.warning(f"Engineer entry without '{f}' key: {e=} in {entry=}") - return False + if missing_keys: + logger.warning(f"Engineer entry without '{missing_keys[0]}' key: {e=} in {entry=}") + return False - if 'Progress' in entry: + if progress_present: # Progress is only a single Engineer, so it's not an array # { "timestamp":"2021-05-24T17:57:52Z", # "event":"EngineerProgress", # "Engineer":"Felicity Farseer", # "EngineerID":300100, # "Progress":"Invited" } - for f in ('Engineer', 'EngineerID', 'Rank', 'Progress', 'RankProgress'): - if f not in entry: - # For some Progress there's no Rank/RankProgress yet - if f in ('Rank', 'RankProgress'): - if (progress := entry.get('Progress', None)) is not None: - if progress in ('Invited', 'Known'): - continue - - logger.warning(f"Progress event without '{f}' key: {entry=}") + # For some Progress there's no Rank/RankProgress yet + required_keys = ('Engineer', 'EngineerID', 'Rank', 'Progress', 'RankProgress') + missing_keys = [key for key in required_keys if key not in entry] + if any(key in ('Rank', 'RankProgress') and entry.get('Progress') in ('Invited', 'Known') for key in + missing_keys): + if missing_keys: + logger.warning(f"Progress event without '{missing_keys[0]}' key: {entry=}") return False return True @@ -2152,7 +2150,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below return True elif sys.platform == 'win32': - def WindowTitle(h): # noqa: N802 # type: ignore + def WindowTitle(h): # noqa: N802 if h: length = GetWindowTextLength(h) + 1 buf = ctypes.create_unicode_buffer(length) @@ -2261,18 +2259,18 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below return ship = util_ships.ship_file_name(self.state['ShipName'], self.state['ShipType']) - regexp = re.compile(re.escape(ship) + r'\.\d{4}\-\d\d\-\d\dT\d\d\.\d\d\.\d\d\.txt') - oldfiles = sorted((x for x in listdir(config.get_str('outdir')) if regexp.match(x))) # type: ignore + regexp = re.compile(re.escape(ship) + r'\.\d{4}-\d\d-\d\dT\d\d\.\d\d\.\d\d\.txt') + oldfiles = sorted((x for x in listdir(config.get_str('outdir')) if regexp.match(x))) if oldfiles: try: - with open(join(config.get_str('outdir'), oldfiles[-1]), 'r', encoding='utf-8') as h: # type: ignore + with open(join(config.get_str('outdir'), oldfiles[-1]), encoding='utf-8') as h: if h.read() == string: return # same as last time - don't write except UnicodeError: logger.exception("UnicodeError reading old ship loadout with utf-8 encoding, trying without...") try: - with open(join(config.get_str('outdir'), oldfiles[-1]), 'r') as h: # type: ignore + with open(join(config.get_str('outdir'), oldfiles[-1])) as h: if h.read() == string: return # same as last time - don't write @@ -2291,9 +2289,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below # Write ts = strftime('%Y-%m-%dT%H.%M.%S', localtime(time())) - filename = join( # type: ignore - config.get_str('outdir'), f'{ship}.{ts}.txt' - ) + filename = join(config.get_str('outdir'), f'{ship}.{ts}.txt') try: with open(filename, 'wt', encoding='utf-8') as h: @@ -2380,7 +2376,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below try: - with open(join(self.currentdir, 'NavRoute.json'), 'r') as f: + with open(join(self.currentdir, 'NavRoute.json')) as f: raw = f.read() except Exception as e: @@ -2391,7 +2387,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below data = json.loads(raw) except json.JSONDecodeError: - logger.exception('Failed to decode NavRoute.json', exc_info=True) + logger.exception('Failed to decode NavRoute.json') return None if 'timestamp' not in data: # quick sanity check @@ -2406,7 +2402,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below try: - with open(join(self.currentdir, 'FCMaterials.json'), 'r') as f: + with open(join(self.currentdir, 'FCMaterials.json')) as f: raw = f.read() except Exception as e: @@ -2417,7 +2413,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below data = json.loads(raw) except json.JSONDecodeError: - logger.exception('Failed to decode FCMaterials.json', exc_info=True) + logger.exception('Failed to decode FCMaterials.json') return None if 'timestamp' not in data: # quick sanity check diff --git a/plug.py b/plug.py index fa7807f2..de67205b 100644 --- a/plug.py +++ b/plug.py @@ -1,4 +1,12 @@ -"""Plugin API.""" +""" +plug.py - Plugin API. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" +from __future__ import annotations + import copy import importlib import logging @@ -6,9 +14,8 @@ import operator import os import sys import tkinter as tk -from builtins import object, str from tkinter import ttk -from typing import Any, Callable, List, Mapping, MutableMapping, Optional +from typing import Any, Mapping, MutableMapping import companion import myNotebook as nb # noqa: N813 @@ -26,7 +33,7 @@ PLUGINS_not_py3 = [] class LastError: """Holds the last plugin error.""" - msg: Optional[str] + msg: str | None root: tk.Tk def __init__(self) -> None: @@ -36,10 +43,10 @@ class LastError: last_error = LastError() -class Plugin(object): +class Plugin: """An EDMC plugin.""" - def __init__(self, name: str, loadfile: Optional[str], plugin_logger: Optional[logging.Logger]): + def __init__(self, name: str, loadfile: str | None, plugin_logger: logging.Logger | None): """ Load a single plugin. @@ -49,9 +56,9 @@ class Plugin(object): :raises Exception: Typically ImportError or OSError """ self.name: str = name # Display name. - self.folder: Optional[str] = name # basename of plugin folder. None for internal plugins. + self.folder: str | None = name # basename of plugin folder. None for internal plugins. self.module = None # None for disabled plugins. - self.logger: Optional[logging.Logger] = plugin_logger + self.logger: logging.Logger | None = plugin_logger if loadfile: logger.info(f'loading plugin "{name.replace(".", "_")}" from "{loadfile}"') @@ -64,7 +71,7 @@ class Plugin(object): ).load_module() if getattr(module, 'plugin_start3', None): newname = module.plugin_start3(os.path.dirname(loadfile)) - self.name = newname and str(newname) or name + self.name = str(newname) if newname else self.name self.module = module elif getattr(module, 'plugin_start', None): logger.warning(f'plugin {name} needs migrating\n') @@ -77,7 +84,7 @@ class Plugin(object): else: logger.info(f'plugin {name} disabled') - def _get_func(self, funcname: str) -> Optional[Callable]: + def _get_func(self, funcname: str): # Removing Unhelpful Type Hint """ Get a function from a plugin. @@ -86,7 +93,7 @@ class Plugin(object): """ return getattr(self.module, funcname, None) - def get_app(self, parent: tk.Frame) -> Optional[tk.Frame]: + def get_app(self, parent: tk.Frame) -> tk.Frame | None: """ If the plugin provides mainwindow content create and return it. @@ -100,7 +107,7 @@ class Plugin(object): if appitem is None: return None - elif isinstance(appitem, tuple): + if isinstance(appitem, tuple): if ( len(appitem) != 2 or not isinstance(appitem[0], tk.Widget) @@ -118,7 +125,7 @@ class Plugin(object): return None - def get_prefs(self, parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> Optional[tk.Frame]: + def get_prefs(self, parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Frame | None: """ If the plugin provides a prefs frame, create and return it. @@ -132,41 +139,50 @@ class Plugin(object): if plugin_prefs: try: frame = plugin_prefs(parent, cmdr, is_beta) - if not isinstance(frame, nb.Frame): - raise AssertionError - return frame + if isinstance(frame, nb.Frame): + return frame + raise AssertionError except Exception: logger.exception(f'Failed for Plugin "{self.name}"') return None -def load_plugins(master: tk.Tk) -> None: # noqa: CCR001 +def load_plugins(master: tk.Tk) -> None: """Find and load all plugins.""" last_error.root = master - internal = [] - for name in sorted(os.listdir(config.internal_plugin_dir_path)): - if name.endswith('.py') and not name[0] in ['.', '_']: - try: - plugin = Plugin(name[:-3], os.path.join(config.internal_plugin_dir_path, name), logger) - plugin.folder = None # Suppress listing in Plugins prefs tab - internal.append(plugin) - except Exception: - logger.exception(f'Failure loading internal Plugin "{name}"') + internal = _load_internal_plugins() PLUGINS.extend(sorted(internal, key=lambda p: operator.attrgetter('name')(p).lower())) # Add plugin folder to load path so packages can be loaded from plugin folder sys.path.append(config.plugin_dir) + found = _load_found_plugins() + PLUGINS.extend(sorted(found, key=lambda p: operator.attrgetter('name')(p).lower())) + + +def _load_internal_plugins(): + internal = [] + for name in sorted(os.listdir(config.internal_plugin_dir_path)): + if name.endswith('.py') and name[0] not in ['.', '_']: + try: + plugin = Plugin(name[:-3], os.path.join(config.internal_plugin_dir_path, name), logger) + plugin.folder = None + internal.append(plugin) + except Exception: + logger.exception(f'Failure loading internal Plugin "{name}"') + return internal + + +def _load_found_plugins(): found = [] # Load any plugins that are also packages first, but note it's *still* # 100% relying on there being a `load.py`, as only that will be loaded. # The intent here is to e.g. have EDMC-Overlay load before any plugins # that depend on it. - for name in sorted( - os.listdir(config.plugin_dir_path), - key=lambda n: (not os.path.isfile(os.path.join(config.plugin_dir_path, n, '__init__.py')), n.lower()) - ): + + for name in sorted(os.listdir(config.plugin_dir_path), key=lambda n: ( + not os.path.isfile(os.path.join(config.plugin_dir_path, n, '__init__.py')), n.lower())): if not os.path.isdir(os.path.join(config.plugin_dir_path, name)) or name[0] in ['.', '_']: pass elif name.endswith('.disabled'): @@ -177,19 +193,17 @@ def load_plugins(master: tk.Tk) -> None: # noqa: CCR001 # Add plugin's folder to load path in case plugin has internal package dependencies sys.path.append(os.path.join(config.plugin_dir_path, name)) - # Create a logger for this 'found' plugin. Must be before the - # load.py is loaded. import EDMCLogging - + # Create a logger for this 'found' plugin. Must be before the load.py is loaded. plugin_logger = EDMCLogging.get_plugin_logger(name) found.append(Plugin(name, os.path.join(config.plugin_dir_path, name, 'load.py'), plugin_logger)) except Exception: logger.exception(f'Failure loading found Plugin "{name}"') pass - PLUGINS.extend(sorted(found, key=lambda p: operator.attrgetter('name')(p).lower())) + return found -def provides(fn_name: str) -> List[str]: +def provides(fn_name: str) -> list[str]: """ Find plugins that provide a function. @@ -202,7 +216,7 @@ def provides(fn_name: str) -> List[str]: def invoke( plugin_name: str, fallback: str | None, fn_name: str, *args: Any -) -> Optional[str]: +) -> str | None: """ Invoke a function on a named plugin. @@ -228,7 +242,7 @@ def invoke( return None -def notify_stop() -> Optional[str]: +def notify_stop() -> str | None: """ Notify each plugin that the program is closing. @@ -251,6 +265,16 @@ def notify_stop() -> Optional[str]: return error +def _notify_prefs_plugins(fn_name: str, cmdr: str | None, is_beta: bool) -> None: + for plugin in PLUGINS: + prefs_callback = plugin._get_func(fn_name) + if prefs_callback: + try: + prefs_callback(cmdr, is_beta) + except Exception: + logger.exception(f'Plugin "{plugin.name}" failed') + + def notify_prefs_cmdr_changed(cmdr: str | None, is_beta: bool) -> None: """ Notify plugins that the Cmdr was changed while the settings dialog is open. @@ -259,13 +283,7 @@ def notify_prefs_cmdr_changed(cmdr: str | None, is_beta: bool) -> None: :param cmdr: current Cmdr name (or None). :param is_beta: whether the player is in a Beta universe. """ - for plugin in PLUGINS: - prefs_cmdr_changed = plugin._get_func('prefs_cmdr_changed') - if prefs_cmdr_changed: - try: - prefs_cmdr_changed(cmdr, is_beta) - except Exception: - logger.exception(f'Plugin "{plugin.name}" failed') + _notify_prefs_plugins("prefs_cmdr_changed", cmdr, is_beta) def notify_prefs_changed(cmdr: str | None, is_beta: bool) -> None: @@ -278,20 +296,14 @@ def notify_prefs_changed(cmdr: str | None, is_beta: bool) -> None: :param cmdr: current Cmdr name (or None). :param is_beta: whether the player is in a Beta universe. """ - for plugin in PLUGINS: - prefs_changed = plugin._get_func('prefs_changed') - if prefs_changed: - try: - prefs_changed(cmdr, is_beta) - except Exception: - logger.exception(f'Plugin "{plugin.name}" failed') + _notify_prefs_plugins("prefs_changed", cmdr, is_beta) def notify_journal_entry( cmdr: str, is_beta: bool, system: str | None, station: str | None, entry: MutableMapping[str, Any], state: Mapping[str, Any] -) -> Optional[str]: +) -> str | None: """ Send a journal entry to each plugin. @@ -303,7 +315,7 @@ def notify_journal_entry( :param is_beta: whether the player is in a Beta universe. :returns: Error message from the first plugin that returns one (if any) """ - if entry['event'] in ('Location'): + if entry['event'] in 'Location': logger.trace_if('journal.locations', 'Notifying plugins of "Location" event') error = None @@ -323,7 +335,7 @@ def notify_journal_entry_cqc( cmdr: str, is_beta: bool, entry: MutableMapping[str, Any], state: Mapping[str, Any] -) -> Optional[str]: +) -> str | None: """ Send an in-CQC journal entry to each plugin. @@ -348,10 +360,7 @@ def notify_journal_entry_cqc( return error -def notify_dashboard_entry( - cmdr: str, is_beta: bool, - entry: MutableMapping[str, Any], -) -> Optional[str]: +def notify_dashboard_entry(cmdr: str, is_beta: bool, entry: MutableMapping[str, Any],) -> str | None: """ Send a status entry to each plugin. @@ -373,10 +382,7 @@ def notify_dashboard_entry( return error -def notify_capidata( - data: companion.CAPIData, - is_beta: bool -) -> Optional[str]: +def notify_capidata(data: companion.CAPIData, is_beta: bool) -> str | None: """ Send the latest EDMC data from the FD servers to each plugin. @@ -404,9 +410,7 @@ def notify_capidata( return error -def notify_capi_fleetcarrierdata( - data: companion.CAPIData -) -> str | None: +def notify_capi_fleetcarrierdata(data: companion.CAPIData) -> str | None: """ Send the latest CAPI Fleetcarrier data from the FD servers to each plugin. diff --git a/stats.py b/stats.py index d690dce6..041e47f3 100644 --- a/stats.py +++ b/stats.py @@ -1,12 +1,16 @@ -"""CMDR Status information.""" +""" +stats.py - CMDR Status Information. + +Copyright (c) EDCD, All Rights Reserved +Licensed under the GNU General Public License. +See LICENSE file. +""" import csv import json import sys -import tkinter import tkinter as tk from tkinter import ttk from typing import TYPE_CHECKING, Any, AnyStr, Callable, NamedTuple, Sequence, cast - import companion import EDMCLogging import myNotebook as nb # noqa: N813 @@ -488,11 +492,11 @@ class StatsResults(tk.Toplevel): :param align: The alignment of the data, defaults to tk.W """ row = -1 # To silence unbound warnings - for i in range(len(content)): - # label = HyperlinkLabel(parent, text=content[i], popup_copy=True) - label = nb.Label(parent, text=content[i]) + for i, col_content in enumerate(content): + # label = HyperlinkLabel(parent, text=col_content, popup_copy=True) + label = nb.Label(parent, text=col_content) if with_copy: - label.bind('', self.copy_callback(label, content[i])) + label.bind('', self.copy_callback(label, col_content)) if i == 0: label.grid(padx=10, sticky=tk.W) @@ -512,7 +516,7 @@ class StatsResults(tk.Toplevel): @staticmethod def copy_callback(label: tk.Label, text_to_copy: str) -> Callable[..., None]: """Copy data in Label to clipboard.""" - def do_copy(event: tkinter.Event) -> None: + def do_copy(event: tk.Event) -> None: label.clipboard_clear() label.clipboard_append(text_to_copy) old_bg = label['bg'] From 170b86b5dc0c17cb1ec1fbc7f0423b29732a6c18 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Thu, 30 Nov 2023 21:45:04 -0500 Subject: [PATCH 54/83] [2051] Remove More Old Types --- build.py | 9 ++++----- docs/examples/click_counter/load.py | 9 ++++----- hotkey/__init__.py | 5 +++-- outfitting.py | 1 - plugins/eddn.py | 9 ++++----- prefs.py | 5 +++-- 6 files changed, 18 insertions(+), 20 deletions(-) diff --git a/build.py b/build.py index 7d182641..d6cecb7d 100644 --- a/build.py +++ b/build.py @@ -9,7 +9,6 @@ import os import shutil import sys import pathlib -from typing import List, Tuple from string import Template from os.path import join, isdir import py2exe @@ -57,8 +56,8 @@ def system_check(dist_dir: str) -> str: def generate_data_files( - app_name: str, gitversion_file: str, plugins: List[str] -) -> List[Tuple[str, List[str]]]: + app_name: str, gitversion_file: str, plugins: list[str] +) -> list[tuple[str, list[str]]]: """Create the required datafiles to build.""" l10n_dir = "L10n" fdevids_dir = "FDevIDs" @@ -106,7 +105,7 @@ def build() -> None: gitversion_filename: str = system_check(dist_dir) # Constants - plugins: List[str] = [ + plugins: list[str] = [ "plugins/coriolis.py", "plugins/eddn.py", "plugins/edsm.py", @@ -141,7 +140,7 @@ def build() -> None: } # Function to generate DATA_FILES list - data_files: List[Tuple[str, List[str]]] = generate_data_files( + data_files: list[tuple[str, list[str]]] = generate_data_files( appname, gitversion_filename, plugins ) diff --git a/docs/examples/click_counter/load.py b/docs/examples/click_counter/load.py index 0c65fc29..ad90a084 100644 --- a/docs/examples/click_counter/load.py +++ b/docs/examples/click_counter/load.py @@ -3,11 +3,10 @@ Example EDMC plugin. It adds a single button to the EDMC interface that displays the number of times it has been clicked. """ +from __future__ import annotations import logging import tkinter as tk -from typing import Optional - import myNotebook as nb # noqa: N813 from config import appname, config @@ -48,7 +47,7 @@ class ClickCounter: """ self.on_preferences_closed("", False) # Save our prefs - def setup_preferences(self, parent: nb.Notebook, cmdr: str, is_beta: bool) -> Optional[tk.Frame]: + def setup_preferences(self, parent: nb.Notebook, cmdr: str, is_beta: bool) -> tk.Frame | None: """ setup_preferences is called by plugin_prefs below. @@ -127,7 +126,7 @@ def plugin_stop() -> None: return cc.on_unload() -def plugin_prefs(parent: nb.Notebook, cmdr: str, is_beta: bool) -> Optional[tk.Frame]: +def plugin_prefs(parent: nb.Notebook, cmdr: str, is_beta: bool) -> tk.Frame | None: """ Handle preferences tab for the plugin. @@ -145,7 +144,7 @@ def prefs_changed(cmdr: str, is_beta: bool) -> None: return cc.on_preferences_closed(cmdr, is_beta) -def plugin_app(parent: tk.Frame) -> Optional[tk.Frame]: +def plugin_app(parent: tk.Frame) -> tk.Frame | None: """ Set up the UI of the plugin. diff --git a/hotkey/__init__.py b/hotkey/__init__.py index 52f8d684..e7515807 100644 --- a/hotkey/__init__.py +++ b/hotkey/__init__.py @@ -1,10 +1,11 @@ """Handle keyboard input for manual update triggering.""" +from __future__ import annotations + # -*- coding: utf-8 -*- import abc import sys from abc import abstractmethod -from typing import Optional, Tuple, Union class AbstractHotkeyMgr(abc.ABC): @@ -31,7 +32,7 @@ class AbstractHotkeyMgr(abc.ABC): pass @abstractmethod - def fromevent(self, event) -> Optional[Union[bool, Tuple]]: + def fromevent(self, event) -> bool | tuple | None: """ Return configuration (keycode, modifiers) or None=clear or False=retain previous. diff --git a/outfitting.py b/outfitting.py index 99d841f1..07e8ae76 100644 --- a/outfitting.py +++ b/outfitting.py @@ -10,7 +10,6 @@ from __future__ import annotations import json from collections import OrderedDict from typing import OrderedDict as OrderedDictT - from config import config from edmc_data import ( outfitting_armour_map as armour_map, diff --git a/plugins/eddn.py b/plugins/eddn.py index 0ab06a83..687b39b7 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -41,7 +41,6 @@ from typing import ( MutableMapping, ) from typing import OrderedDict as OrderedDictT -from typing import Tuple, Union import requests import companion import edmc_data @@ -100,8 +99,8 @@ class This: # Avoid duplicates self.marketId: str | None = None self.commodities: list[OrderedDictT[str, Any]] | None = None - self.outfitting: Tuple[bool, list[str]] | None = None - self.shipyard: Tuple[bool, list[Mapping[str, Any]]] | None = None + self.outfitting: tuple[bool, list[str]] | None = None + self.shipyard: tuple[bool, list[Mapping[str, Any]]] | None = None self.fcmaterials_marketid: int = 0 self.fcmaterials: list[OrderedDictT[str, Any]] | None = None self.fcmaterials_capi_marketid: int = 0 @@ -714,7 +713,7 @@ class EDDN: # Send any FCMaterials.json-equivalent 'orders' as well self.export_capi_fcmaterials(data, is_beta, horizons) - def safe_modules_and_ships(self, data: Mapping[str, Any]) -> Tuple[dict, dict]: + def safe_modules_and_ships(self, data: Mapping[str, Any]) -> tuple[dict, dict]: """ Produce a sanity-checked version of ships and modules from CAPI data. @@ -1091,7 +1090,7 @@ class EDDN: entry: MutableMapping[str, Any], system_name: str, system_coordinates: list - ) -> Union[str, MutableMapping[str, Any]]: + ) -> str | MutableMapping[str, Any]: """ Augment a journal entry with necessary system data. diff --git a/prefs.py b/prefs.py index e1ab6ea2..6e423acc 100644 --- a/prefs.py +++ b/prefs.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- """EDMC preferences library.""" +from __future__ import annotations import contextlib import logging @@ -13,7 +14,7 @@ from os.path import expanduser, expandvars, join, normpath from tkinter import colorchooser as tkColorChooser # type: ignore # noqa: N812 from tkinter import ttk from types import TracebackType -from typing import TYPE_CHECKING, Any, Callable, Optional, Type, Union +from typing import TYPE_CHECKING, Any, Callable, Optional, Type import myNotebook as nb # noqa: N813 import plug @@ -276,7 +277,7 @@ class PreferencesDialog(tk.Toplevel): self.resizable(tk.FALSE, tk.FALSE) - self.cmdr: Union[str, bool, None] = False # Note if Cmdr changes in the Journal + self.cmdr: str | bool | None = False # Note if Cmdr changes in the Journal self.is_beta: bool = False # Note if Beta status changes in the Journal self.cmdrchanged_alarm: Optional[str] = None # This stores an ID that can be used to cancel a scheduled call From f30fb56f6e1767d05d235f6e1077dd91eddce5e0 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Thu, 30 Nov 2023 22:05:59 -0500 Subject: [PATCH 55/83] [2051] Re-add missing context It's not a refactor if I don't accidentally nuke a lang comment --- companion.py | 4 ++++ plug.py | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/companion.py b/companion.py index 4f729479..3384af36 100644 --- a/companion.py +++ b/companion.py @@ -865,11 +865,15 @@ class Session: self.dump(response) if response.status_code == 401: + # TODO: This needs to try a REFRESH, not a full re-auth + # No need for translation, we'll go straight into trying new Auth + # and thus any message would be overwritten. # CAPI doesn't think we're Auth'd raise CredentialsRequireRefresh('Frontier CAPI said "unauthorized"') if response.status_code == 418: # "I'm a teapot" - used to signal maintenance + # LANG: Frontier CAPI returned 418, meaning down for maintenance raise ServerError(_("Frontier CAPI down for maintenance")) logger.exception('Frontier CAPI: Misc. Error') diff --git a/plug.py b/plug.py index de67205b..b343677b 100644 --- a/plug.py +++ b/plug.py @@ -84,7 +84,7 @@ class Plugin: else: logger.info(f'plugin {name} disabled') - def _get_func(self, funcname: str): # Removing Unhelpful Type Hint + def _get_func(self, funcname: str): """ Get a function from a plugin. From bc6b4f8b83bf78c0f00fbdc28c641ec6ed8ee42b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 1 Dec 2023 17:16:08 +0000 Subject: [PATCH 56/83] build(deps-dev): bump mypy from 1.7.0 to 1.7.1 Bumps [mypy](https://github.com/python/mypy) from 1.7.0 to 1.7.1. - [Changelog](https://github.com/python/mypy/blob/master/CHANGELOG.md) - [Commits](https://github.com/python/mypy/compare/v1.7.0...v1.7.1) --- updated-dependencies: - dependency-name: mypy 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 3ab5f9a3..3575f748 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -18,7 +18,7 @@ flake8-noqa==1.3.2 flake8-polyfill==1.0.2 flake8-use-fstring==1.4 -mypy==1.7.0 +mypy==1.7.1 pep8-naming==0.13.3 safety==2.3.5 types-requests==2.31.0.10 From 3646d93b863acae6b42542bd6925a54730b6f6f8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 1 Dec 2023 17:16:19 +0000 Subject: [PATCH 57/83] build(deps): bump certifi from 2023.7.22 to 2023.11.17 Bumps [certifi](https://github.com/certifi/python-certifi) from 2023.7.22 to 2023.11.17. - [Commits](https://github.com/certifi/python-certifi/compare/2023.07.22...2023.11.17) --- updated-dependencies: - dependency-name: certifi 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 4f35c140..398041a1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ -certifi==2023.7.22 +certifi==2023.11.17 requests==2.31.0 # requests depends on this now ? charset-normalizer==2.1.1 From 950c26b977c508f01d2533c2055263a9019dc362 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 1 Dec 2023 17:16:28 +0000 Subject: [PATCH 58/83] build(deps-dev): bump setuptools from 68.2.2 to 69.0.2 Bumps [setuptools](https://github.com/pypa/setuptools) from 68.2.2 to 69.0.2. - [Release notes](https://github.com/pypa/setuptools/releases) - [Changelog](https://github.com/pypa/setuptools/blob/main/NEWS.rst) - [Commits](https://github.com/pypa/setuptools/compare/v68.2.2...v69.0.2) --- updated-dependencies: - dependency-name: setuptools 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 3ab5f9a3..c9217b4a 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -5,7 +5,7 @@ wheel # We can't rely on just picking this up from either the base (not venv), # or venv-init-time version. Specify here so that dependabot will prod us # about new versions. -setuptools==68.2.2 +setuptools==69.0.2 # Static analysis tools flake8==6.1.0 From 7902610d10f57e7c3d58f659cb4147553844c1f3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 1 Dec 2023 17:36:48 +0000 Subject: [PATCH 59/83] build(deps): bump actions/github-script from 6 to 7 Bumps [actions/github-script](https://github.com/actions/github-script) from 6 to 7. - [Release notes](https://github.com/actions/github-script/releases) - [Commits](https://github.com/actions/github-script/compare/v6...v7) --- updated-dependencies: - dependency-name: actions/github-script dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/submodule-update.yml | 2 +- .github/workflows/windows-build.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/submodule-update.yml b/.github/workflows/submodule-update.yml index 17301d66..1f403c56 100644 --- a/.github/workflows/submodule-update.yml +++ b/.github/workflows/submodule-update.yml @@ -53,7 +53,7 @@ jobs: - name: Create or Update pull request against target branch if: steps.check_for_changes.outputs.changes == 'true' - uses: actions/github-script@v6 + uses: actions/github-script@v7 with: github-token: "${{ secrets.GITHUB_TOKEN }}" script: | diff --git a/.github/workflows/windows-build.yml b/.github/workflows/windows-build.yml index b50f868f..a3de381b 100644 --- a/.github/workflows/windows-build.yml +++ b/.github/workflows/windows-build.yml @@ -15,7 +15,7 @@ jobs: runs-on: "ubuntu-latest" steps: - name: Setting global variables - uses: actions/github-script@v6 + uses: actions/github-script@v7 id: var with: script: | From 173c32f31407bdebb5bfd3ce90b83cb8abfe8de9 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Wed, 6 Dec 2023 17:15:46 -0500 Subject: [PATCH 60/83] [Minor] Update Code Checks --- plugins/edsm.py | 2 +- plugins/inara.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/edsm.py b/plugins/edsm.py index 82324ced..4218db00 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -352,7 +352,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: Optional[str], is_beta: bool) -> tk show_password_checkbox = nb.Checkbutton( frame, - text=_('Show API Key'), # LANG: Text EDSM Show API Key + text=_('Show API Key'), # LANG: Text EDSM Show API Key variable=show_password_var, command=toggle_password_visibility ) diff --git a/plugins/inara.py b/plugins/inara.py index ec034840..54f0f090 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -292,7 +292,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str, is_beta: bool) -> tk.Frame: show_password_var.set(False) # Password is initially masked show_password_checkbox = nb.Checkbutton( frame, - text=_('Show API Key'), # LANG: Text Inara Show API key + text=_('Show API Key'), # LANG: Text Inara Show API key variable=show_password_var, command=toggle_password_visibility, ) From c511b510032bf1d62b36b2eaa6b5fe3cab5ce23f Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Wed, 6 Dec 2023 17:41:22 -0500 Subject: [PATCH 61/83] [Translations] Update Translation Template --- L10n/en.template | 12 +++++++++--- plugins/edsm.py | 5 ++--- plugins/inara.py | 2 ++ 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/L10n/en.template b/L10n/en.template index d3b265b7..89ad3396 100644 --- a/L10n/en.template +++ b/L10n/en.template @@ -280,8 +280,8 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Sending data to EDDN..."; -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Send flight log and Cmdr status to EDSM"; +/* edsm.py:Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:316; */ +"Send flight log and CMDR status to EDSM" = "Send flight log and CMDR status to EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite Dangerous Star Map credentials"; @@ -461,7 +461,7 @@ "Enabled Plugins" = "Enabled Plugins"; /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support:" = "Plugins Without Python 3.x Support:"; +"Plugins Without Python 3.x Support" = "Plugins Without Python 3.x Support:"; /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Information on migrating plugins"; @@ -768,3 +768,9 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Ships"; + +/* prefs.py:Label on button used to open a filesystem folder; In files: prefs.py:706; */ +"Open Log Folder" = "Open Log Folder"; + +/* inara.py:Text Inara Show API key; In files: inara.py:305; */ +"Show API Key" = "Show API Key"; \ No newline at end of file diff --git a/plugins/edsm.py b/plugins/edsm.py index 290b168b..754ffb61 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -313,7 +313,7 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr this.log = tk.IntVar(value=config.get_int('edsm_out') and 1) this.log_button = nb.Checkbutton( frame, - text=_('Send flight log and CMDR status to EDSM'), # LANG: Send flight log and CMDR Status to EDSM + text=_('Send flight log and CMDR status to EDSM'), # LANG: Settings>EDSM - Label on checkbox for 'send data' variable=this.log, command=prefsvarchanged ) @@ -335,9 +335,8 @@ def plugin_prefs(parent: ttk.Notebook, cmdr: str | None, is_beta: bool) -> tk.Fr ) if this.label: this.label.grid(row=cur_row, columnspan=2, padx=PADX, pady=PADY, sticky=tk.W) - # LANG: Game Commander name label in EDSM settings cur_row += 1 - this.cmdr_label = nb.Label(frame, text=_('Cmdr')) + this.cmdr_label = nb.Label(frame, text=_('Cmdr')) # LANG: Game Commander name label in EDSM settings this.cmdr_label.grid(row=cur_row, padx=PADX, pady=PADY, sticky=tk.W) this.cmdr_text = nb.Label(frame) this.cmdr_text.grid(row=cur_row, column=1, padx=PADX, pady=BOXY, sticky=tk.W) diff --git a/plugins/inara.py b/plugins/inara.py index 83093972..199e6a1c 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -1611,6 +1611,7 @@ def handle_api_error(data: Mapping[str, Any], status: int, reply: dict[str, Any] error_message = reply['header'].get('eventStatusText', "") logger.warning(f'Inara\t{status} {error_message}') logger.debug(f'JSON data:\n{json.dumps(data, indent=2, separators = (",", ": "))}') + # LANG: INARA API returned some kind of error (error message will be contained in {MSG}) plug.show_error(_('Error: Inara {MSG}').format(MSG=error_message)) @@ -1643,6 +1644,7 @@ def handle_individual_error(data_event: dict[str, Any], reply_status: int, reply logger.debug(f'JSON data:\n{json.dumps(data_event)}') if reply_status // 100 != 2: + # LANG: INARA API returned some kind of error (error message will be contained in {MSG}) plug.show_error(_('Error: Inara {MSG}').format( MSG=f'{data_event["eventName"]}, {reply_text}' )) From 4634232d6ab647cdf579cf9426e3747d276b6c26 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Wed, 6 Dec 2023 18:58:25 -0500 Subject: [PATCH 62/83] [Minor] Bump Appversion --- config/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/__init__.py b/config/__init__.py index ca964274..c9a34c78 100644 --- a/config/__init__.py +++ b/config/__init__.py @@ -54,7 +54,7 @@ appcmdname = 'EDMC' # # Major.Minor.Patch(-prerelease)(+buildmetadata) # NB: Do *not* import this, use the functions appversion() and appversion_nobuild() -_static_appversion = '5.10.0-alpha0' +_static_appversion = '5.10.0-beta1' _cached_version: semantic_version.Version | None = None copyright = '© 2015-2019 Jonathan Harris, 2020-2023 EDCD' From 21268d5f19df3f2bf15cab9f5e718917c1192981 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Thu, 7 Dec 2023 11:55:07 -0500 Subject: [PATCH 63/83] [Minor] Correct Spelling of Spansh --- plugins/spansh_core.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/spansh_core.py b/plugins/spansh_core.py index 8a7d87be..77106da8 100644 --- a/plugins/spansh_core.py +++ b/plugins/spansh_core.py @@ -57,7 +57,7 @@ def plugin_start3(plugin_dir: str) -> str: :param plugin_dir: Name of directory this was loaded from. :return: Identifier string for this plugin. """ - return 'spansh' + return 'Spansh' def plugin_app(parent: tk.Tk) -> None: From 95f2ea40b6626d8000fce99f604507c51798306a Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Tue, 12 Dec 2023 21:28:56 -0500 Subject: [PATCH 64/83] [#1843] Fix URL Parameter Bug Replaces vague space with properly encoded %20. This SHOULD solve the issue, but I can't replicate the original issue. --- companion.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/companion.py b/companion.py index 3384af36..520afff2 100644 --- a/companion.py +++ b/companion.py @@ -395,7 +395,7 @@ class Auth: webbrowser.open( f'{FRONTIER_AUTH_SERVER}{self.FRONTIER_AUTH_PATH_AUTH}?response_type=code' f'&audience=frontier,steam,epic' - f'&scope=auth capi' + f'&scope=auth%20capi' f'&client_id={self.CLIENT_ID}' f'&code_challenge={challenge}' f'&code_challenge_method=S256' From 761e9f0f5939882c1f4ff63489f0cfde0cf15d4a Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Wed, 13 Dec 2023 17:27:33 -0500 Subject: [PATCH 65/83] [Translations] Update Translation Files --- L10n/cs.strings | 8 +- L10n/de.strings | 8 +- L10n/en.template | 24 +++-- L10n/es.strings | 8 +- L10n/fi.strings | 11 ++- L10n/fr.strings | 3 +- L10n/hu.strings | 3 +- L10n/it.strings | 195 ++++++++++++++++++++++++++++++++++++++-- L10n/ja.strings | 16 +++- L10n/ko.strings | 8 +- L10n/lv.strings | 1 + L10n/nl.strings | 3 +- L10n/pl.strings | 12 ++- L10n/pt-BR.strings | 16 +++- L10n/pt-PT.strings | 16 +++- L10n/ru.strings | 16 +++- L10n/sl.strings | 1 + L10n/sr-Latn-BA.strings | 8 +- L10n/sr-Latn.strings | 8 +- L10n/sv-SE.strings | 3 +- L10n/uk.strings | 5 +- L10n/zh-Hans.strings | 41 ++++++++- 22 files changed, 364 insertions(+), 50 deletions(-) diff --git a/L10n/cs.strings b/L10n/cs.strings index ffbc24cb..609a3788 100644 --- a/L10n/cs.strings +++ b/L10n/cs.strings @@ -205,6 +205,9 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Neplatný režim přepisu Coriolis!"; + +/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ +"EDDB Journal processing disabled. See Log." = "Zpracování EDDB deníku je deaktivováno. Zkontrolujte log."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Chyba: Nelze se připojit k EDDN"; @@ -223,9 +226,9 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Odesílání dat do EDDN..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "Odesílat letový log a status CMDRa do EDSM"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Přihlašovací údaje Elite Dangerous Star Map"; @@ -382,9 +385,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Zapnuté pluginy"; + /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ "Plugins Without Python 3.x Support:" = "Pluginy bez podpory Python 3.x:"; - /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informace jak migrovat pluginy."; @@ -618,3 +621,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Lodě"; + diff --git a/L10n/de.strings b/L10n/de.strings index 898821cb..dec95f42 100644 --- a/L10n/de.strings +++ b/L10n/de.strings @@ -253,6 +253,9 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Ungültiger Coriolis-Überschreibungsmodus!"; + +/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ +"EDDB Journal processing disabled. See Log." = "EDDB Journal-Verarbeitung deaktiviert. Siehe Log."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Fehler: Keine Verbindung zum EDDN"; @@ -280,9 +283,9 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Daten werden an das EDDN gesendet..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "Sende Fluglog und CMDR-Status an EDSM"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite: Dangerous Star Map Anmeldedaten"; @@ -460,9 +463,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Aktivierte Plugins"; + /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ "Plugins Without Python 3.x Support:" = "Plugins ohne Python 3.x Support"; - /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informationen zum Migrieren von Plugins"; @@ -744,3 +747,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Schiffe"; + diff --git a/L10n/en.template b/L10n/en.template index 89ad3396..a3432d6d 100644 --- a/L10n/en.template +++ b/L10n/en.template @@ -1,3 +1,11 @@ +/* edsm.py:Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:316; */ +"Send flight log and CMDR status to EDSM" = "Send flight log and CMDR status to EDSM"; + +/* prefs.py:Label on button used to open a filesystem folder; In files: prefs.py:706; */ +"Open Log Folder" = "Open Log Folder"; + +/* inara.py:Text Inara Show API key; In files: inara.py:305; */ +"Show API Key" = "Show API Key"; /* Language name */ "!Language" = "English"; @@ -253,6 +261,9 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Invalid Coriolis override mode!"; + +/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ +"EDDB Journal processing disabled. See Log." = "EDDB Journal processing disabled. See Log."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Error: Can't connect to EDDN"; @@ -280,9 +291,9 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Sending data to EDDN..."; -/* edsm.py:Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:316; */ -"Send flight log and CMDR status to EDSM" = "Send flight log and CMDR status to EDSM"; +/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ +"Send flight log and Cmdr status to EDSM" = "Send flight log and Cmdr status to EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite Dangerous Star Map credentials"; @@ -460,9 +471,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Enabled Plugins"; -/* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support" = "Plugins Without Python 3.x Support:"; +/* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ +"Plugins Without Python 3.x Support:" = "Plugins Without Python 3.x Support:"; /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Information on migrating plugins"; @@ -769,8 +780,3 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Ships"; -/* prefs.py:Label on button used to open a filesystem folder; In files: prefs.py:706; */ -"Open Log Folder" = "Open Log Folder"; - -/* inara.py:Text Inara Show API key; In files: inara.py:305; */ -"Show API Key" = "Show API Key"; \ No newline at end of file diff --git a/L10n/es.strings b/L10n/es.strings index 6377ebc8..4126b73f 100644 --- a/L10n/es.strings +++ b/L10n/es.strings @@ -211,6 +211,9 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "¡Modo sobrescritura de Coriolis Inválido!"; + +/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ +"EDDB Journal processing disabled. See Log." = "Procesamiento de Journal para EDDB desactivado. Ver Log."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Error: No se puede conectar a EDDN"; @@ -238,9 +241,9 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Enviando datos a EDDN..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "Enviar Registro de Vuelo y estado del CMDT a EDSM"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Credenciales de Elite Dangerous Star Map"; @@ -397,9 +400,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Plugins Activados"; + /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ "Plugins Without Python 3.x Support:" = "Plugins sin soporte para Python 3.x:"; - /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Información sobre migración de plugins"; @@ -633,3 +636,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Naves"; + diff --git a/L10n/fi.strings b/L10n/fi.strings index 6a7b54af..af51d505 100644 --- a/L10n/fi.strings +++ b/L10n/fi.strings @@ -178,6 +178,9 @@ /* l10n.py: The system default language choice in Settings > Appearance; prefs.py: Settings > Configuration - Label on 'reset journal files location to default' button; prefs.py: The system default language choice in Settings > Appearance; prefs.py: Label for 'Default' theme radio button; In files: l10n.py:193; prefs.py:455; prefs.py:709; prefs.py:742; */ "Default" = "Oletus"; + +/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ +"EDDB Journal processing disabled. See Log." = "EDDB lokikirjan käsittely ei käytössä. Katso lokitiedot."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Virhe: ei saatu yhteyttä EDDN:ään"; @@ -190,12 +193,15 @@ /* eddn.py: EDDN delay sending until docked option is on, this message notes that a send was skipped due to this; In files: eddn.py:2063; */ "Delay sending until docked" = "Lähetä tiedot vasta telakoitumisen jälkeen"; +/* eddn.py: Killswitch disabled EDDN; In files: eddn.py:2178; */ +"EDDN journal handler disabled. See Log." = "EDDB lokikirjan käsittelijä ei käytössä. Katso lokitiedot."; + /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Lähetetään tietoja EDDN:ään..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "Lähetä lentoloki ja komentajatiedot EDSM:ään"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite Dangerous Star Map -kirjautuminen"; @@ -352,9 +358,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Käytössä olevat liitännäiset"; + /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ "Plugins Without Python 3.x Support:" = "Lisäosat, joissa ei ole Python 3.x -tukea:"; - /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Tietoja lisäosien siirrosta"; @@ -588,3 +594,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Alukset"; + diff --git a/L10n/fr.strings b/L10n/fr.strings index d1ca4b60..7507516a 100644 --- a/L10n/fr.strings +++ b/L10n/fr.strings @@ -151,9 +151,9 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Envoi des données à EDDN..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "Envoyer le journal de vol et le statut Cmdr à EDSM"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Informations d'identification pour Elite Dangerous Star Map"; @@ -516,3 +516,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Vaisseaux"; + diff --git a/L10n/hu.strings b/L10n/hu.strings index b6d622d1..ea34484a 100644 --- a/L10n/hu.strings +++ b/L10n/hu.strings @@ -142,9 +142,9 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Adatok küldése az EDDN-nek..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "Repülési napló és Parancsnok státusz küldése az EDSM-nek"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite Dangerous Csillag térkép hitelesítése"; @@ -501,3 +501,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Hajók"; + diff --git a/L10n/it.strings b/L10n/it.strings index 09149c99..b6ec19ac 100644 --- a/L10n/it.strings +++ b/L10n/it.strings @@ -1,9 +1,15 @@ /* Language name */ "!Language" = "Italiano"; +/* 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?"; + /* companion.py: Generic "something went wrong with Frontier Auth" error; In files: companion.py:271; */ "Error: Invalid Credentials" = "Errore: Credenziali non valide"; @@ -13,6 +19,21 @@ /* companion.py: Generic error prefix - following text is from Frontier auth service; In files: companion.py:432; companion.py:517; */ "Error" = "Errore"; +/* companion.py: Frontier auth, no 'usr' section in returned data; companion.py: Frontier auth, no 'customer_id' in 'usr' section in returned data; In files: companion.py:475; companion.py:480; */ +"Error: Couldn't check token customer_id" = "Errore: Impossibile controllare il token customer_id"; + +/* companion.py: Frontier auth customer_id doesn't match game session FID; In files: companion.py:486; */ +"Error: customer_id doesn't match!" = "Errore: Customer_id non corrisponde!"; + +/* companion.py: Failed to get Access Token from Frontier Auth service; In files: companion.py:508; */ +"Error: unable to get token" = "Errore: impossibile ottenere il token"; + +/* companion.py: Frontier CAPI returned 418, meaning down for maintenance; In files: companion.py:844; */ +"Frontier CAPI down for maintenance" = "CAPI di Frontier inattivo per manutenzione"; + +/* companion.py: Frontier CAPI data retrieval failed; In files: companion.py:856; */ +"Frontier CAPI query failure" = "Errore nella query CAPI di Frontier"; + /* EDMarketConnector.py: Main UI Update button; EDMarketConnector.py: Update button in main window; In files: EDMarketConnector.py:601; EDMarketConnector.py:919; EDMarketConnector.py:1748; */ "Update" = "Recupera"; @@ -20,7 +41,10 @@ "Always on top" = "Sempre in primo piano"; /* EDMarketConnector.py: Unknown suit; In files: EDMarketConnector.py:837; */ -"Unknown" = "Sconosciuto"; +"Unknown" = "Sconosciuta"; + +/* EDMarketConnector.py: ED Journal file location appears to be in error; In files: EDMarketConnector.py:906; */ +"Error: Check E:D journal file location" = "Errore: Controllare la posizione del file journal E:D"; /* EDMarketConnector.py: Label for commander name in main window; edsm.py: Game Commander name label in EDSM settings; stats.py: Cmdr stats; theme.py: Label for commander name in main window; In files: EDMarketConnector.py:913; edsm.py:332; stats.py:57; theme.py:290; */ "Cmdr" = "Cmdr"; @@ -70,6 +94,12 @@ /* EDMarketConnector.py: Help > Documentation; In files: EDMarketConnector.py:933; EDMarketConnector.py:953; */ "Documentation" = "Documentazione"; +/* EDMarketConnector.py: Help > Troubleshooting; In files: EDMarketConnector.py:934; EDMarketConnector.py:954; */ +"Troubleshooting" = "Risoluzione dei problemi"; + +/* EDMarketConnector.py: Help > Report A Bug; In files: EDMarketConnector.py:935; EDMarketConnector.py:955; */ +"Report A Bug" = "Segnalare un bug"; + /* EDMarketConnector.py: Help > Privacy Policy; In files: EDMarketConnector.py:936; EDMarketConnector.py:956; */ "Privacy Policy" = "Informativa sulla privacy"; @@ -85,6 +115,9 @@ /* 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" = "Copia"; +/* 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" = "Autenticazione CAPI disabilitata dal killswitch"; + /* EDMarketConnector.py: Status - Attempting to get a Frontier Auth Access Token; In files: EDMarketConnector.py:978; */ "Logging in..." = "Mi sto loggando..."; @@ -100,9 +133,36 @@ /* EDMarketConnector.py: Status - No station market data from Frontier CAPI; In files: EDMarketConnector.py:1038; */ "Station doesn't have a market!" = "La Stazione non ha un Market !"; +/* EDMarketConnector.py: CAPI queries aborted because Cmdr name is unknown; EDMarketConnector.py: CAPI fleetcarrier query aborted because Cmdr name is unknown; In files: EDMarketConnector.py:1077; EDMarketConnector.py:1164; */ +"CAPI query aborted: Cmdr name unknown" = "Query CAPI interrotta: nome comando sconosciuto"; + +/* EDMarketConnector.py: CAPI queries aborted because game mode unknown; In files: EDMarketConnector.py:1083; */ +"CAPI query aborted: Game mode unknown" = "Query CAPI interrotta: Modalità di gioco sconosciuta"; + +/* EDMarketConnector.py: CAPI queries aborted because GameVersion unknown; EDMarketConnector.py: CAPI fleetcarrier query aborted because GameVersion unknown; In files: EDMarketConnector.py:1089; EDMarketConnector.py:1170; */ +"CAPI query aborted: GameVersion unknown" = "Query CAPI interrotta: Versione del gioco sconosciuta"; + +/* EDMarketConnector.py: CAPI queries aborted because current star system name unknown; In files: EDMarketConnector.py:1095; */ +"CAPI query aborted: Current system unknown" = "Query CAPI interrotta: Sistema attuale sconosciuto"; + +/* EDMarketConnector.py: CAPI queries aborted because player is in multi-crew on other Cmdr's ship; In files: EDMarketConnector.py:1101; */ +"CAPI query aborted: In other-ship multi-crew" = "Query CAPI interrotta: In multi-crew di un'altra nave"; + +/* EDMarketConnector.py: CAPI queries aborted because player is in CQC (Arena); In files: EDMarketConnector.py:1107; */ +"CAPI query aborted: CQC (Arena) detected" = "Query CAPI interrotta: CQC (Arena) rilevato"; + /* EDMarketConnector.py: Status - Attempting to retrieve data from Frontier CAPI; In files: EDMarketConnector.py:1128; EDMarketConnector.py:1179; */ "Fetching data..." = "Sto raccogliendo i dati..."; +/* EDMarketConnector.py: CAPI fleetcarrier query aborted because of killswitch; In files: EDMarketConnector.py:1157; */ +"CAPI fleetcarrier disabled by killswitch" = "Fleetcarrier CAPI disabilitato dal killswitch"; + +/* EDMarketConnector.py: No data was returned for the fleetcarrier from the Frontier CAPI; In files: EDMarketConnector.py:1219; */ +"CAPI: No fleetcarrier data returned" = "CAPI: Nessun dato della fleetcarrier ricevuto"; + +/* EDMarketConnector.py: We didn't have the fleetcarrier callsign when we should have; In files: EDMarketConnector.py:1223; */ +"CAPI: Fleetcarrier data incomplete" = "CAPI: Dati della Fleetcarrier incompleti"; + /* EDMarketConnector.py: No data was returned for the commander from the Frontier CAPI; In files: EDMarketConnector.py:1242; */ "CAPI: No commander data returned" = "CAPI: Nessun dato sul commandante"; @@ -118,6 +178,9 @@ /* EDMarketConnector.py: Frontier CAPI server error when fetching data; In files: EDMarketConnector.py:1384; */ "Frontier CAPI server error" = "Errore nel server Frontier CAPI"; +/* EDMarketConnector.py: Frontier CAPI Access Token expired, trying to get a new one; In files: EDMarketConnector.py:1390; */ +"CAPI: Refreshing access token..." = "CAPI: Aggiornamento del token di accesso in corso..."; + /* EDMarketConnector.py: Time when we last obtained Frontier CAPI data; In files: EDMarketConnector.py:1434; */ "Last updated at %H:%M:%S" = "Ultimo aggiornamento alle %H:%M:%S"; @@ -172,11 +235,14 @@ /* coriolis.py: 'Beta' label for Coriolis site override selection; coriolis.py: Coriolis normal/beta selection - beta; In files: coriolis.py:76; coriolis.py:122; coriolis.py:138; */ "Beta" = "Beta"; +/* coriolis.py: Settings>Coriolis: Help/hint for changing coriolis URLs; In files: coriolis.py:91:93; */ +"Set the URL to use with coriolis.io ship loadouts. Note that this MUST end with '/import?data='" = "Imposta l'URL da utilizzare con gli equipaggiamenti delle navi coriolis.io. Tieni presente che DEVE terminare con '/import?data='"; + /* coriolis.py: Settings>Coriolis: Label for 'NOT alpha/beta game version' URL; In files: coriolis.py:97; */ "Normal URL" = "URL normale"; /* coriolis.py: Generic 'Reset' button label; In files: coriolis.py:100; coriolis.py:109; */ -"Reset" = "Reimposta"; +"Reset" = "Reset"; /* coriolis.py: Settings>Coriolis: Label for 'alpha/beta game version' URL; In files: coriolis.py:106; */ "Beta URL" = "URL Beta"; @@ -184,9 +250,24 @@ /* coriolis.py: Settings>Coriolis: Label for selection of using Normal, Beta or 'auto' Coriolis URL; In files: coriolis.py:116; */ "Override Beta/Normal Selection" = "Sovrascrivi selezione Beta/Normale"; +/* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ +"Invalid Coriolis override mode!" = "Modalità override Coriolis non valida!"; + + +/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ +"EDDB Journal processing disabled. See Log." = "Elaborazione di EDDB Journal disabilitata. Vedi il Log."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Errore: Non riesco a connettermi a EDDN"; +/* eddn.py: EDDN has banned this version of our client; In files: eddn.py:576; */ +"EDDN Error: EDMC is too old for EDDN. Please update." = "Errore EDDN: EDMC è troppo vecchio per EDDN. Per favore aggiornalo."; + +/* eddn.py: EDDN returned an error that indicates something about what we sent it was wrong; In files: eddn.py:582; */ +"EDDN Error: Validation Failed (EDMC Too Old?). See Log" = "Errore EDDN: Convalida fallita (EDMC è troppo vecchio?). Vedi il Log"; + +/* eddn.py: EDDN returned some sort of HTTP error, one we didn't expect. {STATUS} contains a number; In files: eddn.py:587; */ +"EDDN Error: Returned {STATUS} status code" = "Errore EDDN: Restituito codice di stato {STATUS}"; + /* eddn.py: Enable EDDN support for station data checkbox label; In files: eddn.py:2041; */ "Send station data to the Elite Dangerous Data Network" = "Manda i dati della stazione a Elite Dangerous Data Network"; @@ -196,12 +277,15 @@ /* eddn.py: EDDN delay sending until docked option is on, this message notes that a send was skipped due to this; In files: eddn.py:2063; */ "Delay sending until docked" = "Ritarda l'invio fino a che si è ormeggiati"; +/* eddn.py: Killswitch disabled EDDN; In files: eddn.py:2178; */ +"EDDN journal handler disabled. See Log." = "Gestore journal EDDN disabilitato. Vedi il Log."; + /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Sto inviando i dati a EDDN..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "Manda il flight log e lo stato Cmdr a EDSM"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Credenziali per Elite Dangerous Star Map"; @@ -214,6 +298,12 @@ /* edsm.py: We have no data on the current commander; prefs.py: No hotkey/shortcut set; stats.py: No rank; In files: edsm.py:394; prefs.py:527; prefs.py:1157; prefs.py:1190; stats.py:154; stats.py:173; stats.py:192; stats.py:209; */ "None" = "Nessuna"; +/* edsm.py: EDSM plugin - Journal handling disabled by killswitch; In files: edsm.py:516; */ +"EDSM Handler disabled. See Log." = "Gestore EDSM disattivato. Vedi il Log."; + +/* edsm.py: EDSM - Only Live data; In files: edsm.py:632; */ +"EDSM only accepts Live galaxy data" = "EDSM accetta solo dati Galaxy Live"; + /* edsm.py: EDSM Plugin - Error message from EDSM API; In files: edsm.py:916; edsm.py:1048; */ "Error: EDSM {MSG}" = "Errore: EDSM {MSG}"; @@ -226,6 +316,9 @@ /* inara.py: Text for INARA API keys link ( goes to https://inara.cz/settings-api ); In files: inara.py:269; */ "Inara credentials" = "Credenziali per Inara"; +/* inara.py: The Inara API only accepts Live galaxy data, not Legacy galaxy data; inara.py: Inara - Only Live data; In files: inara.py:384; inara.py:386; */ +"Inara only accepts Live galaxy data" = "Inara accetta solo dati Galaxy Live"; + /* inara.py: INARA support disabled via killswitch; In files: inara.py:395; */ "Inara disabled. See Log." = "Inara disabilitato. Vedi il Log."; @@ -265,6 +358,12 @@ /* prefs.py: Settings > Configuration - Label for Journal files location; In files: prefs.py:431; prefs.py:446; */ "E:D journal file location" = "locazione del file E:D journal"; +/* prefs.py: Settings > Configuration - Label for CAPI section; In files: prefs.py:469; */ +"CAPI Settings" = "Impostazioni CAPI"; + +/* prefs.py: Configuration - Enable or disable the Fleet Carrier CAPI calls; In files: prefs.py:475; */ +"Enable Fleetcarrier CAPI Queries" = "Abilita le query CAPI della Fleetcarrier"; + /* prefs.py: Hotkey/Shortcut settings prompt on OSX; In files: prefs.py:490; */ "Keyboard shortcut" = "Scorciatoia di tastiera"; @@ -293,10 +392,10 @@ "Preferred websites" = "Sito web preferito"; /* prefs.py: Label for Shipyard provider selection; In files: prefs.py:588; */ -"Shipyard" = "Spazioporto"; +"Shipyard" = "Shipyard"; /* prefs.py: Label for checkbox to utilise alternative Coriolis URL method; In files: prefs.py:600; */ -"Use alternate URL method" = "Usare metodo URL alternativo"; +"Use alternate URL method" = "Usa metodo URL alternativo"; /* prefs.py: Configuration - Label for selection of Log Level; In files: prefs.py:653; */ "Log Level" = "Livello di Log"; @@ -304,6 +403,15 @@ /* prefs.py: Label for 'Configuration' tab in Settings; In files: prefs.py:681; */ "Configuration" = "Configurazione"; +/* prefs.py: UI elements privacy section header in privacy tab of preferences; In files: prefs.py:690; */ +"Main UI privacy options" = "Opzioni privacy dell'interfaccia utente"; + +/* prefs.py: Hide private group owner name from UI checkbox; In files: prefs.py:695; */ +"Hide private group name in UI" = "Nascondi il nome del private group nell'interfaccia"; + +/* prefs.py: Hide multicrew captain name from main UI checkbox; In files: prefs.py:699; */ +"Hide multi-crew captain name" = "Nascondi il nome del capitano in multi-crew."; + /* prefs.py: Preferences privacy tab title; In files: prefs.py:703; */ "Privacy" = "Dati personali"; @@ -347,7 +455,7 @@ "Plugins folder" = "Cartella dei plugins"; /* prefs.py: Label on button used to open a filesystem folder; In files: prefs.py:915; */ -"Open" = "Apri"; +"Open" = "Sfoglia"; /* 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" = "Suggerimento: è possibile disabilitare un plugin {CR}aggiungendo '{EXT}' nel nome della sua cartella"; @@ -355,9 +463,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Plugin abilitati"; + /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ "Plugins Without Python 3.x Support:" = "Plugin senza il supporto a Python 3.x :"; - /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informazioni sulla migrazione dei plugins"; @@ -373,6 +481,21 @@ /* stats.py: Top rank; In files: stats.py:63; */ "Elite" = "Elite"; +/* stats.py: Top rank +1; In files: stats.py:64; */ +"Elite I" = "Elite I"; + +/* stats.py: Top rank +2; In files: stats.py:65; */ +"Elite II" = "Elite II"; + +/* stats.py: Top rank +3; In files: stats.py:66; */ +"Elite III" = "Elite III"; + +/* stats.py: Top rank +4; In files: stats.py:67; */ +"Elite IV" = "Elite IV"; + +/* stats.py: Top rank +5; In files: stats.py:68; */ +"Elite V" = "Elite V"; + /* stats.py: Ranking; In files: stats.py:74; */ "Combat" = "Combat"; @@ -382,6 +505,12 @@ /* stats.py: Ranking; In files: stats.py:76; */ "Explorer" = "Explorer"; +/* stats.py: Ranking; In files: stats.py:77; */ +"Mercenary" = "Mercenary"; + +/* stats.py: Ranking; In files: stats.py:78; */ +"Exobiologist" = "Exobiologist"; + /* stats.py: Ranking; In files: stats.py:79; */ "CQC" = "CQC"; @@ -466,6 +595,51 @@ /* stats.py: Explorer rank; In files: stats.py:118; */ "Pioneer" = "Pioneer"; +/* stats.py: Mercenary rank; In files: stats.py:122; */ +"Defenceless" = "Defenceless"; + +/* stats.py: Mercenary rank; In files: stats.py:123; */ +"Mostly Defenceless" = "Mostly Defenceless"; + +/* stats.py: Mercenary rank; In files: stats.py:124; */ +"Rookie" = "Rookie"; + +/* stats.py: Mercenary rank; In files: stats.py:125; */ +"Soldier" = "Soldier"; + +/* stats.py: Mercenary rank; In files: stats.py:126; stats.py:128; */ +"Gunslinger" = "Gunslinger"; + +/* stats.py: Mercenary rank; In files: stats.py:127; */ +"Warrior" = "Warrior"; + +/* stats.py: Mercenary rank; In files: stats.py:129; */ +"Deadeye" = "Deadeye"; + +/* stats.py: Exobiologist rank; In files: stats.py:132; */ +"Directionless" = "Directionless"; + +/* stats.py: Exobiologist rank; In files: stats.py:133; */ +"Mostly Directionless" = "Mostly Directionless"; + +/* stats.py: Exobiologist rank; In files: stats.py:134; */ +"Compiler" = "Compiler"; + +/* stats.py: Exobiologist rank; In files: stats.py:135; */ +"Collector" = "Collector"; + +/* stats.py: Exobiologist rank; In files: stats.py:136; */ +"Cataloguer" = "Cataloguer"; + +/* stats.py: Exobiologist rank; In files: stats.py:137; */ +"Taxonomist" = "Taxonomist"; + +/* stats.py: Exobiologist rank; In files: stats.py:138; */ +"Ecologist" = "Ecologist"; + +/* stats.py: Exobiologist rank; In files: stats.py:139; */ +"Geneticist" = "Geneticist"; + /* stats.py: CQC rank; In files: stats.py:142; */ "Helpless" = "Helpless"; @@ -586,8 +760,15 @@ /* stats.py: Power rank; In files: stats.py:197; */ "Rating 5" = "Rating 5"; +/* stats.py: Current commander unknown when trying to use 'File' > 'Status'; In files: stats.py:315; */ +"Status: Don't yet know your Commander name" = "Stato: Non conosco ancora il nome del tuo comandante"; + +/* stats.py: No Frontier CAPI data yet when trying to use 'File' > 'Status'; In files: stats.py:323; */ +"Status: No CAPI data yet" = "Stato: Ancora nessun dato CAPI"; + /* stats.py: Status dialog subtitle - CR value of ship; In files: stats.py:409; */ "Value" = "Valore"; /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Navi"; + diff --git a/L10n/ja.strings b/L10n/ja.strings index 6b999088..3a8553ae 100644 --- a/L10n/ja.strings +++ b/L10n/ja.strings @@ -1,3 +1,11 @@ +/* edsm.py:Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:316; */ +"Send flight log and CMDR status to EDSM" = "フライトログとCMDRステータスを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" = "日本語"; @@ -253,6 +261,9 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "無効なCoriolis上書きモードです!"; + +/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ +"EDDB Journal processing disabled. See Log." = "EDDBジャーナル処理が無効です。ログを確認してください。"; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "エラー: EDDNに接続できません"; @@ -280,9 +291,9 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "EDDNにデータ送信中..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "フライトログとCMDRステータスをEDSMへ送信する"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite Dangerous Star Mapの認証情報"; @@ -460,9 +471,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "有効なプラグイン"; + /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ "Plugins Without Python 3.x Support:" = "Python 3.xサポートのないプラグイン:"; - /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "プラグインの移行に関する情報"; @@ -768,3 +779,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "所有船"; + diff --git a/L10n/ko.strings b/L10n/ko.strings index 2d69243f..b0701d1b 100644 --- a/L10n/ko.strings +++ b/L10n/ko.strings @@ -229,6 +229,9 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "잘못된 Coriolis 오버라이딩 모드입니다!"; + +/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ +"EDDB Journal processing disabled. See Log." = "EDDB 저널 처리 비활성화됨. 로그 참고 바람."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "오류: EDDN에 연결할 수 없음"; @@ -256,9 +259,9 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "EDDN에 정보 전송하는 중..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "EDSM에 flight 로그와 커맨더 상태 정보 전송하기"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite Dangerous Star Map 계정"; @@ -424,9 +427,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "활성 플러그인"; + /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ "Plugins Without Python 3.x Support:" = "Python 3.x을 지원하지 않는 플러그인:"; - /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "플러그인 위치 변경에 대한 정보"; @@ -666,3 +669,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "함선(들)"; + diff --git a/L10n/lv.strings b/L10n/lv.strings index 313620ab..3aa46284 100644 --- a/L10n/lv.strings +++ b/L10n/lv.strings @@ -480,3 +480,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Kuģi"; + diff --git a/L10n/nl.strings b/L10n/nl.strings index 79820570..eabde544 100644 --- a/L10n/nl.strings +++ b/L10n/nl.strings @@ -148,9 +148,9 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Bezig data te versturen naar EDDN..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "Stuur vlucht logboek en Cmdr status naar EDSM"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite Dangerous Star Map inlog gegevens"; @@ -516,3 +516,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Schepen"; + diff --git a/L10n/pl.strings b/L10n/pl.strings index e772dfe9..dc4182ab 100644 --- a/L10n/pl.strings +++ b/L10n/pl.strings @@ -232,6 +232,9 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Niewłaściwy tryb nadpisania Coriolis!"; + +/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ +"EDDB Journal processing disabled. See Log." = "Wyłączone przetwarzanie dziennika EDDB. Sprawdź logi."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Błąd: Brak połączenia z EDDN"; @@ -254,14 +257,14 @@ "Delay sending until docked" = "Czekaj z wysłaniem na zadokowanie"; /* eddn.py: Killswitch disabled EDDN; In files: eddn.py:2178; */ -"EDDN journal handler disabled. See Log." = "Wyłączona obsługa dziennika EDDN. Sprawdź logi."; +"EDDN journal handler disabled. See Log." = "Wyłączona obsługa dziennika EDDB. Sprawdź logi."; /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Wysłanie danych do EDDN..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "Wyślij zapis lotu i status pilota do EDSM"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Dane uwierzytelniające Elite Dangerous Star Map"; @@ -275,7 +278,7 @@ "None" = "Brak"; /* edsm.py: EDSM plugin - Journal handling disabled by killswitch; In files: edsm.py:516; */ -"EDSM Handler disabled. See Log." = "Wyłączona obsługa EDSM. Sprawdź logi."; +"EDSM Handler disabled. See Log." = "Wyłączona obsługa EDDB. Sprawdź logi."; /* edsm.py: EDSM Plugin - Error message from EDSM API; In files: edsm.py:916; edsm.py:1048; */ "Error: EDSM {MSG}" = "Błąd: EDSM {MSG}"; @@ -427,9 +430,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Włączone pluginy"; + /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ "Plugins Without Python 3.x Support:" = "Pluginy nie obsługiwane przez Python 3.x:"; - /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informacja o migracji pluginów"; @@ -735,3 +738,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Statki"; + diff --git a/L10n/pt-BR.strings b/L10n/pt-BR.strings index 27e9b474..51952c05 100644 --- a/L10n/pt-BR.strings +++ b/L10n/pt-BR.strings @@ -1,3 +1,11 @@ +/* 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"; + +/* prefs.py:Label on button used to open a filesystem folder; In files: prefs.py:706; */ +"Open Log Folder" = "Abrir pasta de registros"; + +/* inara.py:Text Inara Show API key; In files: inara.py:305; */ +"Show API Key" = "Exibir chave da API"; /* Language name */ "!Language" = "Português (Brasil)"; @@ -253,6 +261,9 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Modo de substituição Coriolis inválido!"; + +/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ +"EDDB Journal processing disabled. See Log." = "Processamento de Jornais no EDDB desativado. Verifique o Log."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Erro: Não é possível conectar-se ao EDDN"; @@ -280,9 +291,9 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Enviando log para o EDDN..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "Enviar dados de voo e status do cmdt para o EDSM"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Credenciais do Elite Dangerous Star Map (EDSM)"; @@ -460,9 +471,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Plugins Habilitados"; + /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ "Plugins Without Python 3.x Support:" = "Plugins sem suporte a Python 3.x:"; - /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informações de migração de plugins"; @@ -768,3 +779,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Naves"; + diff --git a/L10n/pt-PT.strings b/L10n/pt-PT.strings index bd936059..3002069f 100644 --- a/L10n/pt-PT.strings +++ b/L10n/pt-PT.strings @@ -1,3 +1,11 @@ +/* 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"; + +/* prefs.py:Label on button used to open a filesystem folder; In files: prefs.py:706; */ +"Open Log Folder" = "Abrir directório dos ficheiros de registos"; + +/* inara.py:Text Inara Show API key; In files: inara.py:305; */ +"Show API Key" = "Visualizar chave da API"; /* Language name */ "!Language" = "Português (Portugal)"; @@ -253,6 +261,9 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Modo de sobreposição Coriolis inválido!"; + +/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ +"EDDB Journal processing disabled. See Log." = "Processamento do diário do EDDB desactivado. Verifique o ficheiro de registos."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Erro: Não é possível conectar ao EDDN"; @@ -280,9 +291,9 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "A enviar dados para o EDDN..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "Enviar dados de voo e o estado do CMDT para o EDSM"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Credenciais do Elite Dangerous Star Map (EDSM)"; @@ -460,9 +471,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Plugins Activados"; + /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ "Plugins Without Python 3.x Support:" = "Plugins sem suporte para Python 3.x"; - /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informação para migração de plugins"; @@ -768,3 +779,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Naves"; + diff --git a/L10n/ru.strings b/L10n/ru.strings index 38f3d7a4..539fa21c 100644 --- a/L10n/ru.strings +++ b/L10n/ru.strings @@ -1,3 +1,11 @@ +/* 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" = "Русский"; @@ -253,6 +261,9 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Некорректный режим переопределения URL для coriolis.io"; + +/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ +"EDDB Journal processing disabled. See Log." = "Обработка журнала EDDB отключена. См. логи."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Ошибка: не удается подключиться к EDDN"; @@ -280,9 +291,9 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Отправка данных на EDDN..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "Отправлять данные журнала полёта и информацию статусе командира в EDSM"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Учётные данные Elite Dangerous Star Map"; @@ -460,9 +471,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Включённые плагины"; + /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ "Plugins Without Python 3.x Support:" = "Плагины без поддержки Python 3.x"; - /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Информация о мигрирующих плагинах"; @@ -768,3 +779,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Корабли"; + diff --git a/L10n/sl.strings b/L10n/sl.strings index acef1bdf..1ecb1753 100644 --- a/L10n/sl.strings +++ b/L10n/sl.strings @@ -432,3 +432,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Ladje"; + diff --git a/L10n/sr-Latn-BA.strings b/L10n/sr-Latn-BA.strings index 62d372e3..c872376f 100644 --- a/L10n/sr-Latn-BA.strings +++ b/L10n/sr-Latn-BA.strings @@ -232,6 +232,9 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Neispravan Coriolis režim rada!"; + +/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ +"EDDB Journal processing disabled. See Log." = "EDDB obrada journala je deaktivirana. Pogledajte Log."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Greška: Nemoguće povezivanje sa EDDN"; @@ -259,9 +262,9 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Slanje podataka na EDDN..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "Pošalji log leta i Cmdr status na EDSM"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Kredencijali za Elite Dangerous Star Map"; @@ -430,9 +433,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Aktivirani dodaci (plugins)"; + /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ "Plugins Without Python 3.x Support:" = "Dodaci (plugins) bez Python 3.x podrške:"; - /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informacije o migraciji dodataka (plugins)"; @@ -738,3 +741,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Brodovi"; + diff --git a/L10n/sr-Latn.strings b/L10n/sr-Latn.strings index 3da6c5b9..9515dca2 100644 --- a/L10n/sr-Latn.strings +++ b/L10n/sr-Latn.strings @@ -253,6 +253,9 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Pogrešan Coriolis preinačeni mod!"; + +/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ +"EDDB Journal processing disabled. See Log." = "Obrada žurnala za EDDB je deaktivirana. Pogledajte Log."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Greška: Nemoguće povezivanje na EDDN"; @@ -280,9 +283,9 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Slanje podataka na EDDN..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "Pošalji log leta i Cmdr status na EDSM"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Kredencijali za Elite Dangerous Star Map"; @@ -460,9 +463,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Aktivirani dodaci (plugins)"; + /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ "Plugins Without Python 3.x Support:" = "Pluginovi bez podrške za Python 3.x:"; - /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informacije o migraciji dodataka (plugins)"; @@ -768,3 +771,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Brodovi"; + diff --git a/L10n/sv-SE.strings b/L10n/sv-SE.strings index fa6ad247..6c7daaca 100644 --- a/L10n/sv-SE.strings +++ b/L10n/sv-SE.strings @@ -148,9 +148,9 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Skickar data till EDDN..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "Skicka flight log-data och Cmdr-status till EDSM"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite Dangerous Star Map användaruppgifter"; @@ -510,3 +510,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Skepp"; + diff --git a/L10n/uk.strings b/L10n/uk.strings index 3791318c..bfeff7b0 100644 --- a/L10n/uk.strings +++ b/L10n/uk.strings @@ -184,9 +184,9 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Відправка даних до EDDN..."; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "Відправляти дані бортового журналу до EDSM"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Дані Elite Dangerous Star Map"; @@ -337,9 +337,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Увімкнені плагіни"; + /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ "Plugins Without Python 3.x Support:" = "Плагіни без підтримки Python 3.x:"; - /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Інформація про міграцію плагінів"; @@ -573,3 +573,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "Кораблі"; + diff --git a/L10n/zh-Hans.strings b/L10n/zh-Hans.strings index 83ad58bd..84f70036 100644 --- a/L10n/zh-Hans.strings +++ b/L10n/zh-Hans.strings @@ -94,6 +94,12 @@ /* EDMarketConnector.py: Help > Documentation; In files: EDMarketConnector.py:933; EDMarketConnector.py:953; */ "Documentation" = "帮助文档"; +/* EDMarketConnector.py: Help > Troubleshooting; In files: EDMarketConnector.py:934; EDMarketConnector.py:954; */ +"Troubleshooting" = "故障排除"; + +/* EDMarketConnector.py: Help > Report A Bug; In files: EDMarketConnector.py:935; EDMarketConnector.py:955; */ +"Report A Bug" = "Bug 反馈"; + /* EDMarketConnector.py: Help > Privacy Policy; In files: EDMarketConnector.py:936; EDMarketConnector.py:956; */ "Privacy Policy" = "隐私政策"; @@ -109,6 +115,9 @@ /* 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" = "复制"; +/* 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 禁用"; + /* EDMarketConnector.py: Status - Attempting to get a Frontier Auth Access Token; In files: EDMarketConnector.py:978; */ "Logging in..." = "登录中…"; @@ -130,6 +139,9 @@ /* EDMarketConnector.py: CAPI queries aborted because game mode unknown; In files: EDMarketConnector.py:1083; */ "CAPI query aborted: Game mode unknown" = "CAPI 访问中止:游戏模式未知"; +/* EDMarketConnector.py: CAPI queries aborted because GameVersion unknown; EDMarketConnector.py: CAPI fleetcarrier query aborted because GameVersion unknown; In files: EDMarketConnector.py:1089; EDMarketConnector.py:1170; */ +"CAPI query aborted: GameVersion unknown" = "CAPI 访问中止:未知的游戏版本"; + /* EDMarketConnector.py: CAPI queries aborted because current star system name unknown; In files: EDMarketConnector.py:1095; */ "CAPI query aborted: Current system unknown" = "CAPI 访问中止:现星系名称未知"; @@ -142,6 +154,15 @@ /* EDMarketConnector.py: Status - Attempting to retrieve data from Frontier CAPI; In files: EDMarketConnector.py:1128; EDMarketConnector.py:1179; */ "Fetching data..." = "取得数据…"; +/* 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 fleetcarrier from the Frontier CAPI; In files: EDMarketConnector.py:1219; */ +"CAPI: No fleetcarrier data returned" = "CAPI:无舰队母舰 (fleet carrier) 数据"; + +/* EDMarketConnector.py: We didn't have the fleetcarrier callsign when we should have; In files: EDMarketConnector.py:1223; */ +"CAPI: Fleetcarrier data incomplete" = "CAPI:舰队母舰 (fleet carrier) 数据不完整"; + /* EDMarketConnector.py: No data was returned for the commander from the Frontier CAPI; In files: EDMarketConnector.py:1242; */ "CAPI: No commander data returned" = "CAPI:没有指挥官数据"; @@ -232,6 +253,9 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "无效的 Coriolis 覆盖模式!"; + +/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ +"EDDB Journal processing disabled. See Log." = "EDDB Journal Processing 已禁用。请查看诊断日志。"; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "错误:无法连接到 EDDN"; @@ -259,9 +283,9 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "正在向 EDDN 发送数据…"; + /* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ "Send flight log and Cmdr status to EDSM" = "发送航行日志和指挥官状态到 EDSM"; - /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite Dangerous Star Map 授权凭证"; @@ -277,6 +301,9 @@ /* edsm.py: EDSM plugin - Journal handling disabled by killswitch; In files: edsm.py:516; */ "EDSM Handler disabled. See Log." = "EDSM Handler 已禁用。请查看诊断日志。"; +/* edsm.py: EDSM - Only Live data; In files: edsm.py:632; */ +"EDSM only accepts Live galaxy data" = "EDSM 只接受 Live 模式下的星系数据"; + /* edsm.py: EDSM Plugin - Error message from EDSM API; In files: edsm.py:916; edsm.py:1048; */ "Error: EDSM {MSG}" = "错误:EDSM {MSG}"; @@ -289,6 +316,9 @@ /* inara.py: Text for INARA API keys link ( goes to https://inara.cz/settings-api ); In files: inara.py:269; */ "Inara credentials" = "Inara 授权凭证"; +/* inara.py: The Inara API only accepts Live galaxy data, not Legacy galaxy data; inara.py: Inara - Only Live data; In files: inara.py:384; inara.py:386; */ +"Inara only accepts Live galaxy data" = "Inara 只接受 Live 模式下的星系数据"; + /* inara.py: INARA support disabled via killswitch; In files: inara.py:395; */ "Inara disabled. See Log." = "Inara 已禁用。请查看诊断日志。"; @@ -328,6 +358,12 @@ /* prefs.py: Settings > Configuration - Label for Journal files location; In files: prefs.py:431; prefs.py:446; */ "E:D journal file location" = "E:D 日志文件位置"; +/* 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 Fleetcarrier CAPI Queries" = "开启舰队母舰 (fleet carrier) CAPI 访问"; + /* prefs.py: Hotkey/Shortcut settings prompt on OSX; In files: prefs.py:490; */ "Keyboard shortcut" = "键盘快捷键"; @@ -427,9 +463,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "已启用插件"; + /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ "Plugins Without Python 3.x Support:" = "不支持 Python 3.x 的插件:"; - /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "关于插件迁移"; @@ -735,3 +771,4 @@ /* stats.py: Status dialog title; In files: stats.py:418; */ "Ships" = "所有飞船"; + From bd6f5466aff57f3c2556b9f17a8ff62d65665470 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Wed, 13 Dec 2023 17:35:31 -0500 Subject: [PATCH 66/83] [Docs] Add reminder about find_localized_files Most of these docs are due for a total review, so this is a temporary measure. --- docs/Translations.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/Translations.md b/docs/Translations.md index 333ce27b..a1be7c28 100644 --- a/docs/Translations.md +++ b/docs/Translations.md @@ -34,6 +34,8 @@ _('stuff') #### Edit `L10n/en.template` to add the phrase +##### Hint: It is strongly recommended to use the find_localized_strings.py script to help automate this process! + /* [] */ "" = ""; e.g. From 8888d01760049247f6754b92642e04b7f8256592 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Wed, 13 Dec 2023 18:28:27 -0500 Subject: [PATCH 67/83] [555] Move WinSparkle Keys to Setup File --- build.py | 6 +++- config/__init__.py | 2 +- config/windows.py | 36 ++------------------ docs/Translations.md | 3 +- resources/EDMC_Installer_Config_template.txt | 7 ++++ 5 files changed, 16 insertions(+), 38 deletions(-) diff --git a/build.py b/build.py index d6cecb7d..6d7f865b 100644 --- a/build.py +++ b/build.py @@ -19,12 +19,16 @@ from config import ( copyright, git_shorthash_from_head, _static_appversion, + update_interval ) def iss_build(template_path: str, output_file: str) -> None: """Build the .iss file needed for building the installer EXE.""" - sub_vals = {"appver": _static_appversion} + sub_vals = { + "appver": _static_appversion, + "update_time": str(update_interval), + } with open(template_path, encoding="UTF8") as template_file: src = Template(template_file.read()) newfile = src.substitute(sub_vals) diff --git a/config/__init__.py b/config/__init__.py index c9a34c78..66f973af 100644 --- a/config/__init__.py +++ b/config/__init__.py @@ -60,7 +60,7 @@ _cached_version: semantic_version.Version | None = None copyright = '© 2015-2019 Jonathan Harris, 2020-2023 EDCD' update_feed = 'https://raw.githubusercontent.com/EDCD/EDMarketConnector/releases/edmarketconnector.xml' -update_interval = 8*60*60 +update_interval = 8*60*60 # 8 Hours # Providers marked to be in debug mode. Generally this is expected to switch to sending data to a log file debug_senders: list[str] = [] # TRACE logging code that should actually be used. Means not spamming it diff --git a/config/windows.py b/config/windows.py index 7fb53a37..75e3f697 100644 --- a/config/windows.py +++ b/config/windows.py @@ -15,7 +15,7 @@ import uuid import winreg from ctypes.wintypes import DWORD, HANDLE from typing import Literal -from config import AbstractConfig, applongname, appname, logger, update_interval +from config import AbstractConfig, applongname, appname, logger assert sys.platform == 'win32' @@ -47,7 +47,7 @@ def known_folder_path(guid: uuid.UUID) -> str | None: class WinConfig(AbstractConfig): """Implementation of AbstractConfig for Windows.""" - def __init__(self, do_winsparkle=True) -> None: + def __init__(self) -> None: super().__init__() self.app_dir_path = pathlib.Path(known_folder_path(FOLDERID_LocalAppData)) / appname # type: ignore self.app_dir_path.mkdir(exist_ok=True) @@ -77,8 +77,6 @@ class WinConfig(AbstractConfig): try: self.__reg_handle: winreg.HKEYType = create_key_defaults(sub_key=REGISTRY_SUBKEY) - if do_winsparkle: - self.__setup_winsparkle() except OSError: logger.exception('Could not create required registry keys') @@ -89,36 +87,6 @@ class WinConfig(AbstractConfig): docs = known_folder_path(FOLDERID_Documents) self.set("outdir", docs if docs is not None else self.home) - def __setup_winsparkle(self): - """Ensure the necessary Registry keys for WinSparkle are present.""" - create_key_defaults = functools.partial( - winreg.CreateKeyEx, - key=winreg.HKEY_CURRENT_USER, - access=winreg.KEY_ALL_ACCESS | winreg.KEY_WOW64_64KEY, - ) - - try: - with create_key_defaults(sub_key=r'Software\EDCD\EDMarketConnector') as edcd_handle: - with winreg.CreateKeyEx(edcd_handle, sub_key='WinSparkle', - access=winreg.KEY_ALL_ACCESS | winreg.KEY_WOW64_64KEY) as winsparkle_reg: - # Set WinSparkle defaults - https://github.com/vslavik/winsparkle/wiki/Registry-Settings - UPDATE_INTERVAL_NAME = 'UpdateInterval' # noqa: N806 - CHECK_FOR_UPDATES_NAME = 'CheckForUpdates' # noqa: N806 - REG_SZ = winreg.REG_SZ # noqa: N806 - - winreg.SetValueEx(winsparkle_reg, UPDATE_INTERVAL_NAME, REG_RESERVED_ALWAYS_ZERO, REG_SZ, - str(update_interval)) - - try: - winreg.QueryValueEx(winsparkle_reg, CHECK_FOR_UPDATES_NAME) - except FileNotFoundError: - # Key doesn't exist, set it to a default - winreg.SetValueEx(winsparkle_reg, CHECK_FOR_UPDATES_NAME, REG_RESERVED_ALWAYS_ZERO, REG_SZ, - '1') - except OSError: - logger.exception('Could not open WinSparkle handle') - raise - def __get_regentry(self, key: str) -> None | list | str | int: """Access the Registry for the raw entry.""" try: diff --git a/docs/Translations.md b/docs/Translations.md index a1be7c28..959897f2 100644 --- a/docs/Translations.md +++ b/docs/Translations.md @@ -34,8 +34,7 @@ _('stuff') #### Edit `L10n/en.template` to add the phrase -##### Hint: It is strongly recommended to use the find_localized_strings.py script to help automate this process! - +##### Hint: It is strongly recommended to use the `find_localized_strings.py` script to help automate this process! /* [] */ "" = ""; e.g. diff --git a/resources/EDMC_Installer_Config_template.txt b/resources/EDMC_Installer_Config_template.txt index 254c95ca..b72ed507 100644 --- a/resources/EDMC_Installer_Config_template.txt +++ b/resources/EDMC_Installer_Config_template.txt @@ -1,6 +1,7 @@ #define MyAppName "EDMarketConnector" #define MyAppLongName "Elite Dangerous Market Connector" #define MyAppVersion "$appver" +#define MyAppUpdateTime "$update_time" #define MyAppPublisher "EDCD" #define MyAppURL "https://edcd.github.io/" #define SuppURL "https://github.com/EDCD/EDMarketConnector/" @@ -34,6 +35,7 @@ AlwaysShowDirOnReadyPage=yes UninstallDisplayIcon={app}\{#MyAppExeName} MinVersion=6.2 ChangesAssociations = yes +UsedUserAreasWarning = no [Languages] Name: "english"; MessagesFile: "compiler:Default.isl" @@ -113,6 +115,11 @@ Root: HKCR; Subkey: "edmc\shell\open"; Flags: uninsdeletekey Root: HKCR; Subkey: "edmc\shell\open\command"; ValueType: string; ValueName: ""; ValueData: """{app}\EDMarketConnector.exe"" ""%1"""; Flags: uninsdeletekey ; Create the "ddeexec" subkey under the "open" subkey Root: HKCR; Subkey: "edmc\shell\open\ddeexec"; ValueType: string; ValueName: ""; ValueData: "Open(""%1"")"; Flags: uninsdeletekey +; Create WinSparkle related keys for update values +Root: HKCU; Subkey: "Software\EDCD\EDMarketConnector"; Flags: uninsdeletekey +Root: HKCU; Subkey: "Software\EDCD\EDMarketConnector\WinSparkle"; Flags: uninsdeletekey +Root: HKCU; Subkey: "Software\EDCD\EDMarketConnector\WinSparkle"; ValueType: string; ValueName: "UpdateInterval"; ValueData: "{#MyAppUpdateTime}"; Flags: createvalueifdoesntexist +Root: HKCU; Subkey: "Software\EDCD\EDMarketConnector\WinSparkle"; ValueType: string; ValueName: "CheckForUpdates"; ValueData: "1"; Flags: createvalueifdoesntexist [InstallDelete] Type: filesandordirs; Name: "{app}" From 34d91dfb2d83c2353199afce7840ad12a6d0380c Mon Sep 17 00:00:00 2001 From: Phoebe Date: Thu, 14 Dec 2023 01:06:09 +0100 Subject: [PATCH 68/83] [Enhancement] Broken Plugins Popup - Adds a Popup at startup about Plugins that failed to load. - Adds entry about broken Plugins in the Settings - Plugins tab. - Adds corresponding translation entries. --- EDMarketConnector.py | 34 ++++++++++++++++++++++++++++++++-- L10n/en.template | 11 ++++++++++- plug.py | 2 ++ prefs.py | 17 +++++++++++++++++ 4 files changed, 61 insertions(+), 3 deletions(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 8be745f2..da871032 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -2259,6 +2259,34 @@ sys.path: {sys.path}''' app = AppWindow(root) + def messagebox_broken_plugins(): + """Display message about plugins not updated for Python 3.x.""" + if plug.PLUGINS_broken: + # LANG: Popup-text about 'broken' plugins that failoed to load + popup_text = _( + "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." + ) + + # Substitute in the other words. + popup_text = popup_text.format( + PLUGINS=_('Plugins'), # LANG: Settings > Plugins tab + FILE=_('File'), # LANG: 'File' menu + SETTINGS=_('Settings'), # LANG: File > Settings + 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') + + tk.messagebox.showinfo( + # LANG: Popup window title for list of 'broken' plugins that failoed to load + _('EDMC: Broken Plugins'), + popup_text + ) + def messagebox_not_py3(): """Display message about plugins not updated for Python 3.x.""" plugins_not_py3_last = config.get_int('plugins_not_py3_last', default=0) @@ -2297,9 +2325,11 @@ sys.path: {sys.path}''' root.wm_attributes('-alpha', ui_transparency / 100) # Display message box about plugins without Python 3.x support - root.after(0, messagebox_not_py3) + root.after(0, messagebox_broken_plugins) + # Display message box about plugins without Python 3.x support + root.after(1, messagebox_not_py3) # Show warning popup for killswitches matching current version - root.after(1, show_killswitch_poppup, root) + root.after(2, show_killswitch_poppup, root) # Start the main event loop root.mainloop() diff --git a/L10n/en.template b/L10n/en.template index a3432d6d..52398f25 100644 --- a/L10n/en.template +++ b/L10n/en.template @@ -213,12 +213,18 @@ /* EDMarketConnector.py: Popup-text about 'active' plugins without Python 3.x support; In files: EDMarketConnector.py:2253:2259; */ "One or more of your enabled plugins do not yet have support for Python 3.x. Please see the list on the '{PLUGINS}' tab of '{FILE}' > '{SETTINGS}'. You should check if there is an updated version available, else alert the developer that they need to update the code for Python 3.x.\r\n\r\nYou can disable a plugin by renaming its folder to have '{DISABLED}' on the end of the name." = "One or more of your enabled plugins do not yet have support for Python 3.x. Please see the list on the '{PLUGINS}' tab of '{FILE}' > '{SETTINGS}'. You should check if there is an updated version available, else alert the developer that they need to update the code for Python 3.x.\r\n\r\nYou can disable a plugin by renaming its folder to have '{DISABLED}' on the end of the name."; +/* EDMarketConnector.py: Popup-text about 'broken' plugins without Python 3.x support; In files: EDMarketConnector.py:2266:2271; */ +"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." = "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."; + /* EDMarketConnector.py: Settings > Plugins tab; prefs.py: Label on Settings > Plugins tab; In files: EDMarketConnector.py:2263; prefs.py:986; */ "Plugins" = "Plugins"; /* 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: Plugins Without Python 3.x Support"; +/* EDMarketConnector.py: Popup window title for list of 'broken' plugins that failoed to load; In files: EDMarketConnector.py:2285; */ +"EDMC: Broken Plugins" = "EDMC: Broken Plugins"; + /* journal_lock.py: Title text on popup when Journal directory already locked; In files: journal_lock.py:208; */ "Journal directory already locked" = "Journal directory already locked"; @@ -471,12 +477,15 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Enabled Plugins"; - /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ "Plugins Without Python 3.x Support:" = "Plugins Without Python 3.x Support:"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Information on migrating plugins"; +/* prefs.py: Plugins - Label for list of 'broken' plugins that failed to load; In files: prefs.py:1039; */ +"Broken Plugins" = "Broken Plugins"; + /* prefs.py: Lable on list of user-disabled plugins; In files: prefs.py:977; */ "Disabled Plugins" = "Disabled Plugins"; diff --git a/plug.py b/plug.py index b343677b..aa34ce77 100644 --- a/plug.py +++ b/plug.py @@ -27,6 +27,7 @@ logger = get_main_logger() # List of loaded Plugins PLUGINS = [] PLUGINS_not_py3 = [] +PLUGINS_broken = [] # For asynchronous error display @@ -198,6 +199,7 @@ def _load_found_plugins(): plugin_logger = EDMCLogging.get_plugin_logger(name) found.append(Plugin(name, os.path.join(config.plugin_dir_path, name, 'load.py'), plugin_logger)) except Exception: + PLUGINS_broken.append(Plugin(name, None, logger)) logger.exception(f'Failure loading found Plugin "{name}"') pass return found diff --git a/prefs.py b/prefs.py index 6e423acc..6c2722b6 100644 --- a/prefs.py +++ b/prefs.py @@ -1029,6 +1029,23 @@ class PreferencesDialog(tk.Toplevel): nb.Label(plugins_frame, text=plugin.name).grid( columnspan=2, padx=self.LISTX, pady=self.PADY, sticky=tk.W, row=row.get() ) + ############################################################ + # Show plugins that failed to load + ############################################################ + if len(plug.PLUGINS_broken): + ttk.Separator(plugins_frame, orient=tk.HORIZONTAL).grid( + columnspan=3, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get() + ) + # LANG: Plugins - Label for list of 'broken' plugins that failed to load + nb.Label(plugins_frame, text=_('Broken Plugins')+':').grid( + padx=self.PADX, pady=self.PADY, sticky=tk.W, row=row.get() + ) + + for plugin in plug.PLUGINS_broken: + if plugin.folder: # 'system' ones have this set to None to suppress listing in Plugins prefs tab + nb.Label(plugins_frame, text=plugin.name).grid( + columnspan=2, padx=self.LISTX, pady=self.PADY, sticky=tk.W, row=row.get() + ) # LANG: Label on Settings > Plugins tab notebook.add(plugins_frame, text=_('Plugins')) # Tab heading in settings From dac95425577fe3f91b9f15e61c086125f4f57c47 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Wed, 13 Dec 2023 19:38:42 -0500 Subject: [PATCH 69/83] [Minor] Correct Template S&G Also includes a minor fix for try/except if coriolis-data is missing --- EDMarketConnector.py | 6 +++--- L10n/en.template | 16 +++++----------- coriolis-update-files.py | 8 ++++++-- 3 files changed, 14 insertions(+), 16 deletions(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index da871032..50872ec3 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -2262,11 +2262,11 @@ sys.path: {sys.path}''' def messagebox_broken_plugins(): """Display message about plugins not updated for Python 3.x.""" if plug.PLUGINS_broken: - # LANG: Popup-text about 'broken' plugins that failoed to load + # LANG: Popup-text about 'broken' plugins that failed to load popup_text = _( "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 " + r"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." ) @@ -2282,7 +2282,7 @@ sys.path: {sys.path}''' popup_text = popup_text.replace('\\r', '\r') tk.messagebox.showinfo( - # LANG: Popup window title for list of 'broken' plugins that failoed to load + # LANG: Popup window title for list of 'broken' plugins that failed to load _('EDMC: Broken Plugins'), popup_text ) diff --git a/L10n/en.template b/L10n/en.template index 52398f25..f89873af 100644 --- a/L10n/en.template +++ b/L10n/en.template @@ -213,18 +213,18 @@ /* EDMarketConnector.py: Popup-text about 'active' plugins without Python 3.x support; In files: EDMarketConnector.py:2253:2259; */ "One or more of your enabled plugins do not yet have support for Python 3.x. Please see the list on the '{PLUGINS}' tab of '{FILE}' > '{SETTINGS}'. You should check if there is an updated version available, else alert the developer that they need to update the code for Python 3.x.\r\n\r\nYou can disable a plugin by renaming its folder to have '{DISABLED}' on the end of the name." = "One or more of your enabled plugins do not yet have support for Python 3.x. Please see the list on the '{PLUGINS}' tab of '{FILE}' > '{SETTINGS}'. You should check if there is an updated version available, else alert the developer that they need to update the code for Python 3.x.\r\n\r\nYou can disable a plugin by renaming its folder to have '{DISABLED}' on the end of the name."; -/* EDMarketConnector.py: Popup-text about 'broken' plugins without Python 3.x support; In files: EDMarketConnector.py:2266:2271; */ -"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." = "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."; - /* EDMarketConnector.py: Settings > Plugins tab; prefs.py: Label on Settings > Plugins tab; In files: EDMarketConnector.py:2263; prefs.py:986; */ "Plugins" = "Plugins"; /* 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: Plugins Without Python 3.x Support"; -/* EDMarketConnector.py: Popup window title for list of 'broken' plugins that failoed to load; In files: EDMarketConnector.py:2285; */ +/* EDMarketConnector.py: Popup window title for list of 'broken' plugins that failed to load; In files: EDMarketConnector.py:2285; */ "EDMC: Broken Plugins" = "EDMC: Broken Plugins"; +/* 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." = "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."; + /* journal_lock.py: Title text on popup when Journal directory already locked; In files: journal_lock.py:208; */ "Journal directory already locked" = "Journal directory already locked"; @@ -267,9 +267,6 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Invalid Coriolis override mode!"; - -/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ -"EDDB Journal processing disabled. See Log." = "EDDB Journal processing disabled. See Log."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Error: Can't connect to EDDN"; @@ -297,9 +294,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Sending data to EDDN..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Send flight log and Cmdr status to EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite Dangerous Star Map credentials"; @@ -478,7 +472,7 @@ "Enabled Plugins" = "Enabled Plugins"; /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support:" = "Plugins Without Python 3.x Support:"; +"Plugins Without Python 3.x Support" = "Plugins Without Python 3.x Support"; /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Information on migrating plugins"; diff --git a/coriolis-update-files.py b/coriolis-update-files.py index 09592cfe..0f32b935 100755 --- a/coriolis-update-files.py +++ b/coriolis-update-files.py @@ -28,8 +28,12 @@ if __name__ == "__main__": assert name not in modules, name modules[name] = attributes - # Regenerate coriolis-data distribution - subprocess.check_call('npm install', cwd='coriolis-data', shell=True, stdout=sys.stdout, stderr=sys.stderr) + try: + # Regenerate coriolis-data distribution + subprocess.check_call('npm install', cwd='coriolis-data', shell=True, stdout=sys.stdout, stderr=sys.stderr) + except NotADirectoryError as err: + sys.exit("Coriolis-Data Directory not found! Have you set up your submodules? \n" + "https://github.com/EDCD/EDMarketConnector/wiki/Running-from-source#obtain-a-copy-of-the-application-source") file_path = 'coriolis-data/dist/index.json' with open(file_path) as file: From aa5abeaa9a930a9bb46c07a4211d05295f8940d0 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Wed, 13 Dec 2023 19:40:27 -0500 Subject: [PATCH 70/83] [Minor] Shaddup Flake --- coriolis-update-files.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/coriolis-update-files.py b/coriolis-update-files.py index 0f32b935..d42e4899 100755 --- a/coriolis-update-files.py +++ b/coriolis-update-files.py @@ -31,9 +31,9 @@ if __name__ == "__main__": try: # Regenerate coriolis-data distribution subprocess.check_call('npm install', cwd='coriolis-data', shell=True, stdout=sys.stdout, stderr=sys.stderr) - except NotADirectoryError as err: + except NotADirectoryError: sys.exit("Coriolis-Data Directory not found! Have you set up your submodules? \n" - "https://github.com/EDCD/EDMarketConnector/wiki/Running-from-source#obtain-a-copy-of-the-application-source") + "https://github.com/EDCD/EDMarketConnector/wiki/Running-from-source#obtain-a-copy-of-the-application-source") # noqa: E501 file_path = 'coriolis-data/dist/index.json' with open(file_path) as file: From 49ca678ff6d50028a88a422ce923f9cbadb53da7 Mon Sep 17 00:00:00 2001 From: Phoebe Date: Fri, 15 Dec 2023 00:43:48 +0100 Subject: [PATCH 71/83] [Minor] Clarify Comment Forgot to update the comment to be about broken plugins instead of no 3.x support ones. --- EDMarketConnector.py | 1 + 1 file changed, 1 insertion(+) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 50872ec3..596f0423 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -2325,6 +2325,7 @@ sys.path: {sys.path}''' root.wm_attributes('-alpha', ui_transparency / 100) # Display message box about plugins without Python 3.x support + # Display message box about plugins that failed to load root.after(0, messagebox_broken_plugins) # Display message box about plugins without Python 3.x support root.after(1, messagebox_not_py3) From fe327606aba90578ac5cdd11342efdaa2530bfc1 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 15 Dec 2023 11:51:53 -0500 Subject: [PATCH 72/83] [1801] Add Warning for FDevIDs --- EDMarketConnector.py | 31 +++++++++++++++++++++++++++++++ L10n/en.template | 6 ++++++ 2 files changed, 37 insertions(+) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 596f0423..66c9cb67 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -2318,6 +2318,35 @@ sys.path: {sys.path}''' ) config.set('plugins_not_py3_last', int(time())) + def check_fdev_ids(): + """Display message about missing FDEVID files""" + fdev_files = {'commodity.csv', 'rare_commodity.csv'} + for file in fdev_files: + file = pathlib.Path(config.respath_path / 'FDevIDs' / file) + if file.is_file(): + continue + # LANG: Popup-text about missing FDEVID Files + popup_text = _( + "FDevID Files not found! Some functionality regarding commodities " + r"may be disabled.\r\n\r\n Do you want to open the Wiki page on " + "how to set up submodules?" + ) + # 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') + + openwikipage = tk.messagebox.askquestion( + # LANG: Popup window title for missing FDEVID files + _('FDevIDs: Missing Commodity Files'), + popup_text + ) + if openwikipage == "yes": + webbrowser.open( + "https://github.com/EDCD/EDMarketConnector/wiki/Running-from-source" + "#obtain-a-copy-of-the-application-source" + ) + break + # UI Transparency ui_transparency = config.get_int('ui_transparency') if ui_transparency == 0: @@ -2331,6 +2360,8 @@ sys.path: {sys.path}''' root.after(1, messagebox_not_py3) # Show warning popup for killswitches matching current version root.after(2, show_killswitch_poppup, root) + # Check for FDEV IDs + root.after(3, check_fdev_ids) # Start the main event loop root.mainloop() diff --git a/L10n/en.template b/L10n/en.template index f89873af..3aed0952 100644 --- a/L10n/en.template +++ b/L10n/en.template @@ -213,6 +213,12 @@ /* EDMarketConnector.py: Popup-text about 'active' plugins without Python 3.x support; In files: EDMarketConnector.py:2253:2259; */ "One or more of your enabled plugins do not yet have support for Python 3.x. Please see the list on the '{PLUGINS}' tab of '{FILE}' > '{SETTINGS}'. You should check if there is an updated version available, else alert the developer that they need to update the code for Python 3.x.\r\n\r\nYou can disable a plugin by renaming its folder to have '{DISABLED}' on the end of the name." = "One or more of your enabled plugins do not yet have support for Python 3.x. Please see the list on the '{PLUGINS}' tab of '{FILE}' > '{SETTINGS}'. You should check if there is an updated version available, else alert the developer that they need to update the code for Python 3.x.\r\n\r\nYou can disable a plugin by renaming its folder to have '{DISABLED}' on the end of the name."; +/* EDMarketConnector.py: Popup-text about missing FDEVID Files; In files: EDMarketConnector.py:2329; */ +"FDevID Files not found! Some functionality regarding commodities may be disabled.\r\n\r\n Do you want to open the Wiki page on how to set up submodules?" = "FDevID Files not found! Some functionality regarding commodities may be disabled.\r\n\r\n Do you want to open the Wiki page on how to set up submodules?"; + +/* EDMarketConnector.py: Popup window title for missing FDEVID files; In files: EDMarketConnector.py:2340; */ +"FDevIDs: Missing Commodity Files" = "FDevIDs: Missing Commodity Files"; + /* EDMarketConnector.py: Settings > Plugins tab; prefs.py: Label on Settings > Plugins tab; In files: EDMarketConnector.py:2263; prefs.py:986; */ "Plugins" = "Plugins"; From ad455f144d75d39af33235e0973bdcd33420bac1 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 15 Dec 2023 12:00:51 -0500 Subject: [PATCH 73/83] [1801] Clarify Varnames --- EDMarketConnector.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 66c9cb67..9eec3b1f 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -2319,11 +2319,11 @@ sys.path: {sys.path}''' config.set('plugins_not_py3_last', int(time())) def check_fdev_ids(): - """Display message about missing FDEVID files""" + """Display message about missing FDEVID files.""" fdev_files = {'commodity.csv', 'rare_commodity.csv'} for file in fdev_files: - file = pathlib.Path(config.respath_path / 'FDevIDs' / file) - if file.is_file(): + fdevid_file = pathlib.Path(config.respath_path / 'FDevIDs' / file) + if fdevid_file.is_file(): continue # LANG: Popup-text about missing FDEVID Files popup_text = _( From 25a46545ca4a092b8a44bec7d9eee725b583e51c Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 15 Dec 2023 12:11:23 -0500 Subject: [PATCH 74/83] [1801] Add missing file check to builder --- FDevIDs | 1 - build.py | 21 ++++++++++++++------- 2 files changed, 14 insertions(+), 8 deletions(-) delete mode 160000 FDevIDs diff --git a/FDevIDs b/FDevIDs deleted file mode 160000 index 069b09b1..00000000 --- a/FDevIDs +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 069b09b1afbd2001248ad93b1481d6f6a309c6f5 diff --git a/build.py b/build.py index 6d7f865b..e1d37f49 100644 --- a/build.py +++ b/build.py @@ -177,13 +177,20 @@ def build() -> None: ], } - py2exe.freeze( - version_info=version_info, - windows=[windows_config], - console=[console_config], - data_files=data_files, - options=options, - ) + try: + py2exe.freeze( + version_info=version_info, + windows=[windows_config], + console=[console_config], + data_files=data_files, + options=options, + ) + except FileNotFoundError: + sys.exit( + "Build Failed due to Missing Files! Have you set up your submodules? \n" + "https://github.com/EDCD/EDMarketConnector/wiki/Running-from-source" + "#obtain-a-copy-of-the-application-source" + ) iss_template_path: str = "./resources/EDMC_Installer_Config_template.txt" iss_file_path: str = "./EDMC_Installer_Config.iss" From 62929366464f5368afe908efac9f21c1a6bbcb96 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 15 Dec 2023 13:21:00 -0500 Subject: [PATCH 75/83] [1801] Fix FDEVIDs --- FDevIDs | 1 + 1 file changed, 1 insertion(+) create mode 160000 FDevIDs diff --git a/FDevIDs b/FDevIDs new file mode 160000 index 00000000..069b09b1 --- /dev/null +++ b/FDevIDs @@ -0,0 +1 @@ +Subproject commit 069b09b1afbd2001248ad93b1481d6f6a309c6f5 From 17e740d3ee0b710d959865d1b1d0407c47b546d9 Mon Sep 17 00:00:00 2001 From: Phoebe Date: Sat, 16 Dec 2023 02:10:55 +0100 Subject: [PATCH 76/83] [1801] Check for files at output generation Adds a check to see if the FDevID files exist to the output file generation process. If they don't generate a warning log entry and continue without them. --- companion.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/companion.py b/companion.py index 520afff2..217370d5 100644 --- a/companion.py +++ b/companion.py @@ -1204,6 +1204,9 @@ def fixup(data: CAPIData) -> CAPIData: # noqa: C901, CCR001 # Can't be usefully if not commodity_map: # Lazily populate for f in ('commodity.csv', 'rare_commodity.csv'): + if not os.path.isfile(config.respath_path / 'FDevIDs/' / f): + logger.warning(f'FDevID file {f} not found! Generating output without these commodity name rewrites.') + continue with open(config.respath_path / 'FDevIDs' / f, 'r') as csvfile: reader = csv.DictReader(csvfile) From ff0fdd26e6b07216c60270cb912618993ff42321 Mon Sep 17 00:00:00 2001 From: Phoebe <40956085+C1701D@users.noreply.github.com> Date: Sat, 16 Dec 2023 15:22:55 +0100 Subject: [PATCH 77/83] [Minor] Remove duplicate Comment --- EDMarketConnector.py | 1 - 1 file changed, 1 deletion(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 9eec3b1f..5a8f299d 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -2353,7 +2353,6 @@ sys.path: {sys.path}''' ui_transparency = 100 root.wm_attributes('-alpha', ui_transparency / 100) - # Display message box about plugins without Python 3.x support # Display message box about plugins that failed to load root.after(0, messagebox_broken_plugins) # Display message box about plugins without Python 3.x support From 51cd0f85b0c572c14aa77152179eb5f80eaab1d0 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sat, 16 Dec 2023 14:58:36 -0500 Subject: [PATCH 78/83] [Minor] Bump Version String --- config/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/__init__.py b/config/__init__.py index 66f973af..201e76b6 100644 --- a/config/__init__.py +++ b/config/__init__.py @@ -54,7 +54,7 @@ appcmdname = 'EDMC' # # Major.Minor.Patch(-prerelease)(+buildmetadata) # NB: Do *not* import this, use the functions appversion() and appversion_nobuild() -_static_appversion = '5.10.0-beta1' +_static_appversion = '5.10.0-rc1' _cached_version: semantic_version.Version | None = None copyright = '© 2015-2019 Jonathan Harris, 2020-2023 EDCD' From 6ffbeb8aeebbd6a719e692aabb24376c9dffc41b Mon Sep 17 00:00:00 2001 From: Phoebe Date: Sat, 16 Dec 2023 21:06:30 +0100 Subject: [PATCH 79/83] [Minor] Fix docstring --- EDMarketConnector.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 5a8f299d..93f06f7e 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -2260,7 +2260,7 @@ sys.path: {sys.path}''' app = AppWindow(root) def messagebox_broken_plugins(): - """Display message about plugins not updated for Python 3.x.""" + """Display message about 'broken' plugins that failed to load.""" if plug.PLUGINS_broken: # LANG: Popup-text about 'broken' plugins that failed to load popup_text = _( From 9c9ca42c1326d3adfa03491879a78f97a014a097 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Sat, 16 Dec 2023 21:04:33 -0500 Subject: [PATCH 80/83] [Fix] Re-Add Shebangs Required for some Unix and Mac distributions --- EDMC.py | 1 + EDMarketConnector.py | 1 + coriolis-update-files.py | 1 + l10n.py | 1 + scripts/pip_rev_deps.py | 1 + 5 files changed, 5 insertions(+) diff --git a/EDMC.py b/EDMC.py index df203008..072b0492 100755 --- a/EDMC.py +++ b/EDMC.py @@ -1,3 +1,4 @@ +#!/usr/bin/env python3 """ EDMC.py - Command-line interface. Requires prior setup through the GUI. diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 93f06f7e..87ba6814 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -1,3 +1,4 @@ +#!/usr/bin/env python3 """ EDMarketConnector.py - Entry point for the GUI. diff --git a/coriolis-update-files.py b/coriolis-update-files.py index d42e4899..b68d9647 100755 --- a/coriolis-update-files.py +++ b/coriolis-update-files.py @@ -1,3 +1,4 @@ +#!/usr/bin/env python3 """ coriolis-update-files.py - Build ship and module databases from https://github.com/EDCD/coriolis-data/. diff --git a/l10n.py b/l10n.py index fc144b77..26be12fc 100755 --- a/l10n.py +++ b/l10n.py @@ -1,3 +1,4 @@ +#!/usr/bin/env python3 """ l10n.py - Localize using OSX-Style Strings. diff --git a/scripts/pip_rev_deps.py b/scripts/pip_rev_deps.py index 8a187172..1956f5d0 100644 --- a/scripts/pip_rev_deps.py +++ b/scripts/pip_rev_deps.py @@ -1,3 +1,4 @@ +#!/usr/bin/env python3 """Search for dependencies given a package.""" import sys From 117183ae8f13aae8f1c74ac43b314b9db497e1cb Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Wed, 20 Dec 2023 21:48:04 -0500 Subject: [PATCH 81/83] [Lang] Update Translation Files --- L10n/cs.strings | 10 ++----- L10n/de.strings | 36 +++++++++++++++++------ L10n/es.strings | 10 ++----- L10n/fi.strings | 10 ++----- L10n/fr.strings | 6 ++-- L10n/hu.strings | 3 -- L10n/it.strings | 12 ++------ L10n/ja.strings | 25 ++++++++++------ L10n/ko.strings | 10 ++----- L10n/nl.strings | 6 ++-- L10n/pl.strings | 51 +++++++++++++++++++++++++++------ L10n/pt-BR.strings | 10 ++----- L10n/pt-PT.strings | 25 ++++++++++------ L10n/ru.strings | 10 ++----- L10n/sr-Latn-BA.strings | 63 +++++++++++++++++++++++++++++++++++------ L10n/sr-Latn.strings | 18 ++++++------ L10n/sv-SE.strings | 6 ++-- L10n/uk.strings | 7 ++--- L10n/zh-Hans.strings | 10 ++----- 19 files changed, 198 insertions(+), 130 deletions(-) diff --git a/L10n/cs.strings b/L10n/cs.strings index 609a3788..ba11dc39 100644 --- a/L10n/cs.strings +++ b/L10n/cs.strings @@ -205,9 +205,6 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Neplatný režim přepisu Coriolis!"; - -/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ -"EDDB Journal processing disabled. See Log." = "Zpracování EDDB deníku je deaktivováno. Zkontrolujte log."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Chyba: Nelze se připojit k EDDN"; @@ -226,9 +223,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Odesílání dat do EDDN..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Odesílat letový log a status CMDRa do EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Přihlašovací údaje Elite Dangerous Star Map"; @@ -385,9 +379,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Zapnuté pluginy"; - /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support:" = "Pluginy bez podpory Python 3.x:"; +"Plugins Without Python 3.x Support" = "Pluginy, které nepodporují Python 3.x"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informace jak migrovat pluginy."; diff --git a/L10n/de.strings b/L10n/de.strings index dec95f42..2b7c72c4 100644 --- a/L10n/de.strings +++ b/L10n/de.strings @@ -1,3 +1,11 @@ +/* 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"; + +/* prefs.py:Label on button used to open a filesystem folder; In files: prefs.py:706; */ +"Open Log Folder" = "Öffne Log Ordner"; + +/* inara.py:Text Inara Show API key; In files: inara.py:305; */ +"Show API Key" = "Zeige API Schlüssel"; /* Language name */ "!Language" = "Deutsch"; @@ -205,12 +213,24 @@ /* EDMarketConnector.py: Popup-text about 'active' plugins without Python 3.x support; In files: EDMarketConnector.py:2253:2259; */ "One or more of your enabled plugins do not yet have support for Python 3.x. Please see the list on the '{PLUGINS}' tab of '{FILE}' > '{SETTINGS}'. You should check if there is an updated version available, else alert the developer that they need to update the code for Python 3.x.\r\n\r\nYou can disable a plugin by renaming its folder to have '{DISABLED}' on the end of the name." = "Eins oder mehr deiner aktivierten Plugins hat noch keinen Support für Python 3.x. Du kannst dir die Liste im '{PLUGINS}'-Tab unter '{FILE}' > '{SETTINGS}' ansehen. Du solltest prüfen, ob es für diese Updates gibt und ansonsten dem Entwickler Bescheid geben, dass sie ihren Code für Python 3.x aktualisieren müssen.\n\nDu kannst ein Plugin deaktivieren, indem du dessen Ordner ein '{DISABLED}' am Ende des Namens anhängst."; +/* EDMarketConnector.py: Popup-text about missing FDEVID Files; In files: EDMarketConnector.py:2329; */ +"FDevID Files not found! Some functionality regarding commodities may be disabled.\r\n\r\n Do you want to open the Wiki page on how to set up submodules?" = "FDevID Dateien nicht gefunden! Einige Funktionen in Bezug auf Waren sind möglicherweise deaktiviert.\n\nMöchten du die Wiki-Seite zum Einrichten von Submodulen öffnen?"; + +/* EDMarketConnector.py: Popup window title for missing FDEVID files; In files: EDMarketConnector.py:2340; */ +"FDevIDs: Missing Commodity Files" = "FDevIDs: Warendateien fehlen"; + /* EDMarketConnector.py: Settings > Plugins tab; prefs.py: Label on Settings > Plugins tab; In files: EDMarketConnector.py:2263; prefs.py:986; */ "Plugins" = "Plugins"; /* 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: Plugins ohne Python 3.x Support"; +/* EDMarketConnector.py: Popup window title for list of 'broken' plugins that failed to load; In files: EDMarketConnector.py:2285; */ +"EDMC: Broken Plugins" = "EDMC: Defekte Plugins"; + +/* 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." = "Eins oder mehr deiner aktivierten Plugins konnte nicht geladen werden. Du kannst dir die Liste im '{PLUGINS}'-Tab unter '{FILE}' > '{SETTINGS}' ansehen. Dies könnte an einer falschen Ordnerstruktur liegen. Die Datei load.py sollte sich unter plugins/PLUGIN_NAME/load.py befinden.\n\nDu kannst ein Plugin deaktivieren, indem du dessen Ordner ein '{DISABLED}' am Ende des Namens anhängst."; + /* journal_lock.py: Title text on popup when Journal directory already locked; In files: journal_lock.py:208; */ "Journal directory already locked" = "Journal-Ordner bereits gesperrt"; @@ -253,9 +273,6 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Ungültiger Coriolis-Überschreibungsmodus!"; - -/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ -"EDDB Journal processing disabled. See Log." = "EDDB Journal-Verarbeitung deaktiviert. Siehe Log."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Fehler: Keine Verbindung zum EDDN"; @@ -283,9 +300,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Daten werden an das EDDN gesendet..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Sende Fluglog und CMDR-Status an EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite: Dangerous Star Map Anmeldedaten"; @@ -463,12 +477,15 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Aktivierte Plugins"; - /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support:" = "Plugins ohne Python 3.x Support"; +"Plugins Without Python 3.x Support" = "Plugins ohne Python 3.x Support"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informationen zum Migrieren von Plugins"; +/* prefs.py: Plugins - Label for list of 'broken' plugins that failed to load; In files: prefs.py:1039; */ +"Broken Plugins" = "Defekte Plugins"; + /* prefs.py: Lable on list of user-disabled plugins; In files: prefs.py:977; */ "Disabled Plugins" = "Deaktivierte Plugins"; @@ -616,6 +633,9 @@ /* stats.py: Exobiologist rank; In files: stats.py:132; */ "Directionless" = "Ziellos"; +/* stats.py: Exobiologist rank; In files: stats.py:133; */ +"Mostly Directionless" = "Überwiegend Ziellos"; + /* stats.py: CQC rank; In files: stats.py:142; */ "Helpless" = "Hilflos"; diff --git a/L10n/es.strings b/L10n/es.strings index 4126b73f..d2cb7b4b 100644 --- a/L10n/es.strings +++ b/L10n/es.strings @@ -211,9 +211,6 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "¡Modo sobrescritura de Coriolis Inválido!"; - -/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ -"EDDB Journal processing disabled. See Log." = "Procesamiento de Journal para EDDB desactivado. Ver Log."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Error: No se puede conectar a EDDN"; @@ -241,9 +238,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Enviando datos a EDDN..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Enviar Registro de Vuelo y estado del CMDT a EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Credenciales de Elite Dangerous Star Map"; @@ -400,9 +394,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Plugins Activados"; - /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support:" = "Plugins sin soporte para Python 3.x:"; +"Plugins Without Python 3.x Support" = "Plugins sin Soporte para Python 3.x"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Información sobre migración de plugins"; diff --git a/L10n/fi.strings b/L10n/fi.strings index af51d505..d53d3bc8 100644 --- a/L10n/fi.strings +++ b/L10n/fi.strings @@ -178,9 +178,6 @@ /* l10n.py: The system default language choice in Settings > Appearance; prefs.py: Settings > Configuration - Label on 'reset journal files location to default' button; prefs.py: The system default language choice in Settings > Appearance; prefs.py: Label for 'Default' theme radio button; In files: l10n.py:193; prefs.py:455; prefs.py:709; prefs.py:742; */ "Default" = "Oletus"; - -/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ -"EDDB Journal processing disabled. See Log." = "EDDB lokikirjan käsittely ei käytössä. Katso lokitiedot."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Virhe: ei saatu yhteyttä EDDN:ään"; @@ -199,9 +196,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Lähetetään tietoja EDDN:ään..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Lähetä lentoloki ja komentajatiedot EDSM:ään"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite Dangerous Star Map -kirjautuminen"; @@ -358,9 +352,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Käytössä olevat liitännäiset"; - /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support:" = "Lisäosat, joissa ei ole Python 3.x -tukea:"; +"Plugins Without Python 3.x Support" = "Lisäosat ilman Python 3.x -tukea"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Tietoja lisäosien siirrosta"; diff --git a/L10n/fr.strings b/L10n/fr.strings index 7507516a..93e09777 100644 --- a/L10n/fr.strings +++ b/L10n/fr.strings @@ -151,9 +151,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Envoi des données à EDDN..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Envoyer le journal de vol et le statut Cmdr à EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Informations d'identification pour Elite Dangerous Star Map"; @@ -283,6 +280,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Plugins activés"; +/* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ +"Plugins Without Python 3.x Support" = "Plugins non compatibles avec Python 3.x"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informations sur la migration des plugins"; diff --git a/L10n/hu.strings b/L10n/hu.strings index ea34484a..c3311ac7 100644 --- a/L10n/hu.strings +++ b/L10n/hu.strings @@ -142,9 +142,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Adatok küldése az EDDN-nek..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Repülési napló és Parancsnok státusz küldése az EDSM-nek"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite Dangerous Csillag térkép hitelesítése"; diff --git a/L10n/it.strings b/L10n/it.strings index b6ec19ac..a9d11049 100644 --- a/L10n/it.strings +++ b/L10n/it.strings @@ -253,9 +253,6 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Modalità override Coriolis non valida!"; - -/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ -"EDDB Journal processing disabled. See Log." = "Elaborazione di EDDB Journal disabilitata. Vedi il Log."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Errore: Non riesco a connettermi a EDDN"; @@ -283,9 +280,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Sto inviando i dati a EDDN..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Manda il flight log e lo stato Cmdr a EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Credenziali per Elite Dangerous Star Map"; @@ -413,7 +407,7 @@ "Hide multi-crew captain name" = "Nascondi il nome del capitano in multi-crew."; /* prefs.py: Preferences privacy tab title; In files: prefs.py:703; */ -"Privacy" = "Dati personali"; +"Privacy" = "Privacy"; /* prefs.py: Label for Settings > Appeareance > selection of 'normal' text colour; In files: prefs.py:716; */ "Normal text" = "Testo normale"; @@ -463,9 +457,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Plugin abilitati"; - /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support:" = "Plugin senza il supporto a Python 3.x :"; +"Plugins Without Python 3.x Support" = "Plugins senza Supporto Python 3.x"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informazioni sulla migrazione dei plugins"; diff --git a/L10n/ja.strings b/L10n/ja.strings index 3a8553ae..68a9fd34 100644 --- a/L10n/ja.strings +++ b/L10n/ja.strings @@ -213,12 +213,24 @@ /* EDMarketConnector.py: Popup-text about 'active' plugins without Python 3.x support; In files: EDMarketConnector.py:2253:2259; */ "One or more of your enabled plugins do not yet have support for Python 3.x. Please see the list on the '{PLUGINS}' tab of '{FILE}' > '{SETTINGS}'. You should check if there is an updated version available, else alert the developer that they need to update the code for Python 3.x.\r\n\r\nYou can disable a plugin by renaming its folder to have '{DISABLED}' on the end of the name." = "有効にしている1つ以上のプラグインがPython 3.xをサポートしていません。'{FILE}' > '{SETTINGS}'\nメニューで表示される設定ダイアログの'{PLUGINS}' タブの一覧を確認してください。更新済みのバージョンがあるかを確認し、なければ開発者にPython 3.xに対応するように開発者に連絡してください。\n\nプラグインを無効にするにはフォルダ名の最後に'{DISABLED}'を追加してください。"; +/* EDMarketConnector.py: Popup-text about missing FDEVID Files; In files: EDMarketConnector.py:2329; */ +"FDevID Files not found! Some functionality regarding commodities may be disabled.\r\n\r\n Do you want to open the Wiki page on how to set up submodules?" = "FDevIDファイルが見つかりません!商品に関するいくつかの機能が無効になるかもしれません。\n\nサブモジュールの設定方法についてのWikiページを開きますか?"; + +/* EDMarketConnector.py: Popup window title for missing FDEVID files; In files: EDMarketConnector.py:2340; */ +"FDevIDs: Missing Commodity Files" = "FDevIDs: 商品ファイルが見つかりません"; + /* EDMarketConnector.py: Settings > Plugins tab; prefs.py: Label on Settings > Plugins tab; In files: EDMarketConnector.py:2263; prefs.py:986; */ "Plugins" = "プラグイン"; /* 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." = "有効にしている1つ以上のプラグインがロードに失敗しました。'{FILE}' > '{SETTINGS}' メニューで表示される設定ダイアログの'{PLUGINS}' タブの一覧を確認してください。この問題は誤ったフォルダ構造によって引き起こされます。load.pyファイルはplugins/プラグイン名/plug-in.pyとして配置される必要があります。\n\nプラグインを無効にするにはフォルダ名の最後に'{DISABLED}'を追加してください。"; + /* journal_lock.py: Title text on popup when Journal directory already locked; In files: journal_lock.py:208; */ "Journal directory already locked" = "ジャーナルディレクトリは既にロックされています"; @@ -261,9 +273,6 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "無効なCoriolis上書きモードです!"; - -/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ -"EDDB Journal processing disabled. See Log." = "EDDBジャーナル処理が無効です。ログを確認してください。"; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "エラー: EDDNに接続できません"; @@ -291,9 +300,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "EDDNにデータ送信中..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "フライトログとCMDRステータスをEDSMへ送信する"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite Dangerous Star Mapの認証情報"; @@ -471,12 +477,15 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "有効なプラグイン"; - /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support:" = "Python 3.xサポートのないプラグイン:"; +"Plugins Without Python 3.x Support" = "Python 3.xをサポートしていないプラグイン"; + /* 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" = "無効なプラグイン"; diff --git a/L10n/ko.strings b/L10n/ko.strings index b0701d1b..577695b0 100644 --- a/L10n/ko.strings +++ b/L10n/ko.strings @@ -229,9 +229,6 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "잘못된 Coriolis 오버라이딩 모드입니다!"; - -/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ -"EDDB Journal processing disabled. See Log." = "EDDB 저널 처리 비활성화됨. 로그 참고 바람."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "오류: EDDN에 연결할 수 없음"; @@ -259,9 +256,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "EDDN에 정보 전송하는 중..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "EDSM에 flight 로그와 커맨더 상태 정보 전송하기"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite Dangerous Star Map 계정"; @@ -427,9 +421,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "활성 플러그인"; - /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support:" = "Python 3.x을 지원하지 않는 플러그인:"; +"Plugins Without Python 3.x Support" = "Python 3.x을 지원하지 않는 플러그인"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "플러그인 위치 변경에 대한 정보"; diff --git a/L10n/nl.strings b/L10n/nl.strings index eabde544..f6a4a32f 100644 --- a/L10n/nl.strings +++ b/L10n/nl.strings @@ -148,9 +148,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Bezig data te versturen naar EDDN..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Stuur vlucht logboek en Cmdr status naar EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite Dangerous Star Map inlog gegevens"; @@ -283,6 +280,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Geactiveerde plugins"; +/* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ +"Plugins Without Python 3.x Support" = "Plugins zonder Python 3.x support"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informatie over plugins migreren"; diff --git a/L10n/pl.strings b/L10n/pl.strings index dc4182ab..72a66718 100644 --- a/L10n/pl.strings +++ b/L10n/pl.strings @@ -1,3 +1,11 @@ +/* edsm.py:Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:316; */ +"Send flight log and CMDR status to EDSM" = "Wyślij flight log i status gracza do EDSM"; + +/* prefs.py:Label on button used to open a filesystem folder; In files: prefs.py:706; */ +"Open Log Folder" = "Otwórz folder z zapisami z logów"; + +/* inara.py:Text Inara Show API key; In files: inara.py:305; */ +"Show API Key" = "Pokaż klucz API"; /* Language name */ "!Language" = "Polski"; @@ -94,6 +102,12 @@ /* EDMarketConnector.py: Help > Documentation; In files: EDMarketConnector.py:933; EDMarketConnector.py:953; */ "Documentation" = "Dokumentacja"; +/* EDMarketConnector.py: Help > Troubleshooting; In files: EDMarketConnector.py:934; EDMarketConnector.py:954; */ +"Troubleshooting" = "Rozwiązywanie problemów"; + +/* EDMarketConnector.py: Help > Report A Bug; In files: EDMarketConnector.py:935; EDMarketConnector.py:955; */ +"Report A Bug" = "Zgłoś błąd"; + /* EDMarketConnector.py: Help > Privacy Policy; In files: EDMarketConnector.py:936; EDMarketConnector.py:956; */ "Privacy Policy" = "Polityka prywatności"; @@ -109,6 +123,9 @@ /* 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" = "Kopiuj"; +/* 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" = "Autoryzacja CAPI wyłączona \"kill switchem\"."; + /* EDMarketConnector.py: Status - Attempting to get a Frontier Auth Access Token; In files: EDMarketConnector.py:978; */ "Logging in..." = "Logowanie..."; @@ -130,6 +147,9 @@ /* EDMarketConnector.py: CAPI queries aborted because game mode unknown; In files: EDMarketConnector.py:1083; */ "CAPI query aborted: Game mode unknown" = "Zapytanie CAPI anulowane: tryb gry nieznany"; +/* EDMarketConnector.py: CAPI queries aborted because GameVersion unknown; EDMarketConnector.py: CAPI fleetcarrier query aborted because GameVersion unknown; In files: EDMarketConnector.py:1089; EDMarketConnector.py:1170; */ +"CAPI query aborted: GameVersion unknown" = "Zapytanie CAPI anulowane: wersja gry nieznana"; + /* EDMarketConnector.py: CAPI queries aborted because current star system name unknown; In files: EDMarketConnector.py:1095; */ "CAPI query aborted: Current system unknown" = "Zapytanie CAPI anulowane: obecny system nieznany"; @@ -142,6 +162,15 @@ /* EDMarketConnector.py: Status - Attempting to retrieve data from Frontier CAPI; In files: EDMarketConnector.py:1128; EDMarketConnector.py:1179; */ "Fetching data..." = "Pobieranie danych..."; +/* EDMarketConnector.py: CAPI fleetcarrier query aborted because of killswitch; In files: EDMarketConnector.py:1157; */ +"CAPI fleetcarrier disabled by killswitch" = "Fleetcarier CAPI wyłączony \"kill switchem\""; + +/* EDMarketConnector.py: No data was returned for the fleetcarrier from the Frontier CAPI; In files: EDMarketConnector.py:1219; */ +"CAPI: No fleetcarrier data returned" = "CAPI: Nie zwrócono danych dotyczących lotniskowca"; + +/* EDMarketConnector.py: We didn't have the fleetcarrier callsign when we should have; In files: EDMarketConnector.py:1223; */ +"CAPI: Fleetcarrier data incomplete" = "CAPI: Niekompletne dane lotniskowca"; + /* EDMarketConnector.py: No data was returned for the commander from the Frontier CAPI; In files: EDMarketConnector.py:1242; */ "CAPI: No commander data returned" = "CAPI: Nie zwrócono danych dowódcy"; @@ -232,9 +261,6 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Niewłaściwy tryb nadpisania Coriolis!"; - -/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ -"EDDB Journal processing disabled. See Log." = "Wyłączone przetwarzanie dziennika EDDB. Sprawdź logi."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Błąd: Brak połączenia z EDDN"; @@ -262,9 +288,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Wysłanie danych do EDDN..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Wyślij zapis lotu i status pilota do EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Dane uwierzytelniające Elite Dangerous Star Map"; @@ -280,6 +303,9 @@ /* edsm.py: EDSM plugin - Journal handling disabled by killswitch; In files: edsm.py:516; */ "EDSM Handler disabled. See Log." = "Wyłączona obsługa EDDB. Sprawdź logi."; +/* edsm.py: EDSM - Only Live data; In files: edsm.py:632; */ +"EDSM only accepts Live galaxy data" = "EDSM przyjmuje tylko dane z aktualnej rozgrywki"; + /* edsm.py: EDSM Plugin - Error message from EDSM API; In files: edsm.py:916; edsm.py:1048; */ "Error: EDSM {MSG}" = "Błąd: EDSM {MSG}"; @@ -292,6 +318,9 @@ /* inara.py: Text for INARA API keys link ( goes to https://inara.cz/settings-api ); In files: inara.py:269; */ "Inara credentials" = "Inara - uprawnienia"; +/* inara.py: The Inara API only accepts Live galaxy data, not Legacy galaxy data; inara.py: Inara - Only Live data; In files: inara.py:384; inara.py:386; */ +"Inara only accepts Live galaxy data" = "Inara przyjmuje tylko dane z aktualnej rozgrywki"; + /* inara.py: INARA support disabled via killswitch; In files: inara.py:395; */ "Inara disabled. See Log." = "Inara jest wyłączona. Sprawdź logi."; @@ -331,6 +360,12 @@ /* prefs.py: Settings > Configuration - Label for Journal files location; In files: prefs.py:431; prefs.py:446; */ "E:D journal file location" = "E:D Lokacja pliku dziennika"; +/* prefs.py: Settings > Configuration - Label for CAPI section; In files: prefs.py:469; */ +"CAPI Settings" = "Ustawienia CAPI"; + +/* prefs.py: Configuration - Enable or disable the Fleet Carrier CAPI calls; In files: prefs.py:475; */ +"Enable Fleetcarrier CAPI Queries" = "Włącz zapytania CAPI dla lotniskowca"; + /* prefs.py: Hotkey/Shortcut settings prompt on OSX; In files: prefs.py:490; */ "Keyboard shortcut" = "Skrót klawiaturowy"; @@ -430,9 +465,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Włączone pluginy"; - /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support:" = "Pluginy nie obsługiwane przez Python 3.x:"; +"Plugins Without Python 3.x Support" = "Pluginy nie wspierające Python 3.x"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informacja o migracji pluginów"; diff --git a/L10n/pt-BR.strings b/L10n/pt-BR.strings index 51952c05..e719101a 100644 --- a/L10n/pt-BR.strings +++ b/L10n/pt-BR.strings @@ -261,9 +261,6 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Modo de substituição Coriolis inválido!"; - -/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ -"EDDB Journal processing disabled. See Log." = "Processamento de Jornais no EDDB desativado. Verifique o Log."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Erro: Não é possível conectar-se ao EDDN"; @@ -291,9 +288,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Enviando log para o EDDN..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Enviar dados de voo e status do cmdt para o EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Credenciais do Elite Dangerous Star Map (EDSM)"; @@ -471,9 +465,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Plugins Habilitados"; - /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support:" = "Plugins sem suporte a Python 3.x:"; +"Plugins Without Python 3.x Support" = "Plugins sem Suporte ao Python 3.x"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informações de migração de plugins"; diff --git a/L10n/pt-PT.strings b/L10n/pt-PT.strings index 3002069f..ea292b14 100644 --- a/L10n/pt-PT.strings +++ b/L10n/pt-PT.strings @@ -213,12 +213,24 @@ /* EDMarketConnector.py: Popup-text about 'active' plugins without Python 3.x support; In files: EDMarketConnector.py:2253:2259; */ "One or more of your enabled plugins do not yet have support for Python 3.x. Please see the list on the '{PLUGINS}' tab of '{FILE}' > '{SETTINGS}'. You should check if there is an updated version available, else alert the developer that they need to update the code for Python 3.x.\r\n\r\nYou can disable a plugin by renaming its folder to have '{DISABLED}' on the end of the name." = "Um ou mais dos plugins activados não possui ainda suporte para Python 3.x. Por favor verifique a lista na aba '{PLUGINS}' em '{FILE}' > '{SETTINGS}'. Deverá verificar se está disponível uma versão mais actualizada, caso contrário, informe o desenvolvedor de que necessita de actualizar o código para suportar Python 3.x.\n\nPode desactivar um plugin colocando '{DISABLED}' no fim do nome da pasta correspondente."; +/* EDMarketConnector.py: Popup-text about missing FDEVID Files; In files: EDMarketConnector.py:2329; */ +"FDevID Files not found! Some functionality regarding commodities may be disabled.\r\n\r\n Do you want to open the Wiki page on how to set up submodules?" = "Ficheiros FDevID não encontrados. Algumas funcionalidades relacionadas com mercadorias poderão estar indisponíveis.\nDeseja abrir a página da Wiki sobre configuração de submódulos?"; + +/* EDMarketConnector.py: Popup window title for missing FDEVID files; In files: EDMarketConnector.py:2340; */ +"FDevIDs: Missing Commodity Files" = "FDevIDs: Ficheiros de Mercadorias em falta."; + /* EDMarketConnector.py: Settings > Plugins tab; prefs.py: Label on Settings > Plugins tab; In files: EDMarketConnector.py:2263; prefs.py:986; */ "Plugins" = "Plugins"; /* 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: Plugins sem suporte para 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: Plugins Interrompidos"; + +/* 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." = "Um ou mais dos plugins activados não arrancou correctamente. Por favor consule a lista na aba {PLUGINS}', em '{FILE}' > '{SETTINGS}'. Isto poderá ser causado por má estrutura de pastas. O ficheiro load.py deverá estar dentro de plugins/NOME_DO_PLUGIN/load.py. \nPode desactivar um plugin colocando '{DISABLED}' no fim do nome da pasta."; + /* journal_lock.py: Title text on popup when Journal directory already locked; In files: journal_lock.py:208; */ "Journal directory already locked" = "Directório do Diário já se encontra bloqueado"; @@ -261,9 +273,6 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Modo de sobreposição Coriolis inválido!"; - -/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ -"EDDB Journal processing disabled. See Log." = "Processamento do diário do EDDB desactivado. Verifique o ficheiro de registos."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Erro: Não é possível conectar ao EDDN"; @@ -291,9 +300,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "A enviar dados para o EDDN..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Enviar dados de voo e o estado do CMDT para o EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Credenciais do Elite Dangerous Star Map (EDSM)"; @@ -471,12 +477,15 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Plugins Activados"; - /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support:" = "Plugins sem suporte para Python 3.x"; +"Plugins Without Python 3.x Support" = "Plugins sem suporte para Python 3.x"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informação para migração de plugins"; +/* prefs.py: Plugins - Label for list of 'broken' plugins that failed to load; In files: prefs.py:1039; */ +"Broken Plugins" = "Plugins Interrompidos"; + /* prefs.py: Lable on list of user-disabled plugins; In files: prefs.py:977; */ "Disabled Plugins" = "Plugins Desactivados"; diff --git a/L10n/ru.strings b/L10n/ru.strings index 539fa21c..c3c0fae1 100644 --- a/L10n/ru.strings +++ b/L10n/ru.strings @@ -261,9 +261,6 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Некорректный режим переопределения URL для coriolis.io"; - -/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ -"EDDB Journal processing disabled. See Log." = "Обработка журнала EDDB отключена. См. логи."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Ошибка: не удается подключиться к EDDN"; @@ -291,9 +288,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Отправка данных на EDDN..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Отправлять данные журнала полёта и информацию статусе командира в EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Учётные данные Elite Dangerous Star Map"; @@ -471,9 +465,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Включённые плагины"; - /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support:" = "Плагины без поддержки Python 3.x"; +"Plugins Without Python 3.x Support" = "Плагины без поддержки Python 3.x"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Информация о мигрирующих плагинах"; diff --git a/L10n/sr-Latn-BA.strings b/L10n/sr-Latn-BA.strings index c872376f..2950f8b8 100644 --- a/L10n/sr-Latn-BA.strings +++ b/L10n/sr-Latn-BA.strings @@ -1,3 +1,11 @@ +/* edsm.py:Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:316; */ +"Send flight log and CMDR status to EDSM" = "Pošalji log leta i Cmdr status na EDSM"; + +/* prefs.py:Label on button used to open a filesystem folder; In files: prefs.py:706; */ +"Open Log Folder" = "Otvori folder sa logovima"; + +/* inara.py:Text Inara Show API key; In files: inara.py:305; */ +"Show API Key" = "Prikaži API ključ"; /* Language name */ "!Language" = "Srpski (Latinica, Bosna i Hercegovina)"; @@ -94,6 +102,12 @@ /* EDMarketConnector.py: Help > Documentation; In files: EDMarketConnector.py:933; EDMarketConnector.py:953; */ "Documentation" = "Dokumentacija"; +/* EDMarketConnector.py: Help > Troubleshooting; In files: EDMarketConnector.py:934; EDMarketConnector.py:954; */ +"Troubleshooting" = "Otklanjanje problema"; + +/* EDMarketConnector.py: Help > Report A Bug; In files: EDMarketConnector.py:935; EDMarketConnector.py:955; */ +"Report A Bug" = "Prijavi Bug"; + /* EDMarketConnector.py: Help > Privacy Policy; In files: EDMarketConnector.py:936; EDMarketConnector.py:956; */ "Privacy Policy" = "Politika privatnosti"; @@ -109,6 +123,9 @@ /* 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" = "Kopiraj"; +/* 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 autentifikacija onemogućena putem sistemskog prekidača"; + /* EDMarketConnector.py: Status - Attempting to get a Frontier Auth Access Token; In files: EDMarketConnector.py:978; */ "Logging in..." = "Prijavljivanje..."; @@ -130,6 +147,9 @@ /* EDMarketConnector.py: CAPI queries aborted because game mode unknown; In files: EDMarketConnector.py:1083; */ "CAPI query aborted: Game mode unknown" = "CAPI upit prekinut: nepoznat režim igre"; +/* EDMarketConnector.py: CAPI queries aborted because GameVersion unknown; EDMarketConnector.py: CAPI fleetcarrier query aborted because GameVersion unknown; In files: EDMarketConnector.py:1089; EDMarketConnector.py:1170; */ +"CAPI query aborted: GameVersion unknown" = "CAPI upit prekinut: nepoznat GameVersion"; + /* EDMarketConnector.py: CAPI queries aborted because current star system name unknown; In files: EDMarketConnector.py:1095; */ "CAPI query aborted: Current system unknown" = "CAPI upit prekinut: nepoznat trenutni sistem"; @@ -142,6 +162,15 @@ /* EDMarketConnector.py: Status - Attempting to retrieve data from Frontier CAPI; In files: EDMarketConnector.py:1128; EDMarketConnector.py:1179; */ "Fetching data..." = "Preuzimanje podataka..."; +/* EDMarketConnector.py: CAPI fleetcarrier query aborted because of killswitch; In files: EDMarketConnector.py:1157; */ +"CAPI fleetcarrier disabled by killswitch" = "CAPI fleetcarrier onemogućen putem sistemskog prekidača"; + +/* EDMarketConnector.py: No data was returned for the fleetcarrier from the Frontier CAPI; In files: EDMarketConnector.py:1219; */ +"CAPI: No fleetcarrier data returned" = "CAPI: Fleetcarrier podaci nisu dobijeni"; + +/* EDMarketConnector.py: We didn't have the fleetcarrier callsign when we should have; In files: EDMarketConnector.py:1223; */ +"CAPI: Fleetcarrier data incomplete" = "CAPI: Fleetcarrier podaci nisu potpuni"; + /* EDMarketConnector.py: No data was returned for the commander from the Frontier CAPI; In files: EDMarketConnector.py:1242; */ "CAPI: No commander data returned" = "CAPI: Nema podataka o komandantu"; @@ -184,12 +213,24 @@ /* EDMarketConnector.py: Popup-text about 'active' plugins without Python 3.x support; In files: EDMarketConnector.py:2253:2259; */ "One or more of your enabled plugins do not yet have support for Python 3.x. Please see the list on the '{PLUGINS}' tab of '{FILE}' > '{SETTINGS}'. You should check if there is an updated version available, else alert the developer that they need to update the code for Python 3.x.\r\n\r\nYou can disable a plugin by renaming its folder to have '{DISABLED}' on the end of the name." = "Jedan ili više aktiviranih dodataka (plugins) nemaju podršku za Python 3.x. Pogledajte listu u '{PLUGINS}' tabu u '{FILE}' > '{SETTINGS}'. Provjerite da li postoji nadograđena verzija ili obavijesite autora da treba da promijeni kod za Python 3.x.\n\nMožete deaktivirati dodatak (plugin) dodavanjem '{DISABLED}' na kraju imena njegovog foldera."; +/* EDMarketConnector.py: Popup-text about missing FDEVID Files; In files: EDMarketConnector.py:2329; */ +"FDevID Files not found! Some functionality regarding commodities may be disabled.\r\n\r\n Do you want to open the Wiki page on how to set up submodules?" = "FDevID fajlovi nisu pronađeni. Određene opcije vezane za robu bi mogle da budu nedostupne.\n\nDa li želite da otvorite Wiki stranicu sa uputstvom za podešavanje podmodula?"; + +/* EDMarketConnector.py: Popup window title for missing FDEVID files; In files: EDMarketConnector.py:2340; */ +"FDevIDs: Missing Commodity Files" = "FDevIDs: Nedostaju Commodity fajlovi"; + /* EDMarketConnector.py: Settings > Plugins tab; prefs.py: Label on Settings > Plugins tab; In files: EDMarketConnector.py:2263; prefs.py:986; */ "Plugins" = "Dodaci (plugins)"; /* 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: Dodaci (plugins) bez Python 3.x podrške"; +/* EDMarketConnector.py: Popup window title for list of 'broken' plugins that failed to load; In files: EDMarketConnector.py:2285; */ +"EDMC: Broken Plugins" = "EDMC: Neispravni dodaci (plugins)"; + +/* 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." = "Jedan ili više aktiviranih dodataka (plugins) nemaju podršku za Python 3.x. Pogledajte listu u '{PLUGINS}' tabu u '{FILE}' > '{SETTINGS}'. Pogrešna struktura foldera može da uzrokuje problem. Fajl load.py treba da bude smješten u plugins/PLUGIN_NAME/load.py.\n\nMožete deaktivirati dodatak (plugin) dodavanjem '{DISABLED}' na kraju imena njegovog foldera."; + /* journal_lock.py: Title text on popup when Journal directory already locked; In files: journal_lock.py:208; */ "Journal directory already locked" = "Journal direktorijum je već zaključan"; @@ -232,9 +273,6 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Neispravan Coriolis režim rada!"; - -/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ -"EDDB Journal processing disabled. See Log." = "EDDB obrada journala je deaktivirana. Pogledajte Log."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Greška: Nemoguće povezivanje sa EDDN"; @@ -262,9 +300,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Slanje podataka na EDDN..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Pošalji log leta i Cmdr status na EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Kredencijali za Elite Dangerous Star Map"; @@ -280,6 +315,9 @@ /* edsm.py: EDSM plugin - Journal handling disabled by killswitch; In files: edsm.py:516; */ "EDSM Handler disabled. See Log." = "EDSM obrada je deaktivirana. Pogledajte Log."; +/* edsm.py: EDSM - Only Live data; In files: edsm.py:632; */ +"EDSM only accepts Live galaxy data" = "EDCM prihvata samo Live galaxy podatke"; + /* edsm.py: EDSM Plugin - Error message from EDSM API; In files: edsm.py:916; edsm.py:1048; */ "Error: EDSM {MSG}" = "Greška: EDSM {MSG}"; @@ -334,6 +372,12 @@ /* prefs.py: Settings > Configuration - Label for Journal files location; In files: prefs.py:431; prefs.py:446; */ "E:D journal file location" = "Lokacija E:D journal fajlova"; +/* prefs.py: Settings > Configuration - Label for CAPI section; In files: prefs.py:469; */ +"CAPI Settings" = "CAPI Podešavanja"; + +/* prefs.py: Configuration - Enable or disable the Fleet Carrier CAPI calls; In files: prefs.py:475; */ +"Enable Fleetcarrier CAPI Queries" = "Omogući Fleetcarrier CAPI Upite"; + /* prefs.py: Hotkey/Shortcut settings prompt on OSX; In files: prefs.py:490; */ "Keyboard shortcut" = "Prečica"; @@ -433,12 +477,15 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Aktivirani dodaci (plugins)"; - /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support:" = "Dodaci (plugins) bez Python 3.x podrške:"; +"Plugins Without Python 3.x Support" = "Dodaci (plugins) bez Python 3.x podrške"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informacije o migraciji dodataka (plugins)"; +/* prefs.py: Plugins - Label for list of 'broken' plugins that failed to load; In files: prefs.py:1039; */ +"Broken Plugins" = "Neispravni dodaci (plugins)"; + /* prefs.py: Lable on list of user-disabled plugins; In files: prefs.py:977; */ "Disabled Plugins" = "Deaktivirani dodaci (plugins)"; diff --git a/L10n/sr-Latn.strings b/L10n/sr-Latn.strings index 9515dca2..5f2c01c5 100644 --- a/L10n/sr-Latn.strings +++ b/L10n/sr-Latn.strings @@ -1,3 +1,11 @@ +/* edsm.py:Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:316; */ +"Send flight log and CMDR status to EDSM" = "Pošalji zapisnik leta i CMDR status na EDSM"; + +/* prefs.py:Label on button used to open a filesystem folder; In files: prefs.py:706; */ +"Open Log Folder" = "Otvori folder sa zapisnicima leta"; + +/* inara.py:Text Inara Show API key; In files: inara.py:305; */ +"Show API Key" = "Prikaži API ključ"; /* Language name */ "!Language" = "Srpski (Latinica)"; @@ -253,9 +261,6 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "Pogrešan Coriolis preinačeni mod!"; - -/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ -"EDDB Journal processing disabled. See Log." = "Obrada žurnala za EDDB je deaktivirana. Pogledajte Log."; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "Greška: Nemoguće povezivanje na EDDN"; @@ -283,9 +288,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Slanje podataka na EDDN..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Pošalji log leta i Cmdr status na EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Kredencijali za Elite Dangerous Star Map"; @@ -463,9 +465,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Aktivirani dodaci (plugins)"; - /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support:" = "Pluginovi bez podrške za Python 3.x:"; +"Plugins Without Python 3.x Support" = "Dodaci (plugins) bez Python 3.x podrške:"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Informacije o migraciji dodataka (plugins)"; diff --git a/L10n/sv-SE.strings b/L10n/sv-SE.strings index 6c7daaca..8f944159 100644 --- a/L10n/sv-SE.strings +++ b/L10n/sv-SE.strings @@ -148,9 +148,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Skickar data till EDDN..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Skicka flight log-data och Cmdr-status till EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite Dangerous Star Map användaruppgifter"; @@ -277,6 +274,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Aktiverade plugins"; +/* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ +"Plugins Without Python 3.x Support" = "Plugins utan stöd för Python 3.x"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Information om migrering av plugins"; diff --git a/L10n/uk.strings b/L10n/uk.strings index bfeff7b0..35d2c229 100644 --- a/L10n/uk.strings +++ b/L10n/uk.strings @@ -184,9 +184,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "Відправка даних до EDDN..."; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "Відправляти дані бортового журналу до EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Дані Elite Dangerous Star Map"; @@ -337,9 +334,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "Увімкнені плагіни"; - /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support:" = "Плагіни без підтримки Python 3.x:"; +"Plugins Without Python 3.x Support" = "Плагіни без підтримки Python 3.x"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "Інформація про міграцію плагінів"; diff --git a/L10n/zh-Hans.strings b/L10n/zh-Hans.strings index 84f70036..2b9eb75d 100644 --- a/L10n/zh-Hans.strings +++ b/L10n/zh-Hans.strings @@ -253,9 +253,6 @@ /* coriolis.py: Settings>Coriolis - invalid override mode found; In files: coriolis.py:156; */ "Invalid Coriolis override mode!" = "无效的 Coriolis 覆盖模式!"; - -/* eddb.py: Journal Processing disabled due to an active killswitch; In files: eddb.py:179; */ -"EDDB Journal processing disabled. See Log." = "EDDB Journal Processing 已禁用。请查看诊断日志。"; /* eddn.py: Error while trying to send data to EDDN; In files: eddn.py:458; eddn.py:2413; eddn.py:2451; eddn.py:2519; */ "Error: Can't connect to EDDN" = "错误:无法连接到 EDDN"; @@ -283,9 +280,6 @@ /* eddn.py: Status text shown while attempting to send data; In files: eddn.py:2507; */ "Sending data to EDDN..." = "正在向 EDDN 发送数据…"; - -/* edsm.py: Settings>EDSM - Label on checkbox for 'send data'; In files: edsm.py:308; */ -"Send flight log and Cmdr status to EDSM" = "发送航行日志和指挥官状态到 EDSM"; /* edsm.py: Settings>EDSM - Label on header/URL to EDSM API key page; In files: edsm.py:319; */ "Elite Dangerous Star Map credentials" = "Elite Dangerous Star Map 授权凭证"; @@ -463,9 +457,9 @@ /* prefs.py: Label on list of enabled plugins; In files: prefs.py:934; */ "Enabled Plugins" = "已启用插件"; - /* prefs.py: Plugins - Label for list of 'enabled' plugins that don't work with Python 3.x; In files: prefs.py:954; */ -"Plugins Without Python 3.x Support:" = "不支持 Python 3.x 的插件:"; +"Plugins Without Python 3.x Support" = "不支持 Python 3.x 的插件"; + /* prefs.py: Plugins - Label on URL to documentation about migrating plugins from Python 2.7; In files: prefs.py:962; */ "Information on migrating plugins" = "关于插件迁移"; From af68bbdc00b38bd1cfb79eda776f0b0e996a90af Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Wed, 20 Dec 2023 22:00:02 -0500 Subject: [PATCH 82/83] [5.10.0] Update Version String --- config/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/__init__.py b/config/__init__.py index 201e76b6..77b6a0f7 100644 --- a/config/__init__.py +++ b/config/__init__.py @@ -54,7 +54,7 @@ appcmdname = 'EDMC' # # Major.Minor.Patch(-prerelease)(+buildmetadata) # NB: Do *not* import this, use the functions appversion() and appversion_nobuild() -_static_appversion = '5.10.0-rc1' +_static_appversion = '5.10.0' _cached_version: semantic_version.Version | None = None copyright = '© 2015-2019 Jonathan Harris, 2020-2023 EDCD' From b5311b4a6ece3911adc4e8baa74c840f1820b450 Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Wed, 20 Dec 2023 22:03:30 -0500 Subject: [PATCH 83/83] [Minor] Sync Submodule Document --- .github/workflows/submodule-update.yml | 37 +++++++++----------------- 1 file changed, 12 insertions(+), 25 deletions(-) diff --git a/.github/workflows/submodule-update.yml b/.github/workflows/submodule-update.yml index 1f403c56..0ffa62c8 100644 --- a/.github/workflows/submodule-update.yml +++ b/.github/workflows/submodule-update.yml @@ -1,10 +1,16 @@ name: Submodule Updates on: + workflow_dispatch: + inputs: + logLevel: + description: 'Log level' + required: true + default: 'warning' push: branches: [develop] schedule: - - cron: '0 12 * * *' + - cron: '0 12 * * *' jobs: check_submodules: @@ -47,40 +53,21 @@ jobs: - name: Create or Update submodules changes branch if: steps.check_for_changes.outputs.changes == 'true' run: | - git fetch origin "submodule-change/$GITHUB_RUN_ID" || git checkout -b "submodule-change/$GITHUB_RUN_ID" $CHECKOUT_BRANCH + git checkout -b "submodule-change/$GITHUB_RUN_ID" $CHECKOUT_BRANCH git commit -am "updating submodules" git push --set-upstream origin "submodule-change/$GITHUB_RUN_ID" - - name: Create or Update pull request against target branch + - name: Create pull request against target branch if: steps.check_for_changes.outputs.changes == 'true' uses: actions/github-script@v7 with: github-token: "${{ secrets.GITHUB_TOKEN }}" script: | - const { data: pulls } = await github.rest.pulls.list({ + await github.rest.pulls.create({ owner: '${{ github.repository_owner }}', repo: '${{ github.repository }}'.split('/')[1].trim(), head: 'submodule-change/${{ github.run_id }}', base: '${{ env.PR_AGAINST_BRANCH }}', - state: 'open', + title: `[Auto-generated] Submodule Updates ${process.env.GITHUB_RUN_ID}`, + body: '${{ steps.check_for_changes.outputs.changes_text }}', }); - if (pulls.length > 0) { - // If an open pull request exists, update it - const pull_number = pulls[0].number; - await github.rest.pulls.update({ - owner: '${{ github.repository_owner }}', - repo: '${{ github.repository }}'.split('/')[1].trim(), - pull_number, - body: '${{ steps.check_for_changes.outputs.changes_text }}', - }); - } else { - // If no open pull request exists, create a new one - await github.rest.pulls.create({ - owner: '${{ github.repository_owner }}', - repo: '${{ github.repository }}'.split('/')[1].trim(), - head: 'submodule-change/${{ github.run_id }}', - base: '${{ env.PR_AGAINST_BRANCH }}', - title: `[Auto-generated] Submodule Updates ${process.env.GITHUB_RUN_ID}`, - body: '${{ steps.check_for_changes.outputs.changes_text }}', - }); - }