Merge branch 'beta'

This commit is contained in:
David Sangrey committed 2023-12-20 22:20:21 -05:00
commit 631b7f93d3
87 files changed
+6268 -2091

No files matched your search

+1 -1
View File
@@ -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}}
+1 -1
View File
@@ -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
+6 -6
View File
@@ -5,13 +5,13 @@ on:
workflow_dispatch:
inputs:
logLevel:
description: 'Log level'
description: 'Log level'
required: true
default: 'warning'
push:
branches: [ develop ]
# schedule:
# - cron: '0 12 * * *'
branches: [develop]
schedule:
- cron: '0 12 * * *'
jobs:
check_submodules:
@@ -24,7 +24,7 @@ jobs:
OWNER: 'EDCD'
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
ref: '${{ env.CHECKOUT_BRANCH }}'
submodules: true
@@ -60,7 +60,7 @@ jobs:
- name: Create 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: |
+3 -3
View File
@@ -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: |
@@ -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
+32 -5
View File
@@ -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/
+35 -35
View File
@@ -1,6 +1,12 @@
#!/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 +14,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 +49,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 +72,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 +104,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 +159,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 +188,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 +210,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 +260,8 @@ sys.path: {sys.path}'''
for idx, cmdr in enumerate(cmdrs):
if cmdr.lower() == args.p.lower():
break
else:
raise companion.CredentialsError()
companion.session.login(cmdrs[idx], monitor.is_beta)
else:
@@ -292,9 +295,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 +367,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 +410,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 +462,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)
+9 -17
View File
@@ -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
+234 -172
View File
@@ -1,6 +1,11 @@
#!/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 +14,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 +29,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 +50,8 @@ 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')
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
@@ -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: <https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumwindows>
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 = '<<CAPIResponse>>'
@@ -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
@@ -699,6 +685,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=prefs.help_open_log_folder) # Open Log Folder
self.menubar.add_cascade(menu=self.help_menu)
if sys.platform == 'win32':
@@ -733,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('<Button-1>', self.drag_start)
theme_titlebar.bind('<B1-Motion>', self.drag_continue)
theme_titlebar.bind('<ButtonRelease-1>', self.drag_end)
@@ -807,7 +794,7 @@ class AppWindow(object):
self.w.bind('<KP_Enter>', self.capi_request_data)
self.w.bind_all('<<Invoke>>', 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('<<JournalEvent>>', self.journal_event) # Journal monitoring
self.w.bind_all('<<JournalEvent>>', self.journal_event) # type: ignore # Journal monitoring
self.w.bind_all('<<DashboardEvent>>', self.dashboard_event) # Dashboard monitoring
self.w.bind_all('<<PluginError>>', self.plugin_error) # Statusbar
self.w.bind_all('<<CompanionAuthEvent>>', self.auth) # cAPI auth
@@ -825,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."""
@@ -833,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
@@ -848,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)
@@ -935,6 +916,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 +940,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'
@@ -1016,38 +1000,49 @@ 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
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
# 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
# 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_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 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!")
elif not has_commodities:
# LANG: Status - No station market data from Frontier CAPI
self._handle_status(_("Station doesn't have a market!"))
elif config.get_int('output') & (config.OUT_MKT_CSV | config.OUT_MKT_TD):
# Fixup anomalies in the commodity data
elif output_flags & commodities_flag:
# Fixup anomalies in the comodity data
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.
@@ -1114,13 +1109,13 @@ class AppWindow(object):
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:
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() # Don't play sound in first few seconds to prevent repeats
return
hotkeymgr.play_bad()
return
elif play_sound:
hotkeymgr.play_good()
@@ -1133,6 +1128,7 @@ class AppWindow(object):
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
@@ -1188,12 +1184,16 @@ class AppWindow(object):
)
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)
@@ -1202,8 +1202,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):
@@ -1252,8 +1251,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
@@ -1264,8 +1263,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 "
@@ -1285,7 +1284,7 @@ class AppWindow(object):
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,
@@ -1307,8 +1306,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 "
@@ -1381,9 +1380,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
@@ -1421,11 +1423,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)
@@ -1444,7 +1441,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.
@@ -1572,7 +1569,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)
@@ -1717,27 +1714,27 @@ 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:
"""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']
)
@@ -1745,12 +1742,10 @@ 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())
# 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:
self.button['text'] = self.theme_button['text'] = _('Update') # LANG: Update button in main window
self.button['state'] = self.theme_button['state'] = (
@@ -1771,11 +1766,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."""
@@ -1801,9 +1795,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
@@ -1844,11 +1843,11 @@ class AppWindow(object):
# version <link to changelog>
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'),
@@ -2064,7 +2063,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:
@@ -2126,7 +2125,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.')
@@ -2163,12 +2162,12 @@ sys.path: {sys.path}'''
# <https://en.wikipedia.org/wiki/Windows_10_version_history#Version_1903_(May_2019_Update)>
# 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).
@@ -2205,10 +2204,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):
@@ -2261,10 +2260,38 @@ sys.path: {sys.path}'''
app = AppWindow(root)
def messagebox_broken_plugins():
"""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 = _(
"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 "
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."
)
# 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 failed 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)
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 "
@@ -2292,15 +2319,50 @@ 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:
fdevid_file = pathlib.Path(config.respath_path / 'FDevIDs' / file)
if fdevid_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:
ui_transparency = 100
root.wm_attributes('-alpha', ui_transparency / 100)
root.after(0, messagebox_not_py3)
root.after(1, show_killswitch_poppup, root)
# 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)
# 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()
logger.info('Exiting')
+1 -1
Submodule FDevIDs updated: e8dbd99ddc...069b09b1af.
+2 -4
View File
@@ -223,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";
@@ -383,7 +380,7 @@
"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.";
@@ -618,3 +615,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Lodě";
+28 -4
View File
@@ -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";
@@ -280,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";
@@ -461,11 +478,14 @@
"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";
@@ -613,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";
@@ -744,3 +767,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Schiffe";
+25 -4
View File
@@ -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";
@@ -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." = "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";
/* 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 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";
@@ -280,9 +300,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";
@@ -461,11 +478,14 @@
"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";
/* 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";
@@ -768,3 +788,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Ships";
+2 -4
View File
@@ -238,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";
@@ -398,7 +395,7 @@
"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";
@@ -633,3 +630,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Naves";
+5 -4
View File
@@ -190,12 +190,12 @@
/* 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";
@@ -353,7 +353,7 @@
"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";
@@ -588,3 +588,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Alukset";
+4 -3
View File
@@ -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";
@@ -516,3 +516,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Vaisseaux";
+1 -3
View File
@@ -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";
@@ -501,3 +498,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Hajók";
+185 -10
View File
@@ -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,21 @@
/* 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!";
/* 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 +274,12 @@
/* 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 +292,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 +310,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 +352,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 +386,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,8 +397,17 @@
/* 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";
"Privacy" = "Privacy";
/* prefs.py: Label for Settings > Appeareance > selection of 'normal' text colour; In files: prefs.py:716; */
"Normal text" = "Testo normale";
@@ -347,7 +449,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";
@@ -356,7 +458,7 @@
"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";
@@ -373,6 +475,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 +499,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 +589,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 +754,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";
+25 -4
View File
@@ -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" = "日本語";
@@ -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." = "有効にしている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" = "ジャーナルディレクトリは既にロックされています";
@@ -280,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の認証情報";
@@ -461,11 +478,14 @@
"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" = "無効なプラグイン";
@@ -768,3 +788,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "所有船";
+2 -4
View File
@@ -256,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 계정";
@@ -425,7 +422,7 @@
"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" = "플러그인 위치 변경에 대한 정보";
@@ -666,3 +663,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "함선(들)";
+1
View File
@@ -480,3 +480,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Kuģi";
+4 -3
View File
@@ -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";
@@ -516,3 +516,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Schepen";
+45 -6
View File
@@ -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";
@@ -254,14 +283,11 @@
"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 +301,10 @@
"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 - 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}";
@@ -289,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.";
@@ -328,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";
@@ -428,7 +466,7 @@
"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";
@@ -735,3 +773,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Statki";
+10 -4
View File
@@ -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)";
@@ -280,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)";
@@ -461,7 +466,7 @@
"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";
@@ -768,3 +773,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Naves";
+25 -4
View File
@@ -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)";
@@ -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." = "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";
@@ -280,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)";
@@ -461,11 +478,14 @@
"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";
@@ -768,3 +788,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Naves";
+10 -4
View File
@@ -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" = "Русский";
@@ -280,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";
@@ -461,7 +466,7 @@
"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" = "Информация о мигрирующих плагинах";
@@ -768,3 +773,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Корабли";
+1
View File
@@ -432,3 +432,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Ladje";
+55 -4
View File
@@ -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";
@@ -259,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";
@@ -277,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}";
@@ -331,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";
@@ -431,11 +478,14 @@
"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)";
@@ -738,3 +788,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Brodovi";
+10 -4
View File
@@ -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)";
@@ -280,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";
@@ -461,7 +466,7 @@
"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)";
@@ -768,3 +773,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Brodovi";
+4 -3
View File
@@ -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";
@@ -510,3 +510,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Skepp";
+2 -4
View File
@@ -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";
@@ -338,7 +335,7 @@
"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" = "Інформація про міграцію плагінів";
@@ -573,3 +570,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "Кораблі";
+35 -4
View File
@@ -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:没有指挥官数据";
@@ -259,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 授权凭证";
@@ -277,6 +295,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 +310,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 +352,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" = "键盘快捷键";
@@ -428,7 +458,7 @@
"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" = "关于插件迁移";
@@ -735,3 +765,4 @@
/* stats.py: Status dialog title; In files: stats.py:418; */
"Ships" = "所有飞船";
+28 -15
View File
@@ -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
@@ -20,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)
@@ -57,8 +60,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"
@@ -73,8 +76,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",
@@ -104,12 +109,13 @@ 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",
"plugins/edsy.py",
"plugins/inara.py",
"plugins/spansh_core.py",
]
options: dict = {
"py2exe": {
@@ -138,7 +144,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
)
@@ -171,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"
+2 -2
View File
@@ -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
+99 -92
View File
@@ -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)
@@ -396,7 +395,7 @@ class Auth(object):
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'
@@ -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,32 @@ 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:
# 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')
raise ServerError('Frontier CAPI: Misc. Error')
def capi_station_queries( # noqa: CCR001
capi_host: str, timeout: int = capi_default_requests_timeout
) -> CAPIData:
@@ -939,9 +948,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 +961,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 +1031,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 +1185,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 ''
######################################################################
@@ -1199,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)
@@ -1300,11 +1308,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 +1328,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)}')
######################################################################
+33 -30
View File
@@ -1,11 +1,15 @@
"""
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.
"""
from __future__ import annotations
__all__ = [
# defined in the order they appear in the file
@@ -40,10 +44,8 @@ import sys
import traceback
import warnings
from abc import abstractmethod
from typing import Any, Callable, Optional, Type, TypeVar
from typing import Any, Callable, Type, TypeVar
import semantic_version
from constants import GITVERSION_FILE, applongname, appname
# Any of these may be imported by plugins
@@ -52,13 +54,13 @@ appcmdname = 'EDMC'
# <https://semver.org/#semantic-versioning-specification-semver>
# 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'
_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
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
@@ -66,7 +68,7 @@ debug_senders: 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"):
@@ -79,7 +81,6 @@ else:
_T = TypeVar('_T')
###########################################################################
def git_shorthash_from_head() -> str:
"""
Determine short hash for current git HEAD.
@@ -91,13 +92,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 +133,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,11 +159,14 @@ 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."""
"""
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
@@ -185,7 +190,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 ?
@@ -241,7 +245,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.
@@ -296,14 +300,14 @@ class AbstractConfig(abc.ABC):
def _suppress_call(
func: Callable[..., _T], exceptions: Type[BaseException] | list[Type[BaseException]] = Exception,
*args: Any, **kwargs: Any
) -> Optional[_T]:
) -> _T | None:
if exceptions is None:
exceptions = [Exception]
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
@@ -326,16 +330,16 @@ 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:
@@ -462,16 +466,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()
+20 -14
View File
@@ -1,13 +1,19 @@
"""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.
"""
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
)
from config import AbstractConfig, appname, logger
assert sys.platform == 'darwin'
@@ -48,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.
@@ -82,7 +88,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 +103,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 +120,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 +128,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,14 +138,14 @@ 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
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.
+7 -2
View File
@@ -1,9 +1,14 @@
"""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 config import AbstractConfig, appname, logger
assert sys.platform == 'linux'
+31 -67
View File
@@ -1,6 +1,12 @@
"""Windows config implementation."""
"""
windows.py - Windows config implementation.
Copyright (c) EDCD, All Rights Reserved
Licensed under the GNU General Public License.
See LICENSE file.
"""
from __future__ import annotations
# spell-checker: words folderid deps hkey edcd
import ctypes
import functools
import pathlib
@@ -8,9 +14,8 @@ import sys
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
from typing import Literal
from config import AbstractConfig, applongname, appname, logger
assert sys.platform == 'win32'
@@ -29,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)):
@@ -42,8 +47,9 @@ def known_folder_path(guid: uuid.UUID) -> Optional[str]:
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
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)
self.plugin_dir_path = self.app_dir_path / 'plugins'
@@ -52,19 +58,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,54 +76,18 @@ class WinConfig(AbstractConfig):
)
try:
self.__reg_handle: winreg.HKEYType = create_key_defaults(
sub_key=r'Software\Marginal\EDMarketConnector'
)
if do_winsparkle:
self.__setup_winsparkle()
self.__reg_handle: winreg.HKEYType = create_key_defaults(sub_key=REGISTRY_SUBKEY)
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."""
create_key_defaults = functools.partial(
winreg.CreateKeyEx,
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
)
except OSError:
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]:
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)
@@ -127,20 +95,18 @@ 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:
"""
@@ -152,7 +118,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, str):
if not isinstance(res, str):
raise ValueError(f'Data from registry is not a string: {type(res)=} {res=}')
return res
@@ -167,7 +133,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
@@ -195,11 +161,11 @@ 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)
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.
@@ -209,9 +175,8 @@ class WinConfig(AbstractConfig):
reg_type: 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 +189,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:
+23 -12
View File
@@ -1,16 +1,19 @@
#!/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
@@ -26,10 +29,16 @@ 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:
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") # noqa: E501
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 +53,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 +92,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)
+24 -31
View File
@@ -1,32 +1,32 @@
"""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 +39,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 +56,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 +72,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 +85,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 +176,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 = 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('<<DashboardEvent>>', when="tail")
except Exception:
logger.exception('Processing Status.json')
+7 -8
View File
@@ -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:
+1 -1
View File
@@ -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 ?
+1
View File
@@ -34,6 +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!
/* <use of this phrase> [<file it was first added in>] */
"<text as it appears in the code>" = "<English version of the text>";
e.g.
+6 -7
View File
@@ -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.
@@ -79,7 +78,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 +94,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
@@ -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.
+1 -2
View File
@@ -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:
+11 -13
View File
@@ -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
+6 -6
View File
@@ -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.
@@ -79,16 +80,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
+8 -6
View File
@@ -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:
"""
+2 -1
View File
@@ -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
+12 -13
View File
@@ -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:
"""
+11 -4
View File
@@ -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
+41 -37
View File
@@ -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)
+68 -67
View File
@@ -1,18 +1,28 @@
#!/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 +30,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 +72,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 +116,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 +130,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 +155,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 +165,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 +176,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 +204,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 +226,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 +255,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 +267,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 +290,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 +311,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 +339,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: <n/a> | 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 +371,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]?(['"])(((?<!\\)\\\1|.)+?)\1\)[^#]*(#.+)?''') # match a single line python literal
seen: Dict[str, str] = {}
seen: dict[str, str] = {}
for f in (
sorted(x for x in os.listdir('.') if x.endswith('.py')) +
sorted(join('plugins', x) for x in (os.listdir('plugins') if isdir('plugins') else []) if x.endswith('.py'))
sorted(x for x in listdir('.') if x.endswith('.py')) +
sorted(join('plugins', x) for x in (listdir('plugins') if isdir('plugins') else []) if x.endswith('.py'))
):
with open(f, 'r', encoding='utf-8') as h:
with open(f, encoding='utf-8') as h:
lineno = 0
for line in h:
lineno += 1
@@ -386,9 +387,9 @@ if __name__ == "__main__":
(match.group(4) and (match.group(4)[1:].strip()) + '. ' or '') + f'[{basename(f)}]'
)
if seen:
target_path = pathlib.Path(LOCALISATION_DIR) / 'en.template.new'
target_path.parent.mkdir(exist_ok=True)
with target_path.open('w', encoding='utf-8') as target_file:
target_path = join(LOCALISATION_DIR, 'en.template.new')
makedirs(dirname(target_path), exist_ok=True)
with open(target_path, 'w', encoding='utf-8') as target_file:
target_file.write(f'/* Language name */\n"{LANGUAGE_ID}" = "English";\n\n')
for thing in sorted(seen, key=str.lower):
if seen[thing]:
+18 -16
View File
@@ -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)
+58 -62
View File
@@ -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
+10 -9
View File
@@ -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)
+47 -39
View File
@@ -1,30 +1,36 @@
"""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 +39,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 +57,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 +68,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 +229,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 +252,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 +271,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:
+71 -65
View File
@@ -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
@@ -20,13 +27,14 @@ logger = get_main_logger()
# List of loaded Plugins
PLUGINS = []
PLUGINS_not_py3 = []
PLUGINS_broken = []
# For asynchronous error display
class LastError:
"""Holds the last plugin error."""
msg: Optional[str]
msg: str | None
root: tk.Tk
def __init__(self) -> None:
@@ -36,10 +44,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 +57,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 +72,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 +85,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):
"""
Get a function from a plugin.
@@ -86,7 +94,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 +108,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 +126,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 +140,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 +194,18 @@ 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:
PLUGINS_broken.append(Plugin(name, None, logger))
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 +218,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 +244,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 +267,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 +285,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 +298,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 +317,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 +337,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 +362,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 +384,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 +412,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.
+109 -101
View File
@@ -1,88 +1,91 @@
"""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.
"""
from __future__ import annotations
# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $#
# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $#
#
# 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
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:
"""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)
@@ -90,100 +93,105 @@ 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, 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.Entry(conf_frame, textvariable=normal_textvar).grid(sticky=tk.EW, row=cur_row, column=1, 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, pady=BOXY
)
# LANG: Generic 'Reset' button label
nb.Button(conf_frame, text=_("Reset"), command=lambda: normal_textvar.set(value=DEFAULT_NORMAL_URL)).grid(
sticky=tk.W, row=cur_row, column=2, padx=PADX
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, 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=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: beta_textvar.set(value=DEFAULT_BETA_URL)).grid(
sticky=tk.W, row=cur_row, column=2, padx=PADX
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, 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,
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
).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
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
"""
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]:
def shipyard_url(loadout, is_beta) -> str | bool:
"""Return a URL for the current ship."""
# most compact representation
string = json.dumps(loadout, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8')
if not string:
return False
out = io.BytesIO()
with gzip.GzipFile(fileobj=out, mode='w') as f:
f.write(string)
encoded = base64.urlsafe_b64encode(out.getvalue()).decode().replace('=', '%3D')
return _get_target_url(is_beta) + encoded
+121 -133
View File
@@ -1,26 +1,25 @@
"""Handle exporting data to EDDN."""
"""
eddn.py - Exporting Data to EDDN.
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
# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $#
# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $#
#
# 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 http
import itertools
import json
@@ -34,12 +33,15 @@ 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,
)
from typing import OrderedDict as OrderedDictT
from typing import Tuple, Union
import requests
import companion
import edmc_data
import killswitch
@@ -82,27 +84,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.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
@@ -156,7 +158,7 @@ class EDDNSender:
UNKNOWN_SCHEMA_RE = re.compile(
r"^FAIL: \[JsonValidationException\('Schema "
r"https://eddn.edcd.io/schemas/(?P<schema_name>.+)/(?P<schema_version>[0-9]+) is unknown, "
r"unable to validate.',\)\]$"
r"unable to validate.',\)]$"
)
def __init__(self, eddn: 'EDDN', eddn_endpoint: str) -> None:
@@ -203,10 +205,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 +215,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 +229,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 +244,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:
@@ -423,7 +402,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: dict[str, str] | None = None
if compressed:
headers = {'Content-Encoding': 'gzip'}
@@ -448,20 +427,19 @@ 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
elif 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
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 +463,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 +501,7 @@ class EDDNSender:
db_cursor.execute(
"""
SELECT id FROM messages
ORDER BY created ASC
ORDER BY created
LIMIT 1
"""
)
@@ -586,16 +571,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.
@@ -729,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.
@@ -763,7 +747,7 @@ class EDDN:
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': []}
@@ -1000,7 +984,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,13 +1034,13 @@ 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)
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.
@@ -1106,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.
@@ -1123,8 +1107,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:
@@ -1149,7 +1132,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.
@@ -1191,7 +1174,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.
@@ -1233,7 +1216,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.
@@ -1335,7 +1318,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.
@@ -1389,7 +1372,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.
@@ -1462,7 +1445,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.
@@ -1546,7 +1529,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.
@@ -1609,7 +1592,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.
@@ -1684,7 +1667,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.
@@ -1734,7 +1717,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.
@@ -1804,7 +1787,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.
@@ -1907,7 +1890,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.
@@ -1918,14 +1901,14 @@ 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:
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-'
#######################################################################
@@ -1939,7 +1922,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'
#######################################################################
@@ -1958,7 +1941,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.
@@ -2105,22 +2088,25 @@ def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame:
"""
PADX = 10 # noqa: N806
BUTTONX = 12 # noqa: N806 # indent Checkbuttons and Radiobuttons
PADY = 1 # noqa: N806
if prefsVersion.shouldSetDefaults('0.0.0.0', not bool(config.get_int('output'))):
output: int = (config.OUT_EDDN_SEND_STATION_DATA | config.OUT_EDDN_SEND_NON_STATION) # default settings
output: int = config.OUT_EDDN_SEND_STATION_DATA | config.OUT_EDDN_SEND_NON_STATION # default settings
else:
output = config.get_int('output')
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, 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)
this.eddn_station_button = nb.Checkbutton(
@@ -2130,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=PADY, 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(
@@ -2141,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=PADY, 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(
@@ -2151,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, pady=PADY, sticky=tk.W)
return eddnframe
@@ -2167,7 +2155,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:
@@ -2198,7 +2186,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()
@@ -2222,7 +2210,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()
@@ -2249,7 +2237,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.
@@ -2324,22 +2312,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 +2342,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 +2354,7 @@ def journal_entry( # noqa: C901, CCR001
entry
)
elif event_name == 'fssbodysignals':
if event_name == 'fssbodysignals':
return this.eddn.export_journal_fssbodysignals(
cmdr,
system,
@@ -2506,7 +2494,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.
@@ -2525,7 +2513,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).
+161 -216
View File
@@ -1,36 +1,25 @@
"""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` TO ENSURE THE FILES ARE ACTUALLY PRESENT
IN AN END-USER INSTALLATION ON WINDOWS.
"""
from __future__ import annotations
# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $#
# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $#
#
# 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 tkinter as tk
@@ -39,13 +28,10 @@ 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
import myNotebook
import myNotebook as nb # noqa: N813
import plug
from companion import CAPIData
@@ -58,6 +44,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
@@ -79,17 +74,17 @@ 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
@@ -107,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: tk.IntVar | None = None
self.log_button: ttk.Checkbutton | None = None
self.label: tk.Widget | None = None
self.cmdr_label: myNotebook.Label | None = None
self.cmdr_text: myNotebook.Label | None = None
self.cmdr_label: nb.Label | None = None
self.cmdr_text: nb.Label | None = None
self.user_label: myNotebook.Label | None = None
self.user: myNotebook.Entry | None = None
self.user_label: nb.Label | None = None
self.user: nb.Entry | None = None
self.apikey_label: myNotebook.Label | None = None
self.apikey: myNotebook.Entry | None = None
self.apikey_label: nb.Label | None = None
self.apikey: nb.Entry | None = None
this = This()
@@ -204,13 +199,13 @@ 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
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
@@ -297,77 +292,81 @@ 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 = 1 # noqa: N806
BOXY = 2 # noqa: N806
SEPY = 10 # noqa: N806
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) # Don't translate
).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)
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'), # LANG: Settings>EDSM - Label on checkbox for 'send data'
variable=this.log,
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=PADY, sticky=tk.W)
cur_row += 1
ttk.Separator(frame, orient=tk.HORIZONTAL).grid(
columnspan=2, padx=PADX, pady=SEPY, sticky=tk.EW, row=cur_row
)
cur_row += 1
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'),
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
)
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.grid(row=cur_row, padx=PADX, sticky=tk.W)
this.label.grid(row=cur_row, columnspan=2, padx=PADX, pady=PADY, sticky=tk.W)
cur_row += 1
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=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')) # EDSM setting
this.user_label.grid(row=cur_row, padx=PADX, sticky=tk.W)
this.user_label = nb.Label(frame, text=_('Commander Name'))
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')) # EDSM setting
this.apikey_label.grid(row=cur_row, padx=PADX, sticky=tk.W)
this.apikey_label = nb.Label(frame, text=_('API Key'))
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)
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 EDSM 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)
show_password_checkbox.grid(row=cur_row, columnspan=2, padx=BUTTONX, pady=PADY, sticky=tk.W)
return frame
@@ -381,34 +380,27 @@ 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
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
@@ -429,18 +421,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,10 +450,9 @@ 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=[])
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:
@@ -466,7 +461,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())
@@ -476,7 +470,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.
@@ -495,20 +489,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 +555,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 +572,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 +579,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 +631,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,14 +639,13 @@ 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 ''
# 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.
@@ -675,11 +658,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 +672,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,44 +699,49 @@ 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
pending: list[Mapping[str, Any]] = [] # Unsent events
closing = False
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
@@ -772,21 +754,19 @@ def worker() -> None: # noqa: CCR001 C901 # Cant be broken up currently
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"]=})')
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]], ("", {}))
item = cast(tuple[str, str, str, Mapping[str, Any]], ("", {}))
should_skip, new_item = killswitch.check_killswitch(
'plugins.edsm.worker',
item,
@@ -795,7 +775,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 +796,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 +815,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 +843,20 @@ def worker() -> None: # noqa: CCR001 C901 # Cant be broken up currently
data_elided['apiKey'] = '<elided>'
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 +877,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 +894,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('<<EDSMStatus>>', 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 +907,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,10 +918,8 @@ 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
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.
@@ -967,54 +927,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 +981,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
+31 -31
View File
@@ -1,27 +1,25 @@
"""Export data for ED Shipyard."""
"""
edsy.py - Exporting Data to EDSY.
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
# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $#
# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $#
#
# 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
@@ -40,15 +38,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) -> 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 +55,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
+240 -253
View File
@@ -1,26 +1,25 @@
"""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.
"""
from __future__ import annotations
# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $#
# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $# ! $#
#
# 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
@@ -31,12 +30,9 @@ 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
import myNotebook as nb # noqa: N813
@@ -67,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
@@ -93,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
@@ -119,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
@@ -133,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:
@@ -168,13 +164,14 @@ 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/galaxy-starsystem/'
f'?search={this.system_address}')
elif system_name:
if system_name:
return requests.utils.requote_uri(f'https://inara.cz/galaxy-starsystem/'
f'?search={system_name}')
@@ -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/galaxy-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/galaxy-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('<<InaraLocation>>', update_location)
this.system_link.bind_all('<<InaraShip>>', update_ship)
@@ -254,16 +247,20 @@ 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 # noqa: N806
BUTTONX = 12 # noqa: N806 # indent Checkbuttons and Radiobuttons
PADY = 1 # noqa: N806 # close spacing
BOXY = 2 # noqa: N806 # box spacing
SEPY = 10 # noqa: N806 # seperator line spacing
cur_row = 0
frame = nb.Frame(parent)
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=PADX, pady=PADY, 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(
@@ -273,9 +270,13 @@ 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=BUTTONX, pady=PADY, sticky=tk.W)
cur_row += 1
nb.Label(frame).grid(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
this.label = HyperlinkLabel(
@@ -286,24 +287,26 @@ 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=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=12, padx=x_padding, 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=12, column=1, padx=x_padding, pady=y_padding, 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)
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,
)
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=BUTTONX, pady=PADY, sticky=tk.W)
return frame
@@ -368,7 +371,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.
@@ -379,15 +382,18 @@ 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
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.
@@ -398,7 +404,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:
@@ -422,11 +428,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 +479,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 +532,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 +628,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 +641,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 +720,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:
@@ -881,7 +823,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'],
@@ -928,7 +870,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([
@@ -1156,7 +1098,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)
@@ -1398,7 +1340,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']
@@ -1438,7 +1380,7 @@ def cmdr_data(data: CAPIData, is_beta): # noqa: CCR001
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.
@@ -1508,8 +1450,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.
@@ -1538,18 +1480,23 @@ def new_add_event(
this.events[key].append(Event(name, timestamp, data))
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:
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
: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 +1508,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 +1518,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 +1530,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)
@@ -1593,96 +1543,133 @@ 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 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('<<InaraLocation>>', 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('<<InaraShip>>', 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 = (",", ": "))}')
# 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))
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:
# 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}'
))
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('<<InaraLocation>>', 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('<<InaraShip>>', when="tail")
def update_location(event=None) -> None:
+195
View File
@@ -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
self.system_address: str | None = None
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 ''
+217 -152
View File
@@ -1,27 +1,31 @@
# -*- coding: utf-8 -*-
"""EDMC preferences library."""
from __future__ import annotations
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
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
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 +42,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.
@@ -258,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
@@ -270,7 +289,10 @@ class PreferencesDialog(tk.Toplevel):
self.PADX = 10
self.BUTTONX = 12 # indent Checkbuttons and Radiobuttons
self.PADY = 2 # close spacing
self.LISTX = 25 # indent listed items
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)
@@ -329,11 +351,11 @@ 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'))
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(
@@ -342,7 +364,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(
@@ -351,7 +373,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
@@ -361,7 +383,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
@@ -371,17 +393,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=(5, 0), 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
@@ -397,7 +419,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?
@@ -413,7 +435,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 ''
@@ -429,9 +451,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
@@ -439,97 +461,99 @@ 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(
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.PADX, 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(
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, pady=self.PADY, 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, pady=self.PADY, 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, 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, pady=self.BOXY, 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('<FocusIn>', self.hotkeystart)
self.hotkey_text.bind('<FocusOut>', self.hotkeyend)
self.hotkey_text.grid(column=1, columnspan=2, pady=(5, 0), sticky=tk.W, row=row.get())
self.hotkey_text.bind('<FocusIn>', self.hotkeystart)
self.hotkey_text.bind('<FocusOut>', self.hotkeyend)
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(
@@ -540,7 +564,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=self.PADY, sticky=tk.W, row=row.get())
# Hotkey/Shortcut setting
self.hotkey_play_btn = nb.Checkbutton(
@@ -551,11 +575,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, 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(
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(
@@ -566,16 +590,18 @@ 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, pady=self.PADY, 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
# 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:
@@ -585,13 +611,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(
@@ -602,7 +628,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')
@@ -611,7 +637,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,
@@ -620,7 +646,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')
@@ -629,7 +655,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,
@@ -638,11 +664,11 @@ 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(
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:
@@ -651,7 +677,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:
@@ -672,7 +698,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=self.PADX, pady=0, sticky=tk.NSEW, row=cur_row)
# Big spacer
nb.Label(config_frame).grid(sticky=tk.W, row=row.get())
@@ -681,26 +714,28 @@ 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()
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, pady=self.PADY
)
nb.Checkbutton(
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.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
# 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.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
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()
@@ -718,36 +753,40 @@ 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)
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=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.PADY*4, 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(
@@ -757,11 +796,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(
@@ -772,11 +811,11 @@ 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.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
@@ -784,7 +823,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.BOXY, sticky=tk.NSEW, row=cur_row)
# UI Scaling
"""
@@ -795,12 +834,12 @@ 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
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()
@@ -816,22 +855,22 @@ 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, 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(
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 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
@@ -857,16 +896,16 @@ 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, 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(
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(
@@ -876,7 +915,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(
@@ -885,7 +926,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
@@ -898,41 +939,43 @@ 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=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=self.BOXY, sticky=tk.EW, row=row.get())
plugdirentry.grid(padx=self.PADX, sticky=tk.EW, row=cur_row)
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.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.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(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):
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,
# 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:
@@ -941,21 +984,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, pady=self.PADY, 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, pady=self.PADY, sticky=tk.W, row=row.get()
)
HyperlinkLabel(
# LANG: Plugins - Label on URL to documentation about migrating plugins from Python 2.7
@@ -963,24 +1004,48 @@ 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, 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, pady=self.PADY, 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, 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())
).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.PADX*2, sticky=tk.W, row=row.get()
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
+51 -28
View File
@@ -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('<html><head><title>Authentication successful</title></head>'.encode('utf-8'))
self.wfile.write('<body><p>Authentication successful</p></body>'.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 (
'<html>'
'<head>'
'<title>Authentication successful - Elite: Dangerous</title>'
'<style>'
'body { background-color: #000; color: #fff; font-family: "Helvetica Neue", Arial, sans-serif; }'
'h1 { text-align: center; margin-top: 100px; }'
'p { text-align: center; }'
'</style>'
'</head>'
'<body>'
'<h1>Authentication successful</h1>'
'<p>Thank you for authenticating.</p>'
'<p>Please close this browser tab now.</p>'
'</body>'
'</html>'
)
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
+10 -10
View File
@@ -5,10 +5,10 @@ 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==69.0.2
# 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
@@ -18,29 +18,29 @@ flake8-noqa==1.3.2
flake8-polyfill==1.0.2
flake8-use-fstring==1.4
mypy==1.4.1
mypy==1.7.1
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.2
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.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[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'
+1 -1
View File
@@ -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
@@ -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}"
File diff suppressed because it is too large. Load diff
+116
View File
@@ -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
}
}
+50 -76
View File
@@ -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)}'
def find_calls_in_stmt(statement: ast.AST) -> list[ast.Call]:
@@ -43,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
@@ -62,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) -> Optional[str]: # noqa: CCR001
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.
@@ -74,16 +68,16 @@ 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
out: str | None = None
above = call.lineno - 2
current = call.lineno - 1
above_line = lines[above].strip() if len(lines) >= above else None
above_comment: Optional[str] = None
above_comment: str | None = None
current_line = lines[current].strip()
current_comment: Optional[str] = None
current_comment: str | None = None
bad_comment: Optional[str] = None
bad_comment: str | None = None
if above_line is not None:
match = COMMENT_OWN_LINE_RE.match(above_line)
if match:
@@ -108,16 +102,13 @@ def extract_comments(call: ast.Call, lines: list[str], file: pathlib.Path) -> Op
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
@@ -146,22 +137,17 @@ 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)
else:
raise ValueError(type(thing), thing)
out.update(scan_directory(thing, skip))
return out
@@ -174,14 +160,13 @@ def parse_template(path) -> set[str]:
:param path: The path to the lang file
"""
lang_re = re.compile(r'\s*"((?:[^"]|(?:\"))+)"\s*=\s*"((?:[^"]|(?:\"))+)"\s*;\s*$')
lang_re = re.compile(r'\s*"([^"]+)"\s*=\s*"([^"]+)"\s*;\s*$')
out = 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))
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))
return out
@@ -193,8 +178,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,18 +198,15 @@ 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}; '
return out
file_locations = [
f"{loc.path.name}:{loc.line_start}:{loc.line_end or ''}"
for loc in self.locations
]
return "; ".join(file_locations)
def dedupe_lang_entries(entries: list[LangEntry]) -> list[LangEntry]:
@@ -237,21 +219,17 @@ def dedupe_lang_entries(entries: list[LangEntry]) -> list[LangEntry]:
: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)
if cont:
continue
deduped.append(e)
return deduped
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[:]
)
return list(deduped.values())
def generate_lang_template(data: dict[pathlib.Path, list[ast.Call]]) -> str:
@@ -269,23 +247,19 @@ 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 = ''
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 in range(len(entry.comments)):
if entry.comments[i] 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
header = f'{comment.strip()} {files}'.strip()
out += f'/* {header} */\n'
out += f'{string} = {string};\n'
out += '\n'
out += f'{string} = {string};\n\n'
return out
+9 -4
View File
@@ -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)))
+16 -4
View File
@@ -1,11 +1,11 @@
#!/usr/bin/env python
"""Find the reverse dependencies of a package according to pip."""
#!/usr/bin/env python3
"""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 +19,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 <package_name>")
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}'.")
+12 -8
View File
@@ -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('<Button-1>', self.copy_callback(label, content[i]))
label.bind('<Button-1>', 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']
@@ -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
+26 -29
View File
@@ -1,12 +1,13 @@
# type: ignore
"""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
@@ -81,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)):
@@ -95,7 +96,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
@@ -153,20 +154,19 @@ 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:
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."""
@@ -181,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
@@ -202,7 +202,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)
@@ -279,10 +279,10 @@ 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]:
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()
@@ -304,11 +304,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,10 +327,9 @@ class OldConfig():
):
return default
else:
return key_val.value
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)
@@ -388,7 +386,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:
@@ -398,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)
@@ -407,8 +405,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')
@@ -434,13 +431,13 @@ 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') # 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 +457,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."""
+7 -9
View File
@@ -7,15 +7,13 @@ 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
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
@@ -30,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.
@@ -72,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)]
@@ -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."""
@@ -117,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)
@@ -216,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':
+4 -4
View File
@@ -1,13 +1,13 @@
"""Tests for journal_lock.py code."""
from __future__ import annotations
import multiprocessing as mp
import os
import pathlib
import sys
from typing import Generator
import pytest
from pytest import MonkeyPatch, TempdirFactory, TempPathFactory
from config import config
from journal_lock import JournalLock, JournalLockResult
@@ -142,7 +142,7 @@ class TestJournalLock:
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")
return tmp_path_factory.mktemp("changing") # type: ignore
print('Other key, calling up ...')
return config.get_str(key) # Call the non-mocked
@@ -301,7 +301,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')
+7 -5
View File
@@ -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
@@ -33,11 +35,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:
@@ -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)
+3 -3
View File
@@ -1,7 +1,7 @@
"""Tests of killswitch behaviour."""
import copy
from typing import Optional
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."""
+28 -25
View File
@@ -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('<Button-1>', command)
widget.bind('<Enter>', lambda e: self._enter(e, image))
widget.bind('<Leave>', 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
+17 -12
View File
@@ -1,7 +1,14 @@
"""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
from requests import Session, Response
from requests.adapters import HTTPAdapter
from config import user_agent
REQUEST_TIMEOUT = 10 # reasonable timeout that all HTTP requests should use
@@ -17,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
@@ -25,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.
@@ -35,11 +40,11 @@ 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()
session.headers['User-Agent'] = user_agent
session = session or Session()
session.headers.setdefault("User-Agent", user_agent)
adapter = TimeoutAdapter(timeout)
session.mount("http://", adapter)
session.mount("https://", adapter)
for prefix in ("http://", "https://"):
session.mount(prefix, adapter)
return session
+34 -19
View File
@@ -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('<Button-1>', 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 '<Button-2>' or '<Button-3>', 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:
+24 -17
View File
@@ -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
+7 -1
View File
@@ -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
+9 -3
View File
@@ -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', '<', '>', ':', '"', '/', '\\', '|', '?', '*')})