diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 00000000..019facb4 --- /dev/null +++ b/.coveragerc @@ -0,0 +1,6 @@ +[run] +omit = + # The tests themselves + tests/* + # Any venv files + venv/* diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index e24f8a60..896f0b34 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -13,14 +13,13 @@ assignees: '' **Please complete the following information:** - Version [e.g. 4.0.6 - See 'Help > About E:D Market Connector'. If running from source using git then please paste the output of `git log --decorate=full | head -1`] + - Game Version [e.g. 'Live' or 'Odyssey Alpha'] - OS: [e.g. Windows 10, Linux Debian 10.6, etc.] - OS Locale: [e.g. English, French, Serbian...] - If applicable: Browser [e.g. chrome, safari] - - Please attach **BOTH** log files as follows: + - Please attach **BOTH** log files, by dragging and dropping them into this input: 1. `%TEMP%\EDMarketConnector.log` from *immediately* after the bug occurs (re-running the application overwrites this file). 1. %TEMP%\EDMarketConnector\EDMarketConnector-debug.log`. See [Debug Log File](https://github.com/EDCD/EDMarketConnector/wiki/Troubleshooting#debug-log-files). NB: If you don't have this log file then you're not running the latest version of the application and should update first to see if we already fixed the bug you're reporting. - - Use the Icon that looks like `_`, `|` and `^` all in one character towards the right of the toolbar above. **Describe the bug** A clear and concise description of what the bug is. diff --git a/.github/workflows/pr-annotate-with-flake8.yml b/.github/workflows/pr-annotate-with-flake8.yml deleted file mode 100644 index f293a9fc..00000000 --- a/.github/workflows/pr-annotate-with-flake8.yml +++ /dev/null @@ -1,80 +0,0 @@ -# This workflow will: -# -# 1. Store some github context in env vars. -# 2. Only checkout if base and head ref owners are the same. -# 3. Check if any *.py files are in the diff. -# 4. Only then install python and perform the annotation with flake8. -# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions - -name: PR-annotate-flake8 - -on: - pull_request: - branches: [ develop ] - -jobs: - flake8_annotate: - runs-on: ubuntu-18.04 - - steps: - ################################################################## - # Check if the base and head repos are the same, if not we won't - # be able to add annotations. - ################################################################## - - name: Check head and base repo same - env: - BASE_REPO_OWNER: ${{github.event.pull_request.base.repo.owner.login}} - HEAD_REPO_OWNER: ${{github.event.pull_request.head.repo.owner.login}} - BASE_REF: ${{github.base_ref}} - run: | - # Just to be running something - env - ################################################################## - - ################################################################## - # Perform the checkout - ################################################################## - - name: Checkout - if: ${{ github.event.pull_request.base.repo.owner.login == github.event.pull_request.head.repo.owner.login }} - uses: actions/checkout@v2 - with: - fetch-depth: 0 - ################################################################## - - ################################################################## - # flake8-your-pr 'fails' if no *.py files changed - # So we check if any were affected and store that in env - ################################################################## - - name: Check for PY files - if: ${{ github.event.pull_request.base.repo.owner.login == github.event.pull_request.head.repo.owner.login }} - run: | - # Checkout might not have happened. - if [ ! -d ".git" ]; then exit 0 ; fi - # Get a list of files ending with ".py", stuff in environment. - # We don't rely on exit status because Workflows run with - # "set -e" so any failure in a pipe is total failure. - PYFILES=$(git diff --name-only "refs/remotes/origin/${BASE_REF}" -- | egrep '.py$' || true) - # Use magic output to store in env for rest of workflow - echo "::set-env name=PYFILES::${PYFILES}" - ################################################################## - - ################################################################## - # Get Python set up - ################################################################## - - name: Set up Python 3.7 - if: ${{ env.PYFILES != '' }} - uses: actions/setup-python@v2 - with: - python-version: 3.7 - ################################################################## - - ################################################################## - # Perform the annotation - ################################################################## - - name: Annotate with Flake8 - # Only if at least one *.py file was affected - if: ${{ env.PYFILES != '' }} - uses: "tayfun/flake8-your-pr@master" - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - ################################################################## diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 2afeba77..318ff80f 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -17,6 +17,10 @@ jobs: steps: + # Debug show the info we have to work with + - name: Show github context + run: cat $GITHUB_EVENT_PATH + #################################################################### # Checkout the necessary commits #################################################################### @@ -24,10 +28,11 @@ jobs: # based on. - name: Checkout head commits # https://github.com/actions/checkout - uses: actions/checkout@v2 - with: - repository: ${{github.event.pull_request.head.repo.full_name}} - fetch-depth: 0 + uses: actions/checkout@v2.3.4 + #with: + #ref: ${{github.head.sha}} + #repository: ${{github.event.pull_request.head.repo.full_name}} + #fetch-depth: 0 # But we do need the base references - name: Fetch base commits @@ -36,6 +41,8 @@ jobs: BASE_REPO_OWNER: ${{github.event.pull_request.base.repo.owner.login}} run: | + echo "BASE_REPO_URL: ${BASE_REPO_URL}" + echo "BASE_REPO_OWNER: ${BASE_REPO_OWNER}" # Add the 'base' repo as a new remote git remote add ${BASE_REPO_OWNER} ${BASE_REPO_URL} # And then fetch its references @@ -45,25 +52,20 @@ jobs: #################################################################### # Get Python set up #################################################################### - - name: Set up Python 3.7 - uses: actions/setup-python@v2 + - name: Set up Python 3.9 + uses: actions/setup-python@v2.2.2 with: - python-version: 3.7 + python-version: 3.9 - name: Install dependencies run: | python -m pip install --upgrade pip - pip install flake8 + pip install wheel flake8 if [ -f requirements-dev.txt ]; then pip install -r requirements-dev.txt; elif [ -f requirements.txt ]; then pip install -r requirements.txt ; fi #################################################################### - #################################################################### - # Show full github context to aid debugging. - #################################################################### - - name: Show github context - run: | - env - cat $GITHUB_EVENT_PATH - #################################################################### + # Have issues be annotated on run + - name: Setup flake8 annotations + uses: rbialon/flake8-annotations@v1 #################################################################### # Lint with flake8 @@ -75,6 +77,9 @@ jobs: BASE_REF: ${{github.base_ref}} run: | + echo "BASE_REPO_URL: ${BASE_REPO_URL}" + echo "BASE_REPO_OWNER: ${BASE_REPO_OWNER}" + echo "BASE_REF: ${BASE_REF}" # Explicitly check for some errors # E9 - Runtime (syntax and the like) # F63 - 'tests' checking diff --git a/.github/workflows/push-checks.yml b/.github/workflows/push-checks.yml index b6ad01a5..8438a9a2 100644 --- a/.github/workflows/push-checks.yml +++ b/.github/workflows/push-checks.yml @@ -9,7 +9,7 @@ name: Push-Checks on: push: - branches: [ main ] + branches: [ develop ] jobs: build: @@ -17,26 +17,30 @@ jobs: runs-on: ubuntu-18.04 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v2.3.4 with: fetch-depth: 0 - - name: Set up Python 3.7 - uses: actions/setup-python@v2 + - name: Set up Python 3.9 + uses: actions/setup-python@v2.2.2 with: - python-version: 3.7 + python-version: 3.9 - name: Install dependencies run: | python -m pip install --upgrade pip - pip install flake8 pytest wheel + pip install wheel flake8 pytest if [ -f requirements-dev.txt ]; then pip install -r requirements-dev.txt; fi + + - name: Setup flake8 annotations + uses: rbialon/flake8-annotations@v1 + - name: Lint with flake8 env: ROOT_SHA: ${{github.base_ref}} - run: | DATA=$(jq --raw-output .before $GITHUB_EVENT_PATH) + echo "DATA: ${DATA}" # stop the build if there are Python syntax errors or undefined names, ignore existing git diff "$DATA" | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics --diff # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide - git diff "$DATA" | flake8 . --count --exit-zero --statistics --diff + git diff "$DATA" | flake8 . --count --statistics --diff diff --git a/.github/workflows/windows-build.yml b/.github/workflows/windows-build.yml index bd695779..f42937f9 100644 --- a/.github/workflows/windows-build.yml +++ b/.github/workflows/windows-build.yml @@ -16,10 +16,10 @@ jobs: shell: powershell steps: - - uses: actions/checkout@v2 - - uses: actions/setup-python@v2 + - uses: actions/checkout@v2.3.4 + - uses: actions/setup-python@v2.2.2 with: - python-version: "3.7.9" + python-version: "3.9.5" architecture: "x86" - name: Install python tools diff --git a/.gitignore b/.gitignore index a1e314a8..7474987d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ +.gitversion .DS_Store build +ChangeLog.html dist.* dump *.bak @@ -17,3 +19,7 @@ EDMarketConnector.VisualElementsManifest.xml .idea .vscode venv +*.code-workspace +htmlcov/ +.ignored +.coverage diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 581989af..25f65352 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,7 +2,7 @@ # See https://pre-commit.com/hooks.html for more hooks repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v2.4.0 + rev: 'v3.4.0' hooks: - id: check-merge-conflict - id: debug-statements @@ -14,14 +14,23 @@ repos: # hooks: # - id: autopep8 -# flake8 --show-source -- repo: https://gitlab.com/pycqa/flake8 - rev: '' - hooks: - - id: flake8 +### # flake8 --show-source +### - repo: https://gitlab.com/pycqa/flake8 +### rev: '' +### hooks: +### - id: flake8 +# +# Try using local flake8 +- repo: local + hooks: + - id: flake8 + name: flake8 + entry: flake8 + language: system + types: [ python ] - repo: https://github.com/pre-commit/pygrep-hooks - rev: '' + rev: 'v1.8.0' hooks: - id: python-no-eval - id: python-no-log-warn @@ -31,7 +40,7 @@ repos: # mypy - static type checking # mypy --follow-imports skip - repo: https://github.com/pre-commit/mirrors-mypy - rev: '' + rev: 'v0.812' hooks: - id: mypy args: [ "--follow-imports", "skip", "--ignore-missing-imports", "--scripts-are-modules" ] @@ -50,7 +59,7 @@ repos: # safety.exe check -r requirements.txt - repo: https://github.com/Lucas-C/pre-commit-hooks-safety - rev: '' + rev: 'v1.2.1' hooks: - id: python-safety-dependencies-check entry: safety @@ -58,10 +67,8 @@ repos: language: system default_language_version: - python: python3.7 + python: python3.9 default_stages: [ commit, push ] #files: '([^\.].+/)*.py' - -exclude: cp37-setup-new.py diff --git a/.python-version b/.python-version new file mode 100644 index 00000000..11aaa068 --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.9.5 diff --git a/ChangeLog.md b/ChangeLog.md index f66335f5..daef2530 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,6 +1,384 @@ This is the master changelog for Elite Dangerous Market Connector. Entries are in reverse chronological order (latest first). --- +Release 5.0.0 +=== + +Python 3.9 +--- +* We now test against, and package with, Python 3.9.5. + + **As a consequence of this we no longer support Windows 7. + This is due to + [Python 3.9.x itself not supporting Windows 7](https://www.python.org/downloads/windows/). + The application (both EDMarketConnector.exe and EDMC.exe) will crash on + startup due to a missing DLL.** + + This should have no other impact on users or plugin developers, other + than the latter now being free to use features that were introduced since the + Python 3.7 series. + + Developers can check the contents of the `.python-version` file + in the source (it's not distributed with the Windows installer) for the + currently used version in a given branch. + +This Update Is Mandatory +--- + +This release is a **mandatory upgrade for the release of Elite Dangerous +Odyssey**. Any bug reports against earlier releases, pertaining to Odyssey or +not, will be directed to reproduce them with 5.0.0 or later. There are also +minor bugs in 4.2.7 and earlier that have been fixed in this version. There +will **NOT** be another 4.2.x release. + +The major version has been incremented not for Odyssey support, but because +we have made some minor breaking changes to the APIs we provide for plugin +developers. + +Due to these plugin API changes (see below) users might need to update their +plugins. A check of all the +[Plugins we know about](https://github.com/EDCD/EDMarketConnector/wiki/Plugins#available-plugins---confirmed-working-under-python-37) +only found one with an issue related to the move to `edmc_data.py`, the +developer was informed and the issue addressed. + +Other plugins should, at most, log deprecation warnings about the +`config` changes (again, see below). + +**In the first instance please report any issues with plugins to *their* +developers, not us. They can contact us about EDMC core code issues if +they find such in their investigations.** + +All plugin developers would benefit from having a GitHub account and then +setting up a watch on [EDMarketConnector](https://github.com/EDCD/EDMarketConnector/) +of at least 'Releases' under 'Custom'. + +NB: If you had any beta or -rc1 of 5.0.0 installed and see anything weird +with this full release it would be advisable to manually uninstall, confirm +the installation directory (default `c:\Program Files (x86)\EDMarketConnector`) +is empty, and then re-install 5.0.0 to be sure you have a clean, working, +install. Anyone upgrading from 4.2.7 or earlier shouldn't see any issues +with this. + +Changes and Enhancements +--- + +* If the application detects it's running against a non-live (alpha or beta) + version of the game it will append " (beta)" to the Commander name on the + main UI. + +* Updated translations. Once more, thanks to all the translators! + +* We now sanity check a returned Frontier Authentication token to be sure + it's for the current Commander. If it's not you'll see + `Error: customer_id doesn't match!` on the bottom status line. Double-check + you're using the correct credentials when authing! + +* New 'Main window transparency' slider on `Settings` > `Appearance`. + +* New command-line argument for EDMarketConnector.exe `--reset-ui`. This will: + + 1. Reset to the default Theme. + 2. Reset the UI transparency to fully opaque. + + The intention is this can be used if you've lost sight of the main window + due to tweaking these options. + + There is a new file `EDMarketConnector - reset-ui.bat` to make utilising + this easy on Windows. + +* New CL arg for EDMarketConnector.exe `--force-edmc-protocol`. + This is really only of use to core developers (its purpose being to force + use of the `edmc://` protocol for Frontier Auth callbacks, even when not + 'frozen'). + +* Linux config will be flushed to disk after any change. This means that + EDMC.py can now actually make use of the latest CAPI auth if it's been + updated by EDMarketConnector.py since that started. + + If you want to run multiple instances of the application under Linux then + please check the updated [Troubleshooting: Multi-Accounting](https://github.com/EDCD/EDMarketConnector/wiki/Troubleshooting#multi-accounting) + wiki entry. + +* Linux and macOS: You can now set a font name and size in your config file. + Ensuring this is a TTF font, rather than a bitmap font, should allow the + application UI scaling to work. + + 1. 'font' - the font name to attempt using + 2. 'font_size' - the font size to attempt using. + + There is no UI for this in Preferences, you will need to edit your + [config file](https://github.com/EDCD/EDMarketConnector/wiki/Troubleshooting#location-of-configuration-files) + to set or change it, and then restart the application. + + This is not supported on Windows so as not to risk weird bugs. UI + Scaling works on Windows without this. + +* We now also cite the git 'short hash' in the version string. For a Windows + install of the application this is sourced from the `.gitversion` file + (written during the build process). + + When running from source we attempt to use the command `git rev-parse --short HEAD` + to obtain this. If this doesn't work it will be set to 'UNKNOWN'. + +* We have added a 'killswitch' feature to turn off specific functionality if it + is found to have a bug. An example use of this would be in an "oh + shit! we're sending bad data to EDDN!" moment so as to protect EDDN + listeners such as EDDB. + + If we ever have to use this we'll announce it clearly and endeavour to + get a fixed version of the program released ASAP. We will **NOT** be + using this merely to try and get some laggards to upgrade. + + Plugin Developers: See [Killswitches.md](./docs/Killswitches.md) for more + information about this. + +* Our logging code will make best efforts to still show class name and + other such fields if it has trouble finding any of the required data for + the calling frame. This means no longer seeing `??:??:??` when there is + an issue with this. + +* macOS: We've managed to test the latest code on macOS Catalina. Other than + [keyboard shortcut support not working](https://github.com/EDCD/EDMarketConnector/issues/906) + it appears to be working. + +* We've pulled the latest Coriolis data which might have caused changes to + ship and module names as written out to some files. + +Odyssey +--- + +Every effort was made during the Odyssey Alphas to ensure that this +application will continue to function correctly with it. As always, make a +[Bug Report](https://github.com/EDCD/EDMarketConnector/issues/new?assignees=&labels=bug%2C+unconfirmed&template=bug_report.md&title=) +if you find anything not working, but be sure to check our +[Known Issues](https://github.com/EDCD/EDMarketConnector/issues/618) first. + +* A new UI element 'Suit' now appears below 'Ship' when applicable. It + details the type of suit you currently have equipped and its Loadout name. + This UI element is collapsed/hidden if no suit/on-foot state is detected, + e.g. not playing Odyssey. + +* Note that we can only reliably know about Suits and their Loadouts from a + CAPI data pull (which is what we do automatically on docking if + configured to do so, or when you press the 'Update' button). We do + attempt to gather this data from Journal events as well, but if you + switch to a Suit Loadout that hasn't been mentioned in them yet we won't + be able to display that until the next CAPI data pull. + +If anyone becomes aware of a 'suit loadouts' site/tool, a la Coriolis/EDSY +but for Odyssey Suits, do let us know so we can add support for it! +We're already kicking around ideas to e.g. place JSON text in the clipboard +if the Suit Loadout is clicked. + +Bug Fixes +--- + +* Fix ship loadout export to files to not trip up in the face of file encoding + issues. This relates to the 'Ship Loadout' option on the 'Output' tab of + Settings/Preferences. + +* Ship Type/Name will now be greyed out, and not clickable, if we don't + currently have loadout information for it. This prevents trying to send an + empty loadout to your shipyard provider. + +* Bug fixed when handling CAPI-sourced shipyard information. This happens + due to a Frontier bug with not returning shipyard data at all for normal + stations. + + It has been observed that Frontier has fixed this bug for Odyssey. + +* Don't try to get Ship information from `LoadGame` event if directly in CQC. + +* Inara: Don't attempt to send an empty + `setCommanderReputationMajorFaction` API call. This quietens an error + from the Inara API caused when a Cmdr literally has no Major Faction + Reputation yet. + +Code Clean Up +------------- + +* Code pertaining to processing Journal events was reworked and noisy logging + reduced as a consequence. + +* A little TRACE logging output has been commented out for now. + +* The code for `File` > `Status` has been cleaned up. + +* Localisation code has been cleaned up. + +* Code handling the Frontier Authorisation callback on Windows has been + cleaned up. + +* A lot of general code cleanup relating to: Inara, outfitting, Frontier + CAPI, hotkey (manual Updates), dashboard (Status.json monitoring), + commodities files, and ED format ship loadout files. + +Plugin Developers +--- + +* The files `stations.p` and `systems.p` have been removed from the Windows + Installer. These were never intended for third-party use. Their use in + core code was for generating EDDB-id URLs, but we long since changed the + EDDB plugin's handlers for that to use alternate URL formats based on + game IDs or names. + + If you were using either to lookup EDDB IDs for systems and/or stations + then please see how `system_url()` and `station_url()` now work in + `plugins/eddb.py`. + + This change also removed the core (not plugin) `eddb.py` file which + generated these files. You can find it still in the git history if needs + be. It had gotten to the stage where generating `systems.p` took many + hours and required 64-bit Python to have any hope of working due to + memory usage. + +* All static data that is + [cleared for use by plugins](https://github.com/EDCD/EDMarketConnector/blob/main/PLUGINS.md#available-imports) + is now in the file + `edmc_data.py` and should be imported from there, not *any* other module. + + The one thing we didn't move was the 'bracket map' dictionaries in `td.py` + as they're for use only by the code in that file. + + All future such data will be added to this file, and we'll endeavour not + to make breaking changes to any of it without increasing our Major version. + +* `config.appversion()` is now a function that returns a `semantic_version.Version`. + In contexts where you're expecting a string this should mostly + just work. If needs be wrap it in `str()`. + + For backwards compatibility with pre-5.0.0 you can use: + +```python + from config import appversion + + if callable(appversion): + edmc_version = appversion() + else: + edmc_version = appversion +``` + +* Example plugin + [plugintest](https://github.com/EDCD/EDMarketConnector/tree/main/docs/examples/plugintest) + updated. This includes an example of how to check core EDMC version if needs + be. This example is also in + [PLUGINS.md](https://github.com/EDCD/EDMarketConnector/blob/main/PLUGINS.md#checking-core-edmc-version). + +* `config.py` has undergone a major rewrite. You should no longer be using + `config.get(...)` or `config.getint(...)`, which will both give a + deprecation warning. + Use instead the correct `config.get_()` function: + + * `config.get_list()` + * `config.get_str()` + * `config.get_bool()` + * `config.get_int()` + + Setting still uses `config.set(...)`. + + So: + + 1. Replace all instances of `config.get()` and `config.getint()` as above. + 2. For ease of maintaining compatibility with pre-5.0.0 versions include + this code in at least one module/file (no harm in it being in all that + manipulate plugin config): + +``` +from config import config + +# For compatibility with pre-5.0.0 +if not hasattr(config, 'get_int'): + config.get_int = config.getint + +if not hasattr(config, 'get_str'): + config.get_str = config.get + +if not hasattr(config, 'get_bool'): + config.get_bool = lambda key: bool(config.getint(key)) + +if not hasattr(config, 'get_list'): + config.get_list = config.get +``` + +* Utilising our provided logging from a class-level, i.e. not a solid + instance of a class, property/function will now work. + +* We now change the current working directory of EDMarketConnector.exe to + its location as soon as possible in its execution. We're also + paranoid about ensuring we reference the full path to the `.gitversion` file. + + However, no plugin should itself call `os.chdir(...)` or equivalent. You'll + change the current working directory for all core code and other plugins as + well (it's global to the whole **process**, not per-thread). Use full + absolute paths instead (`pathlib` is what to use for this). + +* The `state` dict passed to plugins in `journal_entry()` calls (which is + actually `monitor.state` in the core code) has received many additions + relating to Odyssey, as well as other fixes and enhancements. + + 1. Support has been added for the `NavRoute` (not `Route` as v28 of the + official Journal documentation erroneously labels it) Journal event and + its associated file `NavRoute.json`. See [PLUGINS.md:Events documentation](https://github.com/EDCD/EDMarketConnector/blob/main/PLUGINS.md#journal-entry) + + 1. Similarly, there is now support for the `ModuleInfo` event and its + associated `ModulesInfo.json` file. + + 1. `state['Credits']` - until now no effort was made to keep this + record of the credits balance up to date after the initial `LoadGame` + event. This has now been addressed, and the balance should stay in sync + as best it can from the available Journal events. It will always correct + back to the actual balance on each CAPI data pull or game relog/restart. + + 1. `state['Cargo']` now takes account of any `CargoTransfer` events. + This was added to the game in the Fleet Carriers update, but also covers + transfers to/from an SRV. + + 1. `state['OnFoot']` is a new boolean, set true whenever we detect + the Cmdr is on-foot, i.e. not in any type of vehicle (Cmdr's own ship, + SRV, multi-crew in another Cmdr's ship, Apex taxi, or a Dropship). + + 1. `state['Suits']` and `state['SuitLoadouts']` added as `dict`s containing + information about the Cmdr's owned Suits and the Loadouts the Cmdr has + defined to utilise them (and on-foot weapons). + Note that in the raw CAPI data these are arrays if all members + contiguously exist, else a dictionary, but we have chosen to always coerce + these to a python `dict` for simplicity. They will be empty `dict`s, not + `None` if there is no data. + We use the CAPI data names for keys, not the Journal ones - e.g. `slots` + for weapons equipped, not `Modules`. + The `id` field found on e.g. weapon details in suit loadouts may be `None` + if we got the data from the Journal rather than the CAPI data. + NB: This data is only guaranteed up to date and correct after a fresh CAPI + data pull, as the current Journal events don't allow for updating it on the + fly (this should change in a future Odyssey patch). + + 1. `state['SuitCurrent']` and `state['SuitLoadoutCurrent']` contain the + obvious "currently in use" data as per the Suits/SuitLoadouts. + + 1. Tracking of the new Odyssey 'Microresources' has been added: + 1. `Component` - `dict` for 'Ship Locker' inventory. + 1. `Item` - `dict` for 'Ship Locker' inventory. + 1. `Consumable` - `dict` for 'Ship Locker' inventory. + 1. `Data` - `dict` for 'Ship Locker' inventory. + 1. `BackPack` - on-foot inventory, a `dict` containing again + dicts for `Component`, `Item`, `Consumable` and `Data`. + However note that the lack of a Journal event when throwing a grenade, + along with no `BackPackMaterials` event if logging in on-foot means that + we can't track the BackPack inventory perfectly. + + See the updated `PLUGINS.md` file for details. + +* As `Status.json`, and thus the EDMC 'dashboard' output now has a 'flags2' + key we have added the associated constants to `edmc_data.py` with a + `Flags2` prefix on the names. + +* Note that during the Odyssey Alpha it was observed that the CAPI + `data['commander']['docked']` boolean was **always true** if the Cmdr was + in their ship. This is a regression from pre-Odyssey behaviour. The + core EDMC code copes with this. Please add a reproduction to the issue + about this: + [PTS CAPI saying Commander is Docked after jumping to new system](https://issues.frontierstore.net/issue-detail/28638). + Release 4.2.7 === diff --git a/Contributing.md b/Contributing.md index 80374301..0f57c12c 100644 --- a/Contributing.md +++ b/Contributing.md @@ -1,3 +1,6 @@ + # Guidelines for contributing to EDMC ## Work on Issues @@ -157,10 +160,33 @@ Note that if your PR does not cleanly (or mostly cleanly) pass a linting scan, y ### Unit testing -Where possible please write unit tests for your PRs, especially in the case of bug fixes, having regression tests help -ensure that we don't accidentally re-introduce a bug down the line. +Where possible please write unit tests for your PRs, especially in the case of +bug fixes, having regression tests help ensure that we don't accidentally +re-introduce a bug down the line. -We use the python stdlib library `unittest` for unit testing. +We use the [`pytest`](https://docs.pytest.org/en/stable/) for unit testing. + +The files for a test should go in a sub-directory of `tests/` named after the +(principal) file that contains the code they are testing. e.g. for +journal_lock.py the tests are in `tests/journal_lock.py/test_journal_lock.py`. +The `test_` prefix on `test_journal_lock.py` is necessary in order for `pytest` +to recognise the file as containing tests to be run. +The sub-directory avoids having a mess of files in `tests`, particularly when +there might be supporting files, e.g. `tests/config.py/_old_config.py` or files +containing test data. + +Invoking just a bare `pytest` command will run all tests. + +To run only a sub-set of tests you can use, e.g. `pytest -k journal_lock`. You +might want to use `pytest -rA -k journal_lock` if you have any debug `print()` +statements within the test code itself, so you can see the output even when the +tests all succeed. + +Adding `--trace` to a `pytest` invocation causes it to drop into a +[`pdb`](https://docs.python.org/3/library/pdb.html) prompt for each test, +handy if you want to step through the testing code to be sure of anything. + +Otherwise, see the [pytest documentation](https://docs.pytest.org/en/stable/contents.html). --- diff --git a/EDMC.py b/EDMC.py index 04701313..4c5283a7 100755 --- a/EDMC.py +++ b/EDMC.py @@ -10,7 +10,7 @@ import re import sys from os.path import getmtime, join from time import sleep, time -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any, List, Optional # isort: off @@ -68,7 +68,7 @@ EXIT_SUCCESS, EXIT_SERVER, EXIT_CREDENTIALS, EXIT_VERIFICATION, EXIT_LAGGING, EX JOURNAL_RE = re.compile(r'^Journal(Beta)?\.[0-9]{12}\.[0-9]{2}\.log$') -def versioncmp(versionstring): +def versioncmp(versionstring) -> List: """Quick and dirty version comparison assuming "strict" numeric only version numbers.""" return list(map(int, versionstring.split('.'))) @@ -106,7 +106,7 @@ def deep_get(target: dict, *args: str, default=None) -> Any: return current -def main(): +def main(): # noqa: C901, CCR001 """Run the main code of the program.""" try: # arg parsing @@ -145,9 +145,9 @@ def main(): updater = Updater(provider='internal') newversion: Optional[EDMCVersion] = updater.check_appcast() if newversion: - print(f'{appversion} ({newversion.title!r} is available)') + print(f'{appversion()} ({newversion.title!r} is available)') else: - print(appversion) + print(appversion()) return @@ -160,7 +160,7 @@ def main(): sys.exit(EXIT_ARGS) edmclogger.set_channels_loglevel(args.loglevel) - logger.debug(f'Startup v{appversion} : Running on Python v{sys.version}') + 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} @@ -189,7 +189,10 @@ sys.path: {sys.path}''' # Get state from latest Journal file logger.debug('Getting state from latest journal file') try: - logdir = config.get('journaldir') or config.default_journal_dir + logdir = config.get_str('journaldir', default=config.default_journal_dir) + if not logdir: + logdir = config.default_journal_dir + logger.debug(f'logdir = "{logdir}"') logfiles = sorted((x for x in os.listdir(logdir) if JOURNAL_RE.search(x)), key=lambda x: x.split('.')[1:]) @@ -215,7 +218,7 @@ sys.path: {sys.path}''' # Get data from Companion API if args.p: logger.debug(f'Attempting to use commander "{args.p}"') - cmdrs = config.get('cmdrs') or [] + cmdrs = config.get_list('cmdrs', default=[]) if args.p in cmdrs: idx = cmdrs.index(args.p) @@ -231,7 +234,7 @@ sys.path: {sys.path}''' else: logger.debug(f'Attempting to use commander "{monitor.cmdr}" from Journal File') - cmdrs = config.get('cmdrs') or [] + cmdrs = config.get_list('cmdrs', default=[]) if monitor.cmdr not in cmdrs: raise companion.CredentialsError() diff --git a/EDMCLogging.py b/EDMCLogging.py index c0898941..6633064e 100644 --- a/EDMCLogging.py +++ b/EDMCLogging.py @@ -41,9 +41,12 @@ import logging.handlers import os import pathlib import tempfile +from contextlib import suppress # So that any warning about accessing a protected member is only in one place. from sys import _getframe as getframe -from typing import Tuple +from threading import get_native_id as thread_native_id +from traceback import print_exc +from typing import TYPE_CHECKING, Tuple, cast from config import appcmdname, appname, config @@ -83,6 +86,18 @@ logging.Logger.trace = lambda self, message, *args, **kwargs: self._log( # type **kwargs ) +if TYPE_CHECKING: + from types import FrameType + + # Fake type that we can use here to tell type checkers that trace exists + + class LoggerMixin(logging.Logger): + """LoggerMixin is a fake class that tells type checkers that trace exists on a given type.""" + + def trace(self, message, *args, **kwargs) -> None: + """Fake trace method.""" + return self._log(LEVEL_TRACE, message, args, **kwargs) + class Logger: """ @@ -118,7 +133,7 @@ class Logger: # This should be affected by the user configured log level self.logger_channel.setLevel(loglevel) - self.logger_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(module)s.%(qualname)s:%(lineno)d: %(message)s') # noqa: E501 + self.logger_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(process)d:%(thread)d:%(osthreadid)d %(module)s.%(qualname)s:%(lineno)d: %(message)s') # noqa: E501 self.logger_formatter.default_time_format = '%Y-%m-%d %H:%M:%S' self.logger_formatter.default_msec_format = '%s.%03d' @@ -147,13 +162,13 @@ class Logger: self.logger_channel_rotating.setFormatter(self.logger_formatter) self.logger.addHandler(self.logger_channel_rotating) - def get_logger(self) -> logging.Logger: + def get_logger(self) -> 'LoggerMixin': """ Obtain the self.logger of the class instance. Not to be confused with logging.getLogger(). """ - return self.logger + return cast('LoggerMixin', self.logger) def get_streamhandler(self) -> logging.Handler: """ @@ -186,7 +201,7 @@ class Logger: logger.trace("Not changing log level because it's TRACE") # type: ignore -def get_plugin_logger(plugin_name: str, loglevel: int = _default_loglevel) -> logging.Logger: +def get_plugin_logger(plugin_name: str, loglevel: int = _default_loglevel) -> 'LoggerMixin': """ Return a logger suitable for a plugin. @@ -222,7 +237,7 @@ def get_plugin_logger(plugin_name: str, loglevel: int = _default_loglevel) -> lo plugin_logger.addFilter(EDMCContextFilter()) - return plugin_logger + return cast('LoggerMixin', plugin_logger) class EDMCContextFilter(logging.Filter): @@ -242,6 +257,7 @@ class EDMCContextFilter(logging.Filter): logging.Formatter() as you can use just this no matter if there is a class involved or not, so you get a nice clean: .[.classB....]. + 3. osthreadid = OS level thread ID. If we fail to be able to properly set either then: @@ -266,10 +282,12 @@ class EDMCContextFilter(logging.Filter): if getattr(record, 'qualname', None) is None: setattr(record, 'qualname', qualname) + setattr(record, 'osthreadid', thread_native_id()) + return True - @classmethod # noqa: CCR001 - this is as refactored as is sensible - def caller_attributes(cls, module_name: str = '') -> Tuple[str, str, str]: + @classmethod + 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. @@ -278,6 +296,9 @@ class EDMCContextFilter(logging.Filter): class if relevant. 3. module is munged if we detect the caller is an EDMC plugin, whether internal or found. + + :param module_name: The name of the calling module. + :return: Tuple[str, str, str] - class_name, qualname, module_name """ frame = cls.find_caller_frame() @@ -300,66 +321,88 @@ class EDMCContextFilter(logging.Filter): except Exception: pass - # We've given up, so just return all '??' to signal we couldn't get the info - return '??', '??', '??' + # We've given up, so just return '??' to signal we couldn't get the info + return '??', '??', module_name + try: + args, _, _, value_dict = inspect.getargvalues(frame) + if len(args) and args[0] in ('self', 'cls'): + frame_class: 'object' = value_dict[args[0]] - args, _, _, value_dict = inspect.getargvalues(frame) - if len(args) and args[0] in ('self', 'cls'): - frame_class: 'object' = value_dict[args[0]] + if frame_class: + # See https://en.wikipedia.org/wiki/Name_mangling#Python for how name mangling works. + # For more detail, see _Py_Mangle in CPython's Python/compile.c. + name = frame_info.function + class_name = frame_class.__class__.__name__.lstrip("_") + if name.startswith("__") and not name.endswith("__") and class_name: + name = f'_{class_name}{frame_info.function}' - if frame_class: - # See https://en.wikipedia.org/wiki/Name_mangling#Python for how name mangling works. - # For more detail, see _Py_Mangle in CPython's Python/compile.c. - name = frame_info.function - class_name = frame_class.__class__.__name__.lstrip("_") - if name.startswith("__") and not name.endswith("__") and class_name: - name = f'_{class_name}{frame_info.function}' + # Find __qualname__ of the caller + fn = inspect.getattr_static(frame_class, name, None) + if fn is None: + # For some reason getattr_static cant grab this. Try and grab it with getattr, bail out + # if we get a RecursionError indicating a property + try: + fn = getattr(frame_class, name, None) + except RecursionError: + print( + "EDMCLogging:EDMCContextFilter:caller_attributes():" + "Failed to get attribute for function info. Bailing out" + ) + # class_name is better than nothing for __qualname__ + return class_name, class_name, module_name - # Find __qualname__ of the caller - fn = inspect.getattr_static(frame_class, name, None) - if fn is None: - # For some reason getattr_static cant grab this. Try and grab it with getattr, bail out - # if we get a RecursionError indicating a property - try: - fn = getattr(frame_class, name, None) - except RecursionError: - print( - "EDMCLogging:EDMCContextFilter:caller_attributes():" - "Failed to get attribute for function info. Bailing out" - ) - return "??", "??", "??" + if fn is not None: + if isinstance(fn, property): + class_name = str(frame_class) + # If somehow you make your __class__ or __class__.__qualname__ recursive, + # I'll be impressed. + if hasattr(frame_class, '__class__') and hasattr(frame_class.__class__, "__qualname__"): + class_name = frame_class.__class__.__qualname__ + caller_qualname = f"{class_name}.{name}(property)" - if fn is not None: - if isinstance(fn, property): - class_name = str(frame_class) - # If somehow you make your __class__ or __class__.__qualname__ recursive, I'll be impressed. - if hasattr(frame_class, '__class__') and hasattr(frame_class.__class__, "__qualname__"): - class_name = frame_class.__class__.__qualname__ - caller_qualname = f"{class_name}.{name}(property)" + else: + caller_qualname = f"" - else: - caller_qualname = f"" + elif not hasattr(fn, '__qualname__'): + caller_qualname = name - elif fn.__qualname__: - caller_qualname = fn.__qualname__ + elif hasattr(fn, '__qualname__') and fn.__qualname__: + caller_qualname = fn.__qualname__ - # Find containing class name(s) of caller, if any - if frame_class.__class__ and frame_class.__class__.__qualname__: - caller_class_names = frame_class.__class__.__qualname__ + # Find containing class name(s) of caller, if any + if ( + frame_class.__class__ and hasattr(frame_class.__class__, '__qualname__') + and frame_class.__class__.__qualname__ + ): + caller_class_names = frame_class.__class__.__qualname__ - # It's a call from the top level module file - elif frame_info.function == '': - caller_class_names = '' - caller_qualname = value_dict['__name__'] + # It's a call from the top level module file + elif frame_info.function == '': + caller_class_names = '' + caller_qualname = value_dict['__name__'] - elif frame_info.function != '': - caller_class_names = '' - caller_qualname = frame_info.function + elif frame_info.function != '': + caller_class_names = '' + caller_qualname = frame_info.function - module_name = cls.munge_module_name(frame_info, module_name) + module_name = cls.munge_module_name(frame_info, module_name) - # https://docs.python.org/3.7/library/inspect.html#the-interpreter-stack - del frame + except Exception as e: + print('ALERT! Something went VERY wrong in handling finding info to log') + print('ALERT! Information is as follows') + with suppress(Exception): + + print(f'ALERT! {e=}') + print_exc() + print(f'ALERT! {frame=}') + with suppress(Exception): + print(f'ALERT! {fn=}') # type: ignore + with suppress(Exception): + print(f'ALERT! {cls=}') + + finally: # Ensure this always happens + # https://docs.python.org/3.7/library/inspect.html#the-interpreter-stack + del frame if caller_qualname == '': print('ALERT! Something went wrong with finding caller qualname for logging!') @@ -381,19 +424,19 @@ class EDMCContextFilter(logging.Filter): # Go up through stack frames until we find the first with a # type(f_locals.self) of logging.Logger. This should be the start # of the frames internal to logging. - frame: 'frame' = getframe(0) + frame: 'FrameType' = getframe(0) while frame: if isinstance(frame.f_locals.get('self'), logging.Logger): - frame = frame.f_back # Want to start on the next frame below + frame = cast('FrameType', frame.f_back) # Want to start on the next frame below break - frame = frame.f_back + frame = cast('FrameType', frame.f_back) # Now continue up through frames until we find the next one where # that is *not* true, as it should be the call site of the logger # call while frame: if not isinstance(frame.f_locals.get('self'), logging.Logger): break # We've found the frame we want - frame = frame.f_back + frame = cast('FrameType', frame.f_back) return frame @classmethod @@ -412,8 +455,8 @@ class EDMCContextFilter(logging.Filter): :return: The munged module_name. """ file_name = pathlib.Path(frame_info.filename).expanduser() - plugin_dir = pathlib.Path(config.plugin_dir).expanduser() - internal_plugin_dir = pathlib.Path(config.internal_plugin_dir).expanduser() + plugin_dir = pathlib.Path(config.plugin_dir_path).expanduser() + internal_plugin_dir = pathlib.Path(config.internal_plugin_dir_path).expanduser() # Find the first parent called 'plugins' plugin_top = file_name while plugin_top and plugin_top.name != '': @@ -449,18 +492,18 @@ class EDMCContextFilter(logging.Filter): return module_name -def get_main_logger() -> logging.Logger: +def get_main_logger() -> 'LoggerMixin': """Return the correct logger for how the program is being run.""" if not os.getenv("EDMC_NO_UI"): # GUI app being run - return logging.getLogger(appname) + return cast('LoggerMixin', logging.getLogger(appname)) else: # Must be the CLI - return logging.getLogger(appcmdname) + return cast('LoggerMixin', logging.getLogger(appcmdname)) # Singleton -loglevel = config.get('loglevel') +loglevel = config.get_str('loglevel') if not loglevel: loglevel = logging.INFO @@ -470,4 +513,4 @@ else: base_logger_name = appcmdname edmclogger = Logger(base_logger_name, loglevel=loglevel) -logger = edmclogger.get_logger() +logger: 'LoggerMixin' = edmclogger.get_logger() diff --git a/EDMarketConnector - reset-ui.bat b/EDMarketConnector - reset-ui.bat new file mode 100644 index 00000000..01db6dfb --- /dev/null +++ b/EDMarketConnector - reset-ui.bat @@ -0,0 +1 @@ +EDMarketConnector.exe --reset-ui diff --git a/EDMarketConnector.py b/EDMarketConnector.py index ce97f9e3..4fad261b 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -1,19 +1,38 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +"""Entry point for the main GUI application.""" import argparse import html import json import locale +import pathlib import re import sys +# import threading import webbrowser from builtins import object, str from os import chdir, environ -from os.path import dirname, isdir, join +from os.path import dirname, join from sys import platform from time import localtime, strftime, time -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Optional, Tuple + +# 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 +# place for things like config.py reading .gitversion +if getattr(sys, 'frozen', False): + # Under py2exe sys.path[0] is the executable name + if platform == 'win32': + chdir(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') + +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 @@ -27,11 +46,17 @@ 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='a', buffering=1) + sys.stdout = sys.stderr = open(join(tempfile.gettempdir(), f'{appname}.log'), mode='wt', buffering=1) # TODO: Test: Make *sure* this redirect is working, else py2exe is going to cause an exit popup -# After the redirect in case config does logging setup +# These need to be after the stdout/err redirect because they will cause +# logging to be set up. +# isort: off +import killswitch from config import appversion, appversion_nobuild, config, copyright +# isort: on + +from companion import CAPIData, index_possibly_sparse_list from EDMCLogging import edmclogger, logger, logging from journal_lock import JournalLock, JournalLockResult @@ -45,20 +70,33 @@ if __name__ == '__main__': # noqa: C901 "such as EDSM, Inara.cz and EDDB." ) - parser.add_argument('--trace', - help='Set the Debug logging loglevel to TRACE', - action='store_true', - ) + parser.add_argument( + '--trace', + help='Set the Debug logging loglevel to TRACE', + action='store_true', + ) + + parser.add_argument( + '--reset-ui', + help='reset UI theme and transparency to defaults', + action='store_true' + ) parser.add_argument('--suppress-dupe-process-popup', help='Suppress the popup from when the application detects another instance already running', action='store_true' ) - parser.add_argument('--force-localserver-for-auth', - help='Force EDMC to use a localhost webserver for Frontier Auth callback', - action='store_true' - ) + auth_options = parser.add_mutually_exclusive_group(required=False) + auth_options.add_argument('--force-localserver-for-auth', + help='Force EDMC to use a localhost webserver for Frontier Auth callback', + action='store_true' + ) + + auth_options.add_argument('--force-edmc-protocol', + help='Force use of the edmc:// protocol handler. Error if not on Windows', + action='store_true', + ) parser.add_argument('edmc', help='Callback from Frontier Auth', @@ -76,7 +114,16 @@ if __name__ == '__main__': # noqa: C901 if args.force_localserver_for_auth: config.set_auth_force_localserver() - def handle_edmc_callback_or_foregrounding(): # noqa: CCR001 + if args.force_edmc_protocol: + if sys.platform == 'win32': + config.set_auth_force_edmc_protocol() + + else: + print("--force-edmc-protocol is only valid on Windows") + parser.print_help() + exit(1) + + def handle_edmc_callback_or_foregrounding() -> None: # noqa: CCR001 """Handle any edmc:// auth callback, else foreground existing window.""" logger.trace('Begin...') @@ -109,7 +156,7 @@ if __name__ == '__main__': # noqa: C901 ShellExecute = ctypes.windll.shell32.ShellExecuteW # noqa: N806 ShellExecute.argtypes = [HWND, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR, INT] - def window_title(h): + def window_title(h: int) -> Optional[str]: if h: text_length = GetWindowTextLength(h) + 1 buf = ctypes.create_unicode_buffer(text_length) @@ -119,7 +166,7 @@ if __name__ == '__main__': # noqa: C901 return None @ctypes.WINFUNCTYPE(BOOL, HWND, LPARAM) - def enumwindowsproc(window_handle, l_param): + def enumwindowsproc(window_handle, l_param): # noqa: CCR001 """ Determine if any window for the Application exists. @@ -142,7 +189,6 @@ if __name__ == '__main__': # noqa: C901 if GetProcessHandleFromHwnd(window_handle): # If GetProcessHandleFromHwnd succeeds then the app is already running as this user if len(sys.argv) > 1 and sys.argv[1].startswith(protocolhandler_redirect): - logger.debug('Invoked with edmc:// protocol handler arg') CoInitializeEx(0, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE) # Wait for it to be responsive to avoid ShellExecute recursing ShowWindow(window_handle, SW_RESTORE) @@ -217,20 +263,14 @@ if __name__ == '__main__': # noqa: C901 # isort: off if TYPE_CHECKING: from logging import trace, TRACE # type: ignore # noqa: F401 + import update + # from infi.systray import SysTrayIcon # isort: on def _(x: str) -> str: """Fake the l10n translation functions for typing.""" return x -if getattr(sys, 'frozen', False): - # Under py2exe sys.path[0] is the executable name - if platform == 'win32': - chdir(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') - import tkinter as tk import tkinter.filedialog import tkinter.font @@ -245,6 +285,7 @@ import stats import td from commodity import COMMODITY_CSV from dashboard import dashboard +from edmc_data import ship_name_map from hotkey import hotkeymgr from l10n import Translations from monitor import monitor @@ -271,14 +312,18 @@ SHIPYARD_HTML_TEMPLATE = """ class AppWindow(object): + """Define the main application window.""" + # Tkinter Event types EVENT_KEYPRESS = 2 EVENT_BUTTON = 4 EVENT_VIRTUAL = 35 - def __init__(self, master): # noqa: C901 + PADX = 5 - self.holdofftime = config.getint('querytime') + companion.holdoff + def __init__(self, master: tk.Tk): # noqa: C901, CCR001 # TODO - can possibly factor something out + + self.holdofftime = config.get_int('querytime', default=0) + companion.holdoff self.w = master self.w.title(applongname) @@ -287,14 +332,28 @@ class AppWindow(object): self.prefsdialog = None + # if platform == 'win32': + # from infi.systray import SysTrayIcon + + # def open_window(systray: 'SysTrayIcon') -> None: + # self.w.deiconify() + + # menu_options = (("Open", None, open_window),) + # # Method associated with on_quit is called whenever the systray is closing + # self.systray = SysTrayIcon("EDMarketConnector.ico", applongname, menu_options, on_quit=self.exit_tray) + # self.systray.start() + plug.load_plugins(master) if platform != 'darwin': if platform == 'win32': self.w.wm_iconbitmap(default='EDMarketConnector.ico') + else: self.w.tk.call('wm', 'iconphoto', self.w, '-default', - tk.PhotoImage(file=join(config.respath, 'EDMarketConnector.png'))) # noqa: E501 + tk.PhotoImage(file=join(config.respath_path, 'EDMarketConnector.png'))) + + # TODO: Export to files and merge from them in future ? self.theme_icon = tk.PhotoImage( data='R0lGODlhFAAQAMZQAAoKCQoKCgsKCQwKCQsLCgwLCg4LCQ4LCg0MCg8MCRAMCRANChINCREOChIOChQPChgQChgRCxwTCyYVCSoXCS0YCTkdCTseCT0fCTsjDU0jB0EnDU8lB1ElB1MnCFIoCFMoCEkrDlkqCFwrCGEuCWIuCGQvCFs0D1w1D2wyCG0yCF82D182EHE0CHM0CHQ1CGQ5EHU2CHc3CHs4CH45CIA6CIE7CJdECIdLEolMEohQE5BQE41SFJBTE5lUE5pVE5RXFKNaFKVbFLVjFbZkFrxnFr9oFsNqFsVrF8RsFshtF89xF9NzGNh1GNl2GP+KG////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////yH5BAEKAH8ALAAAAAAUABAAAAeegAGCgiGDhoeIRDiIjIZGKzmNiAQBQxkRTU6am0tPCJSGShuSAUcLoIIbRYMFra4FAUgQAQCGJz6CDQ67vAFJJBi0hjBBD0w9PMnJOkAiJhaIKEI7HRoc19ceNAolwbWDLD8uAQnl5ga1I9CHEjEBAvDxAoMtFIYCBy+kFDKHAgM3ZtgYSLAGgwkp3pEyBOJCC2ELB31QATGioAoVAwEAOw==') # noqa: E501 self.theme_minimize = tk.BitmapImage( @@ -307,33 +366,51 @@ class AppWindow(object): frame.columnconfigure(1, weight=1) self.cmdr_label = tk.Label(frame) - self.ship_label = tk.Label(frame) - self.system_label = tk.Label(frame) - self.station_label = tk.Label(frame) - - self.cmdr_label.grid(row=1, column=0, sticky=tk.W) - self.ship_label.grid(row=2, column=0, sticky=tk.W) - self.system_label.grid(row=3, column=0, sticky=tk.W) - self.station_label.grid(row=4, column=0, sticky=tk.W) - self.cmdr = tk.Label(frame, compound=tk.RIGHT, anchor=tk.W, name='cmdr') + self.ship_label = tk.Label(frame) self.ship = HyperlinkLabel(frame, compound=tk.RIGHT, url=self.shipyard_url, name='ship') + self.suit_label = tk.Label(frame) + self.suit = tk.Label(frame, compound=tk.RIGHT, anchor=tk.W, name='suit') + self.system_label = tk.Label(frame) self.system = HyperlinkLabel(frame, compound=tk.RIGHT, url=self.system_url, popup_copy=True, name='system') + self.station_label = tk.Label(frame) self.station = HyperlinkLabel(frame, compound=tk.RIGHT, url=self.station_url, name='station') + # system and station text is set/updated by the 'provider' plugins + # eddb, edsm and inara. Look for: + # + # parent.children['system'] / parent.children['station'] - self.cmdr.grid(row=1, column=1, sticky=tk.EW) - self.ship.grid(row=2, column=1, sticky=tk.EW) - self.system.grid(row=3, column=1, sticky=tk.EW) - self.station.grid(row=4, column=1, sticky=tk.EW) + ui_row = 1 + + self.cmdr_label.grid(row=ui_row, column=0, sticky=tk.W) + self.cmdr.grid(row=ui_row, column=1, sticky=tk.EW) + ui_row += 1 + + self.ship_label.grid(row=ui_row, column=0, sticky=tk.W) + self.ship.grid(row=ui_row, column=1, sticky=tk.EW) + ui_row += 1 + + self.suit_grid_row = ui_row + self.suit_shown = False + ui_row += 1 + + self.system_label.grid(row=ui_row, column=0, sticky=tk.W) + self.system.grid(row=ui_row, column=1, sticky=tk.EW) + ui_row += 1 + + self.station_label.grid(row=ui_row, column=0, sticky=tk.W) + self.station.grid(row=ui_row, column=1, sticky=tk.EW) + ui_row += 1 for plugin in plug.PLUGINS: appitem = plugin.get_app(frame) if appitem: tk.Frame(frame, highlightthickness=1).grid(columnspan=2, sticky=tk.EW) # separator if isinstance(appitem, tuple) and len(appitem) == 2: - row = frame.grid_size()[1] - appitem[0].grid(row=row, column=0, sticky=tk.W) - appitem[1].grid(row=row, column=1, sticky=tk.EW) + ui_row = frame.grid_size()[1] + appitem[0].grid(row=ui_row, column=0, sticky=tk.W) + appitem[1].grid(row=ui_row, column=1, sticky=tk.EW) + else: appitem.grid(columnspan=2, sticky=tk.EW) @@ -342,17 +419,21 @@ class AppWindow(object): self.theme_button = tk.Label(frame, width=32 if platform == 'darwin' else 28, state=tk.DISABLED) self.status = tk.Label(frame, name='status', anchor=tk.W) - row = frame.grid_size()[1] - self.button.grid(row=row, columnspan=2, sticky=tk.NSEW) - self.theme_button.grid(row=row, columnspan=2, sticky=tk.NSEW) + ui_row = frame.grid_size()[1] + self.button.grid(row=ui_row, columnspan=2, sticky=tk.NSEW) + self.theme_button.grid(row=ui_row, columnspan=2, sticky=tk.NSEW) theme.register_alternate((self.button, self.theme_button, self.theme_button), - {'row': row, 'columnspan': 2, 'sticky': tk.NSEW}) # noqa: E501 + {'row': ui_row, 'columnspan': 2, 'sticky': tk.NSEW}) self.status.grid(columnspan=2, sticky=tk.EW) self.button.bind('', self.getandsend) theme.button_bind(self.theme_button, self.getandsend) for child in frame.winfo_children(): - child.grid_configure(padx=5, pady=(platform != 'win32' or isinstance(child, tk.Frame)) and 2 or 0) + child.grid_configure(padx=self.PADX, pady=(platform != 'win32' or isinstance(child, tk.Frame)) and 2 or 0) + + # The type needs defining for adding the menu entry, but won't be + # properly set until later + self.updater: update.Updater = None self.menubar = tk.Menu() if platform == 'darwin': @@ -374,7 +455,7 @@ class AppWindow(object): self.menubar.add_cascade(menu=self.edit_menu) self.w.bind('', self.copy) self.view_menu = tk.Menu(self.menubar, name='view') - self.view_menu.add_command(command=lambda: stats.StatsDialog(self)) + self.view_menu.add_command(command=lambda: stats.StatsDialog(self.w, self.status)) self.menubar.add_cascade(menu=self.view_menu) window_menu = tk.Menu(self.menubar, name='window') self.menubar.add_cascade(menu=window_menu) @@ -393,17 +474,17 @@ 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) - self.file_menu.add_command(command=lambda: stats.StatsDialog(self)) + self.file_menu = self.view_menu = tk.Menu(self.menubar, tearoff=tk.FALSE) # type: ignore + 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) + self.edit_menu = tk.Menu(self.menubar, tearoff=tk.FALSE) # type: ignore 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) + self.help_menu = tk.Menu(self.menubar, tearoff=tk.FALSE) # type: ignore self.help_menu.add_command(command=self.help_general) self.help_menu.add_command(command=self.help_privacy) self.help_menu.add_command(command=self.help_releases) @@ -413,7 +494,7 @@ class AppWindow(object): self.menubar.add_cascade(menu=self.help_menu) if platform == 'win32': # Must be added after at least one "real" menu entry - self.always_ontop = tk.BooleanVar(value=config.getint('always_ontop')) + self.always_ontop = tk.BooleanVar(value=bool(config.get_int('always_ontop'))) self.system_menu = tk.Menu(self.menubar, name='system', tearoff=tk.FALSE) self.system_menu.add_separator() self.system_menu.add_checkbutton(label=_('Always on top'), @@ -434,7 +515,7 @@ class AppWindow(object): image=self.theme_icon, cursor='fleur', anchor=tk.W, compound=tk.LEFT) theme_titlebar.grid(columnspan=3, padx=2, sticky=tk.NSEW) - self.drag_offset = None + self.drag_offset: Tuple[Optional[int], Optional[int]] = (None, None) theme_titlebar.bind('', self.drag_start) theme_titlebar.bind('', self.drag_continue) theme_titlebar.bind('', self.drag_end) @@ -445,7 +526,7 @@ class AppWindow(object): theme_close.grid(row=0, column=4, padx=2) theme.button_bind(theme_close, self.onexit, image=self.theme_close) self.theme_file_menu = tk.Label(self.theme_menubar, anchor=tk.W) - self.theme_file_menu.grid(row=1, column=0, padx=5, sticky=tk.W) + self.theme_file_menu.grid(row=1, column=0, padx=self.PADX, sticky=tk.W) theme.button_bind(self.theme_file_menu, lambda e: self.file_menu.tk_popup(e.widget.winfo_rootx(), e.widget.winfo_rooty() @@ -462,7 +543,7 @@ class AppWindow(object): lambda e: self.help_menu.tk_popup(e.widget.winfo_rootx(), e.widget.winfo_rooty() + e.widget.winfo_height())) - tk.Frame(self.theme_menubar, highlightthickness=1).grid(columnspan=5, padx=5, sticky=tk.EW) + tk.Frame(self.theme_menubar, highlightthickness=1).grid(columnspan=5, padx=self.PADX, sticky=tk.EW) theme.register(self.theme_minimize) # images aren't automatically registered theme.register(self.theme_close) self.blank_menubar = tk.Frame(frame) @@ -474,13 +555,13 @@ class AppWindow(object): self.w.resizable(tk.TRUE, tk.FALSE) # update geometry - if config.get('geometry'): - match = re.match('\+([\-\d]+)\+([\-\d]+)', config.get('geometry')) # noqa: W605 + if config.get_str('geometry'): + match = re.match(r'\+([\-\d]+)\+([\-\d]+)', config.get_str('geometry')) if match: if platform == 'darwin': # http://core.tcl.tk/tk/tktview/c84f660833546b1b84e7 if int(match.group(2)) >= 0: - self.w.geometry(config.get('geometry')) + self.w.geometry(config.get_str('geometry')) elif platform == 'win32': # Check that the titlebar will be at least partly on screen import ctypes @@ -490,10 +571,11 @@ class AppWindow(object): MONITOR_DEFAULTTONULL = 0 # noqa: N806 if ctypes.windll.user32.MonitorFromPoint(POINT(int(match.group(1)) + 16, int(match.group(2)) + 16), MONITOR_DEFAULTTONULL): - self.w.geometry(config.get('geometry')) + self.w.geometry(config.get_str('geometry')) else: - self.w.geometry(config.get('geometry')) - self.w.attributes('-topmost', config.getint('always_ontop') and 1 or 0) + self.w.geometry(config.get_str('geometry')) + + self.w.attributes('-topmost', config.get_int('always_ontop') and 1 or 0) theme.register(frame) theme.apply(self.w) @@ -525,23 +607,64 @@ class AppWindow(object): self.updater = update.Updater(tkroot=self.w, provider='internal') self.updater.checkForUpdates() # Sparkle / WinSparkle does this automatically for packaged apps - try: - config.get_password('') # Prod SecureStorage on Linux to initialise - except RuntimeError: - pass - # Migration from <= 3.30 - for username in config.get('fdev_usernames') or []: + for username in config.get_list('fdev_usernames', default=[]): config.delete_password(username) - config.delete('fdev_usernames') - config.delete('username') - config.delete('password') - config.delete('logdir') + config.delete('fdev_usernames', suppress=True) + config.delete('username', suppress=True) + config.delete('password', suppress=True) + config.delete('logdir', suppress=True) self.postprefs(False) # Companion login happens in callback from monitor + self.toggle_suit_row(visible=False) - # callback after the Preferences dialog is applied - def postprefs(self, dologin=True): + def update_suit_text(self) -> None: + """Update the suit text for current type and loadout.""" + if (suit := monitor.state.get('SuitCurrent')) is None: + self.suit['text'] = f'<{_("Unknown")}>' + return + + suitname = suit['locName'] + + if (suitloadout := monitor.state.get('SuitLoadoutCurrent')) is None: + self.suit['text'] = '' + return + + loadout_name = suitloadout['name'] + self.suit['text'] = f'{suitname} ({loadout_name})' + + def toggle_suit_row(self, visible: Optional[bool] = 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 + + if not self.suit_shown: + if platform != 'win32': + pady = 2 + + else: + + pady = 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) + self.suit_shown = True + + else: + # Hide the Suit row + self.suit_label.grid_forget() + self.suit.grid_forget() + self.suit_shown = False + + def postprefs(self, dologin: bool = True): + """Perform necessary actions after the Preferences dialog is applied.""" self.prefsdialog = None self.set_labels() # in case language has changed @@ -551,7 +674,7 @@ class AppWindow(object): self.station.configure(url=self.station_url) # (Re-)install hotkey monitoring - hotkeymgr.register(self.w, config.getint('hotkey_code'), config.getint('hotkey_mods')) + hotkeymgr.register(self.w, config.get_int('hotkey_code'), config.get_int('hotkey_mods')) # Update Journal lock if needs be. journal_lock.update_lock(self.w) @@ -563,11 +686,12 @@ class AppWindow(object): if dologin and monitor.cmdr: self.login() # Login if not already logged in with this Cmdr - # set main window labels, e.g. after language change def set_labels(self): + """Set main window labels, e.g. after language change.""" self.cmdr_label['text'] = _('Cmdr') + ':' # Main window # Multicrew role label in main window self.ship_label['text'] = (monitor.state['Captain'] and _('Role') or _('Ship')) + ':' # Main window + self.suit_label['text'] = _('Suit') + ':' # Main window self.system_label['text'] = _('System') + ':' # Main window self.station_label['text'] = _('Station') + ':' # Main window self.button['text'] = self.theme_button['text'] = _('Update') # Update button in main window @@ -608,38 +732,89 @@ class AppWindow(object): self.edit_menu.entryconfigure(0, label=_('Copy')) # As in Copy and Paste def login(self): + """Initiate CAPI/Frontier login and set other necessary state.""" if not self.status['text']: self.status['text'] = _('Logging in...') + self.button['state'] = self.theme_button['state'] = tk.DISABLED + if platform == 'darwin': self.view_menu.entryconfigure(0, state=tk.DISABLED) # Status self.file_menu.entryconfigure(0, state=tk.DISABLED) # Save Raw Data + else: self.file_menu.entryconfigure(0, state=tk.DISABLED) # Status self.file_menu.entryconfigure(1, state=tk.DISABLED) # Save Raw Data + self.w.update_idletasks() try: if companion.session.login(monitor.cmdr, monitor.is_beta): # Successfully authenticated with the Frontier website self.status['text'] = _('Authentication successful') + if platform == 'darwin': self.view_menu.entryconfigure(0, state=tk.NORMAL) # Status self.file_menu.entryconfigure(0, state=tk.NORMAL) # Save Raw Data + else: self.file_menu.entryconfigure(0, state=tk.NORMAL) # Status self.file_menu.entryconfigure(1, state=tk.NORMAL) # Save Raw Data + except (companion.CredentialsError, companion.ServerError, companion.ServerLagging) as e: self.status['text'] = str(e) + except Exception as e: logger.debug('Frontier CAPI Auth', exc_info=e) self.status['text'] = str(e) + self.cooldown() - def getandsend(self, event=None, retrying=False): # noqa: C901 + def export_market_data(self, data: CAPIData) -> bool: # noqa: CCR001 + """ + Export CAPI market data. + :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 + self.status['text'] = _("You're not docked at a station!") + return False + + # Ignore possibly missing shipyard info + elif (config.get_int('output') & config.OUT_MKT_EDDN) \ + and not (data['lastStarport'].get('commodities') or data['lastStarport'].get('modules')): + if not self.status['text']: + self.status['text'] = _("Station doesn't have anything!") + + elif not data['lastStarport'].get('commodities'): + if not self.status['text']: + self.status['text'] = _("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 + fixed = companion.fixup(data) + if config.get_int('output') & config.OUT_MKT_CSV: + commodity.export(fixed, COMMODITY_CSV) + + if config.get_int('output') & config.OUT_MKT_TD: + td.export(fixed) + + return True + + def getandsend(self, event=None, retrying: bool = False): # noqa: C901, CCR001 + """ + Perform CAPI data retrieval and associated actions. + + This can be triggered by hitting the main UI 'Update' button, + automatically on docking, or due to a retry. + """ auto_update = not event - play_sound = (auto_update or int(event.type) == self.EVENT_VIRTUAL) and not config.getint('hotkey_mute') + play_sound = (auto_update or int(event.type) == self.EVENT_VIRTUAL) and not config.get_int('hotkey_mute') play_bad = False + err: Optional[str] = None if not monitor.cmdr or not monitor.mode or monitor.state['Captain'] or not monitor.system: return # In CQC or on crew - do nothing @@ -651,12 +826,15 @@ class AppWindow(object): if not retrying: if time() < self.holdofftime: # Was invoked by key while in cooldown - self.status['text'] = '' if play_sound and (self.holdofftime - time()) < companion.holdoff * 0.75: + self.status['text'] = '' hotkeymgr.play_bad() # Don't play sound in first few seconds to prevent repeats + return + elif play_sound: hotkeymgr.play_good() + self.status['text'] = _('Fetching data...') self.button['state'] = self.theme_button['state'] = tk.DISABLED self.w.update_idletasks() @@ -669,50 +847,86 @@ class AppWindow(object): # Validation if 'commander' not in data: # This can happen with EGS Auth if no commander created yet - self.status['text'] = _('CAPI: No commander data returned') + err = self.status['text'] = _('CAPI: No commander data returned') elif not data.get('commander', {}).get('name'): - self.status['text'] = _("Who are you?!") # Shouldn't happen + err = self.status['text'] = _("Who are you?!") # Shouldn't happen elif (not data.get('lastSystem', {}).get('name') or (data['commander'].get('docked') - and not data.get('lastStarport', {}).get('name'))): # Only care if docked - self.status['text'] = _("Where are you?!") # Shouldn't happen + and not data.get('lastStarport', {}).get('name'))): + err = self.status['text'] = _("Where are you?!") # Shouldn't happen elif not data.get('ship', {}).get('name') or not data.get('ship', {}).get('modules'): - self.status['text'] = _("What are you flying?!") # Shouldn't happen + err = self.status['text'] = _("What are you flying?!") # Shouldn't happen elif monitor.cmdr and data['commander']['name'] != monitor.cmdr: - # Companion API return doesn't match Journal + # Companion API Commander doesn't match Journal raise companion.CmdrError() - elif ((auto_update and not data['commander'].get('docked')) - or (data['lastSystem']['name'] != monitor.system) - or ((data['commander']['docked'] - and data['lastStarport']['name'] or None) != monitor.station) - or (data['ship']['id'] != monitor.state['ShipID']) - or (data['ship']['name'].lower() != monitor.state['ShipType'])): + elif auto_update and not monitor.state['OnFoot'] and not data['commander'].get('docked'): + # auto update is only when just docked + raise companion.ServerLagging() + + elif data['lastSystem']['name'] != monitor.system: + # CAPI system must match last journal one + raise companion.ServerLagging() + + elif data['lastStarport']['name'] != monitor.station: + if monitor.state['OnFoot'] and monitor.station: + raise companion.ServerLagging() + + else: + last_station = None + if data['commander']['docked']: + last_station = data['lastStarport']['name'] + + if last_station != monitor.station: + # CAPI lastStarport must match + raise companion.ServerLagging() + + self.holdofftime = querytime + companion.holdoff + + elif not monitor.state['OnFoot'] and data['ship']['id'] != monitor.state['ShipID']: + # CAPI ship must match + raise companion.ServerLagging() + + elif not monitor.state['OnFoot'] and data['ship']['name'].lower() != monitor.state['ShipType']: + # CAPI ship type must match raise companion.ServerLagging() else: - if __debug__: # Recording - if isdir('dump'): - with open('dump/{system}{station}.{timestamp}.json'.format( - system=data['lastSystem']['name'], - station=data['commander'].get('docked') and '.' + data['lastStarport']['name'] or '', - timestamp=strftime('%Y-%m-%dT%H.%M.%S', localtime())), 'wb') as h: - h.write(json.dumps(dict(data), - ensure_ascii=False, - indent=2, - sort_keys=True, - separators=(',', ': ')).encode('utf-8')) + companion.session.dump_capi_data(data) if not monitor.state['ShipType']: # Started game in SRV or fighter - self.ship['text'] = companion.ship_map.get(data['ship']['name'].lower(), data['ship']['name']) + self.ship['text'] = ship_name_map.get(data['ship']['name'].lower(), data['ship']['name']) monitor.state['ShipID'] = data['ship']['id'] monitor.state['ShipType'] = data['ship']['name'].lower() + if not monitor.state['Modules']: + self.ship.configure(state=tk.DISABLED) + + # We might have disabled this in the conditional above. + if monitor.state['Modules']: + self.ship.configure(state=True) + + if monitor.state.get('SuitCurrent') is not None: + if (loadout := data.get('loadout')) is not None: + if (suit := loadout.get('suit')) is not None: + if (suitname := suit.get('locName')) is not None: + # We've been paranoid about loadout->suit->suitname, now just assume loadouts is there + loadout_name = index_possibly_sparse_list( + data['loadouts'], loadout['loadoutSlotId'] + )['name'] + + self.suit['text'] = f'{suitname} ({loadout_name})' + + self.toggle_suit_row(visible=True) + + else: + self.toggle_suit_row(visible=False) + if data['commander'].get('credits') is not None: monitor.state['Credits'] = data['commander']['credits'] monitor.state['Loan'] = data['commander'].get('debt', 0) @@ -724,85 +938,44 @@ class AppWindow(object): play_bad = True # Export market data - if config.getint('output') & (config.OUT_STATION_ANY): - if not data['commander'].get('docked'): - 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 - self.status['text'] = _("You're not docked at a station!") - play_bad = True - # Ignore possibly missing shipyard info - elif (config.getint('output') & config.OUT_MKT_EDDN) \ - and not (data['lastStarport'].get('commodities') or data['lastStarport'].get('modules')): - if not self.status['text']: - self.status['text'] = _("Station doesn't have anything!") - elif not data['lastStarport'].get('commodities'): - if not self.status['text']: - self.status['text'] = _("Station doesn't have a market!") - elif config.getint('output') & (config.OUT_MKT_CSV | config.OUT_MKT_TD): - # Fixup anomalies in the commodity data - fixed = companion.fixup(data) - if config.getint('output') & config.OUT_MKT_CSV: - commodity.export(fixed, COMMODITY_CSV) - if config.getint('output') & config.OUT_MKT_TD: - td.export(fixed) + if not self.export_market_data(data): + err = 'Error: Exporting Market data' + play_bad = True self.holdofftime = querytime + companion.holdoff # Companion API problem except companion.ServerLagging as e: + err = str(e) if retrying: - self.status['text'] = str(e) + self.status['text'] = err play_bad = True + else: # Retry once if Companion server is unresponsive self.w.after(int(SERVER_RETRY * 1000), lambda: self.getandsend(event, True)) return # early exit to avoid starting cooldown count except companion.CmdrError as e: # Companion API return doesn't match Journal - self.status['text'] = str(e) + err = self.status['text'] = str(e) play_bad = True companion.session.invalidate() self.login() except Exception as e: # Including CredentialsError, ServerError logger.debug('"other" exception', exc_info=e) - self.status['text'] = str(e) + err = self.status['text'] = str(e) play_bad = True - if not self.status['text']: # no errors + if not err: # not self.status['text']: # no errors self.status['text'] = strftime(_('Last updated at %H:%M:%S'), localtime(querytime)) + if play_sound and play_bad: hotkeymgr.play_bad() self.cooldown() - def retry_for_shipyard(self, tries): - # Try again to get shipyard data and send to EDDN. Don't report errors if can't get or send the data. - try: - data = companion.session.station() - if data['commander'].get('docked'): - if data.get('lastStarport', {}).get('ships'): - report = 'Success' - else: - report = 'Failure' - else: - report = 'Undocked!' - logger.debug(f'Retry for shipyard - {report}') - if not data['commander'].get('docked'): - # might have un-docked while we were waiting for retry in which case station data is unreliable - pass - elif (data.get('lastSystem', {}).get('name') == monitor.system and - data.get('lastStarport', {}).get('name') == monitor.station and - data.get('lastStarport', {}).get('ships', {}).get('shipyard_list')): - self.eddn.export_shipyard(data, monitor.is_beta) - elif tries > 1: # bogus data - retry - self.w.after(int(SERVER_RETRY * 1000), lambda: self.retry_for_shipyard(tries - 1)) - except Exception: - pass - - # Handle event(s) from the journal - def journal_event(self, event: str): # noqa: C901 + def journal_event(self, event): # noqa: C901, CCR001 # Currently not easily broken up. """ Handle a Journal event passed through event queue from monitor.py. @@ -810,8 +983,12 @@ class AppWindow(object): :return: """ - def crewroletext(role): - # Return translated crew role. Needs to be dynamic to allow for changing language. + def crewroletext(role: str) -> str: + """ + Return translated crew role. + + Needs to be dynamic to allow for changing language. + """ return { None: '', 'Idle': '', @@ -824,10 +1001,11 @@ class AppWindow(object): logger.debug('monitor.thread is None, assuming shutdown and returning') return - while True: + while not monitor.event_queue.empty(): entry = monitor.get_entry() if not entry: - logger.trace('No entry from monitor.get_entry()') + # This is expected due to some monitor.py code that appends `None` + # logger.trace('No entry from monitor.get_entry()') return # Update main window @@ -836,22 +1014,45 @@ class AppWindow(object): self.cmdr['text'] = f'{monitor.cmdr} / {monitor.state["Captain"]}' self.ship_label['text'] = _('Role') + ':' # Multicrew role label in main window self.ship.configure(state=tk.NORMAL, text=crewroletext(monitor.state['Role']), url=None) + elif monitor.cmdr: if monitor.group: self.cmdr['text'] = f'{monitor.cmdr} / {monitor.group}' + else: self.cmdr['text'] = monitor.cmdr + self.ship_label['text'] = _('Ship') + ':' # Main window - self.ship.configure( - text=monitor.state['ShipName'] - or companion.ship_map.get(monitor.state['ShipType'], monitor.state['ShipType']) - or '', - url=self.shipyard_url) + + # TODO: Show something else when on_foot + if monitor.state['ShipName']: + ship_text = monitor.state['ShipName'] + + else: + ship_text = ship_name_map.get(monitor.state['ShipType'], monitor.state['ShipType']) + + if not ship_text: + ship_text = '' + + # Ensure the ship type/name text is clickable, if it should be. + if monitor.state['Modules']: + ship_state = True + + else: + ship_state = tk.DISABLED + + self.ship.configure(text=ship_text, url=self.shipyard_url, state=ship_state) + else: self.cmdr['text'] = '' self.ship_label['text'] = _('Ship') + ':' # Main window self.ship['text'] = '' + if monitor.cmdr and monitor.is_beta: + self.cmdr['text'] += ' (beta)' + + self.update_suit_text() + self.edit_menu.entryconfigure(0, state=monitor.system and tk.NORMAL or tk.DISABLED) # Copy if entry['event'] in ( @@ -870,34 +1071,36 @@ class AppWindow(object): 'Synthesis', 'JoinACrew'): self.status['text'] = '' # Periodically clear any old error + self.w.update_idletasks() # Companion login if entry['event'] in [None, 'StartUp', 'NewCommander', 'LoadGame'] and monitor.cmdr: - if not config.get('cmdrs') or monitor.cmdr not in config.get('cmdrs'): - config.set('cmdrs', (config.get('cmdrs') or []) + [monitor.cmdr]) + if not config.get_list('cmdrs') or monitor.cmdr not in config.get_list('cmdrs'): + config.set('cmdrs', config.get_list('cmdrs', default=[]) + [monitor.cmdr]) self.login() if not entry['event'] or not monitor.mode: - logger.trace('Startup or in CQC, returning') + # logger.trace('Startup or in CQC, returning') return # Startup or in CQC if entry['event'] in ['StartUp', 'LoadGame'] and monitor.started: logger.info('Startup or LoadGame event') + # Disable WinSparkle automatic update checks, IFF configured to do so when in-game - if config.getint('disable_autoappupdatecheckingame') and 1: + if config.get_int('disable_autoappupdatecheckingame') and 1: self.updater.setAutomaticUpdatesCheck(False) logger.info('Monitor: Disable WinSparkle automatic update checks') - # Can start dashboard monitoring + + # Can't start dashboard monitoring if not dashboard.start(self.w, monitor.started): logger.info("Can't start Status monitoring") # Export loadout if entry['event'] == 'Loadout' and not monitor.state['Captain'] \ - and config.getint('output') & config.OUT_SHIP: + and config.get_int('output') & config.OUT_SHIP: monitor.export_ship() - # Plugins err = plug.notify_journal_entry(monitor.cmdr, monitor.is_beta, monitor.system, @@ -906,15 +1109,32 @@ class AppWindow(object): monitor.state) if err: self.status['text'] = err - if not config.getint('hotkey_mute'): + if not config.get_int('hotkey_mute'): hotkeymgr.play_bad() - # Auto-Update after docking, but not if auth callback is pending - if entry['event'] in ('StartUp', 'Location', 'Docked') \ - and monitor.station \ - and not config.getint('output') & config.OUT_MKT_MANUAL \ - and config.getint('output') & config.OUT_STATION_ANY \ - and companion.session.state != companion.Session.STATE_AUTH: + auto_update = False + # Only if auth callback is not pending + if companion.session.state != companion.Session.STATE_AUTH: + # Only if configured to do so + if (not config.get_int('output') & config.OUT_MKT_MANUAL + and config.get_int('output') & config.OUT_STATION_ANY): + if entry['event'] in ('StartUp', 'Location', 'Docked') and monitor.station: + # TODO: Can you log out in a docked Taxi and then back in to + # the taxi, so 'Location' should be covered here too ? + if entry['event'] == 'Docked' and entry.get('Taxi'): + # In Odyssey there's a 'Docked' event for an Apex taxi, + # but the CAPI data isn't updated until you Disembark. + auto_update = False + + else: + auto_update = True + + # In Odyssey if you are in a Taxi the `Docked` event for it is before + # the CAPI data is updated, but CAPI *is* updated after you `Disembark`. + elif entry['event'] == 'Disembark' and entry.get('Taxi') and entry.get('OnStation'): + auto_update = True + + if auto_update: self.w.after(int(SERVER_RETRY * 1000), self.getandsend) if entry['event'] == 'ShutDown': @@ -923,9 +1143,14 @@ class AppWindow(object): self.updater.setAutomaticUpdatesCheck(True) logger.info('Monitor: Enable WinSparkle automatic update checks') - # cAPI auth - def auth(self, event=None): - logger.debug('Received "<>') + def auth(self, event=None) -> None: + """ + Handle Frontier auth callback. + + This is the callback function for the CompanionAuthEvent Tk event. + It is triggered by the event() function of class GenericProtocolHandler + in protocol.py. + """ try: companion.session.auth_callback() # Successfully authenticated with the Frontier website @@ -947,33 +1172,48 @@ class AppWindow(object): self.cooldown() - # Handle Status event - def dashboard_event(self, event): - entry = dashboard.status - if entry: - # Currently we don't do anything with these events - err = plug.notify_dashboard_entry(monitor.cmdr, monitor.is_beta, entry) - if err: - self.status['text'] = err - if not config.getint('hotkey_mute'): - hotkeymgr.play_bad() + def dashboard_event(self, event) -> None: + """ + Handle DashBoardEvent tk event. - # Display asynchronous error from plugin - def plugin_error(self, event=None): + Event is sent by code in dashboard.py. + """ + if not dashboard.status: + return + + entry = dashboard.status + # Currently we don't do anything with these events + err = plug.notify_dashboard_entry(monitor.cmdr, monitor.is_beta, entry) + if err: + self.status['text'] = err + if not config.get_int('hotkey_mute'): + hotkeymgr.play_bad() + + def plugin_error(self, event=None) -> None: + """Display asynchronous error from plugin.""" if plug.last_error.get('msg'): self.status['text'] = plug.last_error['msg'] self.w.update_idletasks() - if not config.getint('hotkey_mute'): + if not config.get_int('hotkey_mute'): hotkeymgr.play_bad() - def shipyard_url(self, shipname): - if not bool(config.getint("use_alt_shipyard_open")): - return plug.invoke(config.get('shipyard_provider'), 'EDSY', 'shipyard_url', monitor.ship(), monitor.is_beta) + def shipyard_url(self, shipname: str) -> str: + """Despatch a ship URL to the configured handler.""" + if not (loadout := monitor.ship()): + logger.warning('No ship loadout, aborting.') + return '' + + if not bool(config.get_int("use_alt_shipyard_open")): + return plug.invoke(config.get_str('shipyard_provider'), + 'EDSY', + 'shipyard_url', + loadout, + monitor.is_beta) # Avoid file length limits if possible - provider = config.get('shipyard_provider') or 'EDSY' - target = plug.invoke(config.get('shipyard_provider'), 'EDSY', 'shipyard_url', monitor.ship(), monitor.is_beta) - file_name = join(config.app_dir, "last_shipyard.html") + 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") with open(file_name, 'w') as f: print(SHIPYARD_HTML_TEMPLATE.format( @@ -984,18 +1224,22 @@ class AppWindow(object): return f'file://localhost/{file_name}' - def system_url(self, system): - return plug.invoke(config.get('system_provider'), 'EDSM', 'system_url', monitor.system) + def system_url(self, system: str) -> str: + """Despatch a system URL to the configured handler.""" + return plug.invoke(config.get_str('system_provider'), 'EDSM', 'system_url', monitor.system) - def station_url(self, station): - return plug.invoke(config.get('station_provider'), 'eddb', 'station_url', monitor.system, monitor.station) + def station_url(self, station: str) -> str: + """Despatch a station URL to the configured handler.""" + return plug.invoke(config.get_str('station_provider'), 'eddb', 'station_url', monitor.system, monitor.station) - def cooldown(self): + def cooldown(self) -> None: + """Display and update the cooldown timer for 'Update' button.""" if time() < self.holdofftime: # Update button in main window self.button['text'] = self.theme_button['text'] \ = _('cooldown {SS}s').format(SS=int(self.holdofftime - time())) self.w.after(1000, self.cooldown) + else: self.button['text'] = self.theme_button['text'] = _('Update') # Update button in main window self.button['state'] = self.theme_button['state'] = (monitor.cmdr and @@ -1004,30 +1248,38 @@ class AppWindow(object): monitor.system and tk.NORMAL or tk.DISABLED) - def ontop_changed(self, event=None): + def ontop_changed(self, event=None) -> None: + """Set main window 'on top' state as appropriate.""" config.set('always_ontop', self.always_ontop.get()) self.w.wm_attributes('-topmost', self.always_ontop.get()) - def copy(self, event=None): + def copy(self, event=None) -> None: + """Copy system, and possible station, name to clipboard.""" if monitor.system: self.w.clipboard_clear() self.w.clipboard_append(monitor.station and f'{monitor.system},{monitor.station}' or monitor.system) - def help_general(self, event=None): + def help_general(self, event=None) -> None: + """Open Wiki Help page in browser.""" webbrowser.open('https://github.com/EDCD/EDMarketConnector/wiki') - def help_privacy(self, event=None): + def help_privacy(self, event=None) -> None: + """Open Wiki Privacy page in browser.""" webbrowser.open('https://github.com/EDCD/EDMarketConnector/wiki/Privacy-Policy') - def help_releases(self, event=None): + def help_releases(self, event=None) -> None: + """Open Releases page in browser.""" webbrowser.open('https://github.com/EDCD/EDMarketConnector/releases') class HelpAbout(tk.Toplevel): + """The applications Help > About popup.""" + showing = False - def __init__(self, parent): + def __init__(self, parent: tk.Tk): if self.__class__.showing: return + self.__class__.showing = True tk.Toplevel.__init__(self, parent) @@ -1064,11 +1316,11 @@ class AppWindow(object): # version ttk.Label(frame).grid(row=row, column=0) # spacer row += 1 - self.appversion_label = tk.Label(frame, text=appversion) + self.appversion_label = tk.Label(frame, text=appversion()) self.appversion_label.grid(row=row, column=0, sticky=tk.E) self.appversion = HyperlinkLabel(frame, compound=tk.RIGHT, text=_('Release Notes'), url='https://github.com/EDCD/EDMarketConnector/releases/tag/Release/' - f'{appversion_nobuild}', + f'{appversion_nobuild()}', underline=True) self.appversion.grid(row=row, column=2, sticky=tk.W) row += 1 @@ -1097,36 +1349,45 @@ class AppWindow(object): self.protocol("WM_DELETE_WINDOW", self._destroy) ############################################################ - logger.info(f'Current version is {appversion}') + logger.info(f'Current version is {appversion()}') - def apply(self): + def apply(self) -> None: + """Close the window.""" self._destroy() - def _destroy(self): - self.parent.wm_attributes('-topmost', config.getint('always_ontop') and 1 or 0) + def _destroy(self) -> None: + """Set parent window's topmost appropriately as we close.""" + self.parent.wm_attributes('-topmost', config.get_int('always_ontop') and 1 or 0) self.destroy() self.__class__.showing = False - def save_raw(self): + def save_raw(self) -> None: # noqa: CCR001 # Not easily broken up. + """Save newly acquired CAPI data in the configured file.""" self.status['text'] = _('Fetching data...') self.w.update_idletasks() try: - data = companion.session.station() + data: CAPIData = companion.session.station() self.status['text'] = '' default_extension: str = '' + if platform == 'darwin': default_extension = '.json' + last_system: str = data.get("lastSystem", {}).get("name", "Unknown") last_starport: str = '' + if data['commander'].get('docked'): last_starport = '.' + data.get('lastStarport', {}).get('name', 'Unknown') + timestamp: str = strftime('%Y-%m-%dT%H.%M.%S', localtime()) - f = tkinter.filedialog.asksaveasfilename(parent=self.w, - defaultextension=default_extension, - filetypes=[('JSON', '.json'), ('All Files', '*')], - initialdir=config.get('outdir'), - initialfile=f'{last_system}{last_starport}.{timestamp}') + f = tkinter.filedialog.asksaveasfilename( + parent=self.w, + defaultextension=default_extension, + filetypes=[('JSON', '.json'), ('All Files', '*')], + initialdir=config.get_str('outdir'), + initialfile=f'{last_system}{last_starport}.{timestamp}' + ) if f: with open(f, 'wb') as h: h.write(json.dumps(dict(data), @@ -1136,11 +1397,24 @@ class AppWindow(object): separators=(',', ': ')).encode('utf-8')) except companion.ServerError as e: self.status['text'] = str(e) + except Exception as e: logger.debug('"other" exception', exc_info=e) self.status['text'] = str(e) - def onexit(self, event=None): + # def exit_tray(self, systray: 'SysTrayIcon') -> None: + # """Tray icon is shutting down.""" + # exit_thread = threading.Thread(target=self.onexit) + # exit_thread.setDaemon(True) + # exit_thread.start() + + def onexit(self, event=None) -> None: + """Application shutdown procedure.""" + # if platform == 'win32': + # shutdown_thread = threading.Thread(target=self.systray.shutdown) + # shutdown_thread.setDaemon(True) + # shutdown_thread.start() + config.set_shutdown() # Signal we're in shutdown now. # http://core.tcl.tk/tk/tktview/c84f660833546b1b84e7 @@ -1195,44 +1469,57 @@ class AppWindow(object): """Initiate dragging the window.""" self.drag_offset = (event.x_root - self.w.winfo_rootx(), event.y_root - self.w.winfo_rooty()) - def drag_continue(self, event): - if self.drag_offset: + def drag_continue(self, event) -> None: + """Continued handling of window drag.""" + if self.drag_offset[0]: offset_x = event.x_root - self.drag_offset[0] offset_y = event.y_root - self.drag_offset[1] self.w.geometry(f'+{offset_x:d}+{offset_y:d}') - def drag_end(self, event): - self.drag_offset = None + def drag_end(self, event) -> None: + """Handle end of window dragging.""" + self.drag_offset = (None, None) - def oniconify(self, event=None): + def oniconify(self, event=None) -> None: + """Handle minimization of the application.""" self.w.overrideredirect(0) # Can't iconize while overrideredirect self.w.iconify() self.w.update_idletasks() # Size and windows styles get recalculated here self.w.wait_visibility() # Need main window to be re-created before returning theme.active = None # So theme will be re-applied on map - def onmap(self, event=None): + # TODO: Confirm this is unused and remove. + def onmap(self, event=None) -> None: + """Perform a now unused function.""" if event.widget == self.w: theme.apply(self.w) - def onenter(self, event=None): - if config.getint('theme') > 1: + def onenter(self, event=None) -> None: + """Handle when our window gains focus.""" + # TODO: This assumes that 1) transparent is at least 2, 2) there are + # no new themes added after that. + if config.get_int('theme') > 1: self.w.attributes("-transparentcolor", '') self.blank_menubar.grid_remove() self.theme_menubar.grid(row=0, columnspan=2, sticky=tk.NSEW) - def onleave(self, event=None): - if config.getint('theme') > 1 and event.widget == self.w: + def onleave(self, event=None) -> None: + """Handle when our window loses focus.""" + # TODO: This assumes that 1) transparent is at least 2, 2) there are + # no new themes added after that. + if config.get_int('theme') > 1 and event.widget == self.w: self.w.attributes("-transparentcolor", 'grey4') self.theme_menubar.grid_remove() self.blank_menubar.grid(row=0, columnspan=2, sticky=tk.NSEW) -def test_logging(): +def test_logging() -> None: + """Simple test of top level logging.""" logger.debug('Test from EDMarketConnector.py top-level test_logging()') def log_locale(prefix: str) -> None: + """Log all of the current local settings.""" logger.debug(f'''Locale: {prefix} Locale LC_COLLATE: {locale.getlocale(locale.LC_COLLATE)} Locale LC_CTYPE: {locale.getlocale(locale.LC_CTYPE)} @@ -1242,9 +1529,53 @@ Locale LC_TIME: {locale.getlocale(locale.LC_TIME)}''' ) +def setup_killswitches(): + """Download and setup the main killswitch list.""" + logger.debug('fetching killswitches...') + killswitch.setup_main_list() + + +def show_killswitch_poppup(root=None): + """Show a warning popup if there are any killswitches that match the current version.""" + if len(kills := killswitch.kills_for_version()) == 0: + return + + text = ( + "Some EDMC Features have been disabled due to known issues.\n" + "Please update EDMC as soon as possible to resolve any issues.\n" + ) + + tl = tk.Toplevel(root) + tl.wm_attributes('-topmost', True) + tl.geometry(f'+{root.winfo_rootx()}+{root.winfo_rooty()}') + + tl.columnconfigure(1, weight=1) + tl.title("EDMC Features have been disabled") + + frame = tk.Frame(tl) + frame.grid() + t = tk.Label(frame, text=text) + t.grid(columnspan=2) + idx = 1 + + for version in kills: + tk.Label(frame, text=f'Version: {version.version}').grid(row=idx, sticky=tk.W) + idx += 1 + for id, reason in version.kills.items(): + tk.Label(frame, text=id).grid(column=0, row=idx, sticky=tk.W, padx=(10, 0)) + tk.Label(frame, text=reason).grid(column=1, row=idx, sticky=tk.E, padx=(0, 10)) + idx += 1 + idx += 1 + + ok_button = tk.Button(frame, text="ok", command=tl.destroy) + ok_button.grid(columnspan=2, sticky=tk.EW) + + theme.apply(tl) + + # Run the app -if __name__ == "__main__": # noqa C901 - logger.info(f'Startup v{appversion} : Running on Python v{sys.version}') +if __name__ == "__main__": # noqa: C901 + logger.info(f'Startup v{appversion()} : Running on Python v{sys.version}') logger.debug(f'''Platform: {sys.platform} {sys.platform == "win32" and sys.getwindowsversion()} argv[0]: {sys.argv[0]} exec_prefix: {sys.exec_prefix} @@ -1252,6 +1583,13 @@ executable: {sys.executable} sys.path: {sys.path}''' ) + if args.reset_ui: + config.set('theme', 0) # 'Default' theme uses ID 0 + config.set('ui_transparency', 100) # 100 is completely opaque + config.delete('font') + config.delete('font_size') + logger.info('reset theme, font, font size, and transparency to default.') + # We prefer a UTF-8 encoding gets set, but older Windows versions have # issues with this. From Windows 10 1903 onwards we can rely on the # manifest ActiveCodePage to set this, but that is silently ignored on @@ -1259,6 +1597,9 @@ sys.path: {sys.path}''' # Trying to set a UTF-8 encoding on those older versions will fail with # locale.Error: unsupported locale setting # but we do need to make the attempt for when we're running from source. + # + # Note that this locale magic is partially done in l10n.py as well. So + # removing or modifying this may or may not have the desired effect. log_locale('Initial Locale') try: @@ -1301,7 +1642,8 @@ sys.path: {sys.path}''' except Exception: logger.exception( - f"Exception other than locale.Error on setting LC_ALL=('{locale_startup[0]}', 'UTF_8')") + f"Exception other than locale.Error on setting LC_ALL=('{locale_startup[0]}', 'UTF_8')" + ) else: log_locale('After switching to UTF-8 encoding (same language)') @@ -1311,8 +1653,10 @@ sys.path: {sys.path}''' # test_logging() class A(object): + """Simple top-level class.""" class B(object): + """Simple second-level class.""" def __init__(self): logger.debug('A call from A.B.__init__') @@ -1324,23 +1668,32 @@ sys.path: {sys.path}''' @property def test_prop(self): + """Test property.""" logger.debug("test log from property") return "Test property is testy" # abinit = A.B() # Plain, not via `logger` - print(f'{applongname} {appversion}') + print(f'{applongname} {appversion()}') - Translations.install(config.get('language') or None) # Can generate errors so wait til log set up + Translations.install(config.get_str('language')) # Can generate errors so wait til log set up + setup_killswitches() root = tk.Tk(className=appname.lower()) + if sys.platform != 'win32' and ((f := config.get_str('font')) is not None or f != ''): + size = config.get_int('font_size', default=-1) + if size == -1: + size = 10 + + logger.info(f'Overriding tkinter default font to {f!r} at size {size}') + tk.font.nametofont('TkDefaultFont').configure(family=f, size=size) # UI Scaling """ We scale the UI relative to what we find tk-scaling is on startup. """ - ui_scale = config.getint('ui_scale') + ui_scale = config.get_int('ui_scale') # NB: This *also* catches a literal 0 value to re-set to the default 100 if not ui_scale: ui_scale = 100 @@ -1352,7 +1705,8 @@ sys.path: {sys.path}''' app = AppWindow(root) def messagebox_not_py3(): - plugins_not_py3_last = config.getint('plugins_not_py3_last') or 0 + """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): # Yes, this is horribly hacky so as to be sure we match the key # that we told Translators to use. @@ -1378,7 +1732,15 @@ sys.path: {sys.path}''' ) config.set('plugins_not_py3_last', int(time())) + # 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) root.mainloop() logger.info('Exiting') diff --git a/EDMarketConnector.wxs b/EDMarketConnector.wxs index f0545442..c24a594f 100644 --- a/EDMarketConnector.wxs +++ b/EDMarketConnector.wxs @@ -113,12 +113,18 @@ + + + + + + @@ -128,6 +134,12 @@ + + + + + + @@ -140,6 +152,9 @@ + + + @@ -167,6 +182,9 @@ + + + @@ -179,8 +197,8 @@ - - + + @@ -200,12 +218,6 @@ - - - - - - @@ -227,6 +239,12 @@ + + + + + + @@ -543,15 +561,21 @@ + + + + + + @@ -568,18 +592,19 @@ + + - - + - + @@ -590,9 +615,7 @@ - - @@ -601,6 +624,7 @@ + diff --git a/L10n/cs.strings b/L10n/cs.strings index 253b8d23..04a566a6 100644 --- a/L10n/cs.strings +++ b/L10n/cs.strings @@ -1,12 +1,12 @@ -/* Label for 'UI Scaling' option [prefs.py] */ -"UI Scale Percentage" = "Procenta UI škálování"; +/* Language name */ +"!Language" = "Čeština"; + +/* Message next to 'UI Transparency' slider [prefs.py] */ +"100 means fully opaque.{CR}Window is updated in real time" = "100 znamená plně neprůhledné.{CR}Okno se aktualizuje v reálném čase"; /* Text describing that value '100' means 'default', and changes require a restart [prefs.py] */ "100 means Default{CR}Restart Required for{CR}changes to take effect!" = "100 je výchozí hodnota{CR}je potřeba restartovat,{CR}aby se změna projevila!"; -/* Language name */ -"!Language" = "Čeština"; - /* App menu entry on OSX. [EDMarketConnector.py] */ "About {APP}" = "O {APP}"; @@ -46,12 +46,12 @@ /* Folder selection button on Windows. [prefs.py] */ "Browse..." = "Procházet..."; -/* No 'commander' data in CAPI [EDMarketConnector.py] */ -"CAPI: No commander data returned" = "CAPI: Nebyla vrácena žádná data komandéra"; - /* Federation rank. [stats.py] */ "Cadet" = "Cadet"; +/* No 'commander' data in CAPI [EDMarketConnector.py] */ +"CAPI: No commander data returned" = "CAPI: Nebyla vrácena žádná data komandéra"; + /* CQC rank. [stats.py] */ "Champion" = "Champion"; @@ -130,6 +130,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "Upravit"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC: Pluginy, které nepodporují Python 3.x"; + /* Top rank. [stats.py] */ "Elite" = "Elite"; @@ -148,6 +151,9 @@ /* Trade rank. [stats.py] */ "Entrepreneur" = "Entrepreneur"; +/* [companion.py] */ +"Error" = "Chyba"; + /* [eddn.py] */ "Error: Can't connect to EDDN" = "Chyba: Nelze se připojit k EDDN"; @@ -157,6 +163,12 @@ /* [inara.py] */ "Error: Can't connect to Inara" = "Chyba: Nelze se připojit k Inaře"; +/* [companion.py] */ +"Error: Couldn't check token customer_id" = "Chyba: Nejde ověřit token customer_id"; + +/* [companion.py] */ +"Error: customer_id doesn't match!" = "Chyba: customer_id nesouhlasí!"; + /* [edsm.py] */ "Error: EDSM {MSG}" = "Chyba: EDSM {MSG}"; @@ -175,6 +187,9 @@ /* [companion.py] */ "Error: Invalid Credentials" = "Chyba: Chybné přihlašovací údaje"; +/* [companion.py] */ +"Error: unable to get token" = "Chyba: nepovedlo se získat token"; + /* Raised when the user has multiple accounts and the username/password setting is not for the account they're currently playing OR the user has reset their Cmdr and the Companion API server is still returning data for the old Cmdr. [companion.py] */ "Error: Wrong Cmdr" = "Chyba: Nesprávný CMDR"; @@ -235,6 +250,9 @@ /* Section heading in settings. [inara.py] */ "Inara credentials" = "Přihlašovací údaje k Inaře"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "Informace jak migrovat pluginy."; + /* Changed journal update_lock failed [monitor.py] */ "Journal directory already locked" = "Adresář deníku je již uzamčen"; @@ -262,12 +280,18 @@ /* Cmdr stats. [stats.py] */ "Loan" = "Půjčka"; +/* Label for user configured level of logging [prefs.py] */ +"Log Level" = "Míra logování"; + /* [EDMarketConnector.py] */ "Logging in..." = "Přihlašování..."; /* Empire rank. [stats.py] */ "Lord" = "Lord"; +/* Label for 'UI Transparency' option in [prefs.py] */ +"Main window transparency" = "Průhlednost hlavního okna"; + /* [prefs.py] */ "Market data in CSV format file" = "Obchodní data ve formátu CSV"; @@ -286,6 +310,9 @@ /* Federation rank. [stats.py] */ "Midshipman" = "Midshipman"; +/* Appearance setting. [EDMarketConnector.py] */ +"Minimize to system tray" = "Minimalizovat do lišty"; + /* Explorer rank. [stats.py] */ "Mostly Aimless" = "Mostly Aimless"; @@ -310,6 +337,9 @@ /* [prefs.py] */ "OK" = "OK"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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." = "Jeden nebo více aktivních pluginů ještě stále nepodporuje Python 3.x. Podívejte se na jejich seznam v záložce '{PLUGINS}' v '{FILE}' > '{SETTINGS}'. Zkontrolujte si jestli není dostupná novější verze pluginu, pokud ne, tak kontaktujte vývojáře pluginu o tom, že musí upravit jejich plugin pro Python 3.x.\n\nPlugin můžete vypnout přidáním '{DISABLED}' na konec názvu jeho složky."; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Pouze pokud je Elite: Dangerous aktivní"; @@ -352,17 +382,8 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "Složka pluginů"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC: Pluginy, které nepodporují Python 3.x"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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." = "Jeden nebo více aktivních pluginů ještě stále nepodporuje Python 3.x. Podívejte se na jejich seznam v záložce '{PLUGINS}' v '{FILE}' > '{SETTINGS}'. Zkontrolujte si jestli není dostupná novější verze pluginu, pokud ne, tak kontaktujte vývojáře pluginu o tom, že musí upravit jejich plugin pro Python 3.x.\n\nPlugin můžete vypnout přidáním '{DISABLED}' na konec názvu jeho složky."; - /* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "Pluginy, které nepodporují Python 3.x"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "Informace jak migrovat pluginy."; +"Plugins Without Python 3.x Support:" = "Pluginy bez podpory Python 3.x:"; /* Federation rank. [stats.py] */ "Post Captain" = "Post Captain"; @@ -484,6 +505,9 @@ /* Menu item. [EDMarketConnector.py] */ "Status" = "Status"; +/* 'Suit' label in main UI' [EDMarketConnector.py] */ +"Suit" = "Oblek"; + /* Explorer rank. [stats.py] */ "Surveyor" = "Surveyor"; @@ -511,6 +535,12 @@ /* Trade rank. [stats.py] */ "Tycoon" = "Tycoon"; +/* Label for 'UI Scaling' option [prefs.py] */ +"UI Scale Percentage" = "Procenta UI škálování"; + +/* General 'Unknown', e.g. suit loadout */ +"Unknown" = "Neznámý"; + /* Update button in main window. [EDMarketConnector.py] */ "Update" = "Aktualizovat"; @@ -549,6 +579,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} vyžaduje oprávnění pro použití klávesových zkratek"; - -/* Label for user configured level of logging [prefs.py] */ -"Log Level" = "Míra logování"; diff --git a/L10n/de.strings b/L10n/de.strings index 492de5de..a87a049c 100644 --- a/L10n/de.strings +++ b/L10n/de.strings @@ -1,12 +1,12 @@ -/* Label for 'UI Scaling' option [prefs.py] */ -"UI Scale Percentage" = "UI-Skalierung in Prozent"; +/* Language name */ +"!Language" = "Deutsch"; + +/* Message next to 'UI Transparency' slider [prefs.py] */ +"100 means fully opaque.{CR}Window is updated in real time" = "100 bedeutet komplett undurchsichtig.{CR}Fenster wird in Echtzeit aktualisiert"; /* Text describing that value '100' means 'default', and changes require a restart [prefs.py] */ "100 means Default{CR}Restart Required for{CR}changes to take effect!" = "100 bedeutet Standardwert{CR}Neustart erforderlich, um{CR}Änderungen zu übernehmen!"; -/* Language name */ -"!Language" = "Deutsch"; - /* App menu entry on OSX. [EDMarketConnector.py] */ "About {APP}" = "Über {APP}"; @@ -46,12 +46,12 @@ /* Folder selection button on Windows. [prefs.py] */ "Browse..." = "Durchsuchen..."; -/* No 'commander' data in CAPI [EDMarketConnector.py] */ -"CAPI: No commander data returned" = "CAPI: Keine Kommandanten-Daten erhalten"; - /* Federation rank. [stats.py] */ "Cadet" = "Kadett"; +/* No 'commander' data in CAPI [EDMarketConnector.py] */ +"CAPI: No commander data returned" = "CAPI: Keine Kommandanten-Daten erhalten"; + /* CQC rank. [stats.py] */ "Champion" = "Sieger"; @@ -130,6 +130,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "Bearbeiten"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC: Plugins ohne Python 3.x Support"; + /* Top rank. [stats.py] */ "Elite" = "Elite"; @@ -148,6 +151,9 @@ /* Trade rank. [stats.py] */ "Entrepreneur" = "Unternehmer"; +/* [companion.py] */ +"Error" = "Fehler"; + /* [eddn.py] */ "Error: Can't connect to EDDN" = "Fehler: Keine Verbindung zum EDDN"; @@ -157,6 +163,12 @@ /* [inara.py] */ "Error: Can't connect to Inara" = "Fehler: Verbindung zu Inara fehlgeschlagen"; +/* [companion.py] */ +"Error: Couldn't check token customer_id" = "Fehler: Konnte das Token customer_id nicht prüfen"; + +/* [companion.py] */ +"Error: customer_id doesn't match!" = "Fehler: customer_id stimmt nicht überein!"; + /* [edsm.py] */ "Error: EDSM {MSG}" = "Fehler: EDSM {MSG}"; @@ -175,6 +187,9 @@ /* [companion.py] */ "Error: Invalid Credentials" = "Fehler: Ungültige Anmeldedaten"; +/* [companion.py] */ +"Error: unable to get token" = "Fehler: konnte Token nicht erhalten"; + /* Raised when the user has multiple accounts and the username/password setting is not for the account they're currently playing OR the user has reset their Cmdr and the Companion API server is still returning data for the old Cmdr. [companion.py] */ "Error: Wrong Cmdr" = "Fehler: Falscher Kdt."; @@ -235,6 +250,9 @@ /* Section heading in settings. [inara.py] */ "Inara credentials" = "Inara-Anmeldedaten"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "Informationen zum Migrieren von Plugins"; + /* Changed journal update_lock failed [monitor.py] */ "Journal directory already locked" = "Journal-Ordner bereits gesperrt"; @@ -262,12 +280,18 @@ /* Cmdr stats. [stats.py] */ "Loan" = "Kredit"; +/* Label for user configured level of logging [prefs.py] */ +"Log Level" = "Log-Level"; + /* [EDMarketConnector.py] */ "Logging in..." = "Anmelden..."; /* Empire rank. [stats.py] */ "Lord" = "Fürst"; +/* Label for 'UI Transparency' option in [prefs.py] */ +"Main window transparency" = "Durchsichtigkeit Hauptfenster"; + /* [prefs.py] */ "Market data in CSV format file" = "Marktdaten als CSV Datei"; @@ -286,6 +310,9 @@ /* Federation rank. [stats.py] */ "Midshipman" = "Fähnrich"; +/* Appearance setting. [EDMarketConnector.py] */ +"Minimize to system tray" = "In die Taskleiste minimieren"; + /* Explorer rank. [stats.py] */ "Mostly Aimless" = "Fast Planlos"; @@ -310,6 +337,9 @@ /* [prefs.py] */ "OK" = "OK"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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."; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Nur wenn Elite: Dangerous geöffnet ist"; @@ -352,17 +382,8 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "Plugin-Ordner"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC: Plugins ohne Python 3.x Support"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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."; - /* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "Plugins ohne Python 3.x Support"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "Informationen zum Migrieren von Plugins"; +"Plugins Without Python 3.x Support:" = "Plugins ohne Python 3.x Support"; /* Federation rank. [stats.py] */ "Post Captain" = "Kapitän"; @@ -484,6 +505,9 @@ /* Menu item. [EDMarketConnector.py] */ "Status" = "Status"; +/* 'Suit' label in main UI' [EDMarketConnector.py] */ +"Suit" = "Anzug"; + /* Explorer rank. [stats.py] */ "Surveyor" = "Landkundiger"; @@ -511,6 +535,12 @@ /* Trade rank. [stats.py] */ "Tycoon" = "Magnat"; +/* Label for 'UI Scaling' option [prefs.py] */ +"UI Scale Percentage" = "UI-Skalierung in Prozent"; + +/* General 'Unknown', e.g. suit loadout */ +"Unknown" = "Unbekannt"; + /* Update button in main window. [EDMarketConnector.py] */ "Update" = "Aktualisieren"; @@ -549,6 +579,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} benötigt für Tastenkürzel Systemrechte (Bedienungshilfen)"; - -/* Label for user configured level of logging [prefs.py] */ -"Log Level" = "Log-Level"; diff --git a/L10n/en.template b/L10n/en.template index ef8f7399..9aa3c3ca 100644 --- a/L10n/en.template +++ b/L10n/en.template @@ -1,12 +1,12 @@ -/* Label for 'UI Scaling' option [prefs.py] */ -"UI Scale Percentage" = "UI Scale Percentage"; +/* Language name */ +"!Language" = "English"; + +/* Message next to 'UI Transparency' slider [prefs.py] */ +"100 means fully opaque.{CR}Window is updated in real time" = "100 means fully opaque.{CR}Window is updated in real time"; /* Text describing that value '100' means 'default', and changes require a restart [prefs.py] */ "100 means Default{CR}Restart Required for{CR}changes to take effect!" = "100 means Default{CR}Restart Required for{CR}changes to take effect!"; -/* Language name */ -"!Language" = "English"; - /* App menu entry on OSX. [EDMarketConnector.py] */ "About {APP}" = "About {APP}"; @@ -46,12 +46,12 @@ /* Folder selection button on Windows. [prefs.py] */ "Browse..." = "Browse..."; -/* No 'commander' data in CAPI [EDMarketConnector.py] */ -"CAPI: No commander data returned" = "CAPI: No commander data returned"; - /* Federation rank. [stats.py] */ "Cadet" = "Cadet"; +/* No 'commander' data in CAPI [EDMarketConnector.py] */ +"CAPI: No commander data returned" = "CAPI: No commander data returned"; + /* CQC rank. [stats.py] */ "Champion" = "Champion"; @@ -130,6 +130,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "Edit"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC: Plugins Without Python 3.x Support"; + /* Top rank. [stats.py] */ "Elite" = "Elite"; @@ -148,6 +151,9 @@ /* Trade rank. [stats.py] */ "Entrepreneur" = "Entrepreneur"; +/* [companion.py] */ +"Error" = "Error"; + /* [eddn.py] */ "Error: Can't connect to EDDN" = "Error: Can't connect to EDDN"; @@ -157,6 +163,12 @@ /* [inara.py] */ "Error: Can't connect to Inara" = "Error: Can't connect to Inara"; +/* [companion.py] */ +"Error: Couldn't check token customer_id" = "Error: Couldn't check token customer_id"; + +/* [companion.py] */ +"Error: customer_id doesn't match!" = "Error: customer_id doesn't match!"; + /* [edsm.py] */ "Error: EDSM {MSG}" = "Error: EDSM {MSG}"; @@ -175,6 +187,9 @@ /* [companion.py] */ "Error: Invalid Credentials" = "Error: Invalid Credentials"; +/* [companion.py] */ +"Error: unable to get token" = "Error: unable to get token"; + /* Raised when the user has multiple accounts and the username/password setting is not for the account they're currently playing OR the user has reset their Cmdr and the Companion API server is still returning data for the old Cmdr. [companion.py] */ "Error: Wrong Cmdr" = "Error: Wrong Cmdr"; @@ -235,6 +250,9 @@ /* Section heading in settings. [inara.py] */ "Inara credentials" = "Inara credentials"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "Information on migrating plugins"; + /* Changed journal update_lock failed [monitor.py] */ "Journal directory already locked" = "Journal directory already locked"; @@ -262,12 +280,18 @@ /* Cmdr stats. [stats.py] */ "Loan" = "Loan"; +/* Label for user configured level of logging [prefs.py] */ +"Log Level" = "Log Level"; + /* [EDMarketConnector.py] */ "Logging in..." = "Logging in..."; /* Empire rank. [stats.py] */ "Lord" = "Lord"; +/* Label for 'UI Transparency' option in [prefs.py] */ +"Main window transparency" = "Main window transparency"; + /* [prefs.py] */ "Market data in CSV format file" = "Market data in CSV format file"; @@ -286,6 +310,9 @@ /* Federation rank. [stats.py] */ "Midshipman" = "Midshipman"; +/* Appearance setting. [EDMarketConnector.py] */ +"Minimize to system tray" = "Minimize to system tray"; + /* Explorer rank. [stats.py] */ "Mostly Aimless" = "Mostly Aimless"; @@ -310,6 +337,9 @@ /* [prefs.py] */ "OK" = "OK"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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."; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Only when Elite: Dangerous is the active app"; @@ -352,17 +382,8 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "Plugins folder"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC: Plugins Without Python 3.x Support"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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."; - /* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "Plugins Without Python 3.x Support"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "Information on migrating plugins"; +"Plugins Without Python 3.x Support:" = "Plugins Without Python 3.x Support:"; /* Federation rank. [stats.py] */ "Post Captain" = "Post Captain"; @@ -484,6 +505,9 @@ /* Menu item. [EDMarketConnector.py] */ "Status" = "Status"; +/* 'Suit' label in main UI' [EDMarketConnector.py] */ +"Suit" = "Suit"; + /* Explorer rank. [stats.py] */ "Surveyor" = "Surveyor"; @@ -511,6 +535,12 @@ /* Trade rank. [stats.py] */ "Tycoon" = "Tycoon"; +/* Label for 'UI Scaling' option [prefs.py] */ +"UI Scale Percentage" = "UI Scale Percentage"; + +/* General 'Unknown', e.g. suit loadout */ +"Unknown" = "Unknown"; + /* Update button in main window. [EDMarketConnector.py] */ "Update" = "Update"; @@ -549,6 +579,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} needs permission to use shortcuts"; - -/* Label for user configured level of logging [prefs.py] */ -"Log Level" = "Log Level"; diff --git a/L10n/es.strings b/L10n/es.strings index 8dc4eb49..ce24523c 100644 --- a/L10n/es.strings +++ b/L10n/es.strings @@ -1,6 +1,12 @@ /* Language name */ "!Language" = "Español"; +/* Message next to 'UI Transparency' slider [prefs.py] */ +"100 means fully opaque.{CR}Window is updated in real time" = "100 significa completamente opaco.{CR}La ventana se actualiza en tiempo real."; + +/* Text describing that value '100' means 'default', and changes require a restart [prefs.py] */ +"100 means Default{CR}Restart Required for{CR}changes to take effect!" = "100 significa Por Defecto{CR}Se requiere reiniciar{CR}para que los cambios surtan efecto!"; + /* App menu entry on OSX. [EDMarketConnector.py] */ "About {APP}" = "Acerca de {APP}"; @@ -43,6 +49,9 @@ /* Federation rank. [stats.py] */ "Cadet" = "Cadete"; +/* No 'commander' data in CAPI [EDMarketConnector.py] */ +"CAPI: No commander data returned" = "CAPI: No se devolvió datos de comandante"; + /* CQC rank. [stats.py] */ "Champion" = "Campeón"; @@ -121,6 +130,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "Editar"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC: Plugins Sin Soporte para Python 3.x"; + /* Top rank. [stats.py] */ "Elite" = "Élite"; @@ -139,6 +151,9 @@ /* Trade rank. [stats.py] */ "Entrepreneur" = "Empresario"; +/* [companion.py] */ +"Error" = "Error"; + /* [eddn.py] */ "Error: Can't connect to EDDN" = "Error: No se puede conectar a EDDN"; @@ -148,6 +163,12 @@ /* [inara.py] */ "Error: Can't connect to Inara" = "Error: No se puede conectar con Inara"; +/* [companion.py] */ +"Error: Couldn't check token customer_id" = "Error: No se pudo comprobar el token customer_id"; + +/* [companion.py] */ +"Error: customer_id doesn't match!" = "Error: ¡customer_id no coincide!"; + /* [edsm.py] */ "Error: EDSM {MSG}" = "Error: EDSM {MSG}"; @@ -166,6 +187,9 @@ /* [companion.py] */ "Error: Invalid Credentials" = "Error: Credenciales Inválidas"; +/* [companion.py] */ +"Error: unable to get token" = "Error: no se pudo conseguir el token"; + /* Raised when the user has multiple accounts and the username/password setting is not for the account they're currently playing OR the user has reset their Cmdr and the Companion API server is still returning data for the old Cmdr. [companion.py] */ "Error: Wrong Cmdr" = "Error: Cmdt Incorrecto"; @@ -220,9 +244,18 @@ /* Hotkey/Shortcut settings prompt on Windows. [prefs.py] */ "Hotkey" = "Tecla de acceso directo"; +/* Changed journal update_lock failed [monitor.py] */ +"Ignore" = "Ignorar"; + /* Section heading in settings. [inara.py] */ "Inara credentials" = "Credenciales de Inara"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "Información sobre migración de plugins"; + +/* Changed journal update_lock failed [monitor.py] */ +"Journal directory already locked" = "El Directorio Journal ya está bloqueado"; + /* Hotkey/Shortcut settings prompt on OSX. [prefs.py] */ "Keyboard shortcut" = "Tecla de acceso directo"; @@ -247,12 +280,18 @@ /* Cmdr stats. [stats.py] */ "Loan" = "Préstamo"; +/* Label for user configured level of logging [prefs.py] */ +"Log Level" = "Nivel de registro"; + /* [EDMarketConnector.py] */ "Logging in..." = "Identificándose..."; /* Empire rank. [stats.py] */ "Lord" = "Señor"; +/* Label for 'UI Transparency' option in [prefs.py] */ +"Main window transparency" = "Transparencia de la ventana principal"; + /* [prefs.py] */ "Market data in CSV format file" = "Datos de mercado en formato CSV"; @@ -271,6 +310,9 @@ /* Federation rank. [stats.py] */ "Midshipman" = "Guardiamarina"; +/* Appearance setting. [EDMarketConnector.py] */ +"Minimize to system tray" = "Minimizar a la bandeja de sistema"; + /* Explorer rank. [stats.py] */ "Mostly Aimless" = "Casi perdido"; @@ -295,6 +337,9 @@ /* [prefs.py] */ "OK" = "Aceptar"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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." = "Uno o más de tus plugins habilitados aún no tienen soporte para Python 3.x. Por favor, consulta la lista en la pestaña '{PLUGINS}' de '{FILE}' > '{SETTINGS}'. Deberías comprobar si hay una versión actualizada disponible, si no, avisa al desarrollador de que necesita actualizar el código para Python 3.x.\n\nPuedes deshabilitar un plugin cambiando el nombre de su carpeta para que tenga '{DISABLED}' al final del nombre."; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Solo cuando Elite: Dangerous es la aplicación activa"; @@ -337,17 +382,8 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "Carpeta de Plugins"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC: Plugins Sin Soporte para Python 3.x"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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." = "Uno o más de tus plugins habilitados aún no tienen soporte para Python 3.x. Por favor, consulta la lista en la pestaña '{PLUGINS}' de '{FILE}' > '{SETTINGS}'. Deberías comprobar si hay una versión actualizada disponible, si no, avisa al desarrollador de que necesita actualizar el código para Python 3.x.\n\nPuedes deshabilitar un plugin cambiando el nombre de su carpeta para que tenga '{DISABLED}' al final del nombre."; - /* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "Plugins sin Soporte para Python 3.x"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "Información sobre migración de plugins"; +"Plugins Without Python 3.x Support:" = "Plugins sin soporte para Python 3.x:"; /* Federation rank. [stats.py] */ "Post Captain" = "Capitán de navío"; @@ -403,6 +439,9 @@ /* Help menu item. [EDMarketConnector.py] */ "Release Notes" = "Notas de la versión"; +/* Changed journal update_lock failed [monitor.py] */ +"Retry" = "Reintentar"; + /* Multicrew role label in main window. [EDMarketConnector.py] */ "Role" = "Rol"; @@ -448,6 +487,9 @@ /* Setting to decide which ship outfitting website to link to - either E:D Shipyard or Coriolis. [prefs.py] */ "Shipyard" = "Astillero"; +/* Status line text that appears when process exit sequence starts [EDMarketConnector.py] */ +"Shutting down..." = "Apagando..."; + /* Empire rank. [stats.py] */ "Squire" = "Escudero"; @@ -469,6 +511,9 @@ /* Main window. [EDMarketConnector.py] */ "System" = "Sistema"; +/* Changed journal update_lock failed [monitor.py] */ +"The new Journal Directory location is already locked.{CR}You can either attempt to resolve this and then Retry, or choose to Ignore this." = "La localización Directorio Journal ya está bloqueada.{CR}Puedes intentar resolverlo y pulsar Reintentar, o elegir Ignorar esto."; + /* Appearance setting. [prefs.py] */ "Theme" = "Tema"; @@ -487,9 +532,18 @@ /* Trade rank. [stats.py] */ "Tycoon" = "Magnate"; +/* Label for 'UI Scaling' option [prefs.py] */ +"UI Scale Percentage" = "Porcentaje escala UI"; + +/* General 'Unknown', e.g. suit loadout */ +"Unknown" = "Desconocido"; + /* Update button in main window. [EDMarketConnector.py] */ "Update" = "Actualizar"; +/* Option to use alternate URL method on shipyard links [prefs.py] */ +"Use alternate URL method" = "Usar método URL alternativo"; + /* Status dialog subtitle - CR value of ship. [stats.py] */ "Value" = "Valor"; @@ -522,4 +576,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} necesita permisos para usar teclas de acceso directo"; - diff --git a/L10n/fi.strings b/L10n/fi.strings index 98782961..7f577415 100644 --- a/L10n/fi.strings +++ b/L10n/fi.strings @@ -1,12 +1,12 @@ -/* Label for 'UI Scaling' option [prefs.py] */ -"UI Scale Percentage" = "Käyttöliittymän skaalausprosentti"; +/* Language name */ +"!Language" = "Suomi"; + +/* Message next to 'UI Transparency' slider [prefs.py] */ +"100 means fully opaque.{CR}Window is updated in real time" = "100 tarkoittaa täysin peittävää.{CR}Ikkuna päivittyy reaaliajassa."; /* Text describing that value '100' means 'default', and changes require a restart [prefs.py] */ "100 means Default{CR}Restart Required for{CR}changes to take effect!" = "100 tarkoittaa oletusta{CR}Muutosten käyttöönotto{CR}edellyttää uudelleenkäynnistystä!"; -/* Language name */ -"!Language" = "Suomi"; - /* App menu entry on OSX. [EDMarketConnector.py] */ "About {APP}" = "Ohjelmasta {APP}"; @@ -49,6 +49,9 @@ /* Federation rank. [stats.py] */ "Cadet" = "Cadet"; +/* No 'commander' data in CAPI [EDMarketConnector.py] */ +"CAPI: No commander data returned" = "CAPI: tietoja ei löytynyt"; + /* CQC rank. [stats.py] */ "Champion" = "Champion"; @@ -127,6 +130,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "Muokkaa"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC: Lisäosat ilman Python 3.x -tukea"; + /* Top rank. [stats.py] */ "Elite" = "Elite"; @@ -145,6 +151,9 @@ /* Trade rank. [stats.py] */ "Entrepreneur" = "Entrepreneur"; +/* [companion.py] */ +"Error" = "Virhe"; + /* [eddn.py] */ "Error: Can't connect to EDDN" = "Virhe: ei saatu yhteyttä EDDN:ään"; @@ -154,6 +163,12 @@ /* [inara.py] */ "Error: Can't connect to Inara" = "Virhe: Ei yhteyttä Inaraan"; +/* [companion.py] */ +"Error: Couldn't check token customer_id" = "Virhe: Ei kyetty tarkastamaan polettia customer_id"; + +/* [companion.py] */ +"Error: customer_id doesn't match!" = "Virhe: customer_id ei löydy vastaavuutta!"; + /* [edsm.py] */ "Error: EDSM {MSG}" = "Virhe: EDSM {MSG}"; @@ -172,6 +187,9 @@ /* [companion.py] */ "Error: Invalid Credentials" = "Virhe: kirjautuminen ei kelpaa"; +/* [companion.py] */ +"Error: unable to get token" = "Virhe: ei kyetty saamaan polettia"; + /* Raised when the user has multiple accounts and the username/password setting is not for the account they're currently playing OR the user has reset their Cmdr and the Companion API server is still returning data for the old Cmdr. [companion.py] */ "Error: Wrong Cmdr" = "Virhe: väärä komentaja"; @@ -226,9 +244,18 @@ /* Hotkey/Shortcut settings prompt on Windows. [prefs.py] */ "Hotkey" = "Pikanäppäin"; +/* Changed journal update_lock failed [monitor.py] */ +"Ignore" = "Älä huomioi"; + /* Section heading in settings. [inara.py] */ "Inara credentials" = "Inaran kirjautuminen"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "Tietoja lisäosien siirrosta"; + +/* Changed journal update_lock failed [monitor.py] */ +"Journal directory already locked" = "Journal -hakemisto on jo lukittu"; + /* Hotkey/Shortcut settings prompt on OSX. [prefs.py] */ "Keyboard shortcut" = "Näppäimistöoikopolku"; @@ -253,12 +280,18 @@ /* Cmdr stats. [stats.py] */ "Loan" = "Lainaa jäljellä"; +/* Label for user configured level of logging [prefs.py] */ +"Log Level" = "Lokin syvyys"; + /* [EDMarketConnector.py] */ "Logging in..." = "Kirjaudutaan..."; /* Empire rank. [stats.py] */ "Lord" = "Lord"; +/* Label for 'UI Transparency' option in [prefs.py] */ +"Main window transparency" = "Pääikkunan läpinäkyvyys"; + /* [prefs.py] */ "Market data in CSV format file" = "Markkinadata CSV -formaatissa"; @@ -277,6 +310,9 @@ /* Federation rank. [stats.py] */ "Midshipman" = "Midshipman"; +/* Appearance setting. [EDMarketConnector.py] */ +"Minimize to system tray" = "Pienennä tehtäväpalkkiin"; + /* Explorer rank. [stats.py] */ "Mostly Aimless" = "Mostly Aimless"; @@ -301,6 +337,9 @@ /* [prefs.py] */ "OK" = "OK"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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." = "Yksi tai useampi käyttämistäsi lisäosista ei sisällä vielä Pyhton 3.x -tukea. Tarkista tiedoston '{FILE}' > '{SETTINGS}' välilehti '{PLUGINS}' lisäosista, onko niistä uudempaa versiota saatavilla; muussa tapauksessa ota yhteyttä sen kehittäjään ja kerro, että sen lähdekoodi on päivitettävä Python 3.x -tasolle.\n\nVoit estää lisäosan toiminnan nimeämällä sen hakemiston siten, että se päättyy tekstiin '{DISABLED}'."; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Vain jos Elite:Dangerous on käynnissä"; @@ -343,17 +382,8 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "Lisäosien hakemistosijainti"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC: Lisäosat ilman Python 3.x -tukea"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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." = "Yksi tai useampi käyttämistäsi lisäosista ei sisällä vielä Pyhton 3.x -tukea. Tarkista tiedoston '{FILE}' > '{SETTINGS}' välilehti '{PLUGINS}' lisäosista, onko niistä uudempaa versiota saatavilla; muussa tapauksessa ota yhteyttä sen kehittäjään ja kerro, että sen lähdekoodi on päivitettävä Python 3.x -tasolle.\n\nVoit estää lisäosan toiminnan nimeämällä sen hakemiston siten, että se päättyy tekstiin '{DISABLED}'."; - /* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "Lisäosat ilman Python 3.x -tukea"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "Tietoja lisäosien siirrosta"; +"Plugins Without Python 3.x Support:" = "Lisäosat, joissa ei ole Python 3.x -tukea:"; /* Federation rank. [stats.py] */ "Post Captain" = "Post Captain"; @@ -409,6 +439,9 @@ /* Help menu item. [EDMarketConnector.py] */ "Release Notes" = "Julkaisutiedot"; +/* Changed journal update_lock failed [monitor.py] */ +"Retry" = "Yritä uudelleen"; + /* Multicrew role label in main window. [EDMarketConnector.py] */ "Role" = "Rooli"; @@ -472,12 +505,18 @@ /* Menu item. [EDMarketConnector.py] */ "Status" = "Tila"; +/* 'Suit' label in main UI' [EDMarketConnector.py] */ +"Suit" = "Asuste"; + /* Explorer rank. [stats.py] */ "Surveyor" = "Surveyor"; /* Main window. [EDMarketConnector.py] */ "System" = "Järjestelmä"; +/* Changed journal update_lock failed [monitor.py] */ +"The new Journal Directory location is already locked.{CR}You can either attempt to resolve this and then Retry, or choose to Ignore this." = "Uusi Journal -hakemisto on jo lukittu.{CR}Voit joko yrittää ratkaista tämän ja yrittää uudelleen, tai jättää asian huomiotta."; + /* Appearance setting. [prefs.py] */ "Theme" = "Teema"; @@ -496,6 +535,12 @@ /* Trade rank. [stats.py] */ "Tycoon" = "Tycoon"; +/* Label for 'UI Scaling' option [prefs.py] */ +"UI Scale Percentage" = "Käyttöliittymän skaalausprosentti"; + +/* General 'Unknown', e.g. suit loadout */ +"Unknown" = "Tuntematon"; + /* Update button in main window. [EDMarketConnector.py] */ "Update" = "Päivitä"; @@ -534,6 +579,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} tarvitsee lupasi pikakuvakkeiden käyttämiseen"; - -/* Label for user configured level of logging [prefs.py] */ -"Log Level" = "Lokin syvyys"; diff --git a/L10n/fr.strings b/L10n/fr.strings index 617fc168..5dd8c2ba 100644 --- a/L10n/fr.strings +++ b/L10n/fr.strings @@ -121,6 +121,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "Édition"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC: Plugins non compatibles avec Python 3.x"; + /* Top rank. [stats.py] */ "Elite" = "Élite"; @@ -223,6 +226,9 @@ /* Section heading in settings. [inara.py] */ "Inara credentials" = "Informations d'identification pour Inara"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "Informations sur la migration des plugins"; + /* Hotkey/Shortcut settings prompt on OSX. [prefs.py] */ "Keyboard shortcut" = "Raccourci clavier"; @@ -295,6 +301,9 @@ /* [prefs.py] */ "OK" = "OK"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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." = "Un ou plusieurs de vos plugins activés ne sont pas encore compatibles avec Python 3.x. Regardez la liste sur l'onglet '{PLUGINS}' de '{FILE}' > '{SETTINGS}'. Vous devriez vérifier s'il y a une version mise à jour, sinon alertez le développeur qu'il doit mettre à jour le code pour Python 3.x.\n\nVous pouvez désactiver un plugin en renommant son dossier pour qu'il ait '{DISABLED}' à la fin du nom."; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Seulement quand Elite: Dangerous est l'application active"; @@ -337,18 +346,6 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "Répertoire des plugins"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC: Plugins non compatibles avec Python 3.x"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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." = "Un ou plusieurs de vos plugins activés ne sont pas encore compatibles avec Python 3.x. Regardez la liste sur l'onglet '{PLUGINS}' de '{FILE}' > '{SETTINGS}'. Vous devriez vérifier s'il y a une version mise à jour, sinon alertez le développeur qu'il doit mettre à jour le code pour Python 3.x.\n\nVous pouvez désactiver un plugin en renommant son dossier pour qu'il ait '{DISABLED}' à la fin du nom."; - -/* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "Plugins non compatibles avec Python 3.x"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "Informations sur la migration des plugins"; - /* Federation rank. [stats.py] */ "Post Captain" = "Capitaine de Vaisseau"; @@ -522,4 +519,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} a besoin de permissions pour utiliser les raccourcis"; - diff --git a/L10n/hu.strings b/L10n/hu.strings index 18880370..6d5fa988 100644 --- a/L10n/hu.strings +++ b/L10n/hu.strings @@ -507,4 +507,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} engedély szükséges a parancsikon használatához"; - diff --git a/L10n/it.strings b/L10n/it.strings index c6f9258c..81c6cf2e 100644 --- a/L10n/it.strings +++ b/L10n/it.strings @@ -1,12 +1,9 @@ -/* Label for 'UI Scaling' option [prefs.py] */ -"UI Scale Percentage" = "Percentuale zoom della UI"; +/* Language name */ +"!Language" = "Italiano"; /* Text describing that value '100' means 'default', and changes require a restart [prefs.py] */ "100 means Default{CR}Restart Required for{CR}changes to take effect!" = "100 significa Default{CR}Riavvio Richiesto per{CR}applicare i cambiamenti!"; -/* Language name */ -"!Language" = "Italiano"; - /* App menu entry on OSX. [EDMarketConnector.py] */ "About {APP}" = "Informazioni su {APP}"; @@ -46,12 +43,12 @@ /* Folder selection button on Windows. [prefs.py] */ "Browse..." = "Sfoglia..."; -/* No 'commander' data in CAPI [EDMarketConnector.py] */ -"CAPI: No commander data returned" = "CAPI: Nessun dato sul commandante"; - /* Federation rank. [stats.py] */ "Cadet" = "Cadet"; +/* No 'commander' data in CAPI [EDMarketConnector.py] */ +"CAPI: No commander data returned" = "CAPI: Nessun dato sul commandante"; + /* CQC rank. [stats.py] */ "Champion" = "Champion"; @@ -130,6 +127,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "Appunti"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC: Plugins senza Supporto Python 3.x"; + /* Top rank. [stats.py] */ "Elite" = "Elite"; @@ -235,6 +235,9 @@ /* Section heading in settings. [inara.py] */ "Inara credentials" = "Credenziali per Inara"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "Informazioni sulla migrazione dei plugins"; + /* Changed journal update_lock failed [monitor.py] */ "Journal directory already locked" = "cartella Journal già bloccata"; @@ -262,6 +265,9 @@ /* Cmdr stats. [stats.py] */ "Loan" = "Prestito"; +/* Label for user configured level of logging [prefs.py] */ +"Log Level" = "Livello di Log"; + /* [EDMarketConnector.py] */ "Logging in..." = "Mi sto loggando..."; @@ -310,6 +316,9 @@ /* [prefs.py] */ "OK" = "OK"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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." = "Uno o più dei tuoi plugin non ha ancora il supporto per Python 3.x. Per favore guarda la lista '{PLUGINS}' nella tab a '{FILE}' > '{SETTINGS}'. Dovresti controllare se ci sono aggiornamenti, altrimenti avvisa gli sviluppatori che devono aggiornare il codice a Python 3.x.\n\nPuoi disabilitare il plugin rinominando la cartella aggiungendo '{DISABLED}' alla fine del nome."; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Solo quando “Elite: Dangerous” è in primo piano"; @@ -352,18 +361,6 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "Cartella dei plugins"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC: Plugins senza Supporto Python 3.x"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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." = "Uno o più dei tuoi plugin non ha ancora il supporto per Python 3.x. Per favore guarda la lista '{PLUGINS}' nella tab a '{FILE}' > '{SETTINGS}'. Dovresti controllare se ci sono aggiornamenti, altrimenti avvisa gli sviluppatori che devono aggiornare il codice a Python 3.x.\n\nPuoi disabilitare il plugin rinominando la cartella aggiungendo '{DISABLED}' alla fine del nome."; - -/* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "Plugins senza Supporto Python 3.x"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "Informazioni sulla migrazione dei plugins"; - /* Federation rank. [stats.py] */ "Post Captain" = "Post Captain"; @@ -511,6 +508,9 @@ /* Trade rank. [stats.py] */ "Tycoon" = "Tycoon"; +/* Label for 'UI Scaling' option [prefs.py] */ +"UI Scale Percentage" = "Percentuale zoom della UI"; + /* Update button in main window. [EDMarketConnector.py] */ "Update" = "Recupera"; @@ -549,6 +549,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} ha bisogno dei permessi per usare le scorciatoie"; - -/* Label for user configured level of logging [prefs.py] */ -"Log Level" = "Livello di Log"; diff --git a/L10n/ja.strings b/L10n/ja.strings index 3e933735..34c440cf 100644 --- a/L10n/ja.strings +++ b/L10n/ja.strings @@ -1,12 +1,12 @@ -/* Label for 'UI Scaling' option [prefs.py] */ -"UI Scale Percentage" = "UIスケール比率"; +/* Language name */ +"!Language" = "日本語"; + +/* Message next to 'UI Transparency' slider [prefs.py] */ +"100 means fully opaque.{CR}Window is updated in real time" = "100は完全に不透明であることを意味します。{CR}ウィンドウはリアルタイムで更新されます"; /* Text describing that value '100' means 'default', and changes require a restart [prefs.py] */ "100 means Default{CR}Restart Required for{CR}changes to take effect!" = "100はデフォルトを意味します{CR}変更した値を反映するには{CR}再起動が必要です!"; -/* Language name */ -"!Language" = "日本語"; - /* App menu entry on OSX. [EDMarketConnector.py] */ "About {APP}" = "{APP} について"; @@ -46,12 +46,12 @@ /* Folder selection button on Windows. [prefs.py] */ "Browse..." = "参照..."; -/* No 'commander' data in CAPI [EDMarketConnector.py] */ -"CAPI: No commander data returned" = "CAPI: コマンダーのデータが返ってきませんでした"; - /* Federation rank. [stats.py] */ "Cadet" = "Cadet"; +/* No 'commander' data in CAPI [EDMarketConnector.py] */ +"CAPI: No commander data returned" = "CAPI: コマンダーのデータが返ってきませんでした"; + /* CQC rank. [stats.py] */ "Champion" = "Champion"; @@ -130,6 +130,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "編集"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC: プラグインがPython 3.xをサポートしていません"; + /* Top rank. [stats.py] */ "Elite" = "Elite"; @@ -148,6 +151,9 @@ /* Trade rank. [stats.py] */ "Entrepreneur" = "Entrepreneur"; +/* [companion.py] */ +"Error" = "エラー"; + /* [eddn.py] */ "Error: Can't connect to EDDN" = "エラー: EDDNに接続できません"; @@ -157,6 +163,12 @@ /* [inara.py] */ "Error: Can't connect to Inara" = "エラー: Inaraに接続できません"; +/* [companion.py] */ +"Error: Couldn't check token customer_id" = "エラー: customer_idトークンを確認できませんでした"; + +/* [companion.py] */ +"Error: customer_id doesn't match!" = "エラー: customer_idがマッチしません!"; + /* [edsm.py] */ "Error: EDSM {MSG}" = "エラー: EDSM {MSG}"; @@ -175,6 +187,9 @@ /* [companion.py] */ "Error: Invalid Credentials" = "エラー: 認証情報に誤りがあります"; +/* [companion.py] */ +"Error: unable to get token" = "エラー: トークンが取得できません"; + /* Raised when the user has multiple accounts and the username/password setting is not for the account they're currently playing OR the user has reset their Cmdr and the Companion API server is still returning data for the old Cmdr. [companion.py] */ "Error: Wrong Cmdr" = "エラー: 不適切なCmdr"; @@ -235,6 +250,9 @@ /* Section heading in settings. [inara.py] */ "Inara credentials" = "Inara認証情報"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "プラグインの移行に関する情報"; + /* Changed journal update_lock failed [monitor.py] */ "Journal directory already locked" = "ジャーナルディレクトリは既にロックされています"; @@ -262,12 +280,18 @@ /* Cmdr stats. [stats.py] */ "Loan" = "負債"; +/* Label for user configured level of logging [prefs.py] */ +"Log Level" = "ログレベル"; + /* [EDMarketConnector.py] */ "Logging in..." = "ログイン中..."; /* Empire rank. [stats.py] */ "Lord" = "Lord"; +/* Label for 'UI Transparency' option in [prefs.py] */ +"Main window transparency" = "メインウィンドウの透明度"; + /* [prefs.py] */ "Market data in CSV format file" = "市場データをCSV形式で記録する"; @@ -286,6 +310,9 @@ /* Federation rank. [stats.py] */ "Midshipman" = "Midshipman"; +/* Appearance setting. [EDMarketConnector.py] */ +"Minimize to system tray" = "システムトレイに最小化する"; + /* Explorer rank. [stats.py] */ "Mostly Aimless" = "Mostly Aimless"; @@ -310,6 +337,9 @@ /* [prefs.py] */ "OK" = "了解"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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}'を追加してください。"; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Elite: Dangerousがアクティブの時だけ有効"; @@ -352,17 +382,8 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "プラグインフォルダ"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC: プラグインがPython 3.xをサポートしていません"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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}'を追加してください。"; - /* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "EDMC: プラグインがPython 3.xをサポートしていません"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "プラグインの移行に関する情報"; +"Plugins Without Python 3.x Support:" = "Python 3.xサポートのないプラグイン:"; /* Federation rank. [stats.py] */ "Post Captain" = "Post Captain"; @@ -484,6 +505,9 @@ /* Menu item. [EDMarketConnector.py] */ "Status" = "ステータス"; +/* 'Suit' label in main UI' [EDMarketConnector.py] */ +"Suit" = "スーツ"; + /* Explorer rank. [stats.py] */ "Surveyor" = "Surveyor"; @@ -511,6 +535,12 @@ /* Trade rank. [stats.py] */ "Tycoon" = "Tycoon"; +/* Label for 'UI Scaling' option [prefs.py] */ +"UI Scale Percentage" = "UIスケール比率"; + +/* General 'Unknown', e.g. suit loadout */ +"Unknown" = "不明"; + /* Update button in main window. [EDMarketConnector.py] */ "Update" = "更新"; @@ -549,6 +579,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} がショートカットを利用するには許可が必要です"; - -/* Label for user configured level of logging [prefs.py] */ -"Log Level" = "ログレベル"; diff --git a/L10n/ko.strings b/L10n/ko.strings index 626116fd..3f0f45ce 100644 --- a/L10n/ko.strings +++ b/L10n/ko.strings @@ -1,12 +1,12 @@ -/* Label for 'UI Scaling' option [prefs.py] */ -"UI Scale Percentage" = "UI 스케일 백분율"; +/* Language name */ +"!Language" = "한국어(Korean)"; + +/* Message next to 'UI Transparency' slider [prefs.py] */ +"100 means fully opaque.{CR}Window is updated in real time" = "100은 완전히 불투명함을 의미합니다.{CR}창은 실시간으로 업데이트됨"; /* Text describing that value '100' means 'default', and changes require a restart [prefs.py] */ "100 means Default{CR}Restart Required for{CR}changes to take effect!" = "100은 '기본 설정'을 의미하며{CR}변경사항 적용을 위해{CR}재시작이 요구됩니다!"; -/* Language name */ -"!Language" = "한국어(Korean)"; - /* App menu entry on OSX. [EDMarketConnector.py] */ "About {APP}" = "{APP} 정보"; @@ -46,12 +46,12 @@ /* Folder selection button on Windows. [prefs.py] */ "Browse..." = "찾아보기..."; -/* No 'commander' data in CAPI [EDMarketConnector.py] */ -"CAPI: No commander data returned" = "CAPI: 커맨더 정보가 반환되지 않음"; - /* Federation rank. [stats.py] */ "Cadet" = "Cadet"; +/* No 'commander' data in CAPI [EDMarketConnector.py] */ +"CAPI: No commander data returned" = "CAPI: 커맨더 정보가 반환되지 않음"; + /* CQC rank. [stats.py] */ "Champion" = "Champion"; @@ -130,6 +130,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "편집"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC: Python 3.x을 지원하지 않는 플러그인"; + /* Top rank. [stats.py] */ "Elite" = "Elite"; @@ -148,6 +151,9 @@ /* Trade rank. [stats.py] */ "Entrepreneur" = "Entrepreneur"; +/* [companion.py] */ +"Error" = "오류"; + /* [eddn.py] */ "Error: Can't connect to EDDN" = "오류: EDDN에 연결할 수 없음"; @@ -157,6 +163,12 @@ /* [inara.py] */ "Error: Can't connect to Inara" = "오류: Inara에 연결할 수 없음"; +/* [companion.py] */ +"Error: Couldn't check token customer_id" = "오류: customer_id 토큰을 확인할 수 없었음"; + +/* [companion.py] */ +"Error: customer_id doesn't match!" = "오류: customer_id가 일치하지 않습니다!"; + /* [edsm.py] */ "Error: EDSM {MSG}" = "오류: EDSM {MSG}"; @@ -175,6 +187,9 @@ /* [companion.py] */ "Error: Invalid Credentials" = "오류: 잘못된 자격 증명"; +/* [companion.py] */ +"Error: unable to get token" = "오류: 토큰을 받지 못함"; + /* Raised when the user has multiple accounts and the username/password setting is not for the account they're currently playing OR the user has reset their Cmdr and the Companion API server is still returning data for the old Cmdr. [companion.py] */ "Error: Wrong Cmdr" = "오류: 잘못된 Cmdr"; @@ -235,6 +250,9 @@ /* Section heading in settings. [inara.py] */ "Inara credentials" = "Inara 계정 정보"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "플러그인 위치 변경에 대한 정보"; + /* Changed journal update_lock failed [monitor.py] */ "Journal directory already locked" = "저널 디렉터리가 이미 잠김"; @@ -262,12 +280,18 @@ /* Cmdr stats. [stats.py] */ "Loan" = "대출"; +/* Label for user configured level of logging [prefs.py] */ +"Log Level" = "로깅 수준"; + /* [EDMarketConnector.py] */ "Logging in..." = "로그인하는 중..."; /* Empire rank. [stats.py] */ "Lord" = "Lord"; +/* Label for 'UI Transparency' option in [prefs.py] */ +"Main window transparency" = "메인 창 투명도"; + /* [prefs.py] */ "Market data in CSV format file" = "CSV 형식 파일의 마켓 정보"; @@ -286,6 +310,9 @@ /* Federation rank. [stats.py] */ "Midshipman" = "Midshipman"; +/* Appearance setting. [EDMarketConnector.py] */ +"Minimize to system tray" = "시스템 트레이로 최소화"; + /* Explorer rank. [stats.py] */ "Mostly Aimless" = "Mostly Aimless"; @@ -310,6 +337,9 @@ /* [prefs.py] */ "OK" = "OK"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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}' 에서 '{PLUGINS}' 탭에 들어가 활성화되어있는 플러그인 목록을 확인하십시오. 플러그인들 중 새 버전이 나온 것이 있는지도 확인해보시고, 만약 3.x를 지원하지도, 새 버전도 없다면 해당 플러그인의 개발자에게 코드를 수정하기를 문의하십시오.\n\n플러그인을 비활성화하려면 '{DISABLED}'를 폴더명 뒤에 추가하면 됩니다."; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Elite: Dangerous가 활성 창 상태일때만"; @@ -352,17 +382,8 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "플러그인 폴더"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC: Python 3.x을 지원하지 않는 플러그인"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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}' 에서 '{PLUGINS}' 탭에 들어가 활성화되어있는 플러그인 목록을 확인하십시오. 플러그인들 중 새 버전이 나온 것이 있는지도 확인해보시고, 만약 3.x를 지원하지도, 새 버전도 없다면 해당 플러그인의 개발자에게 코드를 수정하기를 문의하십시오.\n\n플러그인을 비활성화하려면 '{DISABLED}'를 폴더명 뒤에 추가하면 됩니다."; - /* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "Python 3.x을 지원하지 않는 플러그인"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "플러그인 위치 변경에 대한 정보"; +"Plugins Without Python 3.x Support:" = "Python 3.x을 지원하지 않는 플러그인:"; /* Federation rank. [stats.py] */ "Post Captain" = "Post Captain"; @@ -484,6 +505,9 @@ /* Menu item. [EDMarketConnector.py] */ "Status" = "상태"; +/* 'Suit' label in main UI' [EDMarketConnector.py] */ +"Suit" = "슈트"; + /* Explorer rank. [stats.py] */ "Surveyor" = "Surveyor"; @@ -511,6 +535,12 @@ /* Trade rank. [stats.py] */ "Tycoon" = "Tycoon"; +/* Label for 'UI Scaling' option [prefs.py] */ +"UI Scale Percentage" = "UI 스케일 백분율"; + +/* General 'Unknown', e.g. suit loadout */ +"Unknown" = "알 수 없음"; + /* Update button in main window. [EDMarketConnector.py] */ "Update" = "새로 고침"; @@ -549,6 +579,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "단축기 사용을 위해선 {APP}이 권한 허용을 필요로 합니다"; - -/* Label for user configured level of logging [prefs.py] */ -"Log Level" = "로깅 수준"; diff --git a/L10n/lv.strings b/L10n/lv.strings index 8247abc4..673421ff 100644 --- a/L10n/lv.strings +++ b/L10n/lv.strings @@ -480,4 +480,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} vajag atļaujas lai izmantotu īssceļus"; - diff --git a/L10n/nl.strings b/L10n/nl.strings index 747d4452..3c58da8b 100644 --- a/L10n/nl.strings +++ b/L10n/nl.strings @@ -121,6 +121,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "Bewerken"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMS: Plugins zonder Python 3.x ondersteuning"; + /* Top rank. [stats.py] */ "Elite" = "Elite"; @@ -223,6 +226,9 @@ /* Section heading in settings. [inara.py] */ "Inara credentials" = "Inara inlog gegevens"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "Informatie over plugins migreren"; + /* Hotkey/Shortcut settings prompt on OSX. [prefs.py] */ "Keyboard shortcut" = "Toetscombinaties"; @@ -295,6 +301,9 @@ /* [prefs.py] */ "OK" = "OK"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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." = "Een of meer ingeschakelde plugins hebben nog geen Python 3.x ondersteuning. Kijk op de lijst op de '{PLUGINS}' tab van '{FILE}' > '{SETTINGS}'. Check of er een bijgewerkte versie beschikbaar is. Laat anders de developer weten dat ze de code moeten updaten voor Python 3.x.\n\nJe kan de plugin uitschakelen door het mapje te hernoemen met '{DISABLED}' aan het eind van de naam."; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Alleen wanneer Elite: Dangerous de actieve applicatie is"; @@ -337,18 +346,6 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "Plugins map"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMS: Plugins zonder Python 3.x ondersteuning"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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." = "Een of meer ingeschakelde plugins hebben nog geen Python 3.x ondersteuning. Kijk op de lijst op de '{PLUGINS}' tab van '{FILE}' > '{SETTINGS}'. Check of er een bijgewerkte versie beschikbaar is. Laat anders de developer weten dat ze de code moeten updaten voor Python 3.x.\n\nJe kan de plugin uitschakelen door het mapje te hernoemen met '{DISABLED}' aan het eind van de naam."; - -/* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "Plugins zonder Python 3.x support"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "Informatie over plugins migreren"; - /* Federation rank. [stats.py] */ "Post Captain" = "Post Captain"; @@ -525,4 +522,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} heeft toestemming nodig om toetscombinaties te gebruiken"; - diff --git a/L10n/pl.strings b/L10n/pl.strings index 7f41bbdd..47c166a3 100644 --- a/L10n/pl.strings +++ b/L10n/pl.strings @@ -1,12 +1,12 @@ -/* Label for 'UI Scaling' option [prefs.py] */ -"UI Scale Percentage" = "Skalowanie UI"; +/* Language name */ +"!Language" = "Polski"; + +/* Message next to 'UI Transparency' slider [prefs.py] */ +"100 means fully opaque.{CR}Window is updated in real time" = "100 oznacza nieprzeźroczyste.{CR}Okno aktualizowane w czasie rzeczywistym."; /* Text describing that value '100' means 'default', and changes require a restart [prefs.py] */ "100 means Default{CR}Restart Required for{CR}changes to take effect!" = "100 oznacza wartość domyślną{CR}Zmiany zostaną wprowadzone po{CR}ponownym uruchomieniu programu!"; -/* Language name */ -"!Language" = "Polski"; - /* App menu entry on OSX. [EDMarketConnector.py] */ "About {APP}" = "{APP}..."; @@ -46,12 +46,12 @@ /* Folder selection button on Windows. [prefs.py] */ "Browse..." = "Przeglądaj..."; -/* No 'commander' data in CAPI [EDMarketConnector.py] */ -"CAPI: No commander data returned" = "CAPI: Nie zwrócono danych dowódcy"; - /* Federation rank. [stats.py] */ "Cadet" = "Cadet"; +/* No 'commander' data in CAPI [EDMarketConnector.py] */ +"CAPI: No commander data returned" = "CAPI: Nie zwrócono danych dowódcy"; + /* CQC rank. [stats.py] */ "Champion" = "Champion"; @@ -130,6 +130,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "Edycja"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC: Pluginy Nie Wspierające Python 3.x"; + /* Top rank. [stats.py] */ "Elite" = "Elite"; @@ -148,6 +151,9 @@ /* Trade rank. [stats.py] */ "Entrepreneur" = "Entrepreneur"; +/* [companion.py] */ +"Error" = "Błąd"; + /* [eddn.py] */ "Error: Can't connect to EDDN" = "Błąd: Brak połączenia z EDDN"; @@ -157,6 +163,12 @@ /* [inara.py] */ "Error: Can't connect to Inara" = "Błąd: Nie można połączyć się z serwisem Inara"; +/* [companion.py] */ +"Error: Couldn't check token customer_id" = "Błąd: Nie można sprawdzić ID klienta z tokenu"; + +/* [companion.py] */ +"Error: customer_id doesn't match!" = "Błąd: ID klienta nie pasuje!"; + /* [edsm.py] */ "Error: EDSM {MSG}" = "Błąd: EDSM {MSG}"; @@ -175,6 +187,9 @@ /* [companion.py] */ "Error: Invalid Credentials" = "Błąd: Dane uwierzytelniające niepoprawne"; +/* [companion.py] */ +"Error: unable to get token" = "Błąd: Nie można pobrać tokenu"; + /* Raised when the user has multiple accounts and the username/password setting is not for the account they're currently playing OR the user has reset their Cmdr and the Companion API server is still returning data for the old Cmdr. [companion.py] */ "Error: Wrong Cmdr" = "Błąd: Niepoprawny Cmdr"; @@ -235,6 +250,9 @@ /* Section heading in settings. [inara.py] */ "Inara credentials" = "Inara - uprawnienia"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "Informacja o migracji pluginów"; + /* Changed journal update_lock failed [monitor.py] */ "Journal directory already locked" = "Katalog dziennika zablokowany"; @@ -262,12 +280,18 @@ /* Cmdr stats. [stats.py] */ "Loan" = "Pożyczka"; +/* Label for user configured level of logging [prefs.py] */ +"Log Level" = "Poziom logowania"; + /* [EDMarketConnector.py] */ "Logging in..." = "Logowanie..."; /* Empire rank. [stats.py] */ "Lord" = "Lord"; +/* Label for 'UI Transparency' option in [prefs.py] */ +"Main window transparency" = "Przeźroczystość okna głównego"; + /* [prefs.py] */ "Market data in CSV format file" = "Dane rynkowe w formacie CSV"; @@ -286,6 +310,9 @@ /* Federation rank. [stats.py] */ "Midshipman" = "Midshipman"; +/* Appearance setting. [EDMarketConnector.py] */ +"Minimize to system tray" = "Zminimalizuj do zasobnika systemowego"; + /* Explorer rank. [stats.py] */ "Mostly Aimless" = "Mostly Aimless"; @@ -310,6 +337,9 @@ /* [prefs.py] */ "OK" = "OK"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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." = "Co najmniej jeden z uruchomionych pluginów nie wspiera Python 3.x. Sprawdź listę w '{FILE}' > '{SETTINGS}', sekcja '{PLUGINS}'. Upewnij się, że dostępna jest aktualna wersja pluginu, w przeciwnym razie poinformuj twórcę, że należy zaktualizować kod do wersji Python 3.x.\n\nMożesz wyłączyć plugin, dodając '{DISABLED}' na koniec nazwy jego folderu."; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Tylko gdy Elite: Dangerous jest aplikacją aktywną"; @@ -352,17 +382,8 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "Folder pluginów"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC: Pluginy Nie Wspierające Python 3.x"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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." = "Co najmniej jeden z uruchomionych pluginów nie wspiera Python 3.x. Sprawdź listę w '{FILE}' > '{SETTINGS}', sekcja '{PLUGINS}'. Upewnij się, że dostępna jest aktualna wersja pluginu, w przeciwnym razie poinformuj twórcę, że należy zaktualizować kod do wersji Python 3.x.\n\nMożesz wyłączyć plugin, dodając '{DISABLED}' na koniec nazwy jego folderu."; - /* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "Pluginy nie wspierające Python 3.x"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "Informacja o migracji pluginów"; +"Plugins Without Python 3.x Support:" = "Pluginy nie obsługiwane przez Python 3.x:"; /* Federation rank. [stats.py] */ "Post Captain" = "Post Captain"; @@ -484,6 +505,9 @@ /* Menu item. [EDMarketConnector.py] */ "Status" = "Status"; +/* 'Suit' label in main UI' [EDMarketConnector.py] */ +"Suit" = "Kombinezon"; + /* Explorer rank. [stats.py] */ "Surveyor" = "Surveyor"; @@ -511,6 +535,12 @@ /* Trade rank. [stats.py] */ "Tycoon" = "Tycoon"; +/* Label for 'UI Scaling' option [prefs.py] */ +"UI Scale Percentage" = "Skalowanie UI"; + +/* General 'Unknown', e.g. suit loadout */ +"Unknown" = "Nieznany"; + /* Update button in main window. [EDMarketConnector.py] */ "Update" = "Aktualizacja"; @@ -549,6 +579,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} wymaga uprawnień by{CR}móc korzystać ze skrótów klawiszowych."; - -/* Label for user configured level of logging [prefs.py] */ -"Log Level" = "Poziom logowania"; diff --git a/L10n/pt-BR.strings b/L10n/pt-BR.strings index 7e6b1e5f..bd9404f1 100644 --- a/L10n/pt-BR.strings +++ b/L10n/pt-BR.strings @@ -1,12 +1,12 @@ -/* Label for 'UI Scaling' option [prefs.py] */ -"UI Scale Percentage" = "Porcentagem de escala da IU"; +/* Language name */ +"!Language" = "Português (Brasil)"; + +/* Message next to 'UI Transparency' slider [prefs.py] */ +"100 means fully opaque.{CR}Window is updated in real time" = "100 significa totalmente opaco.{CR}A janela é atualizada em tempo real."; /* Text describing that value '100' means 'default', and changes require a restart [prefs.py] */ "100 means Default{CR}Restart Required for{CR}changes to take effect!" = "100 significa Padrão{CR}Necessário Reiniciar para as{CR}alterações entrarem em vigor!"; -/* Language name */ -"!Language" = "Português (Brasil)"; - /* App menu entry on OSX. [EDMarketConnector.py] */ "About {APP}" = "Sobre {APP}"; @@ -49,6 +49,9 @@ /* Federation rank. [stats.py] */ "Cadet" = "Aspirante"; +/* No 'commander' data in CAPI [EDMarketConnector.py] */ +"CAPI: No commander data returned" = "CAPI: Nenhum dado de comandante retornado"; + /* CQC rank. [stats.py] */ "Champion" = "Campeão"; @@ -127,6 +130,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "Editar"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC: Plugins sem Suporte ao Python 3.x"; + /* Top rank. [stats.py] */ "Elite" = "Elite"; @@ -145,6 +151,9 @@ /* Trade rank. [stats.py] */ "Entrepreneur" = "Empresário"; +/* [companion.py] */ +"Error" = "Erro"; + /* [eddn.py] */ "Error: Can't connect to EDDN" = "Erro: Não é possível conectar-se ao EDDN"; @@ -154,6 +163,12 @@ /* [inara.py] */ "Error: Can't connect to Inara" = "Erro: Não é possível conectar-se a Inara"; +/* [companion.py] */ +"Error: Couldn't check token customer_id" = "Erro: não foi possível verificar o token customer_id"; + +/* [companion.py] */ +"Error: customer_id doesn't match!" = "Erro: customer_id diferente!"; + /* [edsm.py] */ "Error: EDSM {MSG}" = "Erro: EDSM {MSG}"; @@ -172,6 +187,9 @@ /* [companion.py] */ "Error: Invalid Credentials" = "Erro: Credenciais Inválidas"; +/* [companion.py] */ +"Error: unable to get token" = "Erro: não foi possível obter o token"; + /* Raised when the user has multiple accounts and the username/password setting is not for the account they're currently playing OR the user has reset their Cmdr and the Companion API server is still returning data for the old Cmdr. [companion.py] */ "Error: Wrong Cmdr" = "Erro: Cmdt Errado"; @@ -226,9 +244,18 @@ /* Hotkey/Shortcut settings prompt on Windows. [prefs.py] */ "Hotkey" = "Tecla de atalho"; +/* Changed journal update_lock failed [monitor.py] */ +"Ignore" = "Ignorar"; + /* Section heading in settings. [inara.py] */ "Inara credentials" = "Credenciais do Inara"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "Informações de migração de plugins"; + +/* Changed journal update_lock failed [monitor.py] */ +"Journal directory already locked" = "Diretório de Jornais já está bloqueado"; + /* Hotkey/Shortcut settings prompt on OSX. [prefs.py] */ "Keyboard shortcut" = "Atalho de teclado"; @@ -253,12 +280,18 @@ /* Cmdr stats. [stats.py] */ "Loan" = "Empréstimo"; +/* Label for user configured level of logging [prefs.py] */ +"Log Level" = "Nível de Log"; + /* [EDMarketConnector.py] */ "Logging in..." = "Efetuando login..."; /* Empire rank. [stats.py] */ "Lord" = "Lorde"; +/* Label for 'UI Transparency' option in [prefs.py] */ +"Main window transparency" = "Transparência da janela principal"; + /* [prefs.py] */ "Market data in CSV format file" = "Dados de mercado no arquivo de formato CSV"; @@ -277,6 +310,9 @@ /* Federation rank. [stats.py] */ "Midshipman" = "Cabo"; +/* Appearance setting. [EDMarketConnector.py] */ +"Minimize to system tray" = "Minimizar para a área de notificação"; + /* Explorer rank. [stats.py] */ "Mostly Aimless" = "Quase perdido"; @@ -301,6 +337,9 @@ /* [prefs.py] */ "OK" = "OK"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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 habilitados não possuem suporte ao Python 3.x. Você pode ver a lista na guia '{PLUGINS}' em '{FILE}' > '{SETTINGS}'. Você deve verificar se existe versão atualizada ou então avisar o desenvolvedor de que ele precisa atualizar o código para o Python 3.x.\n\nVocê pode desabilitar um plugin renomeando sua pasta para que seu nome termine com '{DISABLED}'."; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Somente quando o Elite: Dangerous é o aplicativo ativo"; @@ -343,17 +382,8 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "Pasta dos plugins"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC: Plugins sem Suporte ao Python 3.x"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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 habilitados não possuem suporte ao Python 3.x. Você pode ver a lista na guia '{PLUGINS}' em '{FILE}' > '{SETTINGS}'. Você deve verificar se existe versão atualizada ou então avisar o desenvolvedor de que ele precisa atualizar o código para o Python 3.x.\n\nVocê pode desabilitar um plugin renomeando sua pasta para que seu nome termine com '{DISABLED}'."; - /* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "Plugins sem Suporte ao Python 3.x"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "Informações de migração de plugins"; +"Plugins Without Python 3.x Support:" = "Plugins sem suporte a Python 3.x:"; /* Federation rank. [stats.py] */ "Post Captain" = "Capitão de Fragata"; @@ -409,6 +439,9 @@ /* Help menu item. [EDMarketConnector.py] */ "Release Notes" = "Notas de atualização"; +/* Changed journal update_lock failed [monitor.py] */ +"Retry" = "Tentar novamente"; + /* Multicrew role label in main window. [EDMarketConnector.py] */ "Role" = "Função"; @@ -454,6 +487,9 @@ /* Setting to decide which ship outfitting website to link to - either E:D Shipyard or Coriolis. [prefs.py] */ "Shipyard" = "Estaleiro"; +/* Status line text that appears when process exit sequence starts [EDMarketConnector.py] */ +"Shutting down..." = "Encerrando..."; + /* Empire rank. [stats.py] */ "Squire" = "Escudeiro"; @@ -469,12 +505,18 @@ /* Menu item. [EDMarketConnector.py] */ "Status" = "Status"; +/* 'Suit' label in main UI' [EDMarketConnector.py] */ +"Suit" = "Traje"; + /* Explorer rank. [stats.py] */ "Surveyor" = "Cartógrafo"; /* Main window. [EDMarketConnector.py] */ "System" = "Sistema"; +/* Changed journal update_lock failed [monitor.py] */ +"The new Journal Directory location is already locked.{CR}You can either attempt to resolve this and then Retry, or choose to Ignore this." = "O novo Diretório de Jornais já está bloqueado.{CR}Você pode resolver o problema e Tentar novamente, ou Ignorar o erro."; + /* Appearance setting. [prefs.py] */ "Theme" = "Tema"; @@ -493,6 +535,12 @@ /* Trade rank. [stats.py] */ "Tycoon" = "Magnata"; +/* Label for 'UI Scaling' option [prefs.py] */ +"UI Scale Percentage" = "Porcentagem de escala da IU"; + +/* General 'Unknown', e.g. suit loadout */ +"Unknown" = "Desconhecido"; + /* Update button in main window. [EDMarketConnector.py] */ "Update" = "Atualizar"; @@ -531,6 +579,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} precisa de permissão para usar atalhos"; - -/* Label for user configured level of logging [prefs.py] */ -"Log Level" = "Nível de Log"; diff --git a/L10n/pt-PT.strings b/L10n/pt-PT.strings index 9b5ec61e..17287cad 100644 --- a/L10n/pt-PT.strings +++ b/L10n/pt-PT.strings @@ -1,12 +1,12 @@ -/* Label for 'UI Scaling' option [prefs.py] */ -"UI Scale Percentage" = "Percentagem da escala de UI"; +/* Language name */ +"!Language" = "Português (Portugal)"; + +/* Message next to 'UI Transparency' slider [prefs.py] */ +"100 means fully opaque.{CR}Window is updated in real time" = "100 é completamente opaco.{CR}A janela é actualizada em tempo real."; /* Text describing that value '100' means 'default', and changes require a restart [prefs.py] */ "100 means Default{CR}Restart Required for{CR}changes to take effect!" = "100 significa Predefinido{CR}Requer reinício para{CR}que as mudanças façam efeito!"; -/* Language name */ -"!Language" = "Português (Portugal)"; - /* App menu entry on OSX. [EDMarketConnector.py] */ "About {APP}" = "Sobre {APP}"; @@ -46,12 +46,12 @@ /* Folder selection button on Windows. [prefs.py] */ "Browse..." = "Procurar..."; -/* No 'commander' data in CAPI [EDMarketConnector.py] */ -"CAPI: No commander data returned" = "CAPI: Dados do Comandante não recebidos"; - /* Federation rank. [stats.py] */ "Cadet" = "Cadete"; +/* No 'commander' data in CAPI [EDMarketConnector.py] */ +"CAPI: No commander data returned" = "CAPI: Dados do Comandante não recebidos"; + /* CQC rank. [stats.py] */ "Champion" = "Campeão"; @@ -130,6 +130,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "Editar"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC: Plugins sem suporte para Python 3.x"; + /* Top rank. [stats.py] */ "Elite" = "Elite"; @@ -148,6 +151,9 @@ /* Trade rank. [stats.py] */ "Entrepreneur" = "Empreendedor"; +/* [companion.py] */ +"Error" = "Erro"; + /* [eddn.py] */ "Error: Can't connect to EDDN" = "Erro: Não é possível conectar ao EDDN"; @@ -157,6 +163,12 @@ /* [inara.py] */ "Error: Can't connect to Inara" = "Erro: Não é possível conectar ao Inara"; +/* [companion.py] */ +"Error: Couldn't check token customer_id" = "Erro: Impossível verificar o token de customer_id"; + +/* [companion.py] */ +"Error: customer_id doesn't match!" = "Erro: customer_id não foi encontrado!"; + /* [edsm.py] */ "Error: EDSM {MSG}" = "Erro: EDSM {MSG}"; @@ -175,6 +187,9 @@ /* [companion.py] */ "Error: Invalid Credentials" = "Erro: Credenciais Inválidas"; +/* [companion.py] */ +"Error: unable to get token" = "Erro: Não é possível obter o token"; + /* Raised when the user has multiple accounts and the username/password setting is not for the account they're currently playing OR the user has reset their Cmdr and the Companion API server is still returning data for the old Cmdr. [companion.py] */ "Error: Wrong Cmdr" = "Erro: Cmdt errado"; @@ -235,6 +250,9 @@ /* Section heading in settings. [inara.py] */ "Inara credentials" = "Credenciais Inara"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "Informação para migração de plugins"; + /* Changed journal update_lock failed [monitor.py] */ "Journal directory already locked" = "Directório do Diário já se encontra bloqueado"; @@ -262,12 +280,18 @@ /* Cmdr stats. [stats.py] */ "Loan" = "Empréstimo"; +/* Label for user configured level of logging [prefs.py] */ +"Log Level" = "Nível de Log"; + /* [EDMarketConnector.py] */ "Logging in..." = "Realizando login..."; /* Empire rank. [stats.py] */ "Lord" = "Lorde"; +/* Label for 'UI Transparency' option in [prefs.py] */ +"Main window transparency" = "Transparência da janela principal"; + /* [prefs.py] */ "Market data in CSV format file" = "Ficheiro dos dados de Mercado no formato CSV"; @@ -286,6 +310,9 @@ /* Federation rank. [stats.py] */ "Midshipman" = "Aspirante"; +/* Appearance setting. [EDMarketConnector.py] */ +"Minimize to system tray" = "Minimizar para a barra de tarefas"; + /* Explorer rank. [stats.py] */ "Mostly Aimless" = "Quase sem destino"; @@ -310,6 +337,9 @@ /* [prefs.py] */ "OK" = "OK"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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."; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Apenas quando o Elite:Dangerous é a aplicação activa"; @@ -352,17 +382,8 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "Pasta dos Plugins"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC: Plugins sem suporte para Python 3.x"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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."; - /* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "Plugins sem suporte para Python 3.x"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "Informação para migração de plugins"; +"Plugins Without Python 3.x Support:" = "Plugins sem suporte para Python 3.x"; /* Federation rank. [stats.py] */ "Post Captain" = "Capitão de Fragata"; @@ -484,6 +505,9 @@ /* Menu item. [EDMarketConnector.py] */ "Status" = "Estado"; +/* 'Suit' label in main UI' [EDMarketConnector.py] */ +"Suit" = "Fato"; + /* Explorer rank. [stats.py] */ "Surveyor" = "Cartógrafo"; @@ -511,6 +535,12 @@ /* Trade rank. [stats.py] */ "Tycoon" = "Magnata"; +/* Label for 'UI Scaling' option [prefs.py] */ +"UI Scale Percentage" = "Percentagem da escala de UI"; + +/* General 'Unknown', e.g. suit loadout */ +"Unknown" = "Desconhecido"; + /* Update button in main window. [EDMarketConnector.py] */ "Update" = "Actualizar"; @@ -549,6 +579,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "A {APP} precisa de autorização para usar atalhos"; - -/* Label for user configured level of logging [prefs.py] */ -"Log Level" = "Nível de Log"; diff --git a/L10n/ru.strings b/L10n/ru.strings index 934ab0b8..f6bbe980 100644 --- a/L10n/ru.strings +++ b/L10n/ru.strings @@ -1,12 +1,12 @@ -/* Label for 'UI Scaling' option [prefs.py] */ -"UI Scale Percentage" = "Процент масштабирования интерфейса"; +/* Language name */ +"!Language" = "Русский"; + +/* Message next to 'UI Transparency' slider [prefs.py] */ +"100 means fully opaque.{CR}Window is updated in real time" = "100 означает полностью непрозрачный.{CR}Окно обновляется в режиме реального времени."; /* Text describing that value '100' means 'default', and changes require a restart [prefs.py] */ "100 means Default{CR}Restart Required for{CR}changes to take effect!" = "100 - значение по умолчанию{CR}требуется перезапуск для вступления в силу изменений{CR}!"; -/* Language name */ -"!Language" = "Русский"; - /* App menu entry on OSX. [EDMarketConnector.py] */ "About {APP}" = "О программе {APP}"; @@ -46,12 +46,12 @@ /* Folder selection button on Windows. [prefs.py] */ "Browse..." = "Просмотреть..."; -/* No 'commander' data in CAPI [EDMarketConnector.py] */ -"CAPI: No commander data returned" = "CAPI: Нет данных пилота"; - /* Federation rank. [stats.py] */ "Cadet" = "Кадет"; +/* No 'commander' data in CAPI [EDMarketConnector.py] */ +"CAPI: No commander data returned" = "CAPI: Нет данных пилота"; + /* CQC rank. [stats.py] */ "Champion" = "Чемпион"; @@ -130,6 +130,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "Правка"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC: Без поддержки Python 3.x"; + /* Top rank. [stats.py] */ "Elite" = "Элита"; @@ -148,6 +151,9 @@ /* Trade rank. [stats.py] */ "Entrepreneur" = "Предприниматель"; +/* [companion.py] */ +"Error" = "Ошибка"; + /* [eddn.py] */ "Error: Can't connect to EDDN" = "Ошибка: не удается подключиться к EDDN"; @@ -157,6 +163,12 @@ /* [inara.py] */ "Error: Can't connect to Inara" = "Ошибка: не удается подключиться к Inara"; +/* [companion.py] */ +"Error: Couldn't check token customer_id" = "Ошибка: невозможно проверить токен customer_id"; + +/* [companion.py] */ +"Error: customer_id doesn't match!" = "Ошибка: customer_id не совпадает!"; + /* [edsm.py] */ "Error: EDSM {MSG}" = "Ошибка: EDSM {MSG}"; @@ -175,6 +187,9 @@ /* [companion.py] */ "Error: Invalid Credentials" = "Ошибка: неизвестное имя пользователя или неверный пароль"; +/* [companion.py] */ +"Error: unable to get token" = "Ошибка: не удается получить токен"; + /* Raised when the user has multiple accounts and the username/password setting is not for the account they're currently playing OR the user has reset their Cmdr and the Companion API server is still returning data for the old Cmdr. [companion.py] */ "Error: Wrong Cmdr" = "Ошибка: неверное имя командира"; @@ -235,6 +250,9 @@ /* Section heading in settings. [inara.py] */ "Inara credentials" = "Учётные данные Inara"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "Информация о мигрирующих плагинах"; + /* Changed journal update_lock failed [monitor.py] */ "Journal directory already locked" = "Каталог журнала уже заблокирован"; @@ -262,12 +280,18 @@ /* Cmdr stats. [stats.py] */ "Loan" = "Долг"; +/* Label for user configured level of logging [prefs.py] */ +"Log Level" = "Уровень лога"; + /* [EDMarketConnector.py] */ "Logging in..." = "Идет подключение..."; /* Empire rank. [stats.py] */ "Lord" = "Лорд"; +/* Label for 'UI Transparency' option in [prefs.py] */ +"Main window transparency" = "Прозрачность главного окна"; + /* [prefs.py] */ "Market data in CSV format file" = "Данные рынков в формате CSV"; @@ -286,6 +310,9 @@ /* Federation rank. [stats.py] */ "Midshipman" = "Гардемарин"; +/* Appearance setting. [EDMarketConnector.py] */ +"Minimize to system tray" = "Сворачивать в системный трей"; + /* Explorer rank. [stats.py] */ "Mostly Aimless" = "Почти бесцельный"; @@ -310,6 +337,9 @@ /* [prefs.py] */ "OK" = "OK"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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." = "Один или несколько ваших подключённых плагинов ещё не имеют поддержки Python 3.x. Пожалуйста, ознакомьтесь со списком во вкладке '{PLUGINS}' '{FILE}' > '{SETTINGS}'. Вы должны проверить наличие обновлённой версии, в противном случае предупредите разработчика о необходимости обновления кода на Python 3.x.\n\nВы можете отключить плагин, переименовав его папку в '{DISABLED}'."; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Только когда окно Elite: Dangerous активно"; @@ -352,17 +382,8 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "Папка плагинов"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC: Без поддержки Python 3.x"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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." = "Один или несколько ваших подключённых плагинов ещё не имеют поддержки Python 3.x. Пожалуйста, ознакомьтесь со списком во вкладке '{PLUGINS}' '{FILE}' > '{SETTINGS}'. Вы должны проверить наличие обновлённой версии, в противном случае предупредите разработчика о необходимости обновления кода на Python 3.x.\n\nВы можете отключить плагин, переименовав его папку в '{DISABLED}'."; - /* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "Плагины без поддержки Python 3.x"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "Информация о мигрирующих плагинах"; +"Plugins Without Python 3.x Support:" = "Плагины без поддержки Python 3.x"; /* Federation rank. [stats.py] */ "Post Captain" = "Командир корабля"; @@ -484,6 +505,9 @@ /* Menu item. [EDMarketConnector.py] */ "Status" = "Статус"; +/* 'Suit' label in main UI' [EDMarketConnector.py] */ +"Suit" = "Костюм"; + /* Explorer rank. [stats.py] */ "Surveyor" = "Изыскатель"; @@ -511,6 +535,12 @@ /* Trade rank. [stats.py] */ "Tycoon" = "Магнат"; +/* Label for 'UI Scaling' option [prefs.py] */ +"UI Scale Percentage" = "Процент масштабирования интерфейса"; + +/* General 'Unknown', e.g. suit loadout */ +"Unknown" = "Неизвестно"; + /* Update button in main window. [EDMarketConnector.py] */ "Update" = "Обновить данные"; @@ -549,6 +579,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} требуется разрешение на использование глобальных сочетаний клавиш"; - -/* Label for user configured level of logging [prefs.py] */ -"Log Level" = "Уровень лога"; diff --git a/L10n/sl.strings b/L10n/sl.strings index 2020469c..8601189f 100644 --- a/L10n/sl.strings +++ b/L10n/sl.strings @@ -429,4 +429,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} potrebuje dovoljenja za uporabo bližnjic"; - diff --git a/L10n/sr-Latn-BA.strings b/L10n/sr-Latn-BA.strings index d9dba531..0e83eac4 100644 --- a/L10n/sr-Latn-BA.strings +++ b/L10n/sr-Latn-BA.strings @@ -1,12 +1,12 @@ -/* Label for 'UI Scaling' option [prefs.py] */ -"UI Scale Percentage" = "Procenat UI skaliranja"; +/* Language name */ +"!Language" = "Srpski (Latinica, Bosna i Hercegovina)"; + +/* Message next to 'UI Transparency' slider [prefs.py] */ +"100 means fully opaque.{CR}Window is updated in real time" = "100 znači potpuno neprozirno.{CR}Prozor se osvježava u realnom vremenu"; /* Text describing that value '100' means 'default', and changes require a restart [prefs.py] */ "100 means Default{CR}Restart Required for{CR}changes to take effect!" = "100 je standardna vrijednost{CR}Potreban je restart{CR}za primjenu podešavanja!"; -/* Language name */ -"!Language" = "Srpski (Latinica, Bosna i Hercegovina)"; - /* App menu entry on OSX. [EDMarketConnector.py] */ "About {APP}" = "O {APP}"; @@ -46,12 +46,12 @@ /* Folder selection button on Windows. [prefs.py] */ "Browse..." = "Potraži..."; -/* No 'commander' data in CAPI [EDMarketConnector.py] */ -"CAPI: No commander data returned" = "CAPI: Nema podataka o komandantu"; - /* Federation rank. [stats.py] */ "Cadet" = "Cadet"; +/* No 'commander' data in CAPI [EDMarketConnector.py] */ +"CAPI: No commander data returned" = "CAPI: Nema podataka o komandantu"; + /* CQC rank. [stats.py] */ "Champion" = "Champion"; @@ -130,6 +130,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "Uredi"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC: Dodaci (plugins) bez Python 3.x podrške"; + /* Top rank. [stats.py] */ "Elite" = "Elite"; @@ -148,6 +151,9 @@ /* Trade rank. [stats.py] */ "Entrepreneur" = "Entrepreneur"; +/* [companion.py] */ +"Error" = "Greška"; + /* [eddn.py] */ "Error: Can't connect to EDDN" = "Greška: Nemoguće povezivanje sa EDDN"; @@ -157,6 +163,12 @@ /* [inara.py] */ "Error: Can't connect to Inara" = "Greška: Nemoguće povezivanje sa Inara"; +/* [companion.py] */ +"Error: Couldn't check token customer_id" = "Greška: Nemoguća provjera tokena customer_id"; + +/* [companion.py] */ +"Error: customer_id doesn't match!" = "Greška: customer_id se ne poklapa!"; + /* [edsm.py] */ "Error: EDSM {MSG}" = "Greška: EDSM {MSG}"; @@ -175,6 +187,9 @@ /* [companion.py] */ "Error: Invalid Credentials" = "Greška: Neispravni kredencijali"; +/* [companion.py] */ +"Error: unable to get token" = "Greška: Nemoguće dobaviti token"; + /* Raised when the user has multiple accounts and the username/password setting is not for the account they're currently playing OR the user has reset their Cmdr and the Companion API server is still returning data for the old Cmdr. [companion.py] */ "Error: Wrong Cmdr" = "Greška: Pogrešan Cmdr"; @@ -235,6 +250,9 @@ /* Section heading in settings. [inara.py] */ "Inara credentials" = "Kredencijali za Inara"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "Informacije o migraciji dodataka (plugins)"; + /* Changed journal update_lock failed [monitor.py] */ "Journal directory already locked" = "Journal direktorijum je već zaključan"; @@ -262,12 +280,18 @@ /* Cmdr stats. [stats.py] */ "Loan" = "Zajam"; +/* Label for user configured level of logging [prefs.py] */ +"Log Level" = "Log nivo"; + /* [EDMarketConnector.py] */ "Logging in..." = "Prijavljivanje..."; /* Empire rank. [stats.py] */ "Lord" = "Lord"; +/* Label for 'UI Transparency' option in [prefs.py] */ +"Main window transparency" = "Prozirnost glavnog prozora"; + /* [prefs.py] */ "Market data in CSV format file" = "Fajl sa market podacima u CSV formatu"; @@ -286,6 +310,9 @@ /* Federation rank. [stats.py] */ "Midshipman" = "Midshipman"; +/* Appearance setting. [EDMarketConnector.py] */ +"Minimize to system tray" = "Minimiziranje u system tray"; + /* Explorer rank. [stats.py] */ "Mostly Aimless" = "Mostly Aimless"; @@ -310,6 +337,9 @@ /* [prefs.py] */ "OK" = "OK"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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."; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Samo kada je Elite: Dangerous aktivna aplikacija"; @@ -352,17 +382,8 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "Folder za dodatke (plugins)"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC: Dodaci (plugins) bez Python 3.x podrške"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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."; - /* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "Dodaci (plugins) bez Python 3.x podrške"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "Informacije o migraciji dodataka (plugins)"; +"Plugins Without Python 3.x Support:" = "Dodaci (plugins) bez Python 3.x podrške:"; /* Federation rank. [stats.py] */ "Post Captain" = "Post Captain"; @@ -484,6 +505,9 @@ /* Menu item. [EDMarketConnector.py] */ "Status" = "Status"; +/* 'Suit' label in main UI' [EDMarketConnector.py] */ +"Suit" = "Odijelo"; + /* Explorer rank. [stats.py] */ "Surveyor" = "Surveyor"; @@ -511,6 +535,12 @@ /* Trade rank. [stats.py] */ "Tycoon" = "Tycoon"; +/* Label for 'UI Scaling' option [prefs.py] */ +"UI Scale Percentage" = "Procenat UI skaliranja"; + +/* General 'Unknown', e.g. suit loadout */ +"Unknown" = "Nepoznato"; + /* Update button in main window. [EDMarketConnector.py] */ "Update" = "Osvježi"; @@ -549,6 +579,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} traži dozvolu da koristi prečice"; - -/* Label for user configured level of logging [prefs.py] */ -"Log Level" = "Log nivo"; diff --git a/L10n/sr-Latn.strings b/L10n/sr-Latn.strings index 9154e070..30dda2c1 100644 --- a/L10n/sr-Latn.strings +++ b/L10n/sr-Latn.strings @@ -1,12 +1,12 @@ -/* Label for 'UI Scaling' option [prefs.py] */ -"UI Scale Percentage" = "Procenat UI skaliranja"; +/* Language name */ +"!Language" = "Srpski (Latinica)"; + +/* Message next to 'UI Transparency' slider [prefs.py] */ +"100 means fully opaque.{CR}Window is updated in real time" = "100 znači potpuno neprozirno.{CR}Prozor se osvežava u realnom vremenu."; /* Text describing that value '100' means 'default', and changes require a restart [prefs.py] */ "100 means Default{CR}Restart Required for{CR}changes to take effect!" = "100 znači podrazumevano{CR}Restart je potreban{CR}da bi se promene primenile!"; -/* Language name */ -"!Language" = "Srpski (Latinica)"; - /* App menu entry on OSX. [EDMarketConnector.py] */ "About {APP}" = "O {APP}"; @@ -46,12 +46,12 @@ /* Folder selection button on Windows. [prefs.py] */ "Browse..." = "Potraži..."; -/* No 'commander' data in CAPI [EDMarketConnector.py] */ -"CAPI: No commander data returned" = "CAPI: Nema podataka o komandiru"; - /* Federation rank. [stats.py] */ "Cadet" = "Cadet"; +/* No 'commander' data in CAPI [EDMarketConnector.py] */ +"CAPI: No commander data returned" = "CAPI: Nema podataka o komandiru"; + /* CQC rank. [stats.py] */ "Champion" = "Champion"; @@ -130,6 +130,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "Izmeni"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC: Dodaci (plugins) bez Python 3.x podrške"; + /* Top rank. [stats.py] */ "Elite" = "Elite"; @@ -148,6 +151,9 @@ /* Trade rank. [stats.py] */ "Entrepreneur" = "Entrepreneur"; +/* [companion.py] */ +"Error" = "Greška"; + /* [eddn.py] */ "Error: Can't connect to EDDN" = "Greška: Nemoguće povezivanje na EDDN"; @@ -157,6 +163,12 @@ /* [inara.py] */ "Error: Can't connect to Inara" = "Greška: Nemoguće povezivanje na Inara"; +/* [companion.py] */ +"Error: Couldn't check token customer_id" = "Greška: Nemoguća provera tokena customer_id"; + +/* [companion.py] */ +"Error: customer_id doesn't match!" = "Greška: customer_id se ne poklapa!"; + /* [edsm.py] */ "Error: EDSM {MSG}" = "Greška: EDSM {MSG}"; @@ -175,6 +187,9 @@ /* [companion.py] */ "Error: Invalid Credentials" = "Greška: Pogrešni kredencijali"; +/* [companion.py] */ +"Error: unable to get token" = "Greška: nemoguće dobaviti token"; + /* Raised when the user has multiple accounts and the username/password setting is not for the account they're currently playing OR the user has reset their Cmdr and the Companion API server is still returning data for the old Cmdr. [companion.py] */ "Error: Wrong Cmdr" = "Greška: Pogrešan Cmdr"; @@ -235,6 +250,9 @@ /* Section heading in settings. [inara.py] */ "Inara credentials" = "Inara kredencijali"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "Informacije o migraciji dodataka (plugins)"; + /* Changed journal update_lock failed [monitor.py] */ "Journal directory already locked" = "Žurnal direktorijum je već zaključan"; @@ -262,12 +280,18 @@ /* Cmdr stats. [stats.py] */ "Loan" = "Pozajmica"; +/* Label for user configured level of logging [prefs.py] */ +"Log Level" = "Log Nivo"; + /* [EDMarketConnector.py] */ "Logging in..." = "Prijavljivanje..."; /* Empire rank. [stats.py] */ "Lord" = "Lord"; +/* Label for 'UI Transparency' option in [prefs.py] */ +"Main window transparency" = "Prozirnost glavnog prozora"; + /* [prefs.py] */ "Market data in CSV format file" = "Fajl sa market podacima u CSV formatu"; @@ -286,6 +310,9 @@ /* Federation rank. [stats.py] */ "Midshipman" = "Midshipman"; +/* Appearance setting. [EDMarketConnector.py] */ +"Minimize to system tray" = "Minimizuj u sistemsku paletu (SysTray)"; + /* Explorer rank. [stats.py] */ "Mostly Aimless" = "Mostly Aimless"; @@ -310,6 +337,9 @@ /* [prefs.py] */ "OK" = "OK"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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}'. Proverite da li postoji nadograđena verzija ili obavesite autora da treba da promeni kod za Python 3.x.\n\nMožete deaktivirati dodatak (plugin) dodavanjem '{DISABLED}' na kraju imena njegovog foldera."; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Samo kada je Elite: Dangerous aktivna aplikacija"; @@ -352,17 +382,8 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "Folder za dodatke (plugins)"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC: Dodaci (plugins) bez Python 3.x podrške"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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}'. Proverite da li postoji nadograđena verzija ili obavesite autora da treba da promeni kod za Python 3.x.\n\nMožete deaktivirati dodatak (plugin) dodavanjem '{DISABLED}' na kraju imena njegovog foldera."; - /* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "Dodaci (plugins) bez Python 3.x podrške"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "Informacije o migraciji dodataka (plugins)"; +"Plugins Without Python 3.x Support:" = "Pluginovi bez podrške za Python 3.x:"; /* Federation rank. [stats.py] */ "Post Captain" = "Post Captain"; @@ -484,6 +505,9 @@ /* Menu item. [EDMarketConnector.py] */ "Status" = "Status"; +/* 'Suit' label in main UI' [EDMarketConnector.py] */ +"Suit" = "Odelo"; + /* Explorer rank. [stats.py] */ "Surveyor" = "Surveyor"; @@ -511,6 +535,12 @@ /* Trade rank. [stats.py] */ "Tycoon" = "Tycoon"; +/* Label for 'UI Scaling' option [prefs.py] */ +"UI Scale Percentage" = "Procenat UI skaliranja"; + +/* General 'Unknown', e.g. suit loadout */ +"Unknown" = "Nepoznato"; + /* Update button in main window. [EDMarketConnector.py] */ "Update" = "Osveži"; @@ -549,6 +579,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} traži dozvolu da koristi skraćenice"; - -/* Label for user configured level of logging [prefs.py] */ -"Log Level" = "Log Nivo"; diff --git a/L10n/sv-SE.strings b/L10n/sv-SE.strings index b968a501..82c4ced8 100644 --- a/L10n/sv-SE.strings +++ b/L10n/sv-SE.strings @@ -121,6 +121,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "Ändra"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC: Plugins utan stöd för Python 3.x"; + /* Top rank. [stats.py] */ "Elite" = "Elite"; @@ -223,6 +226,9 @@ /* Section heading in settings. [inara.py] */ "Inara credentials" = "Inara autentiseringsuppgifter"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "Information om migrering av plugins"; + /* Hotkey/Shortcut settings prompt on OSX. [prefs.py] */ "Keyboard shortcut" = "Genväg, tangentbord"; @@ -295,6 +301,9 @@ /* [prefs.py] */ "OK" = "OK"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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." = "En eller flera aktiverade plugins har inte stöd för Python 3.x. Var vänlig kontrollera listan med plugins under fliken '{PLUGINS}' under '{FILE}' > '{SETTINGS}'. Kontrollera om det finns en nyare version tillgänglig eller informera utvecklaren.\n\nDu kan också avaktivera din plugin genom att ändra slutet av namnet på mappen till '{DISABLED}'"; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Bara när: Elite Dangerous är det aktiva programmet"; @@ -337,18 +346,6 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "Mapp för plugins"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC: Plugins utan stöd för Python 3.x"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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." = "En eller flera aktiverade plugins har inte stöd för Python 3.x. Var vänlig kontrollera listan med plugins under fliken '{PLUGINS}' under '{FILE}' > '{SETTINGS}'. Kontrollera om det finns en nyare version tillgänglig eller informera utvecklaren.\n\nDu kan också avaktivera din plugin genom att ändra slutet av namnet på mappen till '{DISABLED}'"; - -/* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "Plugins utan stöd för Python 3.x"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "Information om migrering av plugins"; - /* Federation rank. [stats.py] */ "Post Captain" = "Post Captain"; @@ -522,4 +519,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} behöver rättigheter för att använda genvägar"; - diff --git a/L10n/uk.strings b/L10n/uk.strings index ace0df1f..35e5c954 100644 --- a/L10n/uk.strings +++ b/L10n/uk.strings @@ -1,6 +1,12 @@ /* Language name */ "!Language" = "Українська"; +/* Message next to 'UI Transparency' slider [prefs.py] */ +"100 means fully opaque.{CR}Window is updated in real time" = "100 означає повністю непрозоре. {CR} Вікно буде оновлюватись в режимі реального часу"; + +/* Text describing that value '100' means 'default', and changes require a restart [prefs.py] */ +"100 means Default{CR}Restart Required for{CR}changes to take effect!" = "100 означає, що {CR} потрібно перезапустити за замовчуванням, щоб зміни вступили в силу {CR}!"; + /* App menu entry on OSX. [EDMarketConnector.py] */ "About {APP}" = "Про {APP}"; @@ -43,6 +49,9 @@ /* Federation rank. [stats.py] */ "Cadet" = "Кадет"; +/* No 'commander' data in CAPI [EDMarketConnector.py] */ +"CAPI: No commander data returned" = "CAPI: Не отримано данних пілота"; + /* CQC rank. [stats.py] */ "Champion" = "Чемпіон"; @@ -121,6 +130,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "Редагувати"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC: Плагіни без підтримки Python 3.x!"; + /* Top rank. [stats.py] */ "Elite" = "Еліта"; @@ -139,6 +151,9 @@ /* Trade rank. [stats.py] */ "Entrepreneur" = "Підприємець"; +/* [companion.py] */ +"Error" = "Помилка"; + /* [eddn.py] */ "Error: Can't connect to EDDN" = "Помилка: Немає зв'язку з EDDN!"; @@ -148,6 +163,12 @@ /* [inara.py] */ "Error: Can't connect to Inara" = "Помилка: Немає з'єднання з Inara"; +/* [companion.py] */ +"Error: Couldn't check token customer_id" = "Помилка: Не вдалося перевірити токен customer_id"; + +/* [companion.py] */ +"Error: customer_id doesn't match!" = "Error: customer_id не співпадає!"; + /* [edsm.py] */ "Error: EDSM {MSG}" = "Помилка: EDSM {MSG}!"; @@ -166,6 +187,9 @@ /* [companion.py] */ "Error: Invalid Credentials" = "Помилка: Невірні облікові дані!"; +/* [companion.py] */ +"Error: unable to get token" = "Помилка: не вдалося отримати токен"; + /* Raised when the user has multiple accounts and the username/password setting is not for the account they're currently playing OR the user has reset their Cmdr and the Companion API server is still returning data for the old Cmdr. [companion.py] */ "Error: Wrong Cmdr" = "Помилка! Не той обліковий запис!"; @@ -220,9 +244,18 @@ /* Hotkey/Shortcut settings prompt on Windows. [prefs.py] */ "Hotkey" = "Гаряча клавіша"; +/* Changed journal update_lock failed [monitor.py] */ +"Ignore" = "Ігнорувати"; + /* Section heading in settings. [inara.py] */ "Inara credentials" = "Обліковий запис Inara"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "Інформація про міграцію плагінів"; + +/* Changed journal update_lock failed [monitor.py] */ +"Journal directory already locked" = "Каталог журналу вже заблокований"; + /* Hotkey/Shortcut settings prompt on OSX. [prefs.py] */ "Keyboard shortcut" = "Сполучення клавіш"; @@ -247,12 +280,18 @@ /* Cmdr stats. [stats.py] */ "Loan" = "Борг"; +/* Label for user configured level of logging [prefs.py] */ +"Log Level" = "Рівень подробиць журналу"; + /* [EDMarketConnector.py] */ "Logging in..." = "Вхід в..."; /* Empire rank. [stats.py] */ "Lord" = "Пан"; +/* Label for 'UI Transparency' option in [prefs.py] */ +"Main window transparency" = "Прозорість головного вікна"; + /* [prefs.py] */ "Market data in CSV format file" = "Ринкові дані у форматі CSV файлу"; @@ -271,6 +310,9 @@ /* Federation rank. [stats.py] */ "Midshipman" = "Гардемарин"; +/* Appearance setting. [EDMarketConnector.py] */ +"Minimize to system tray" = "Згорнути програму"; + /* Explorer rank. [stats.py] */ "Mostly Aimless" = "Здебільшого Безцільний"; @@ -295,6 +337,9 @@ /* [prefs.py] */ "OK" = "Згода"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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." = "Один або кілька увімкнених плагінів ще не підтримують Python 3.x. Перегляньте список на вкладці '{PLUGINS}' в '{FILE}' > '{SETTINGS}'. Ви повинні перевірити, чи є в наявності оновлена ​​версія, інакше повідомити розробника плагіну про те, що їм потрібно оновити код для Python 3.x.\n\nВи можете відключити плагін, перейменувавши його папку додавши '{DISABLED}' в кінці назви."; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "Тільки тоді, коли Elite: Dangerous є активним додатком"; @@ -337,17 +382,8 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "Сховище плагінів"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC: Плагіни без підтримки Python 3.x!"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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." = "Один або кілька увімкнених плагінів ще не підтримують Python 3.x. Перегляньте список на вкладці '{PLUGINS}' в '{FILE}' > '{SETTINGS}'. Ви повинні перевірити, чи є в наявності оновлена ​​версія, інакше повідомити розробника плагіну про те, що їм потрібно оновити код для Python 3.x.\n\nВи можете відключити плагін, перейменувавши його папку додавши '{DISABLED}' в кінці назви."; - /* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "Плагіни без підтримки Python 3.x"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "Інформація про міграцію плагінів"; +"Plugins Without Python 3.x Support:" = "Плагіни без підтримки Python 3.x:"; /* Federation rank. [stats.py] */ "Post Captain" = "Капітан I рангу"; @@ -403,6 +439,9 @@ /* Help menu item. [EDMarketConnector.py] */ "Release Notes" = "Інформація про реліз"; +/* Changed journal update_lock failed [monitor.py] */ +"Retry" = "Повторна спроба"; + /* Multicrew role label in main window. [EDMarketConnector.py] */ "Role" = "Посада"; @@ -448,6 +487,9 @@ /* Setting to decide which ship outfitting website to link to - either E:D Shipyard or Coriolis. [prefs.py] */ "Shipyard" = "Корабельна верф"; +/* Status line text that appears when process exit sequence starts [EDMarketConnector.py] */ +"Shutting down..." = "Закриття..."; + /* Empire rank. [stats.py] */ "Squire" = "Зброєносець"; @@ -463,12 +505,18 @@ /* Menu item. [EDMarketConnector.py] */ "Status" = "Статус"; +/* 'Suit' label in main UI' [EDMarketConnector.py] */ +"Suit" = "Костюм"; + /* Explorer rank. [stats.py] */ "Surveyor" = "Геодезист"; /* Main window. [EDMarketConnector.py] */ "System" = "Система"; +/* Changed journal update_lock failed [monitor.py] */ +"The new Journal Directory location is already locked.{CR}You can either attempt to resolve this and then Retry, or choose to Ignore this." = "Нове розташування каталогу журналів уже заблоковано. {CR} Ви можете спробувати вирішити це, а потім повторити спробу, або Ігнорувати це."; + /* Appearance setting. [prefs.py] */ "Theme" = "Тема"; @@ -487,6 +535,12 @@ /* Trade rank. [stats.py] */ "Tycoon" = "Магнат"; +/* Label for 'UI Scaling' option [prefs.py] */ +"UI Scale Percentage" = "Відсоток шкали інтерфейсу користувача"; + +/* General 'Unknown', e.g. suit loadout */ +"Unknown" = "Невідомо"; + /* Update button in main window. [EDMarketConnector.py] */ "Update" = "Оновлення"; @@ -525,4 +579,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} необхідні дозволи для використання ярликів"; - diff --git a/L10n/zh-Hans.strings b/L10n/zh-Hans.strings index 16d3102d..b7c1f88b 100644 --- a/L10n/zh-Hans.strings +++ b/L10n/zh-Hans.strings @@ -1,12 +1,12 @@ -/* Label for 'UI Scaling' option [prefs.py] */ -"UI Scale Percentage" = "UI 缩放比例"; +/* Language name */ +"!Language" = "简体中文"; + +/* Message next to 'UI Transparency' slider [prefs.py] */ +"100 means fully opaque.{CR}Window is updated in real time" = "100 为完全不透明{CR}效果实时更新"; /* Text describing that value '100' means 'default', and changes require a restart [prefs.py] */ "100 means Default{CR}Restart Required for{CR}changes to take effect!" = "100 为默认设置{CR}需要重启应用{CR}以使修改生效"; -/* Language name */ -"!Language" = "简体中文"; - /* App menu entry on OSX. [EDMarketConnector.py] */ "About {APP}" = "关于 {APP}"; @@ -46,12 +46,12 @@ /* Folder selection button on Windows. [prefs.py] */ "Browse..." = "浏览…"; -/* No 'commander' data in CAPI [EDMarketConnector.py] */ -"CAPI: No commander data returned" = "CAPI:没有指挥官数据"; - /* Federation rank. [stats.py] */ "Cadet" = "Cadet"; +/* No 'commander' data in CAPI [EDMarketConnector.py] */ +"CAPI: No commander data returned" = "CAPI:没有指挥官数据"; + /* CQC rank. [stats.py] */ "Champion" = "Champion"; @@ -130,6 +130,9 @@ /* Menu title. [EDMarketConnector.py] */ "Edit" = "编辑"; +/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"EDMC: Plugins Without Python 3.x Support" = "EDMC:不支持 Python 3.x 的插件"; + /* Top rank. [stats.py] */ "Elite" = "Elite"; @@ -148,6 +151,9 @@ /* Trade rank. [stats.py] */ "Entrepreneur" = "Entrepreneur"; +/* [companion.py] */ +"Error" = "错误"; + /* [eddn.py] */ "Error: Can't connect to EDDN" = "错误:无法连接到 EDDN"; @@ -157,6 +163,12 @@ /* [inara.py] */ "Error: Can't connect to Inara" = "错误:无法连接到 Inara"; +/* [companion.py] */ +"Error: Couldn't check token customer_id" = "错误:无法检查 customer_id 令牌"; + +/* [companion.py] */ +"Error: customer_id doesn't match!" = "错误:customer_id 不匹配!"; + /* [edsm.py] */ "Error: EDSM {MSG}" = "错误:EDSM {MSG}"; @@ -175,6 +187,9 @@ /* [companion.py] */ "Error: Invalid Credentials" = "错误:无效的登录凭证"; +/* [companion.py] */ +"Error: unable to get token" = "错误:无法获取令牌"; + /* Raised when the user has multiple accounts and the username/password setting is not for the account they're currently playing OR the user has reset their Cmdr and the Companion API server is still returning data for the old Cmdr. [companion.py] */ "Error: Wrong Cmdr" = "错误:指挥官不一致"; @@ -235,6 +250,9 @@ /* Section heading in settings. [inara.py] */ "Inara credentials" = "Inara 授权凭证"; +/* Settings>Plugins>Information on migrating plugins [prefs.py] */ +"Information on migrating plugins" = "关于插件迁移"; + /* Changed journal update_lock failed [monitor.py] */ "Journal directory already locked" = "日志目录已被锁定"; @@ -262,12 +280,18 @@ /* Cmdr stats. [stats.py] */ "Loan" = "贷款"; +/* Label for user configured level of logging [prefs.py] */ +"Log Level" = "诊断模式"; + /* [EDMarketConnector.py] */ "Logging in..." = "登录中…"; /* Empire rank. [stats.py] */ "Lord" = "Lord"; +/* Label for 'UI Transparency' option in [prefs.py] */ +"Main window transparency" = "主窗口透明度"; + /* [prefs.py] */ "Market data in CSV format file" = "货物市场数据,以 CSV 文件格式"; @@ -310,6 +334,9 @@ /* [prefs.py] */ "OK" = "确定"; +/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ +"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." = "一项或多项你所启用的插件尚不支持 Python 3.x,详情请见 {FILE} > {SETTINGS} > {PLUGINS}。请检查上述插件是否有可用的更新,若没有,则应与插件的开发者就 Python 3.x 的支持问题取得联系。\n\n你也可以禁用某一项插件,只需在其文件夹名称的末尾添加 {DISABLED} 即可。"; + /* Hotkey/Shortcut setting. [prefs.py] */ "Only when Elite: Dangerous is the active app" = "仅当 Elite: Dangerous 在前台运行时生效"; @@ -352,17 +379,8 @@ /* Section heading in settings. [prefs.py] */ "Plugins folder" = "插件文件夹"; -/* Popup title: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"EDMC: Plugins Without Python 3.x Support" = "EDMC:不支持 Python 3.x 的插件"; - -/* Popup body: Warning about plugins without Python 3.x support [EDMarketConnector.py] */ -"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." = "一项或多项你所启用的插件尚不支持 Python 3.x,详情请见 {FILE} > {SETTINGS} > {PLUGINS}。请检查上述插件是否有可用的更新,若没有,则应与插件的开发者就 Python 3.x 的支持问题取得联系。\n\n你也可以禁用某一项插件,只需在其文件夹名称的末尾添加 {DISABLED} 即可。"; - /* Settings>Plugins>Plugins without Python 3.x support [prefs.py] */ -"Plugins Without Python 3.x Support" = "不支持 Python 3.x 的插件"; - -/* Settings>Plugins>Information on migrating plugins [prefs.py] */ -"Information on migrating plugins" = "关于插件迁移"; +"Plugins Without Python 3.x Support:" = "不支持 Python 3.x 的插件:"; /* Federation rank. [stats.py] */ "Post Captain" = "Post Captain"; @@ -511,6 +529,12 @@ /* Trade rank. [stats.py] */ "Tycoon" = "Tycoon"; +/* Label for 'UI Scaling' option [prefs.py] */ +"UI Scale Percentage" = "UI 缩放比例"; + +/* General 'Unknown', e.g. suit loadout */ +"Unknown" = "未知"; + /* Update button in main window. [EDMarketConnector.py] */ "Update" = "更新"; @@ -549,6 +573,3 @@ /* Shortcut settings prompt on OSX. [prefs.py] */ "{APP} needs permission to use shortcuts" = "{APP} 需要权限以使用快捷键"; - -/* Label for user configured level of logging [prefs.py] */ -"Log Level" = "诊断模式"; diff --git a/PLUGINS.md b/PLUGINS.md index 6bfb4290..e5355faa 100644 --- a/PLUGINS.md +++ b/PLUGINS.md @@ -9,6 +9,9 @@ wiki. ## Writing a Plugin +Check [Releasing.md](docs/Releasing.md#environment) to be sure of the current +version of Python that we've tested against. + Plugins are loaded when EDMC starts up. Each plugin has it's own folder in the `plugins` directory: @@ -28,15 +31,20 @@ If you're developing your plugin simply against an install of EDMarketConnector then you'll be relying on the bundled version of Python (it's baked into the .exe via the py2exe build process). ---- - -### Examples - -We have some example plugins available in the docs/examples directory. See the readme in each folder for more info. +Please be sure to read the [Avoiding potential pitfalls](#avoiding-potential-pitfalls) +section, else you might inadvertently cause issues for the core EDMC code +including whole application crashes. --- -### Available imports +## Examples + +We have some example plugins available in the docs/examples directory. See the +readme in each folder for more info. + +--- + +## Available imports **`import`ing anything from the core EDMarketConnector code that is not explicitly mentioned here is unsupported and may lead to your plugin @@ -52,30 +60,40 @@ breaking with future code changes.** `from prefs import prefsVersion` - to allow for versioned preferences. -`from companion import category_map` - Or any of the other static date -contained therein. NB: There's a plan to move such to a `data` module. +`import edmc_data` (or specific 'from' imports) - This contains various static +data that used to be in other files. You should **not** now import anything +from the original files unless specified as allowed in this section. -`import plug` - Mostly for using `plug.show_error()`. Also the flags -for `dashboard_entry()` to be useful (see example below). Relying on anything -else isn't supported. +`import plug` - For using `plug.show_error()` only. `from monitor import game_running` - in case a plugin needs to know if we think the game is running. *NB: This is a function, and should be called as such. Using the bare word `game_running` will always be `True`.* -`import timeout_session` - provides a method called `new_session` that creates a requests.session with a default timeout -on all requests. Recommended to reduce noise in HTTP requests - -```python -from ttkHyperlinkLabel import HyperlinkLabel -import myNotebook as nb -``` +`import timeout_session` - provides a method called `new_session` that creates +a requests.session with a default timeout on all requests. Recommended to +reduce noise in HTTP requests +`from ttkHyperlinkLabel import HyperlinkLabel` and `import myNotebook as nb` - For creating UI elements. +In addition to the above we also explicitly package the following python +modules for plugin use: + +- shutil +- sqlite3 +- zipfile + +And, of course, anything in the [Python Standard Library](https://docs.python.org/3/library/) +will always be available, dependent on the version of Python we're using to +build Windows installed versions. Check the 'Startup' line in an application +[Debug Log File](https://github.com/EDCD/EDMarketConnector/wiki/Troubleshooting#debug-log-files) +for the version of Python being used. + + --- -### Logging +## Logging In the past the only way to provide any logged output from a plugin was to use `print(...)` statements. When running the application from @@ -87,7 +105,8 @@ EDMC now implements proper logging using the Python `logging` module. Plugin developers should now use the following code instead of simple `print(...)` statements. -Insert this at the top-level of your load.py file (so not inside `plugin_start3()` ): +Insert this at the top-level of your load.py file (so not inside +`plugin_start3()`): ```python import logging @@ -158,8 +177,8 @@ Replace all `print(...)` statements with one of the following: logger.debug('Exception we only note in debug output', exc_info=e) ``` -Remember you can use [fstrings](https://www.python.org/dev/peps/pep-0498/) to include variables, and even the returns of -functions, in the output. +Remember you can use [fstrings](https://www.python.org/dev/peps/pep-0498/) to +include variables, and even the returns of functions, in the output. ```python logger.debug(f"Couldn't frob the {thing} with the {wotsit()}") @@ -167,7 +186,41 @@ functions, in the output. --- -### Startup +## Checking core EDMC version + +If you have code that needs to act differently under different versions of +this application then you can check utilise `config.appversion`. + +Prior to version 5.0.0 this was a simple string. From 5.0.0 onwards it is, +instead, a function which returns an instance of `semantic_version.Version`. + +```python +import semantic_version +from config import appversion + +... + # Up until 5.0.0-beta1 config.appversion is a string + if isinstance(appversion, str): + core_version = semantic_version.Version(appversion) + + elif callable(appversion): + # From 5.0.0-beta1 it's a function, returning semantic_version.Version + core_version = appversion() + + # Yes, just blow up if config.appverison is neither str or callable + + logger.info(f'Core EDMC version: {core_version}') + # And then compare like this + if core_version < semantic_version.Version('5.0.0-beta1'): + logger.info('EDMC core version is before 5.0.0-beta1') + + else: + logger.info('EDMC core version is at least 5.0.0-beta1') +``` + +--- + +## Startup EDMC will import the `load.py` file as a module and then call the `plugin_start3()` function. @@ -192,20 +245,77 @@ Mac, and `$TMP/EDMarketConnector.log` on Linux. | `plugin_dir` | `str` | The directory that your plugin is located in. | | `RETURN` | `str` | The name you want to be used for your plugin internally | -### Shutdown +--- -This gets called when the user closes the program: +## Avoiding potential pitfalls + +There are a number of things that your code should either do or avoiding +doing so as to play nicely with the core EDMC code and not risk causing +application crashes or hangs. + +### Use a thread for long-running code + +By default, your plugin code will be running in the main thread. So, if you +perform some operation that takes significant time (more than a second) you +will be blocking both the core code from continuing *and* any other plugins +from running their main-thread code. + +This includes any connections to remote services, such as a website or +remote database. So please place such code within its own thread. + +See the [EDSM plugin](https://github.com/EDCD/EDMarketConnector/blob/main/plugins/edsm.py) +code for an example of using a thread worker, along +with a queue to send data, and telling the sub-thread to stop during shutdown. + +### All tkinter calls in main thread + +The only tkinter calls that should ever be made from a sub-thread are +`event_generate()` calls to send data back to the main thread. + +Any attempt to manipulate tkinter UI elements directly from a sub-thread +will most likely crash the whole program. + +See the [EDSM plugin](https://github.com/EDCD/EDMarketConnector/blob/main/plugins/edsm.py) +code for an example of using `event_generate()` to cause the plugin main +thread code to update a UI element. Start from the `plugin_app()` +implementation. + +### Do not call tkinter `event_generate` during shutdown. + +However, you must **not** make *any* tkinter `event_generate()` call whilst +the application is shutting down. + +The application shutdown sequence is itself triggered from the `<>` event +handler, and generating another event from any code in, or called from, +there causes the application to hang somewhere in the tk libraries. + +You can detect if the application is shutting down with the boolean +`config.shutting_down`. Note that although this is technically a function +its implementation is of a property on `config.AbstractConfig` and thus you +should treat it as a variable. + +**Do NOT use**: ```python -def plugin_stop() -> None: - """ - EDMC is closing - """ - print("Farewell cruel world!") + from config import shutting_down + + if shutting_down(): + # During shutdown ``` -If your plugin uses one or more threads to handle Events then `stop()` and `join()` -(to wait for their exit -- Recommended, not required) the threads before returning from this function. +as this will cause the 'During shutdown' branch to *always* be taken, as in +this context you're testing if the function exists, and that is always True. + +So instead use: + +```python + from config import shutting_down + + if shutting_down: + # During shutdown +``` + +--- ## Plugin Hooks @@ -217,20 +327,47 @@ title will be the value that you returned from `plugin_start3`. Use widgets from EDMC's myNotebook.py for the correct look-and-feel. You can be notified when the settings dialog is closed so you can save your settings. -You can use `set()`, `get()` and `getint()` from EDMC's `config.config` object -to retrieve your plugin's settings in a platform-independent way. +You can use `set()` and `get_$type()` (where type is one of: `int`, `bool`, +`str`, `list`) from EDMC's `config.config` object to retrieve your plugin's +settings in a platform-independent way. Previously this was done with a single +set and two get methods, the new methods provide better type safety. + +If you want to maintain compatibility with pre-5.0.0 versions of this +application (please encourage plugin users to update!) then you'll need to +include this code in at least once in your plugin (no harm in putting it in +all modules/files): + +```python +from config import config + +# For compatibility with pre-5.0.0 +if not hasattr(config, 'get_int'): + config.get_int = config.getint + +if not hasattr(config, 'get_str'): + config.get_str = config.get + +if not hasattr(config, 'get_bool'): + config.get_bool = lambda key: bool(config.getint(key)) + +if not hasattr(config, 'get_list'): + config.get_list = config.get +``` **Be sure to use a unique prefix for any settings you save so as not to clash with core EDMC or other plugins.** -Use `numberFromString()` from EDMC's `l10n.Locale` object to parse input -numbers in a locale-independent way. +Use `number_from_string()` from EDMC's `l10n.Locale` object to parse input +numbers in a locale-independent way. NB: the old CamelCase versions of +`number_from_string` and `string_from_number` do still exist, but are +deprecated. They will continue to work, but will throw warnings. Note that in the following example the function signature defines that it returns `Optional[tk.Frame]` only because we need to allow for `None` if something goes wrong with the creation of the frame (the calling code checks this). You absolutely need to return the `nb.Frame()` instance that you get as in the code below. + ```python import tkinter as tk from tkinter import ttk @@ -245,7 +382,7 @@ def plugin_prefs(parent: nb.Notebook, cmdr: str, is_beta: bool) -> Optional[tk.F Return a TK Frame for adding to the EDMC settings dialog. """ global my_setting - my_setting = tk.IntVar(value=config.getint("MyPluginSetting")) # Retrieve saved value from config + my_setting = tk.IntVar(value=config.get_int("MyPluginSetting")) # Retrieve saved value from config frame = nb.Frame(parent) nb.Label(frame, text="Hello").grid() nb.Label(frame, text="Commander").grid() @@ -275,6 +412,8 @@ def prefs_changed(cmdr: str, is_beta: bool) -> None: | `cmdr` | `str` | The current commander | | `is_beta` | `bool` | If the game is currently a beta version | +--- + ### Display You can also have your plugin add an item to the EDMC main window and update @@ -284,7 +423,7 @@ For a more complicated item create a tk.Frame widget and populate it with other ttk widgets. Return `None` if you just want to use this as a callback after the main window and all other plugins are initialised. -You can use `stringFromNumber()` from EDMC's `l10n.Locale` object to format +You can use `string_from_number()` from EDMC's `l10n.Locale` object to format numbers in your widgets in a locale-independent way. ```python @@ -315,12 +454,15 @@ def some_other_function() -> None: | `parent` | `tk.Frame` | The root EDMC window | | `RETURN` | `Union[tk.Widget, Tuple[tk.Widget, tk.Widget]]` | A widget to add to the main window. See below for more info | -The return from plugin_app can either be any widget (Frame, Label, Notebook, etc.), or a 2 tuple of widgets. In the case of -a 2 tuple, indices 0 and 1 are placed automatically in the outer grid on column indices 0 and 1. Otherwise, the only thing done -to your return widget is it is set to use a columnspan of 2, and placed on the grid. +The return from `plugin_app()` can either be any widget (`Frame`, `Label`, +`Notebook`, etc.), or a 2-tuple of widgets. In the case of a 2-tuple, indices +0 and 1 are placed automatically in the outer grid on column indices 0 and 1. +Otherwise, the only thing done to your return widget is it is set to use a +columnspan of 2, and placed on the grid. -You can dynamically add and remove widgets on the main window by returning a tk.Frame from `plugin_app()` and later -creating and destroying child widgets of that frame. +You can dynamically add and remove widgets on the main window by returning a +`tk.Frame` from `plugin_app()` and later creating and destroying child widgets +of that frame. ```python from typing import Option @@ -348,6 +490,11 @@ def some_other_function_called_later() -> None: theme.update(this.frame) # Apply theme colours to the frame and its children, including the new widgets ``` +Remember, you must **NOT** manipulate any tkinter elements from a sub-thread! +See [Avoiding potential pitfalls](#avoiding-potential-pitfalls). + +--- + ### Events Once you have created your plugin and EDMC has loaded it there are three other @@ -406,6 +553,7 @@ Content of `state` (updated to the current journal entry): | `Raw` | `dict` | Current raw engineering materials | | `Manufactured` | `dict` | Current manufactured engineering materials | | `Encoded` | `dict` | Current encoded engineering materials | +| `Component` | `dict` | Current component materials | | `Engineers` | `dict` | Current Raw engineering materials | | `Rank` | `Dict[str, Tuple[int, int]` | Current ranks, each entry is a tuple of the current rank, and age | | `Statistics` | `dict` | Contents of a Journal Statistics event, ie, data shown in the stats panel. See the Journal manual for more info | @@ -419,12 +567,63 @@ Content of `state` (updated to the current journal entry): | `ModulesValue` | `int` | Value of the current ship's modules | | `Rebuy` | `int` | Current ship's rebuy cost | | `Modules` | `dict` | Currently fitted modules | +| `NavRoute` | `dict` | Last plotted multi-hop route | +| `ModuleInfo` | `dict` | Last loaded ModulesInfo.json data | +| `OnFoot` | `bool` | Whether the Cmdr is on foot | +| `Component` | `dict` | 'Component' MicroResources in Odyssey, `int` count each. | +| `Item` | `dict` | 'Item' MicroResources in Odyssey, `int` count each. | +| `Consumable` | `dict` | 'Consumable' MicroResources in Odyssey, `int` count each. | +| `Data` | `dict` | 'Data' MicroResources in Odyssey, `int` count each. | +| `BackPack` | `dict` | `dict` of Odyssey MicroResources in backpack. | +| `SuitCurrent` | `dict` | CAPI-returned data of currently worn suit. NB: May be `None` if no data. | +| `Suits` | `dict`[1] | CAPI-returned data of owned suits. NB: May be `None` if no data. | +| `SuitLoadoutCurrent` | `dict` | CAPI-returned data of current Suit Loadout. NB: May be `None` if no data. | +| `SuitLoadouts` | `dict`[1] | CAPI-returned data of all Suit Loadouts. NB: May be `None` if no data. | + +[1] - Some data from the CAPI is sometimes returned as a `list` (when all +members are present) and other times as an integer-keyed `dict` (when at +least one member is missing, so the indices are not contiguous). We choose to +always convert to the integer-keyed `dict` form so that code utilising the data +is simpler. + +New in version 4.1.6: + +`CargoJSON` contains the raw data from the last read of `Cargo.json` passed +through json.load. It contains more information about the cargo contents, such +as the mission ID for mission specific cargo + +**NB: Because this is only the data loaded from the `Cargo.json` file, and that +is not written at Commander login (instead the in-Journal `Cargo` event +contains all the data), this will not be populated at login.** + +New in version 5.0.0: + +`NavRoute` contains the `json.load()` of `NavRoute.json` as indicated by a +journal `NavRoute` event. + +`ModuleInfo` contains the `json.load()` of `ModulesInfo.json` as indicated by a +Journal `ModuleInfo` event. + +`OnFoot` is an indication as to if the player is on-foot, rather than in a +vehicle. + +`Component`, `Item`, `Consumable` & `Data` are `dict`s tracking your +Odyssey MicroResources in your Ship Locker. `BacKPack` contains `dict`s for +the same when you're on-foot. + +`SuitCurrent`, `Suits`, `SuitLoadoutCurrent` & `SuitLoadouts` hold CAPI data +relating to suits and their loadouts. + +##### Synthetic Events A special "StartUp" entry is sent if EDMC is started while the game is already running. In this case you won't receive initial events such as "LoadGame", "Rank", "Location", etc. However the `state` dictionary will reflect the cumulative effect of these missed events. +**NB: Any of the values in this might be `None` if the Cmdr has loaded into +Arena (CQC) from the Main Menu.** + Similarly, a special "ShutDown" entry is sent when the game stops writing to the Journal without writing a "Shutdown" event. This might happen, for example, when the game client crashes. @@ -437,17 +636,77 @@ between the two scenarios. This event is not sent when EDMC is running on a different machine so you should not *rely* on receiving this event. -#### Player Dashboard +##### Augmented Events + +In some cases we augment the events, as seen in the Journal, with extra data. +Examples of this are: + +1. Every `Cargo` event passed to plugins contains the data from + `Cargo.json` (but see above for caveats). + +1. Every `NavRoute` event contains the full `Route` array as loaded from + `NavRoute.json`. You do not need to access this via + `monitor.state['NavRoute']`, although it is available there. + + *NB: There is no indication available when a player cancels a route.* The + game itself does not provide any such, not in a Journal event, not in a + `Status.json` flag. + + The Journal documentation v28 is incorrect about the event + and file being `Route(.json)` the word is `NavRoute`. Also the format of + the data is, e.g. + + ```json + { "timestamp":"2021-03-10T11:31:37Z", + "event":"NavRoute", + "Route": [ + { "StarSystem": "Esuvit", "SystemAddress": 2869709317505, "StarPos": [-13.18750,-1.15625,-92.68750], "StarClass": "M" }, + { "StarSystem": "Ndozins", "SystemAddress": 3446451210595, "StarPos": [-14.31250,-10.68750,-60.56250], "StarClass": "M" }, + { "StarSystem": "Tascheter Sector MN-T b3-6", "SystemAddress": 13864825529753, "StarPos": [-11.87500,-21.96875,-29.03125], "StarClass": "M" }, + { "StarSystem": "LP 823-4", "SystemAddress": 9466778953129, "StarPos": [-8.62500,-27.84375,3.93750], "StarClass": "M" } + ] + } + ``` + +1. Every `ModuleInfo` event contains the full data as loaded from the + `ModulesInfo.json` file. It's also available as `monitor.stat['ModuleInfo']` + (noting that we used the singular form there to stay consistent with the + Journal event name). + +--- + +### Shutdown + +This gets called when the user closes the program: + +```python +def plugin_stop() -> None: + """ + EDMC is closing + """ + print("Farewell cruel world!") +``` + +If your plugin uses one or more threads to handle Events then `stop()` and +`join()` (to wait for their exit -- Recommended, not required) the threads +before returning from this function. + +--- + +### Player Dashboard ```python import plug def dashboard_entry(cmdr: str, is_beta: bool, entry: Dict[str, Any]): - is_deployed = entry['Flags'] & plug.FlagsHardpointsDeployed + is_deployed = entry['Flags'] & edmc_data.FlagsHardpointsDeployed sys.stderr.write("Hardpoints {}\n".format(is_deployed and "deployed" or "stowed")) ``` -This gets called when something on the player's cockpit display changes - +`dashboard_entry()` is called with the latest data from the `Status.json` +file when an update to that file is detected. + +This will be when something on the player's cockpit display changes - typically about once a second when in orbital flight. | Parameter | Type | Description | @@ -456,19 +715,15 @@ typically about once a second when in orbital flight. | `is_beta` | `bool` | if the game is currently in beta | | `entry` | `dict` | Data from status.json (see below) | - For more info on `status.json`, See the "Status File" section in the Frontier [Journal documentation](https://forums.frontier.co.uk/showthread.php/401661) for the available `entry` properties and for the list of available `"Flags"`. Refer to the source code of [plug.py](./plug.py) for the list of available constants. +For more info on `Status.json`, See the "Status File" section in the Frontier +[Journal documentation](https://forums.frontier.co.uk/showthread.php/401661). +That includes the available `entry` properties and the list of `"Flags"`. +Refer to [edmc_data.py](./edmc_data.py) for the list of available +constants. -New in version 4.1.6: +--- -`CargoJSON` contains the raw data from the last read of `Cargo.json` passed -through json.load. It contains more information about the cargo contents, such -as the mission ID for mission specific cargo - -**NB: Because this is only the data loaded from the `Cargo.json` file, and that -is not written at Commander login (instead the in-Journal `Cargo` event -contains all the data), this will not be populated at login.** - -#### Getting Commander Data +### Commander Data from Frontier CAPI ```python def cmdr_data(data, is_beta): @@ -481,16 +736,19 @@ def cmdr_data(data, is_beta): logger.info(data['commander']['name']) ``` -This gets called when EDMC has just fetched fresh Cmdr and station data from -Frontier's servers. +This gets called when the application has just fetched fresh Cmdr and station +data from Frontier's servers. | Parameter | Type | Description | | :-------- | :--------------: | :------------------------------------------------------------------------------------------------------- | | `data` | `Dict[str, Any]` | `/profile` API response, with `/market` and `/shipyard` added under the keys `marketdata` and `shipdata` | | `is_beta` | `bool` | If the game is currently in beta | -#### Plugin-specific events +--- +### Plugin-specific events + +#### EDSM Notify System ```python def edsm_notify_system(reply): """ @@ -517,6 +775,7 @@ some time after the corresponding `journal_entry()` event. | :-------- | :--------------: | :--------------------------------------------------------------------------------------------- | | `reply` | `Dict[str, Any]` | Response to an API call to [EDSM's journal API target](https://www.edsm.net/en/api-journal-v1) | +#### Inara Notify Location ```python def inara_notify_location(event_data): """ @@ -543,8 +802,7 @@ event. | :----------- | :--------------: | :----------------------------------------------------------------------------------------------------------- | | `event_data` | `Dict[str, Any]` | Response to an API call to [INARA's `Commander Flight Log` event](https://inara.cz/inara-api-docs/#event-29) | ---- - +#### Inara Notify Ship ```python def inara_notify_ship(event_data): """ @@ -564,6 +822,8 @@ time after the corresponding `journal_entry()` event. | :----------- | :--------------: | :----------------------------------------------------------------------------------------------------------------------------- | | `event_data` | `Dict[str, Any]` | Response to an API call to [INARA's `addCommanderShip` or `setCommanderShip` event](https://inara.cz/inara-api-docs/#event-11) | +--- + ## Error messages You can display an error in EDMC's status area by returning a string from your @@ -576,6 +836,8 @@ The status area is shared between EDMC itself and all other plugins, so your message won't be displayed for very long. Create a dedicated widget if you need to display routine status information. +--- + ## Localisation You can localise your plugin to one of the languages that EDMC itself supports. @@ -609,6 +871,8 @@ See EDMC's own [`L10n`](https://github.com/EDCD/EDMarketConnector/tree/main/L10n folder for the list of supported language codes and for example translation files. +--- + ## Python Package Plugins A _Package Plugin_ is both a standard Python package (i.e. contains an @@ -619,6 +883,8 @@ before any non-Package plugins. Other plugins can access features in a Package Plugin by `import`ing the package by name in the usual way. +--- + ## Distributing a Plugin To package your plugin for distribution simply create a `.zip` archive of your @@ -631,7 +897,10 @@ plugin's folder: If there are any external dependencies then include them in the plugin's folder. -Optionally, for tidiness delete any `.pyc` and `.pyo` files in the archive, as well as the `__pycache__` directory. +Optionally, for tidiness delete any `.pyc` and `.pyo` files in the archive, as +well as the `__pycache__` directory. + +--- ## Disable a plugin @@ -641,29 +910,33 @@ plugin folder to append ".disabled". Eg, Disabled and enabled plugins are listed on the "Plugins" Settings tab -## Migration +--- -Starting with pre-release 3.5 EDMC uses Python **3.7**. The first full -release under Python 3.7 was 4.0.0.0. This is a brief outline of the steps -required to migrate a plugin from earlier versions of EDMC: +## Migration from Python 2.7 + +Starting with pre-release 3.5 EDMC used Python 3.7. The first full +release under Python 3.7 was 4.0.0.0. The 4.2.x series was the last to use +Python 3.7, with releases moving on to the latest Python 3.9.x after that. + +This is a brief outline of the steps required to migrate a plugin from earlier +versions of EDMC: - Rename the function `plugin_start` to `plugin_start3(plugin_dir)`. Plugins without a `plugin_start3` function are listed as disabled on EDMC's "Plugins" tab and a message like "plugin SuperSpaceHelper needs migrating" - appears in the log. Such plugins are also listed in a section "Plugins Without - Python 3.x Support:" on the Settings > Plugins tab. + appears in the log. Such plugins are also listed in a section "Plugins + Without Python 3.x Support:" on the Settings > Plugins tab. - Check that callback functions `plugin_prefs`, `prefs_changed`, - `journal_entry`, `dashboard_entry` and `cmdr_data` if used are declared with - the correct number of arguments. Older versions of this app were tolerant - of missing arguments in these function declarations. + `journal_entry`, `dashboard_entry` and `cmdr_data`, if used, are declared + with the correct number of arguments. Older versions of this app were + tolerant of missing arguments in these function declarations. -- Port the code to Python 3.7. The [2to3](https://docs.python.org/3/library/2to3.html) - tool can automate much of this work. +- Port the code to Python 3.9+. The + [2to3](https://docs.python.org/3/library/2to3.html) + tool can automate much of this work. -Depending on the complexity of the plugin it may be feasible to make it -compatible with both EDMC 3.4 + Python 2.7 and EDMC 3.5 + Python 3.7. - -[Here's](https://python-future.org/compatible_idioms.html) a guide on writing -Python 2/3 compatible code and [here's](https://github.com/Marginal/HabZone/commit/3c41cd41d5ad81ef36aab40e967e3baf77b4bd06) -an example of the changes required for a simple plugin. +We advise *against* making any attempt to have a plugin's code work under +both Python 2.7 and 3.x. We no longer maintain the Python 2.7-based +versions of this application and you shouldn't support use of them with +your plugin. diff --git a/README.md b/README.md index fe5c5371..1d297395 100644 --- a/README.md +++ b/README.md @@ -42,16 +42,9 @@ Please see the [Troubleshooting](https://github.com/EDCD/EDMarketConnector/wiki/ Reporting a problem --- Please report a problem as a new GitHub [issue](https://github.com/EDCD/EDMarketConnector/issues/new?assignees=&labels=bug%2C+unconfirmed&template=bug_report.md&title=). -Please wait for the error to occur and zip up and attach this app's log file to the new issue: - -Mac: - -* `$TMPDIR/EDMarketConnector.log` - -Windows: - -* `%TMP%\EDMarketConnector.log` - +See [Reporting a problem](https://github.com/EDCD/EDMarketConnector/wiki/Troubleshooting#reporting-a-problem) +for further guidance, including how to find the necessary log files to +attach to the report. Packaging for distribution -------- @@ -74,6 +67,6 @@ Please see the [Acknowledgements](https://github.com/EDCD/EDMarketConnector/wiki License ------- -Copyright © 2015-2019 Jonathan Harris, 2020 EDCD +Copyright © 2015-2019 Jonathan Harris, 2020-2021 EDCD Licensed under the [GNU Public License (GPL)](http://www.gnu.org/licenses/gpl-2.0.html) version 2 or later. diff --git a/collate.py b/collate.py index a5fa219f..a47b4a45 100755 --- a/collate.py +++ b/collate.py @@ -1,17 +1,16 @@ #!/usr/bin/env python3 -# -# Script for collating lists of seen commodities, modules and ships from dumps of the Companion API output -# +"""Collate lists of seen commodities, modules and ships from dumps of the Companion API output.""" import csv import json import os -from os.path import isfile import sys +from os.path import isfile from traceback import print_exc import companion import outfitting +from edmc_data import companion_category_map, ship_name_map def __make_backup(file_name: str, suffix: str = '.bak') -> None: @@ -21,7 +20,6 @@ def __make_backup(file_name: str, suffix: str = '.bak') -> None: :param file_name: The name of the file to make a backup of :param suffix: The suffix to use for backup files (default '.bak') """ - backup_name = file_name + suffix if isfile(backup_name): @@ -30,9 +28,13 @@ def __make_backup(file_name: str, suffix: str = '.bak') -> None: os.rename(file_name, backup_name) -# keep a summary of commodities found using in-game names -# Assumes that the commodity data has already been 'fixed up' -def addcommodities(data): +def addcommodities(data) -> None: # noqa: CCR001 + """ + Keep a summary of commodities found using in-game names. + + Assumes that the commodity data has already been 'fixed up' + :param data: - Fixed up commodity data. + """ if not data['lastStarport'].get('commodities'): return @@ -51,17 +53,17 @@ def addcommodities(data): for commodity in data['lastStarport'].get('commodities'): key = int(commodity['id']) new = { - 'id' : commodity['id'], - 'symbol' : commodity['name'], - 'category' : companion.category_map.get(commodity['categoryname']) or commodity['categoryname'], - 'name' : commodity.get('locName') or 'Limpets', + 'id': commodity['id'], + 'symbol': commodity['name'], + 'category': companion_category_map.get(commodity['categoryname']) or commodity['categoryname'], + 'name': commodity.get('locName') or 'Limpets', } old = commodities.get(key) - if old and companion.category_map.get(commodity['categoryname'], True): + if old and companion_category_map.get(commodity['categoryname'], True): if new['symbol'] != old['symbol'] or new['name'] != old['name']: - raise ValueError('{}: {!r} != {!r}'.format(key, new, old)) + raise ValueError(f'{key}: {new!r} != {old!r}') commodities[key] = new @@ -71,18 +73,18 @@ def addcommodities(data): if isfile(commodityfile): __make_backup(commodityfile) - with open(commodityfile, 'w') as csvfile: + with open(commodityfile, 'w', newline='\n') as csvfile: writer = csv.DictWriter(csvfile, ['id', 'symbol', 'category', 'name']) writer.writeheader() for key in sorted(commodities): writer.writerow(commodities[key]) - print('Added {} new commodities'.format(len(commodities) - size_pre)) + print(f'Added {len(commodities) - size_pre} new commodities') -# keep a summary of modules found -def addmodules(data): +def addmodules(data): # noqa: C901, CCR001 + """Keep a summary of modules found.""" if not data['lastStarport'].get('modules'): return @@ -103,13 +105,13 @@ def addmodules(data): # sanity check key = int(key) if key != module.get('id'): - raise ValueError('id: {} != {}'.format(key, module['id'])) + raise ValueError(f'id: {key} != {module["id"]}') try: - new = outfitting.lookup(module, companion.ship_map, True) + new = outfitting.lookup(module, ship_name_map, True) except Exception: - print('{}, {}:'.format(module['id'], module['name'])) + print(f'{module["id"]}, {module["name"]}:') print_exc(0) new = None @@ -122,7 +124,7 @@ def addmodules(data): size_pre -= 1 elif str(new.get(thing, '')) != old.get(thing): - raise ValueError('{}: {} {!r}!={!r}'.format(key, thing, new.get(thing), old.get(thing))) + raise ValueError(f'{key}: {thing} {new.get(thing)!r}!={old.get(thing)!r}') modules[key] = new @@ -132,18 +134,18 @@ def addmodules(data): if isfile(outfile): __make_backup(outfile) - with open(outfile, 'w') as csvfile: + with open(outfile, 'w', newline='\n') as csvfile: writer = csv.DictWriter(csvfile, fields, extrasaction='ignore') writer.writeheader() for key in sorted(modules): writer.writerow(modules[key]) - print('Added {} new modules'.format(len(modules) - size_pre)) + print(f'Added {len(modules) - size_pre} new modules') -# keep a summary of ships found -def addships(data): +def addships(data) -> None: # noqa: CCR001 + """Keep a summary of ships found.""" if not data['lastStarport'].get('ships'): return @@ -164,7 +166,7 @@ def addships(data): for ship in tuple(data_ships.get('shipyard_list', {}).values()) + data_ships.get('unavailable_list'): # sanity check key = int(ship['id']) - new = {'id': key, 'symbol': ship['name'], 'name': companion.ship_map.get(ship['name'].lower())} + new = {'id': key, 'symbol': ship['name'], 'name': ship_name_map.get(ship['name'].lower())} if new: old = ships.get(key) if old: @@ -175,7 +177,7 @@ def addships(data): size_pre -= 1 elif str(new.get(thing, '')) != old.get(thing): - raise ValueError('{}: {} {!r} != {!r}'.format(key, thing, new.get(thing), old.get(thing))) + raise ValueError(f'{key}: {thing} {new.get(thing)!r} != {old.get(thing)!r}') ships[key] = new @@ -185,14 +187,14 @@ def addships(data): if isfile(shipfile): __make_backup(shipfile) - with open(shipfile, 'w') as csvfile: + with open(shipfile, 'w', newline='\n') as csvfile: writer = csv.DictWriter(csvfile, ['id', 'symbol', 'name']) writer.writeheader() for key in sorted(ships): writer.writerow(ships[key]) - print('Added {} new ships'.format(len(ships) - size_pre)) + print(f'Added {len(ships) - size_pre} new ships') if __name__ == "__main__": diff --git a/commodity.py b/commodity.py index fec7d2b7..a7c39e79 100644 --- a/commodity.py +++ b/commodity.py @@ -1,35 +1,35 @@ -# Export various CSV formats +"""Export various CSV formats.""" # -*- coding: utf-8 -*- -from os.path import join -import hashlib import time +from os.path import join from config import config - -bracketmap = { - 0: '', - 1: 'Low', - 2: 'Med', - 3: 'High', -} +from edmc_data import commodity_bracketmap as bracketmap # DEFAULT means semi-colon separation # CSV means comma separation (COMMODITY_DEFAULT, COMMODITY_CSV) = range(2) -def export(data, kind=COMMODITY_DEFAULT, filename=None): - querytime = config.getint('querytime') or int(time.time()) +def export(data, kind=COMMODITY_DEFAULT, filename=None) -> None: + """ + Export commodity data from the given CAPI data. + + :param data: CAPI data. + :param kind: The type of file to write. + :param filename: Filename to write to, or None for a standard format name. + :return: + """ + querytime = config.get_int('querytime', default=int(time.time())) if not filename: - filename = '{system}.{starport}.{time}.{kind}'.format( - system=data['lastSystem']['name'].strip(), - starport=data['lastStarport']['name'].strip(), - time=time.strftime('%Y-%m-%dT%H.%M.%S', time.localtime(querytime)), - kind='csv' - ) - filename = join(config.get('outdir'), filename) + filename_system = data['lastSystem']['name'].strip(), + filename_starport = data['lastStarport']['name'].strip(), + filename_time = time.strftime('%Y-%m-%dT%H.%M.%S', time.localtime(querytime)), + filename_kind = 'csv' + filename = f'{filename_system}.{filename_starport}.{filename_time}.{filename_kind}' + filename = join(config.get_str('outdir'), filename) if kind == COMMODITY_CSV: sep = ';' # BUG: for fixing later after cleanup @@ -44,27 +44,32 @@ def export(data, kind=COMMODITY_DEFAULT, filename=None): rowheader = sep.join((data['lastSystem']['name'], data['lastStarport']['name'])) - h = open(filename, 'wt') # codecs can't automatically handle line endings, so encode manually where required - h.write(header) + with open(filename, 'wt') as h: # codecs can't automatically handle line endings, so encode manually where required + h.write(header) - for commodity in data['lastStarport']['commodities']: - line = sep.join(( - rowheader, - commodity['name'], - commodity['sellPrice'] and str(int(commodity['sellPrice'])) or '', - commodity['buyPrice'] and str(int(commodity['buyPrice'])) or '', - str(int(commodity['demand'])) if commodity['demandBracket'] else '', - bracketmap[commodity['demandBracket']], - str(int(commodity['stock'])) if commodity['stockBracket'] else '', - bracketmap[commodity['stockBracket']] - )) + for commodity in data['lastStarport']['commodities']: + line = sep.join(( + rowheader, + commodity['name'], + commodity['sellPrice'] and str(int(commodity['sellPrice'])) or '', + commodity['buyPrice'] and str(int(commodity['buyPrice'])) or '', + str(int(commodity['demand'])) if commodity['demandBracket'] else '', + bracketmap[commodity['demandBracket']], + str(int(commodity['stock'])) if commodity['stockBracket'] else '', + bracketmap[commodity['stockBracket']] + )) - if kind == COMMODITY_DEFAULT: - line = sep.join((line, str(int(commodity['meanPrice'])), str(commodity['id']), data['timestamp'] + '\n')) + if kind == COMMODITY_DEFAULT: + line = sep.join( + ( + line, + str(int(commodity['meanPrice'])), + str(commodity['id']), + data['timestamp'] + '\n' + ) + ) - else: - line = sep.join((line, data['timestamp'] + '\n')) + else: + line = sep.join((line, data['timestamp'] + '\n')) - h.write(line) - - h.close() + h.write(line) diff --git a/companion.py b/companion.py index 36fb62cb..4243f817 100644 --- a/companion.py +++ b/companion.py @@ -7,8 +7,10 @@ protocol used for the callback. """ import base64 +import collections import csv import hashlib +import json import numbers import os import random @@ -20,22 +22,28 @@ from email.utils import parsedate # TODO: see https://github.com/EDCD/EDMarketConnector/issues/569 from http.cookiejar import LWPCookieJar # noqa: F401 - No longer needed but retained in case plugins use it from os.path import join -from typing import TYPE_CHECKING, Any, Dict, List, NewType, Union +from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, OrderedDict, TypeVar, Union import requests from config import appname, appversion, config +from edmc_data import companion_category_map as category_map from EDMCLogging import get_main_logger +from monitor import monitor from protocol import protocolhandler logger = get_main_logger() if TYPE_CHECKING: - _ = lambda x: x # noqa: E731 # to make flake8 stop complaining that the hacked in _ method doesnt exist + def _(x): return x + + 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 # Define custom type for the dicts that hold CAPI data -CAPIData = NewType('CAPIData', Dict) +# CAPIData = NewType('CAPIData', Dict) holdoff = 60 # be nice timeout = 10 # requests timeout @@ -48,8 +56,9 @@ CLIENT_ID = os.getenv('CLIENT_ID') or 'fb88d428-9110-475f-a3d2-dc151c2b9c7a' SERVER_AUTH = 'https://auth.frontierstore.net' URL_AUTH = '/auth' URL_TOKEN = '/token' +URL_DECODE = '/decode' -USER_AGENT = f'EDCD-{appname}-{appversion}' +USER_AGENT = f'EDCD-{appname}-{appversion()}' SERVER_LIVE = 'https://companion.orerve.net' SERVER_BETA = 'https://pts-companion.orerve.net' @@ -57,64 +66,67 @@ URL_QUERY = '/profile' URL_MARKET = '/market' URL_SHIPYARD = '/shipyard' - -# Map values reported by the Companion interface to names displayed in-game -# May be imported by plugins -category_map = { - 'Narcotics': 'Legal Drugs', - 'Slaves': 'Slavery', - 'Waste ': 'Waste', - 'NonMarketable': False, # Don't appear in the in-game market so don't report -} - commodity_map: Dict = {} -ship_map = { - 'adder': 'Adder', - 'anaconda': 'Anaconda', - 'asp': 'Asp Explorer', - 'asp_scout': 'Asp Scout', - 'belugaliner': 'Beluga Liner', - 'cobramkiii': 'Cobra MkIII', - 'cobramkiv': 'Cobra MkIV', - 'clipper': 'Panther Clipper', - 'cutter': 'Imperial Cutter', - 'diamondback': 'Diamondback Scout', - 'diamondbackxl': 'Diamondback Explorer', - 'dolphin': 'Dolphin', - 'eagle': 'Eagle', - 'empire_courier': 'Imperial Courier', - 'empire_eagle': 'Imperial Eagle', - 'empire_fighter': 'Imperial Fighter', - 'empire_trader': 'Imperial Clipper', - 'federation_corvette': 'Federal Corvette', - 'federation_dropship': 'Federal Dropship', - 'federation_dropship_mkii': 'Federal Assault Ship', - 'federation_gunship': 'Federal Gunship', - 'federation_fighter': 'F63 Condor', - 'ferdelance': 'Fer-de-Lance', - 'hauler': 'Hauler', - 'independant_trader': 'Keelback', - 'independent_fighter': 'Taipan Fighter', - 'krait_mkii': 'Krait MkII', - 'krait_light': 'Krait Phantom', - 'mamba': 'Mamba', - 'orca': 'Orca', - 'python': 'Python', - 'scout': 'Taipan Fighter', - 'sidewinder': 'Sidewinder', - 'testbuggy': 'Scarab', - 'type6': 'Type-6 Transporter', - 'type7': 'Type-7 Transporter', - 'type9': 'Type-9 Heavy', - 'type9_military': 'Type-10 Defender', - 'typex': 'Alliance Chieftain', - 'typex_2': 'Alliance Crusader', - 'typex_3': 'Alliance Challenger', - 'viper': 'Viper MkIII', - 'viper_mkiv': 'Viper MkIV', - 'vulture': 'Vulture', -} + +class CAPIData(UserDict): + """CAPI Response.""" + + def __init__(self, data: Union[str, Dict[str, Any], 'CAPIData', None] = None, source_endpoint: str = None) -> None: + if data is None: + super().__init__() + elif isinstance(data, str): + super().__init__(json.loads(data)) + else: + super().__init__(data) + + self.original_data = self.data.copy() # Just in case + + self.source_endpoint = source_endpoint + + if source_endpoint is None: + return + + if source_endpoint == URL_SHIPYARD and self.data.get('lastStarport'): + # All the other endpoints may or may not have a lastStarport, but definitely wont have valid data + # for this check, which means it'll just make noise for no reason while we're working on other things + self.check_modules_ships() + + def check_modules_ships(self) -> None: + """ + Sanity check our `data` for modules and ships being as expected. + + 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') + 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: + logger.debug('modules is empty list. Damaged Station?') + + else: + logger.error(f'modules is non-empty list: {modules!r}') + + else: + logger.error(f'modules was not None, a list, or a dict! type: {type(modules)}, content: {modules}') + + # Set a safe value + self.data['lastStarport']['modules'] = modules = {} + + 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}') + + # Set a safe value + self.data['lastStarport']['ships'] = {'shipyard_list': {}, 'unavailable_list': []} def listify(thing: Union[List, Dict]) -> List: @@ -153,7 +165,7 @@ def listify(thing: Union[List, Dict]) -> List: class ServerError(Exception): """Exception Class for CAPI ServerErrors.""" - def __init__(self, *args): + def __init__(self, *args) -> None: # Raised when cannot contact the Companion API server self.args = args if not args: @@ -167,7 +179,7 @@ class ServerLagging(Exception): servers are too busy. """ - def __init__(self, *args): + def __init__(self, *args) -> None: self.args = args if not args: self.args = (_('Error: Frontier server is lagging'),) @@ -180,7 +192,7 @@ class SKUError(Exception): purchased E:D i.e. doesn't have the correct 'SKU'. """ - def __init__(self, *args): + def __init__(self, *args) -> None: self.args = args if not args: self.args = (_('Error: Frontier server SKU problem'),) @@ -189,7 +201,7 @@ class SKUError(Exception): class CredentialsError(Exception): """Exception Class for CAPI Credentials error.""" - def __init__(self, *args): + def __init__(self, *args) -> None: self.args = args if not args: self.args = (_('Error: Invalid Credentials'),) @@ -204,7 +216,7 @@ class CmdrError(Exception): for the old Cmdr. """ - def __init__(self, *args): + def __init__(self, *args) -> None: self.args = args if not args: self.args = (_('Error: Wrong Cmdr'),) @@ -213,14 +225,19 @@ class CmdrError(Exception): class Auth(object): """Handles authentication with the Frontier CAPI service via oAuth2.""" - def __init__(self, cmdr: str): + def __init__(self, cmdr: str) -> None: self.cmdr: str = cmdr self.session = requests.Session() self.session.headers['User-Agent'] = USER_AGENT self.verifier: Union[bytes, None] = None self.state: Union[str, None] = None - def refresh(self) -> Union[str, None]: + def __del__(self) -> None: + """Ensure our Session is closed if we're being deleted.""" + if self.session: + self.session.close() + + def refresh(self) -> Optional[str]: """ Attempt use of Refresh Token to get a valid Access Token. @@ -231,13 +248,13 @@ class Auth(object): logger.debug(f'Trying for "{self.cmdr}"') self.verifier = None - cmdrs = config.get('cmdrs') + cmdrs = config.get_list('cmdrs', default=[]) logger.debug(f'Cmdrs: {cmdrs}') idx = cmdrs.index(self.cmdr) logger.debug(f'idx = {idx}') - tokens = config.get('fdev_apikeys') or [] + tokens = config.get_list('fdev_apikeys', default=[]) tokens = tokens + [''] * (len(cmdrs) - len(tokens)) if tokens[idx]: logger.debug('We have a refresh token for that idx') @@ -255,6 +272,7 @@ class Auth(object): tokens[idx] = data.get('refresh_token', '') config.set('fdev_apikeys', tokens) config.save() # Save settings now for use by command-line app + return data.get('access_token') else: @@ -278,12 +296,19 @@ class Auth(object): logger.info(f'Trying auth from scratch for Commander "{self.cmdr}"') challenge = self.base64_url_encode(hashlib.sha256(self.verifier).digest()) webbrowser.open( - f'{SERVER_AUTH}{URL_AUTH}?response_type=code&audience=frontier,steam,epic&scope=capi&client_id={CLIENT_ID}&code_challenge={challenge}&code_challenge_method=S256&state={self.state}&redirect_uri={protocolhandler.redirect}' # noqa: E501 # I cant make this any shorter + f'{SERVER_AUTH}{URL_AUTH}?response_type=code' + f'&audience=frontier,steam,epic' + f'&scope=auth capi' + f'&client_id={CLIENT_ID}' + f'&code_challenge={challenge}' + f'&code_challenge_method=S256' + f'&state={self.state}' + f'&redirect_uri={protocolhandler.redirect}' ) return None - def authorize(self, payload: str) -> str: + def authorize(self, payload: str) -> str: # noqa: CCR001 """Handle oAuth authorization callback. :return: access token if successful, otherwise raises CredentialsError. @@ -304,7 +329,7 @@ class Auth(object): (data[k] for k in ('error_description', 'error', 'message') if k in data), '' ) - raise CredentialsError(f'Error: {error!r}') + raise CredentialsError(f'{_("Error")}: {error!r}') r = None try: @@ -317,26 +342,62 @@ class Auth(object): 'redirect_uri': protocolhandler.redirect, } + # import http.client as http_client + # http_client.HTTPConnection.debuglevel = 1 + # import logging + # requests_log = logging.getLogger("requests.packages.urllib3") + # requests_log.setLevel(logging.DEBUG) + # requests_log.propagate = True + r = self.session.post(SERVER_AUTH + URL_TOKEN, data=request_data, timeout=auth_timeout) - data = r.json() + data_token = r.json() if r.status_code == requests.codes.ok: + # Now we need to /decode the token to check the customer_id against FID + r = self.session.get( + SERVER_AUTH + URL_DECODE, + headers={ + 'Authorization': f'Bearer {data_token.get("access_token", "")}', + 'Content-Type': 'application/json', + }, + timeout=auth_timeout + ) + data_decode = r.json() + if r.status_code != requests.codes.ok: + r.raise_for_status() + + if (usr := data_decode.get('usr')) is None: + logger.error('No "usr" in /decode data') + raise CredentialsError(_("Error: Couldn't check token customer_id")) + + if (customer_id := usr.get('customer_id')) is None: + logger.error('No "usr"->"customer_id" in /decode data') + raise CredentialsError(_("Error: Couldn't check token customer_id")) + + # All 'FID' seen in Journals so far have been 'F' + # Frontier, Steam and Epic + if f'F{customer_id}' != monitor.state.get('FID'): + raise CredentialsError(_("Error: customer_id doesn't match!")) + logger.info(f'Frontier CAPI Auth: New token for \"{self.cmdr}\"') - cmdrs = config.get('cmdrs') + cmdrs = config.get_list('cmdrs', default=[]) idx = cmdrs.index(self.cmdr) - tokens = config.get('fdev_apikeys') or [] + tokens = config.get_list('fdev_apikeys', default=[]) tokens = tokens + [''] * (len(cmdrs) - len(tokens)) - tokens[idx] = data.get('refresh_token', '') + tokens[idx] = data_token.get('refresh_token', '') config.set('fdev_apikeys', tokens) config.save() # Save settings now for use by command-line app - return str(data.get('access_token')) + return str(data_token.get('access_token')) + + except CredentialsError: + raise except Exception as e: logger.exception(f"Frontier CAPI Auth: Can't get token for \"{self.cmdr}\"") if r: self.dump(r) - raise CredentialsError('unable to get token') from e + raise CredentialsError(_('Error: unable to get token')) from e logger.error(f"Frontier CAPI Auth: Can't get token for \"{self.cmdr}\"") self.dump(r) @@ -344,15 +405,15 @@ class Auth(object): (data[k] for k in ('error_description', 'error', 'message') if k in data), '' ) - raise CredentialsError(f'Error: {error!r}') + raise CredentialsError(f'{_("Error")}: {error!r}') @staticmethod def invalidate(cmdr: str) -> None: """Invalidate Refresh Token for specified Commander.""" logger.info(f'Frontier CAPI Auth: Invalidated token for "{cmdr}"') - cmdrs = config.get('cmdrs') + cmdrs = config.get_list('cmdrs', default=[]) idx = cmdrs.index(cmdr) - tokens = config.get('fdev_apikeys') or [] + tokens = config.get_list('fdev_apikeys', default=[]) tokens = tokens + [''] * (len(cmdrs) - len(tokens)) tokens[idx] = '' config.set('fdev_apikeys', tokens) @@ -378,12 +439,12 @@ class Session(object): STATE_INIT, STATE_AUTH, STATE_OK = list(range(3)) - def __init__(self): + def __init__(self) -> None: self.state = Session.STATE_INIT - self.server = None - self.credentials = None - self.session = None - self.auth = None + self.server: Optional[str] = None + self.credentials: Optional[Dict[str, Any]] = None + self.session: Optional[requests.Session] = None + self.auth: Optional[Auth] = None self.retrying = False # Avoid infinite loop when successful auth / unsuccessful query def login(self, cmdr: str = None, is_beta: Union[None, bool] = None) -> bool: @@ -446,7 +507,7 @@ class Session(object): try: logger.debug('Trying authorize with payload from handler') - self.start(self.auth.authorize(protocolhandler.lastpayload)) + self.start(self.auth.authorize(protocolhandler.lastpayload)) # type: ignore self.auth = None except Exception: @@ -476,7 +537,7 @@ class Session(object): try: logger.trace('Trying...') - r = self.session.get(self.server + endpoint, timeout=timeout) + r = self.session.get(self.server + endpoint, timeout=timeout) # type: ignore except Exception as e: logger.debug('Attempting GET', exc_info=e) @@ -499,7 +560,7 @@ class Session(object): try: r.raise_for_status() # Typically 403 "Forbidden" on token expiry - data = r.json() # May also fail here if token expired since response is empty + data = CAPIData(r.json(), endpoint) # May also fail here if token expired since response is empty except (requests.HTTPError, ValueError) as e: logger.exception('Frontier CAPI Auth: GET ') @@ -525,9 +586,13 @@ class Session(object): self.retrying = False if 'timestamp' not in data: - logger.trace('timestamp not in data, adding from response headers') + # logger.trace('timestamp not in data, adding from response headers') data['timestamp'] = time.strftime('%Y-%m-%dT%H:%M:%SZ', parsedate(r.headers['Date'])) # type: ignore + # Update Odyssey Suit data + if endpoint == URL_QUERY: + self.suit_update(data) + return data def profile(self) -> CAPIData: @@ -538,20 +603,53 @@ class Session(object): return data - def station(self) -> CAPIData: - """Perform CAPI /profile endpoint query for station data.""" + def station(self) -> CAPIData: # noqa: CCR001 + """ + Perform CAPI quer(y|ies) for station data. + + A /profile query is performed to check that we are docked (or on foot) + and the station name and marketid match the prior Docked event. + If they do match, and the services list says they're present, also + retrieve CAPI market and/or shipyard/outfitting data and merge into + the /profile data. + + :return: Possibly augmented CAPI data. + """ data = self.query(URL_QUERY) if 'commander' not in data: logger.error('No commander in returned data') return data - if not data['commander'].get('docked'): + if not data['commander'].get('docked') and not monitor.state['OnFoot']: return data - services = data['lastStarport'].get('services', {}) + # Sanity checks in case data isn't as we expect, and maybe 'docked' flag + # is also lagging. + if (last_starport := data.get('lastStarport')) is None: + logger.error("No lastStarport in data!") + return data - last_starport_name = data['lastStarport']['name'] - last_starport_id = int(data['lastStarport']['id']) + if ((last_starport_name := last_starport.get('name')) is None + or last_starport_name == ''): + # This could well be valid if you've been out exploring for a long + # time. + logger.warning("No lastStarport name!") + return data + + services = last_starport.get('services', {}) + if not isinstance(services, dict): + # Odyssey Alpha Phase 3 4.0.0.20 has been observed having + # this be an empty list when you've jumped to another system + # and not yet docked. As opposed to no services key at all + # or an empty dict. + logger.error(f'services is "{type(services)}", not dict !') + if __debug__: + self.dump_capi_data(data) + + # Set an empty dict so as to not have to retest below. + services = {} + + last_starport_id = int(last_starport.get('id')) if services.get('commodities'): marketdata = self.query(URL_MARKET) @@ -571,6 +669,36 @@ class Session(object): return data + def suit_update(self, data: CAPIData) -> None: + """ + Update monitor.state suit data. + + :param data: CAPI data to extra suit data from. + """ + if (current_suit := data.get('suit')) is None: + # Probably no Odyssey on the account, so point attempting more. + return + + monitor.state['SuitCurrent'] = current_suit + # It's easier to always have this in the 'sparse array' dict form + suits = data.get('suits') + if isinstance(suits, list): + monitor.state['Suits'] = dict(enumerate(suits)) + + else: + monitor.state['Suits'] = suits + + if (suit_loadouts := data.get('loadouts')) is None: + logger.warning('CAPI data had "suit" but no (suit) "loadouts"') + + monitor.state['SuitLoadoutCurrent'] = data.get('loadout') + # It's easier to always have this in the 'sparse array' dict form + if isinstance(suit_loadouts, list): + monitor.state['SuitLoadouts'] = dict(enumerate(suit_loadouts)) + + else: + monitor.state['SuitLoadouts'] = suit_loadouts + def close(self) -> None: """Close CAPI authorization session.""" self.state = Session.STATE_INIT @@ -588,13 +716,40 @@ class Session(object): logger.debug('Forcing a full re-authentication') # Force a full re-authentication self.close() - Auth.invalidate(self.credentials['cmdr']) + Auth.invalidate(self.credentials['cmdr']) # type: ignore # noinspection PyMethodMayBeStatic def dump(self, r: requests.Response) -> None: """Log, as error, status of requests.Response from CAPI request.""" logger.error(f'Frontier CAPI Auth: {r.url} {r.status_code} {r.reason and r.reason or "None"} {r.text}') + def dump_capi_data(self, data: CAPIData) -> None: + """Dump CAPI data to file for examination.""" + if os.path.isdir('dump'): + try: + system = data['lastSystem']['name'] + + except (KeyError, ValueError): + system = '' + + try: + if data['commander'].get('docked'): + station = f'.{data["lastStarport"]["name"]}' + + else: + station = '' + + except (KeyError, ValueError): + station = '' + + timestamp = time.strftime('%Y-%m-%dT%H.%M.%S', time.localtime()) + with open(f'dump/{system}{station}.{timestamp}.json', 'wb') as h: + h.write(json.dumps(dict(data), + ensure_ascii=False, + indent=2, + sort_keys=True, + separators=(',', ': ')).encode('utf-8')) + def fixup(data: CAPIData) -> CAPIData: # noqa: C901, CCR001 # Can't be usefully simplified """ @@ -606,7 +761,7 @@ 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'): - with open(join(config.respath, f), 'r') as csvfile: + with open(join(config.respath_path, f), 'r') as csvfile: reader = csv.DictReader(csvfile) for row in reader: @@ -670,14 +825,14 @@ def fixup(data: CAPIData) -> CAPIData: # noqa: C901, CCR001 # Can't be usefully datacopy = data.copy() datacopy['lastStarport'] = data['lastStarport'].copy() datacopy['lastStarport']['commodities'] = commodities - return CAPIData(datacopy) + return datacopy def ship(data: CAPIData) -> CAPIData: """Construct a subset of the received data describing the current ship.""" def filter_ship(d: CAPIData) -> CAPIData: """Filter provided ship data.""" - filtered: CAPIData = CAPIData({}) + filtered = CAPIData() for k, v in d.items(): if not v: pass # just skip empty fields for brevity @@ -704,18 +859,34 @@ def ship(data: CAPIData) -> CAPIData: return filter_ship(data['ship']) -def ship_file_name(ship_name: str, ship_type: str) -> str: - """Return a ship name suitable for a filename.""" - name = str(ship_name or ship_map.get(ship_type.lower(), ship_type)).strip() - if name.endswith('.'): - name = name[:-1] +V = TypeVar('V') - if name.lower() in ('con', 'prn', 'aux', 'nul', - 'com1', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7', 'com8', 'com9', - 'lpt1', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7', 'lpt8', 'lpt9'): - name = name + '_' - return name.translate({ord(x): u'_' for x in ('\0', '<', '>', ':', '"', '/', '\\', '|', '?', '*')}) +def index_possibly_sparse_list(data: Union[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 key: Key to use to index + :raises ValueError: When data is of an unexpected type + :return: The value at the key + + >>> data = {"1": "test"} + >>> index_possibly_sparse_list(data, 1) + 'test' + + >>> data = ["test_list"] + >>> index_possibly_sparse_list(data, 0) + 'test_list' + """ + if isinstance(data, list): + return data[key] + + elif isinstance(data, (dict, OrderedDict)): + return data[str(key)] + + else: + raise ValueError(f'Unexpected data type {type(data)}') # singleton diff --git a/config.py b/config.py index b07aa20a..f92eea4c 100644 --- a/config.py +++ b/config.py @@ -1,39 +1,73 @@ -import numbers +""" +Code dealing with the configuration of the program. + +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. +""" + +# spell-checker: words HKEY FOLDERID wchar wstring edcdhkey + +import abc +import contextlib +import functools +import logging +import os +import pathlib +import re +import subprocess import sys +import traceback import warnings -from os import getenv, makedirs, mkdir, pardir -from os.path import expanduser, dirname, exists, isdir, join, normpath +from abc import abstractmethod from sys import platform +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Type, TypeVar, Union + import semantic_version -from constants import applongname, appname +from constants import GITVERSION_FILE, applongname, appname # Any of these may be imported by plugins appcmdname = 'EDMC' # appversion **MUST** follow Semantic Versioning rules: # # Major.Minor.Patch(-prerelease)(+buildmetadata) -appversion = '4.2.7' # -rc1+a872b5f' -# For some things we want appversion without (possible) +build metadata -appversion_nobuild = str(semantic_version.Version(appversion).truncate('prerelease')) -copyright = u'© 2015-2019 Jonathan Harris, 2020-2021 EDCD' +# NB: Do *not* import this, use the functions appversion() and appversion_nobuild() +_static_appversion = '5.0.0' +copyright = '© 2015-2019 Jonathan Harris, 2020-2021 EDCD' update_feed = 'https://raw.githubusercontent.com/EDCD/EDMarketConnector/releases/edmarketconnector.xml' update_interval = 8*60*60 +# 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"): + logger = logging.getLogger(appcmdname) -if platform=='darwin': - from Foundation import NSBundle, NSUserDefaults, NSSearchPathForDirectoriesInDomains, NSApplicationSupportDirectory, NSDocumentDirectory, NSLibraryDirectory, NSUserDomainMask +else: + logger = logging.getLogger(appname) -elif platform=='win32': +if platform == 'darwin': + from Foundation import ( # type: ignore + NSApplicationSupportDirectory, NSBundle, NSDocumentDirectory, NSSearchPathForDirectoriesInDomains, + NSUserDefaults, NSUserDomainMask + ) + +elif platform == 'win32': import ctypes - from ctypes.wintypes import * import uuid + import winreg + from ctypes.wintypes import DWORD, HANDLE + if TYPE_CHECKING: + import ctypes.windll # type: ignore - FOLDERID_Documents = uuid.UUID('{FDD39AD0-238F-46AF-ADB4-6C85480369C7}') + REG_RESERVED_ALWAYS_ZERO = 0 + + # This is the only way to do this from python without external deps (which do this anyway). + FOLDERID_Documents = uuid.UUID('{FDD39AD0-238F-46AF-ADB4-6C85480369C7}') FOLDERID_LocalAppData = uuid.UUID('{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}') - FOLDERID_Profile = uuid.UUID('{5E6C858F-0E22-4760-9AFE-EA3317B67173}') - FOLDERID_SavedGames = uuid.UUID('{4C5C32FF-BB9D-43b0-B5B4-2D72E54EAAA4}') + FOLDERID_Profile = uuid.UUID('{5E6C858F-0E22-4760-9AFE-EA3317B67173}') + FOLDERID_SavedGames = uuid.UUID('{4C5C32FF-BB9D-43b0-B5B4-2D72E54EAAA4}') SHGetKnownFolderPath = ctypes.windll.shell32.SHGetKnownFolderPath SHGetKnownFolderPath.argtypes = [ctypes.c_char_p, DWORD, HANDLE, ctypes.POINTER(ctypes.c_wchar_p)] @@ -41,401 +75,985 @@ elif platform=='win32': CoTaskMemFree = ctypes.windll.ole32.CoTaskMemFree CoTaskMemFree.argtypes = [ctypes.c_void_p] - # winreg in Python <= 3.7.4 handles REG_MULTI_SZ incorrectly, so do this instead. https://bugs.python.org/issue32587 - HKEY_CURRENT_USER = 0x80000001 - KEY_ALL_ACCESS = 0x000F003F - REG_CREATED_NEW_KEY = 0x00000001 - REG_OPENED_EXISTING_KEY = 0x00000002 - REG_SZ = 1 - REG_DWORD = 4 - REG_MULTI_SZ = 7 - - RegCreateKeyEx = ctypes.windll.advapi32.RegCreateKeyExW - RegCreateKeyEx.restype = LONG - RegCreateKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, LPCVOID, DWORD, DWORD, LPCVOID, ctypes.POINTER(HKEY), ctypes.POINTER(DWORD)] - - RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW - RegOpenKeyEx.restype = LONG - RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] - - RegCloseKey = ctypes.windll.advapi32.RegCloseKey - RegCloseKey.restype = LONG - RegCloseKey.argtypes = [HKEY] - - RegQueryValueEx = ctypes.windll.advapi32.RegQueryValueExW - RegQueryValueEx.restype = LONG - RegQueryValueEx.argtypes = [HKEY, LPCWSTR, LPCVOID, ctypes.POINTER(DWORD), LPCVOID, ctypes.POINTER(DWORD)] - - RegSetValueEx = ctypes.windll.advapi32.RegSetValueExW - RegSetValueEx.restype = LONG - RegSetValueEx.argtypes = [HKEY, LPCWSTR, LPCVOID, DWORD, LPCVOID, DWORD] - - RegCopyTree = ctypes.windll.advapi32.RegCopyTreeW - RegCopyTree.restype = LONG - RegCopyTree.argtypes = [HKEY, LPCWSTR, HKEY] - - RegDeleteKey = ctypes.windll.advapi32.RegDeleteTreeW - RegDeleteKey.restype = LONG - RegDeleteKey.argtypes = [HKEY, LPCWSTR] - - RegDeleteValue = ctypes.windll.advapi32.RegDeleteValueW - RegDeleteValue.restype = LONG - RegDeleteValue.argtypes = [HKEY, LPCWSTR] - - def KnownFolderPath(guid): + def known_folder_path(guid: uuid.UUID) -> Optional[str]: + """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)): return None - retval = buf.value # copy data - CoTaskMemFree(buf) # and free original + retval = buf.value # copy data + CoTaskMemFree(buf) # and free original return retval - -elif platform=='linux': - import codecs - from configparser import RawConfigParser +elif platform == 'linux': + from configparser import ConfigParser -class Config(object): +_T = TypeVar('_T') - OUT_MKT_EDDN = 1 - # OUT_MKT_BPC = 2 # No longer supported - OUT_MKT_TD = 4 - OUT_MKT_CSV = 8 - OUT_SHIP = 16 - # OUT_SHIP_EDS = 16 # Replaced by OUT_SHIP - # OUT_SYS_FILE = 32 # No longer supported - # OUT_STAT = 64 # No longer available + +########################################################################### +def git_shorthash_from_head() -> str: + """ + Determine short hash for current git HEAD. + + :return: str - None if we couldn't determine the short hash. + """ + shorthash: str = None # type: ignore + try: + 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: + logger.error(f"Couldn't run git command for short hash: {e!r}") + + else: + shorthash = out.decode().rstrip('\n') + if re.match(r'^[0-9a-f]{7,}$', shorthash) is None: + logger.error(f"'{shorthash}' doesn't look like a valid git short hash, forcing to None") + shorthash = None # type: ignore + + return shorthash + + +def appversion() -> semantic_version.Version: + """ + Determine app version including git short hash if possible. + + :return: The augmented app 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: + shorthash = gitv.read() + + else: + # Running from source + shorthash = git_shorthash_from_head() + if shorthash is None: + shorthash = 'UNKNOWN' + + return semantic_version.Version(f'{_static_appversion}+{shorthash}') + + +def appversion_nobuild() -> semantic_version.Version: + """ + Determine app version without *any* build meta data. + + This will not only strip any added git short hash, but also any trailing + '+' in _static_appversion. + + :return: App version without any build meta data. + """ + return appversion().truncate('prerelease') +########################################################################### + + +class AbstractConfig(abc.ABC): + """Abstract root class of all platform specific Config implementations.""" + + OUT_MKT_EDDN = 1 + # OUT_MKT_BPC = 2 # No longer supported + OUT_MKT_TD = 4 + OUT_MKT_CSV = 8 + OUT_SHIP = 16 + # OUT_SHIP_EDS = 16 # Replaced by OUT_SHIP + # OUT_SYS_FILE = 32 # No longer supported + # OUT_STAT = 64 # No longer available # OUT_SHIP_CORIOLIS = 128 # Replaced by OUT_SHIP - OUT_STATION_ANY = OUT_MKT_EDDN|OUT_MKT_TD|OUT_MKT_CSV - # OUT_SYS_EDSM = 256 # Now a plugin - # OUT_SYS_AUTO = 512 # Now always automatic - OUT_MKT_MANUAL = 1024 - OUT_SYS_EDDN = 2048 - OUT_SYS_DELAY = 4096 + OUT_STATION_ANY = OUT_MKT_EDDN | OUT_MKT_TD | OUT_MKT_CSV + # OUT_SYS_EDSM = 256 # Now a plugin + # OUT_SYS_AUTO = 512 # Now always automatic + OUT_MKT_MANUAL = 1024 + OUT_SYS_EDDN = 2048 + OUT_SYS_DELAY = 4096 + + app_dir_path: pathlib.Path + plugin_dir_path: pathlib.Path + internal_plugin_dir_path: pathlib.Path + 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 ? + __auth_force_localserver = False # Should we use localhost for auth callback ? + __auth_force_edmc_protocol = False # Should we force edmc:// protocol ? + + def __init__(self) -> None: + self.home_path = pathlib.Path.home() + + def set_shutdown(self): + """Set flag denoting we're in the shutdown sequence.""" + self.__in_shutdown = True + + @property + def shutting_down(self) -> bool: + """ + Determine if we're in the shutdown sequence. + + :return: bool - True if in shutdown sequence. + """ + return self.__in_shutdown + + def set_auth_force_localserver(self): + """Set flag to force use of localhost web server for Frontier Auth callback.""" + self.__auth_force_localserver = True + + @property + def auth_force_localserver(self) -> bool: + """ + Determine if use of localhost is forced for Frontier Auth callback. + + :return: bool - True if we should use localhost web server. + """ + return self.__auth_force_localserver + + def set_auth_force_edmc_protocol(self): + """Set flag to force use of localhost web server for Frontier Auth callback.""" + self.__auth_force_edmc_protocol = True + + @property + def auth_force_edmc_protocol(self) -> bool: + """ + Determine if use of localhost is forced for Frontier Auth callback. + + :return: bool - True if we should use localhost web server. + """ + return self.__auth_force_edmc_protocol + + @property + def app_dir(self) -> str: + """Return a string version of app_dir.""" + return str(self.app_dir_path) + + @property + def plugin_dir(self) -> str: + """Return a string version of plugin_dir.""" + return str(self.plugin_dir_path) + + @property + def internal_plugin_dir(self) -> str: + """Return a string version of internal_plugin_dir.""" + return str(self.internal_plugin_dir_path) + + @property + def respath(self) -> str: + """Return a string version of respath.""" + return str(self.respath_path) + + @property + def home(self) -> str: + """Return a string version of home.""" + return str(self.home_path) + + @property + def default_journal_dir(self) -> str: + """Return a string version of default_journal_dir.""" + return str(self.default_journal_dir_path) + + @staticmethod + def _suppress_call( + func: Callable[..., _T], exceptions: Union[Type[BaseException], List[Type[BaseException]]] = Exception, + *args: Any, **kwargs: Any + ) -> Optional[_T]: + if exceptions is None: + exceptions = [Exception] + + if not isinstance(exceptions, list): + exceptions = [exceptions] + + with contextlib.suppress(*exceptions): # type: ignore # it works fine, mypy + return func(*args, **kwargs) + + return None + + def get(self, key: str, default: Union[list, str, bool, int] = None) -> Union[list, str, bool, int]: + """ + Return the data for the requested key, or a default. + + :param key: The key data is being requested for. + :param default: The default to return if the key does not exist, defaults to None. + :raises OSError: On Windows, if a Registry error occurs. + :return: The data or the default. + """ + warnings.warn(DeprecationWarning('get is Deprecated. use the specific getter for your type')) + logger.debug('Attempt to use Deprecated get() method\n' + ''.join(traceback.format_stack())) + + if (l := self._suppress_call(self.get_list, ValueError, key, default=None)) is not None: + return l + + elif (s := self._suppress_call(self.get_str, ValueError, key, default=None)) is not None: + return s + + elif (b := self._suppress_call(self.get_bool, ValueError, key, default=None)) is not None: + return b + + elif (i := self._suppress_call(self.get_int, ValueError, key, default=None)) is not None: + return i + + return default # type: ignore + + @abstractmethod + def get_list(self, key: str, *, default: list = None) -> list: + """ + Return the list referred to by the given key if it exists, or the default. + + Implements :meth:`AbstractConfig.get_list`. + """ + raise NotImplementedError + + @abstractmethod + def get_str(self, key: str, *, default: str = None) -> str: + """ + Return the string referred to by the given key if it exists, or the default. + + :param key: The key data is being requested for. + :param default: Default to return if the key does not exist, defaults to None. + :raises ValueError: If an internal error occurs getting or converting a value. + :raises OSError: On Windows, if a Registry error occurs. + :return: The requested data or the default. + """ + raise NotImplementedError + + @abstractmethod + def get_bool(self, key: str, *, default: bool = None) -> bool: + """ + Return the bool referred to by the given key if it exists, or the default. + + :param key: The key data is being requested for. + :param default: Default to return if the key does not exist, defaults to None + :raises ValueError: If an internal error occurs getting or converting a value + :raises OSError: On Windows, if a Registry error occurs. + :return: The requested data or the default + """ + raise NotImplementedError + + def getint(self, key: str, *, default: int = 0) -> int: + """ + Getint is a Deprecated getter method. + + See get_int for its replacement. + :raises OSError: On Windows, if a Registry error occurs. + """ + warnings.warn(DeprecationWarning('getint is Deprecated. Use get_int instead')) + logger.debug('Attempt to use Deprecated getint() method\n' + ''.join(traceback.format_stack())) + + return self.get_int(key, default=default) + + @abstractmethod + def get_int(self, key: str, *, default: int = 0) -> int: + """ + Return the int referred to by key if it exists in the config. + + For legacy reasons, the default is 0 and not None. + + :param key: The key data is being requested for. + :param default: Default to return if the key does not exist, defaults to 0. + :raises ValueError: If the internal representation of this key cannot be converted to an int. + :raises OSError: On Windows, if a Registry error occurs. + :return: The requested data or the default. + """ + raise NotImplementedError + + @abstractmethod + def set(self, key: str, val: Union[int, str, List[str], bool]) -> None: + """ + Set the given key's data to the given value. + + :param key: The key to set the value on. + :param val: The value to set the key's data to. + :raises ValueError: On an invalid type. + :raises OSError: On Windows, if a Registry error occurs. + """ + raise NotImplementedError + + @abstractmethod + def delete(self, key: str, *, suppress=False) -> None: + """ + Delete the given key from the config. + + :param key: The key to delete. + :param suppress: bool - Whether to suppress any errors. Useful in case + code to migrate settings is blindly removing an old key. + :raises OSError: On Windows, if a registry error occurs. + """ + raise NotImplementedError + + @abstractmethod + def save(self) -> None: + """ + Save the current configuration. + + :raises OSError: On Windows, if a Registry error occurs. + """ + raise NotImplementedError + + @abstractmethod + def close(self) -> None: + """Close this config and release any associated resources.""" + raise NotImplementedError + + def get_password(self, account: str) -> None: + """Legacy password retrieval.""" + warnings.warn("password subsystem is no longer supported", DeprecationWarning) + + def set_password(self, account: str, password: str) -> None: + """Legacy password setting.""" + warnings.warn("password subsystem is no longer supported", DeprecationWarning) + + def delete_password(self, account: str) -> None: + """Legacy password deletion.""" + warnings.warn("password subsystem is no longer supported", DeprecationWarning) + + +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 + self.app_dir_path.mkdir(exist_ok=True) + + self.plugin_dir_path = self.app_dir_path / 'plugins' + self.plugin_dir_path.mkdir(exist_ok=True) + + 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 + 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' + + create_key_defaults = functools.partial( + winreg.CreateKeyEx, + key=winreg.HKEY_CURRENT_USER, + access=winreg.KEY_ALL_ACCESS | winreg.KEY_WOW64_64KEY, + ) + + try: + self.__reg_handle: winreg.HKEYType = create_key_defaults( + sub_key=r'Software\Marginal\EDMarketConnector' + ) + if do_winsparkle: + self.__setup_winsparkle() + + except OSError: + 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) + + 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]: + """Access the Registry for the raw entry.""" + try: + value, _type = winreg.QueryValueEx(self.__reg_handle, key) + except FileNotFoundError: + # 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: + return int(value) + + elif _type == winreg.REG_MULTI_SZ: + return list(value) + + else: + logger.warning(f'registry key {key=} returned unknown type {_type=} {value=}') + return None + + def get_str(self, key: str, *, default: str = None) -> str: + """ + Return the string referred to by the given key if it exists, or the default. + + Implements :meth:`AbstractConfig.get_str`. + """ + res = self.__get_regentry(key) + 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): + raise ValueError(f'Data from registry is not a string: {type(res)=} {res=}') + + return res + + def get_list(self, key: str, *, default: list = None) -> list: + """ + Return the list referred to by the given key if it exists, or the default. + + Implements :meth:`AbstractConfig.get_list`. + """ + res = self.__get_regentry(key) + 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): + raise ValueError(f'Data from registry is not a list: {type(res)=} {res}') + + return res + + def get_int(self, key: str, *, default: int = 0) -> int: + """ + Return the int referred to by key if it exists in the config. + + Implements :meth:`AbstractConfig.get_int`. + """ + res = self.__get_regentry(key) + if res is None: + return default + + if not isinstance(res, int): + raise ValueError(f'Data from registry is not an int: {type(res)=} {res}') + + return res + + def get_bool(self, key: str, *, default: bool = None) -> bool: + """ + Return the bool referred to by the given key if it exists, or the default. + + Implements :meth:`AbstractConfig.get_bool`. + """ + res = self.get_int(key) + if res is None: + return default # type: ignore # Yes it could be None, but we're _assuming_ that people gave us a default - if platform=='darwin': + return bool(res) - def __init__(self): - self.__in_shutdown = False # Is the application currently shutting down ? - self.__auth_force_localserver = False # Should we use localhost for auth callback ? + def set(self, key: str, val: Union[int, str, List[str], bool]) -> None: + """ + Set the given key's data to the given value. - self.app_dir = join(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], appname) - if not isdir(self.app_dir): - mkdir(self.app_dir) + Implements :meth:`AbstractConfig.set`. + """ + reg_type = None + if isinstance(val, str): + reg_type = winreg.REG_SZ + winreg.SetValueEx(self.__reg_handle, key, REG_RESERVED_ALWAYS_ZERO, winreg.REG_SZ, val) - self.plugin_dir = join(self.app_dir, 'plugins') - if not isdir(self.plugin_dir): - mkdir(self.plugin_dir) + elif isinstance(val, int): # The original code checked for numbers.Integral, I dont think that is needed. + reg_type = winreg.REG_DWORD + + elif isinstance(val, list): + reg_type = winreg.REG_MULTI_SZ + + elif isinstance(val, bool): + reg_type = winreg.REG_DWORD + val = int(val) + + 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 - self.internal_plugin_dir = getattr(sys, 'frozen', False) and normpath(join(dirname(sys.executable), pardir, 'Library', 'plugins')) or join(dirname(__file__), 'plugins') + def delete(self, key: str, *, suppress=False) -> None: + """ + Delete the given key from the config. - self.default_journal_dir = join(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], 'Frontier Developments', 'Elite Dangerous') + 'key' is relative to the base Registry path we use. - self.home = expanduser('~') + Implements :meth:`AbstractConfig.delete`. + """ + try: + winreg.DeleteValue(self.__reg_handle, key) + except OSError: + if suppress: + return - self.respath = getattr(sys, 'frozen', False) and normpath(join(dirname(sys.executable), pardir, 'Resources')) or dirname(__file__) + raise - if not getattr(sys, 'frozen', False): - # Don't use Python's settings if interactive - self.identifier = 'uk.org.marginal.%s' % appname.lower() - NSBundle.mainBundle().infoDictionary()['CFBundleIdentifier'] = self.identifier - else: - self.identifier = NSBundle.mainBundle().bundleIdentifier() - self.defaults = NSUserDefaults.standardUserDefaults() - self.settings = dict(self.defaults.persistentDomainForName_(self.identifier) or {}) # make writeable + def save(self) -> None: + """ + Save the configuration. - # Check out_dir exists - if not self.get('outdir') or not isdir(self.get('outdir')): - self.set('outdir', NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, True)[0]) + Not required for WinConfig as Registry keys are flushed on write. + """ + pass - def get(self, key): - val = self.settings.get(key) - if val is None: - return None - elif isinstance(val, str): - return str(val) - elif hasattr(val, '__iter__'): - return list(val) # make writeable - else: - return None + def close(self): + """ + Close this config and release any associated resources. - def get_str(self, key): - return self.get(key) - - def get_list(self, key): - return self.get(key) - - def get_bool(self, key): - return self.get(key) - - def getint(self, key): - try: - return int(self.settings.get(key, 0)) # should already be int, but check by casting - except: - return 0 - - def get_int(self, key): - return self.getint(key) - - def set(self, key, val): - self.settings[key] = val - - def delete(self, key): - self.settings.pop(key, None) - - def save(self): - self.defaults.setPersistentDomain_forName_(self.settings, self.identifier) - self.defaults.synchronize() - - def close(self): - self.save() - self.defaults = None - - def set_shutdown(self): - self.__in_shutdown = True - - @property - def shutting_down(self) -> bool: - return self.__in_shutdown - - def set_auth_force_localserver(self): - self.__auth_force_localserver = True - - @property - def auth_force_localserver(self) -> bool: - return self.__auth_force_localserver - - elif platform=='win32': - - def __init__(self): - self.__in_shutdown = False # Is the application currently shutting down ? - self.__auth_force_localserver = False # Should we use localhost for auth callback ? - - self.app_dir = join(KnownFolderPath(FOLDERID_LocalAppData), appname) - if not isdir(self.app_dir): - mkdir(self.app_dir) - - self.plugin_dir = join(self.app_dir, 'plugins') - if not isdir(self.plugin_dir): - mkdir(self.plugin_dir) - - self.internal_plugin_dir = join(dirname(getattr(sys, 'frozen', False) and sys.executable or __file__), u'plugins') - - # expanduser in Python 2 on Windows doesn't handle non-ASCII - http://bugs.python.org/issue13207 - self.home = KnownFolderPath(FOLDERID_Profile) or u'\\' - - journaldir = KnownFolderPath(FOLDERID_SavedGames) - self.default_journal_dir = journaldir and join(journaldir, 'Frontier Developments', 'Elite Dangerous') or None - - self.respath = dirname(getattr(sys, 'frozen', False) and sys.executable or __file__) - - self.identifier = applongname - - self.hkey = HKEY() - disposition = DWORD() - if RegCreateKeyEx(HKEY_CURRENT_USER, r'Software\Marginal\EDMarketConnector', 0, None, 0, KEY_ALL_ACCESS, None, ctypes.byref(self.hkey), ctypes.byref(disposition)): - raise Exception() - - # set WinSparkle defaults - https://github.com/vslavik/winsparkle/wiki/Registry-Settings - edcdhkey = HKEY() - if RegCreateKeyEx(HKEY_CURRENT_USER, r'Software\EDCD\EDMarketConnector', 0, None, 0, KEY_ALL_ACCESS, None, ctypes.byref(edcdhkey), ctypes.byref(disposition)): - raise Exception() - - sparklekey = HKEY() - if not RegCreateKeyEx(edcdhkey, 'WinSparkle', 0, None, 0, KEY_ALL_ACCESS, None, ctypes.byref(sparklekey), ctypes.byref(disposition)): - if disposition.value == REG_CREATED_NEW_KEY: - buf = ctypes.create_unicode_buffer('1') - RegSetValueEx(sparklekey, 'CheckForUpdates', 0, 1, buf, len(buf)*2) - buf = ctypes.create_unicode_buffer(str(update_interval)) - RegSetValueEx(sparklekey, 'UpdateInterval', 0, 1, buf, len(buf)*2) - RegCloseKey(sparklekey) - - if not self.get('outdir') or not isdir(self.get('outdir')): - self.set('outdir', KnownFolderPath(FOLDERID_Documents) or self.home) + Implements :meth:`AbstractConfig.close`. + """ + self.__reg_handle.Close() + + +class MacConfig(AbstractConfig): + """MacConfig is the implementation of AbstractConfig for Darwin based OSes.""" + + def __init__(self) -> None: + super().__init__() + support_path = pathlib.Path( + NSSearchPathForDirectoriesInDomains( + NSApplicationSupportDirectory, NSUserDomainMask, True + )[0] + ) - def get(self, key): - typ = DWORD() - size = DWORD() - if RegQueryValueEx(self.hkey, key, 0, ctypes.byref(typ), None, ctypes.byref(size)) or typ.value not in [REG_SZ, REG_MULTI_SZ]: - return None - buf = ctypes.create_unicode_buffer(int(size.value / 2)) - if RegQueryValueEx(self.hkey, key, 0, ctypes.byref(typ), buf, ctypes.byref(size)): - return None - elif typ.value == REG_MULTI_SZ: - return [x for x in ctypes.wstring_at(buf, len(buf)-2).split(u'\x00')] - else: - return str(buf.value) - - def getint(self, key): - typ = DWORD() - size = DWORD(4) - val = DWORD() - if RegQueryValueEx(self.hkey, key, 0, ctypes.byref(typ), ctypes.byref(val), ctypes.byref(size)) or typ.value != REG_DWORD: - return 0 - else: - return val.value - - def set(self, key, val): - if isinstance(val, str): - buf = ctypes.create_unicode_buffer(val) - RegSetValueEx(self.hkey, key, 0, REG_SZ, buf, len(buf)*2) - elif isinstance(val, numbers.Integral): - RegSetValueEx(self.hkey, key, 0, REG_DWORD, ctypes.byref(DWORD(val)), 4) - elif hasattr(val, '__iter__'): # iterable - stringval = u'\x00'.join([str(x) or u' ' for x in val] + [u'']) # null terminated non-empty strings - buf = ctypes.create_unicode_buffer(stringval) - RegSetValueEx(self.hkey, key, 0, REG_MULTI_SZ, buf, len(buf)*2) - else: - raise NotImplementedError() - - def delete(self, key): - RegDeleteValue(self.hkey, key) - - def save(self): - pass # Redundant since registry keys are written immediately - - def close(self): - RegCloseKey(self.hkey) - self.hkey = None - - def set_shutdown(self): - self.__in_shutdown = True - - @property - def shutting_down(self) -> bool: - return self.__in_shutdown - - def set_auth_force_localserver(self): - self.__auth_force_localserver = True - - @property - def auth_force_localserver(self) -> bool: - return self.__auth_force_localserver - - elif platform=='linux': - - SECTION = 'config' - - def __init__(self): - self.__in_shutdown = False # Is the application currently shutting down ? - self.__auth_force_localserver = False # Should we use localhost for auth callback ? - - # http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html - self.app_dir = join(getenv('XDG_DATA_HOME', expanduser('~/.local/share')), appname) - if not isdir(self.app_dir): - makedirs(self.app_dir) - - self.plugin_dir = join(self.app_dir, 'plugins') - if not isdir(self.plugin_dir): - mkdir(self.plugin_dir) - - self.internal_plugin_dir = join(dirname(__file__), 'plugins') - - self.default_journal_dir = None - - self.home = expanduser('~') - - self.respath = dirname(__file__) - - self.identifier = 'uk.org.marginal.%s' % appname.lower() - - self.filename = join(getenv('XDG_CONFIG_HOME', expanduser('~/.config')), appname, '%s.ini' % appname) - if not isdir(dirname(self.filename)): - makedirs(dirname(self.filename)) - - self.config = RawConfigParser(comment_prefixes = ('#',)) - try: - with codecs.open(self.filename, 'r') as h: - self.config.read_file(h) - except: - self.config.add_section(self.SECTION) - - if not self.get('outdir') or not isdir(self.get('outdir')): - self.set('outdir', expanduser('~')) - - def get(self, key): - try: - val = self.config.get(self.SECTION, key) - if u'\n' in val: # list - # ConfigParser drops the last entry if blank, 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(u'\n')[:-1]] - else: - return self._unescape(val) - except: - return None - - def getint(self, key): - try: - return self.config.getint(self.SECTION, key) - except: - return 0 - - def set(self, key, val): - if isinstance(val, bool): - 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)) - elif hasattr(val, '__iter__'): # iterable - self.config.set(self.SECTION, key, u'\n'.join([self._escape(x) for x in val] + [u';'])) - else: - raise NotImplementedError() - - def delete(self, key): - self.config.remove_option(self.SECTION, key) - - def save(self): - with codecs.open(self.filename, 'w', 'utf-8') as h: - self.config.write(h) + self.app_dir_path = support_path / appname + self.app_dir_path.mkdir(exist_ok=True) + + self.plugin_dir_path = self.app_dir_path / 'plugins' + self.plugin_dir_path.mkdir(exist_ok=True) - def close(self): - self.save() - self.config = None - - def set_shutdown(self): - self.__in_shutdown = True - - @property - def shutting_down(self) -> bool: - return self.__in_shutdown - - def set_auth_force_localserver(self): - self.__auth_force_localserver = True - - @property - def auth_force_localserver(self) -> bool: - return self.__auth_force_localserver - - def _escape(self, val): - return str(val).replace(u'\\', u'\\\\').replace(u'\n', u'\\n').replace(u';', u'\\;') - - def _unescape(self, val): - chars = list(val) - i = 0 - while i < len(chars): - if chars[i] == '\\': - chars.pop(i) - if chars[i] == 'n': - chars[i] = '\n' + # Bundle IDs identify a singled app though out a system + + if getattr(sys, 'frozen', False): + exe_dir = pathlib.Path(sys.executable).parent + self.internal_plugin_dir_path = exe_dir.parent / 'Library' / 'plugins' + self.respath_path = exe_dir.parent / 'Resources' + self.identifier = NSBundle.mainBundle().bundleIdentifier() + + else: + file_dir = pathlib.Path(__file__).parent + self.internal_plugin_dir_path = file_dir / 'plugins' + self.respath_path = file_dir + + self.identifier = f'uk.org.marginal.{appname.lower()}' + NSBundle.mainBundle().infoDictionary()['CFBundleIdentifier'] = self.identifier + + self.default_journal_dir_path = support_path / 'Frontier Developments' / 'Elite Dangerous' + self._defaults = NSUserDefaults.standardUserDefaults() + self._settings: Dict[str, Union[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]: + """ + Retrieve the raw data for the given key. + + :param str: str - The key data is being requested for. + :return: The requested data. + """ + res = self._settings.get(key) + # On MacOS Catalina, with python.org python 3.9.2 any 'list' + # has type __NSCFArray so a simple `isinstance(res, list)` is + # False. So, check it's not-None, and not the other types. + # + # If we can find where to import the definition of NSCFArray + # then we could possibly test against that. + if res is not None and not isinstance(res, str) and not isinstance(res, int): + return list(res) + + return res + + def get_str(self, key: str, *, default: str = None) -> str: + """ + Return the string referred to by the given key if it exists, or the default. + + Implements :meth:`AbstractConfig.get_str`. + """ + 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 + + if not isinstance(res, str): + raise ValueError(f'unexpected data returned from __raw_get: {type(res)=} {res}') + + return res + + def get_list(self, key: str, *, default: list = None) -> list: + """ + Return the list referred to by the given key if it exists, or the default. + + Implements :meth:`AbstractConfig.get_list`. + """ + 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 + + elif not isinstance(res, list): + raise ValueError(f'__raw_get returned unexpected type {type(res)=} {res!r}') + + return res + + def get_int(self, key: str, *, default: int = 0) -> int: + """ + Return the int referred to by key if it exists in the config. + + Implements :meth:`AbstractConfig.get_int`. + """ + res = self.__raw_get(key) + if res is None: + return default + + elif not isinstance(res, (str, int)): + raise ValueError(f'__raw_get returned unexpected type {type(res)=} {res!r}') + + try: + return int(res) + + 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 + + def get_bool(self, key: str, *, default: bool = None) -> bool: + """ + Return the bool referred to by the given key if it exists, or the default. + + Implements :meth:`AbstractConfig.get_bool`. + """ + 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 + + elif 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: + """ + Set the given key's data to the given value. + + Implements :meth:`AbstractConfig.set`. + """ + if self._settings is None: + raise ValueError('attempt to use a closed _settings') + + if not isinstance(val, (bool, str, int, list)): + raise ValueError(f'Unexpected type for value {type(val)=}') + + self._settings[key] = val + + def delete(self, key: str, *, suppress=False) -> None: + """ + Delete the given key from the config. + + Implements :meth:`AbstractConfig.delete`. + """ + try: + del self._settings[key] + + except Exception: + if suppress: + pass + + def save(self) -> None: + """ + Save the current configuration. + + Implements :meth:`AbstractConfig.save`. + """ + self._defaults.setPersistentDomain_forName_(self._settings, self.identifier) + self._defaults.synchronize() + + def close(self) -> None: + """ + Close this config and release any associated resources. + + Implements :meth:`AbstractConfig.close`. + """ + self.save() + self._defaults = None + + +class LinuxConfig(AbstractConfig): + """Linux implementation of AbstractConfig.""" + + SECTION = 'config' + # TODO: I dislike this, would rather use a sane config file format. But here we are. + __unescape_lut = {'\\': '\\', 'n': '\n', ';': ';', 'r': '\r', '#': '#'} + __escape_lut = {'\\': '\\', '\n': 'n', ';': ';', '\r': 'r'} + + def __init__(self, filename: Optional[str] = None) -> None: + super().__init__() + # http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html + xdg_data_home = pathlib.Path(os.getenv('XDG_DATA_HOME', default='~/.local/share')).expanduser() + self.app_dir_path = xdg_data_home / appname + self.app_dir_path.mkdir(exist_ok=True, parents=True) + + self.plugin_dir_path = self.app_dir_path / 'plugins' + self.plugin_dir_path.mkdir(exist_ok=True) + + self.respath_path = pathlib.Path(__file__).parent + + self.internal_plugin_dir_path = self.respath_path / 'plugins' + self.default_journal_dir_path = None # type: ignore + self.identifier = f'uk.org.marginal.{appname.lower()}' # TODO: Unused? + + config_home = pathlib.Path(os.getenv('XDG_CONFIG_HOME', default='~/.config')).expanduser() + + self.filename = config_home / appname / f'{appname}.ini' + if filename is not None: + self.filename = pathlib.Path(filename) + + self.filename.parent.mkdir(exist_ok=True, parents=True) + + self.config: Optional[ConfigParser] = ConfigParser(comment_prefixes=('#',), interpolation=None) + self.config.read(self.filename) # read() ignores files that dont exist + + # Ensure that our section exists. This is here because configparser will happily create files for us, but it + # does not magically create sections + try: + self.config[self.SECTION].get("this_does_not_exist", fallback=None) + except KeyError: + logger.info("Config section not found. Backing up existing file (if any) and readding a section header") + if self.filename.exists(): + (self.filename.parent / f'{appname}.ini.backup').write_bytes(self.filename.read_bytes()) + + self.config.add_section(self.SECTION) + + if (outdir := self.get_str('outdir')) is None or not pathlib.Path(outdir).is_dir(): + self.set('outdir', self.home) + + def __escape(self, s: str) -> str: + """ + Escape a string using self.__escape_lut. + + This does NOT support multi-character escapes. + + :param s: str - String to be escaped. + :return: str - The escaped string. + """ + out = "" + for c in s: + if c not in self.__escape_lut: + out += c + continue + + out += '\\' + self.__escape_lut[c] + + return out + + def __unescape(self, s: str) -> str: + """ + Unescape a string. + + :param s: str - The string to unescape. + :return: str - The unescaped string. + """ + out: List[str] = [] + i = 0 + while i < len(s): + c = s[i] + if c != '\\': + out.append(c) i += 1 - return u''.join(chars) + continue - else: # ??? + # We have a backslash, check what its escaping + if i == len(s)-1: + raise ValueError('Escaped string has unescaped trailer') - def __init__(self): - raise NotImplementedError('Implement me') + unescaped = self.__unescape_lut.get(s[i+1]) + if unescaped is None: + raise ValueError(f'Unknown escape: \\ {s[i+1]}') - # Common + out.append(unescaped) + i += 2 - def get_password(self, account): - warnings.warn("password subsystem is no longer supported", DeprecationWarning) + return "".join(out) - def set_password(self, account, password): - warnings.warn("password subsystem is no longer supported", DeprecationWarning) + def __raw_get(self, key: str) -> Optional[str]: + """ + Get a raw data value from the config file. - def delete_password(self, account): - warnings.warn("password subsystem is no longer supported", DeprecationWarning) + :param key: str - The key data is being requested for. + :return: str - The raw data, if found. + """ + if self.config is None: + raise ValueError('Attempt to use a closed config') -# singleton -config = Config() + return self.config[self.SECTION].get(key) + + def get_str(self, key: str, *, default: str = None) -> str: + """ + Return the string referred to by the given key if it exists, or the default. + + Implements :meth:`AbstractConfig.get_str`. + """ + data = self.__raw_get(key) + if data is None: + return default # type: ignore # Yes it could be None, but we're _assuming_ that people gave us a default + + if '\n' in data: + raise ValueError('asked for string, got list') + + return self.__unescape(data) + + def get_list(self, key: str, *, default: list = None) -> list: + """ + Return the list referred to by the given key if it exists, or the default. + + Implements :meth:`AbstractConfig.get_list`. + """ + data = self.__raw_get(key) + + if data is None: + return default # type: ignore # Yes it could be None, but we're _assuming_ that people gave us a default + + split = data.split('\n') + if split[-1] != ';': + raise ValueError('Encoded list does not have trailer sentinel') + + return list(map(self.__unescape, split[:-1])) + + def get_int(self, key: str, *, default: int = 0) -> int: + """ + Return the int referred to by key if it exists in the config. + + Implements :meth:`AbstractConfig.get_int`. + """ + data = self.__raw_get(key) + + if data is None: + return default + + try: + return int(data) + + except ValueError as e: + raise ValueError(f'requested {key=} as int cannot be converted to int') from e + + def get_bool(self, key: str, *, default: bool = None) -> bool: + """ + Return the bool referred to by the given key if it exists, or the default. + + Implements :meth:`AbstractConfig.get_bool`. + """ + if self.config is None: + raise ValueError('attempt to use a closed config') + + data = self.__raw_get(key) + if data is None: + return default # type: ignore # Yes it could be None, but we're _assuming_ that people gave us a default + + return bool(int(data)) + + def set(self, key: str, val: Union[int, str, List[str]]) -> None: + """ + Set the given key's data to the given value. + + Implements :meth:`AbstractConfig.set`. + """ + if self.config is None: + raise ValueError('attempt to use a closed config') + + to_set: Optional[str] = None + if isinstance(val, bool): + to_set = str(int(val)) + + elif isinstance(val, str): + to_set = self.__escape(val) + + elif isinstance(val, int): + to_set = str(val) + + elif isinstance(val, list): + to_set = '\n'.join([self.__escape(s) for s in val] + [';']) + + else: + raise ValueError(f'Unexpected type for value {type(val)=}') + + self.config.set(self.SECTION, key, to_set) + self.save() + + def delete(self, key: str, *, suppress=False) -> None: + """ + Delete the given key from the config. + + Implements :meth:`AbstractConfig.delete`. + """ + if self.config is None: + raise ValueError('attempt to use a closed config') + + self.config.remove_option(self.SECTION, key) + self.save() + + def save(self) -> None: + """ + Save the current configuration. + + Implements :meth:`AbstractConfig.save`. + """ + if self.config is None: + raise ValueError('attempt to use a closed config') + + with open(self.filename, 'w', encoding='utf-8') as f: + self.config.write(f) + + def close(self) -> None: + """ + Close this config and release any associated resources. + + Implements :meth:`AbstractConfig.close`. + """ + self.save() + self.config = None + + +def get_config(*args, **kwargs) -> AbstractConfig: + """ + Get the appropriate config class for the current platform. + + :param args: Args to be passed through to implementation. + :param kwargs: Args to be passed through to implementation. + :return: Instance of the implementation. + """ + if sys.platform == "darwin": + return MacConfig(*args, **kwargs) + elif sys.platform == "win32": + return WinConfig(*args, **kwargs) + elif sys.platform == "linux": + return LinuxConfig(*args, **kwargs) + else: + raise ValueError(f'Unknown platform: {sys.platform=}') + + +config = get_config() diff --git a/constants.py b/constants.py index 814471e4..9e757be7 100644 --- a/constants.py +++ b/constants.py @@ -9,6 +9,7 @@ found necessary to move out of other files. # config.py appname = 'EDMarketConnector' applongname = 'E:D Market Connector' +GITVERSION_FILE = '.gitversion' # protocol.py protocolhandler_redirect = 'edmc://auth' diff --git a/coriolis-data b/coriolis-data index a4f5d3fb..e499f684 160000 --- a/coriolis-data +++ b/coriolis-data @@ -1 +1 @@ -Subproject commit a4f5d3fb8176b808618962aceda27efda8947df2 +Subproject commit e499f68469bb4c3d7cecbc91ab67bd4a0bc40993 diff --git a/coriolis.py b/coriolis.py index bf694d37..5ce76a29 100755 --- a/coriolis.py +++ b/coriolis.py @@ -1,26 +1,23 @@ #!/usr/bin/env python3 -# -# build ship and module databases from https://github.com/EDCD/coriolis-data/ -# +"""Build ship and module databases from https://github.com/EDCD/coriolis-data/ .""" + import csv -import base64 -from collections import OrderedDict -import pickle import json +import pickle import subprocess import sys +from collections import OrderedDict from traceback import print_exc -from config import config import outfitting -import companion - +from edmc_data import coriolis_ship_map, ship_name_map if __name__ == "__main__": - def add(modules, name, attributes): - assert name not in modules or modules[name] == attributes, '%s: %s!=%s' % (name, modules.get(name), attributes) + def add(modules, name, attributes) -> None: + """Add the given module to the modules dict.""" + assert name not in modules or modules[name] == attributes, f'{name}: {modules.get(name)} != {attributes}' assert name not in modules, name modules[name] = attributes @@ -29,17 +26,8 @@ if __name__ == "__main__": data = json.load(open('coriolis-data/dist/index.json')) - # Map Coriolis's names to names displayed in the in-game shipyard - coriolis_ship_map = { - 'Cobra Mk III' : 'Cobra MkIII', - 'Cobra Mk IV' : 'Cobra MkIV', - 'Krait Mk II' : 'Krait MkII', - 'Viper' : 'Viper MkIII', - 'Viper Mk IV' : 'Viper MkIV', - } - # Symbolic name from in-game name - reverse_ship_map = {v: k for k, v in list(companion.ship_map.items())} + reverse_ship_map = {v: k for k, v in list(ship_name_map.items())} bulkheads = list(outfitting.armour_map.keys()) @@ -50,11 +38,11 @@ if __name__ == "__main__": for m in list(data['Ships'].values()): name = coriolis_ship_map.get(m['properties']['name'], str(m['properties']['name'])) assert name in reverse_ship_map, name - ships[name] = { 'hullMass' : m['properties']['hullMass'] } + 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'] } + modules['_'.join([reverse_ship_map[name], 'armour', bulkheads[i]])] = {'mass': m['bulkheads'][i]['mass']} - ships = OrderedDict([(k,ships[k]) for k in sorted(ships)]) # sort for easier diffing + ships = OrderedDict([(k, ships[k]) for k in sorted(ships)]) # sort for easier diffing pickle.dump(ships, open('ships.p', 'wb')) # Module masses @@ -65,32 +53,32 @@ if __name__ == "__main__": key = str(m['symbol'].lower()) if grp == 'fsd': modules[key] = { - 'mass' : m['mass'], - 'optmass' : m['optmass'], - 'maxfuel' : m['maxfuel'], - 'fuelmul' : m['fuelmul'], - 'fuelpower' : m['fuelpower'], + 'mass': m['mass'], + 'optmass': m['optmass'], + 'maxfuel': m['maxfuel'], + 'fuelmul': m['fuelmul'], + 'fuelpower': m['fuelpower'], } elif grp == 'gfsb': modules[key] = { - 'mass' : m['mass'], - 'jumpboost' : m['jumpboost'], + 'mass': m['mass'], + 'jumpboost': m['jumpboost'], } else: - modules[key] = { 'mass': m.get('mass', 0) } # Some modules don't have mass + modules[key] = {'mass': m.get('mass', 0)} # Some modules don't have mass # Pre 3.3 modules - add(modules, 'int_stellarbodydiscoveryscanner_standard', { 'mass': 2 }) - add(modules, 'int_stellarbodydiscoveryscanner_intermediate', { 'mass': 2 }) - add(modules, 'int_stellarbodydiscoveryscanner_advanced', { 'mass': 2 }) + add(modules, 'int_stellarbodydiscoveryscanner_standard', {'mass': 2}) + add(modules, 'int_stellarbodydiscoveryscanner_intermediate', {'mass': 2}) + add(modules, 'int_stellarbodydiscoveryscanner_advanced', {'mass': 2}) # Missing - add(modules, 'hpt_dumbfiremissilerack_fixed_small_advanced', { 'mass': 2 }) - add(modules, 'hpt_dumbfiremissilerack_fixed_medium_advanced',{ 'mass': 4 }) - add(modules, 'hpt_multicannon_fixed_small_advanced', { 'mass': 2 }) - add(modules, 'hpt_multicannon_fixed_medium_advanced', { 'mass': 4 }) + add(modules, 'hpt_dumbfiremissilerack_fixed_small_advanced', {'mass': 2}) + add(modules, 'hpt_dumbfiremissilerack_fixed_medium_advanced', {'mass': 4}) + add(modules, 'hpt_multicannon_fixed_small_advanced', {'mass': 2}) + add(modules, 'hpt_multicannon_fixed_medium_advanced', {'mass': 4}) - modules = OrderedDict([(k,modules[k]) for k in sorted(modules)]) # sort for easier diffing + modules = OrderedDict([(k, modules[k]) for k in sorted(modules)]) # sort for easier diffing pickle.dump(modules, open('modules.p', 'wb')) # Check data is present for all modules @@ -98,7 +86,7 @@ if __name__ == "__main__": reader = csv.DictReader(csvfile, restval='') for row in reader: try: - module = outfitting.lookup({ 'id': row['id'], 'name': row['symbol'] }, companion.ship_map) - except: + module = outfitting.lookup({'id': row['id'], 'name': row['symbol']}, ship_name_map) + except AssertionError: print(row['symbol']) print_exc() diff --git a/dashboard.py b/dashboard.py index 4259dccb..43e7e52b 100644 --- a/dashboard.py +++ b/dashboard.py @@ -1,51 +1,70 @@ +"""Handle the game Status.json file.""" + import json -from calendar import timegm -from os.path import isdir, isfile, join, getsize -from sys import platform +import pathlib import time +import tkinter as tk +from calendar import timegm +from os.path import getsize, isdir, isfile +from sys import platform +from typing import Any, Dict from config import config from EDMCLogging import get_main_logger logger = get_main_logger() -if platform=='darwin': - from watchdog.observers import Observer +if platform == 'darwin': from watchdog.events import FileSystemEventHandler + from watchdog.observers import Observer -elif platform=='win32': - from watchdog.observers import Observer +elif 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 + FileSystemEventHandler = object # dummy -# Status.json handler class Dashboard(FileSystemEventHandler): + """Status.json handler.""" - _POLL = 1 # Fallback polling interval + _POLL = 1 # Fallback polling interval - def __init__(self): - FileSystemEventHandler.__init__(self) # futureproofing - not need for current version of watchdog - self.root = None - self.currentdir = None # The actual logdir that we're monitoring - self.observer = None - self.observed = None # a watchdog ObservedWatch, or None if polling - self.status = {} # Current status for communicating status back to main thread + def __init__(self) -> None: + FileSystemEventHandler.__init__(self) # futureproofing - not need for current version of watchdog + self.root: tk.Tk = None # type: ignore + self.currentdir: str = None # type: ignore # The actual logdir that we're monitoring + self.observer: Observer = 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 - def start(self, root, started): + def start(self, root: tk.Tk, started: int) -> bool: + """ + Start monitoring of Journal directory. + + :param root: tkinter parent window. + :param started: unix epoch timestamp of LoadGame event. Ref: monitor.started. + :return: Successful start. + """ + logger.debug('Starting...') self.root = root self.session_start = started - logdir = config.get('journaldir') or config.default_journal_dir + logdir = config.get_str('journaldir', default=config.default_journal_dir) + if logdir == '': + logdir = config.default_journal_dir + if not logdir or not isdir(logdir): + logger.info(f"No logdir, or it isn't a directory: {logdir=}") self.stop() return False if self.currentdir and self.currentdir != logdir: + logger.debug(f"{self.currentdir=} != {logdir=}") self.stop() + self.currentdir = logdir # Set up a watchdog observer. @@ -54,84 +73,128 @@ class Dashboard(FileSystemEventHandler): # any non-standard logdir might be on a network drive and poll instead. polling = platform != 'win32' if not polling and not self.observer: + logger.debug('Setting up observer...') self.observer = Observer() self.observer.daemon = True self.observer.start() + logger.debug('Done') + elif polling and self.observer: + logger.debug('Using polling, stopping observer...') self.observer.stop() - self.observer = None + self.observer = None # type: ignore + logger.debug('Done') if not self.observed and not polling: + logger.debug('Starting observer...') self.observed = self.observer.schedule(self, self.currentdir) + logger.debug('Done') - if polling: - logger.debug(f'Polling Dashboard "{self.currentdir}"') - else: - logger.debug(f'Monitoring Dashboard "{self.currentdir}"') + logger.info(f'{polling and "Polling" or "Monitoring"} Dashboard "{self.currentdir}"') # Even if we're not intending to poll, poll at least once to process pre-existing # data and to check whether the watchdog thread has crashed due to events not # being supported on this filesystem. + logger.debug('Polling once to process pre-existing data, and check whether watchdog thread crashed...') self.root.after(int(self._POLL * 1000/2), self.poll, True) + logger.debug('Done.') return True - def stop(self): + def stop(self) -> None: + """Stop monitoring dashboard.""" logger.debug('Stopping monitoring Dashboard') + self.currentdir = None # type: ignore - self.currentdir = None if self.observed: + logger.debug('Was observed') self.observed = None + logger.debug('Unscheduling all observer') self.observer.unschedule_all() + logger.debug('Done.') + self.status = {} + logger.debug('Done.') - def close(self): + def close(self) -> None: + """Close down dashboard.""" + logger.debug('Calling self.stop()') self.stop() - if self.observer: - self.observer.stop() - if self.observer: - self.observer.join() - self.observer = None - def poll(self, first_time=False): + if self.observer: + logger.debug('Calling self.observer.stop()') + self.observer.stop() + logger.debug('Done') + + if self.observer: + logger.debug('Joining self.observer...') + self.observer.join() + logger.debug('Done') + self.observer = None # type: ignore + + logger.debug('Done.') + + def poll(self, first_time: bool = False) -> None: + """ + Poll Status.json via calling self.process() once a second. + + :param first_time: True if first call of this. + """ if not self.currentdir: # Stopped self.status = {} + else: self.process() if first_time: + emitter = None # Watchdog thread - emitter = self.observed and self.observer._emitter_for_watch[self.observed] # Note: Uses undocumented attribute - if emitter and emitter.is_alive(): - return # Watchdog thread still running - stop polling + if self.observed: + emitter = self.observer._emitter_for_watch[self.observed] # Note: Uses undocumented attribute - self.root.after(self._POLL * 1000, self.poll) # keep polling + if emitter and emitter.is_alive(): # type: ignore + return # Watchdog thread still running - stop polling - def on_modified(self, event): - # watchdog callback - DirModifiedEvent on macOS, FileModifiedEvent on Windows - if event.is_directory or (isfile(event.src_path) and getsize(event.src_path)): # Can get on_modified events when the file is emptied + self.root.after(self._POLL * 1000, self.poll) # keep polling + + def on_modified(self, event) -> None: + """ + Watchdog callback - DirModifiedEvent on macOS, FileModifiedEvent on Windows. + + :param event: Watchdog event. + """ + if event.is_directory or (isfile(event.src_path) and getsize(event.src_path)): + # Can get on_modified events when the file is emptied self.process(event.src_path if not event.is_directory else None) - # Can be called either in watchdog thread or, if polling, in main thread. - def process(self, logfile=None): + def process(self, logfile: str = None) -> None: + """ + Process the contents of current Status.json file. + + Can be called either in watchdog thread or, if polling, in main thread. + """ if config.shutting_down: return try: - with open(join(self.currentdir, 'Status.json'), 'rb') as h: + with (pathlib.Path(self.currentdir) / 'Status.json').open('rb') as h: data = h.read().strip() - if data: # Can be empty if polling while the file is being re-written + + 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): + if ( + timegm(time.strptime(entry['timestamp'], '%Y-%m-%dT%H:%M:%SZ')) >= self.session_start + and self.status != entry + ): self.status = entry self.root.event_generate('<>', when="tail") except Exception: - logger.exception('Reading Status.json') + logger.exception('Processing Status.json') + # singleton dashboard = Dashboard() diff --git a/docs/Killswitches.md b/docs/Killswitches.md new file mode 100644 index 00000000..9e08feb5 --- /dev/null +++ b/docs/Killswitches.md @@ -0,0 +1,62 @@ +# Kill Switches + +EDMarketConnector implements a Kill Switch system that allows us to disable features based on a version mask. Meaning that we can stop major bugs from affecting the services we support, at the expense of disabling that support. + +## Format + +Killswitches are stored in a JSON file that is queried by EDMC on startup. The format is as follows: + +| Key | Type | Description | +| --------------: | :------: | :------------------------------------------------------------ | +| `version` | `int` | the version of the Kill Switch JSON file, always 1 | +| `last_updated` | `string` | When last the kill switches were updated (for human use only) | +| `kill_switches` | `array` | The kill switches this file contains (expanded below) | + +The `kill_switches` array contains kill switch objects. Each contains two fields: + +| Key | Type | Description | +| --------: | :--------------: | :--------------------------------------------------------------------------- | +| `version` | `version spec` | The version of EDMC these kill switches apply to (Must be valid semver spec) | +| `kills` | `Dict[str, str]` | The different keys to disable, and the reason for the disable | +An example follows: + +```json +{ + "version": 1, + "last_updated": "19 October 2020", + "kill_switches": [ + { + "version": "1.0.0", + "kills": { + "plugins.eddn.send": "some reason" + } + } + ] +} +``` + +### Versions + +Versions are checked using contains checks on `semantic_version.SimpleSpec` instances. + +## Plugin support + +Plugins may use the killswitch system simply by hosting their own version of the killswitch file, and fetching it +using `killswitch.get_kill_switches(target='https://example.com/myplugin_killswitches.json')`. The returned object can +be used to query the kill switch set, see the docstrings for more information on specifying versions. + +## Currently supported killswitch strings + +The current recognised (to EDMC and its internal plugins) killswitch strings are as follows: +| Kill Switch | Description | +| :--------------------------------------------------- | :------------------------------------------------------------------------------------------- | +| `plugins.eddn.send` | Disables all use of the send method on EDDN (effectively disables EDDN updates) | +| `plugins.(eddn\|inara\|edsm\|eddb).journal` | Disables all journal processing for EDDN/EDSM/INARA | +| `plugins.(edsm\|inara).worker` | Disables the EDSM/INARA worker thread (effectively disables updates) (does not close thread) | +| `plugins.(eddn\|inara\|edsm).journal.event.$eventname`| Specific events to disable processing for | + +## File location + +The main killswitch file is kept in the `releases` branch on the EDMC github repo. The file should NEVER be committed to +any other repos. In the case that the killswitch file is found in other repos, the one in releases should always +be taken as correct regardless of others. diff --git a/docs/Releasing.md b/docs/Releasing.md index 846324e2..f3d81e24 100644 --- a/docs/Releasing.md +++ b/docs/Releasing.md @@ -25,16 +25,17 @@ You will need several pieces of software installed, or the files from their into your checkout of the EDMC git files. 1. [Windows SDK](https://developer.microsoft.com/en-US/windows/downloads/windows-10-sdk/). This is needed for the internationalisation support in EDMC. - [Windows 10 SDK, version 1903 (10.0.18362.1)](https://go.microsoft.com/fwlink/?linkid=2083338) + [Windows 10 SDK, version 2004 (10.0.19041.0)](https://go.microsoft.com/fwlink/p/?linkid=2120843) is the most recently tested version. Technically you only need the following components: `MSI Tools`, `Windows SDK for Desktop C++ x86 Apps` (which will auto-select some others). NB: If you have need to uninstall this it's - "Windows Software Development Kit - Windows 10.0.18362.1" in + "Windows Software Development Kit - Windows 10.0.19041.1" in "Apps & Features", *not* "Windows SDK AddOn". -1. [Python](https://python.org): 32-bit version of Python 3.7 for Windows. - [v3.7.9](https://www.python.org/downloads/release/python-379/) is the most +1. [Python](https://python.org): 32-bit version of Python 3.9 for Windows. + [v3.9.2](https://www.python.org/downloads/release/python-392/) is the most recently tested version. You need the `Windows x86 executable installer` - file, for the 32-bit version. + file, for the 32-bit version. Double-check the version against the + `.python.version` file, as it should always contain the intended version. 1. [py2exe](https://github.com/albertosottile/py2exe) - Now available via PyPi, so will be picked up with the `pip install` below. Latest tested as per `requirements-dev.txt`. @@ -92,9 +93,6 @@ that. appears in the EXE properties, and is also used as the location of WinSparkle registry entries on Windows. -1. Location of release files. To change this edit `setup.py`. Look for the -`appcast.write()` statement and change the `url="...` line. - 1. Application names, version and URL of the file with latest release information. These are all in the `config.py` file. See the `from config import ...` lines in setup.py. @@ -112,6 +110,21 @@ that. URL doesn't change over application versions) version of the appcast_win_.xml file. The original upstream value is `https://raw.githubusercontent.com/EDCD/EDMarketConnector/releases/edmarketconnector.xml`. + +1. Location of release files. This needs to be cited correctly in the + `edmarketconnector.xml` file, which is what the application queries to + see if there is a newer version. + Look for the `url="...` line in the ` + ## Adding a new file @@ -162,8 +175,12 @@ Before you create a new install each time you should: 1. Ensure the data sourced from coriolis.io is up to date and works: 1. Update the `coriolis-data` repo. **NB: You will need 'npm' installed for this.** + 1. `cd coriolis-data` + 1. `git pull` + 1. `npm install` - to check it's worked. 1. Run `coriolis.py` to update `modules.p` and `ships.p` 1. XXX: Test ? + 1. `git commit` the changes to the repo and the `.p` files. 1. Ensure translations are up to date, see [Translations.md](Translations.md). # Preparing to Package @@ -212,12 +229,19 @@ a `stable` release, as well as any social media posts you make. string, not the Windows A.B.C.D form.** 1. As you're working in a version-specific branch, `release-4.0.2`, you can safely commit these changes and push to GitHub. - **Do not merge the branch with `releases` until the GitHub release is in - place.** + **Do not merge the branch with `releases` until the GitHub release is in place.** If you're wondering, you needed to get the changelog prepared before building the .exe and .msi because ChangeLog.md is bundled with the install. + +# Adding killswitches + +If anything in this new release addresses a bug that causes, e.g. bad data +to be sent over EDDN, then you should add an appropriate entry to the +killswitches.json file *in the `releases` branch*. That file **must only ever +be commited to the `releases` branch!!!** See [docs/Killswitches.md](docs/Killswitches.md). + # Packaging & Installer Generation You'll want to do the .exe and .msi generation in a `cmd.exe` window, not e.g. @@ -231,9 +255,9 @@ else you might need this, which assumes correct python.exe is in your PATH: python.exe setup.py py2exe -else you'll have to specify the path to python.exe: +else you'll have to specify the path to python.exe, e.g.: - "%LOCALAPPDATA%\Programs\Python\Python37-32\python.exe" setup.py py2exe + "C:\Program Files \(x86)\Python38-32\python.exe" setup.py py2exe Output will be something like (`...` denoting parts elided for brevity): @@ -270,6 +294,9 @@ without errors. Finally, uninstall your current version of ED Market Connector and re-install using the newly generated `EDMarketConnector_win_4.0.2.msi` file. Check the resulting installation does work (the installer will run the program for you). +If it doesn't then check if there are any files, particularly `.dll` or `.pyd` +files in `dist.win32` that aren't yet specified in the `EDMarketConnector.wxs` +file, i.e. they're not packaged into the installer. Update `edmarketconnector.xml` once more to set the `length=` attribute of the enclosure to match the file size of the `EDMarketConnector_win_4.0.2.msi` file. @@ -346,3 +373,22 @@ If you are making a pre-release then: 1. **DO NOT** merge into `stable`. 1. *Do* merge the code into `beta` after you have made a 'pre-release' on GitHub. + +# Changing Python version + +When changing the Python version (Major.Minor.Patch) used: + +1. Change the contents of `.python-version` so that pyenv notices. + +1. Any version change: + + 1. `.github/workflows/windows-build.yml` needs updating to have the GitHub + based build use the correct version. + +1. Major or Minor level changes: + + 1. `setup.py` will need its version check updating. + 1. `EDMarketConnector.wxs` will need updating to reference the correct + pythonXX.dll file. + 1. `.pre-commit-config.yaml` will need the `default_language_version` + section updated to the appropriate version. diff --git a/docs/Windows-Manifest.md b/docs/Windows-Manifest.md new file mode 100644 index 00000000..68136778 --- /dev/null +++ b/docs/Windows-Manifest.md @@ -0,0 +1,21 @@ +# Introduction + +There are some attributes that can be set on a Windows executable via a +manifest. This is a section in the executable. The easiest way to set +this is to include an XML-format .manifest file at build time. + +## Build time + +We specify .manifest files in setup.py. + +## Editing or changing a manifest + +You can use the `mt.exe` from your Windows SDK +e.g. "c:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x64\mt.exe" +to inspect or change an executable's manifest. + +To set a whole new manifest: + +1. Make a copy of the relevant manifest file, e.g. `EDMarketConnector.manifest`. +1. Edit this file. +1. Run mt.exe thus: `mt.exe -manifest EDMarketConnector-new.manifest -outputresource:EDMarketConnector.exe`. diff --git a/docs/examples/click_counter/load.py b/docs/examples/click_counter/load.py index 02403f2f..ff9b449d 100644 --- a/docs/examples/click_counter/load.py +++ b/docs/examples/click_counter/load.py @@ -26,7 +26,7 @@ class ClickCounter: def __init__(self) -> None: # Be sure to use names that wont collide in our config variables - self.click_count: Optional[tk.StringVar] = tk.StringVar(value=str(config.getint('click_counter_count'))) + self.click_count: Optional[tk.StringVar] = tk.StringVar(value=str(config.get_int('click_counter_count'))) logger.info("ClickCounter instantiated") def on_load(self) -> str: diff --git a/docs/examples/plugintest/load.py b/docs/examples/plugintest/load.py index 4a614aa2..2639cfd9 100644 --- a/docs/examples/plugintest/load.py +++ b/docs/examples/plugintest/load.py @@ -6,12 +6,25 @@ import logging import os import shutil import sqlite3 -import sys import zipfile +import semantic_version from SubA import SubA -from config import appname +from config import appname, appversion, config + +# For compatibility with pre-5.0.0 +if not hasattr(config, 'get_int'): + config.get_int = config.getint + +if not hasattr(config, 'get_str'): + config.get_str = config.get + +if not hasattr(config, 'get_bool'): + config.get_bool = lambda key: bool(config.getint(key)) + +if not hasattr(config, 'get_list'): + config.get_list = config.get # This could also be returned from plugin_start3() plugin_name = os.path.basename(os.path.dirname(__file__)) @@ -32,9 +45,16 @@ if not logger.hasHandlers(): logger.addHandler(logger_channel) -this = sys.modules[__name__] # For holding module globals -this.DBFILE = 'plugintest.db' -this.mt = None +class This: + """Module global variables.""" + + def __init__(self): + self.DBFILE = 'plugintest.db' + self.plugin_test: PluginTest + self.suba: SubA + + +this = This() class PluginTest(object): @@ -86,8 +106,42 @@ def plugin_start3(plugin_dir: str) -> str: :param plugin_dir: :return: 'Pretty' name of this plugin. """ + # Up until 5.0.0-beta1 config.appversion is a string + if isinstance(appversion, str): + core_version = semantic_version.Version(appversion) + + elif callable(appversion): + # From 5.0.0-beta1 it's a function, returning semantic_version.Version + core_version = appversion() + + config.set('plugintest_bool', True) + somebool = config.get_bool('plugintest_bool') + logger.debug(f'Stored bool: {somebool=} ({type(somebool)})') + + config.set('plugintest_str', 'Test String') + somestr = config.get_str('plugintest_str') + logger.debug(f'Stored str: {somestr=} ({type(somestr)})') + + config.set('plugintest_int', 42) + someint = config.get_int('plugintest_int') + logger.debug(f'Stored int: {someint=} ({type(someint)})') + + config.set('plugintest_list', ['test', 'one', 'two']) + somelist = config.get_list('plugintest_list') + logger.debug(f'Stored list: {somelist=} ({type(somelist)})') + + logger.info(f'Core EDMC version: {core_version}') + # And then compare like this + if core_version < semantic_version.Version('5.0.0-beta1'): + logger.info('EDMC core version is before 5.0.0-beta1') + + else: + logger.info('EDMC core version is at least 5.0.0-beta1') + + # Yes, just blow up if config.appverison is neither str or callable + logger.info(f'Folder is {plugin_dir}') - this.mt = PluginTest(plugin_dir) + this.plugin_test = PluginTest(plugin_dir) this.suba = SubA(logger) @@ -117,5 +171,9 @@ def journal_entry(cmdrname: str, is_beta: bool, system: str, station: str, entry :param state: :return: None """ - logger.debug(f'cmdr = "{cmdrname}", is_beta = "{is_beta}", system = "{system}", station = "{station}"') - this.mt.store(entry['timestamp'], cmdrname, system, station, entry['event']) + logger.debug( + f'cmdr = "{cmdrname}", is_beta = "{is_beta}"' + f', system = "{system}", station = "{station}"' + f', event = "{entry["event"]}"' + ) + this.plugin_test.store(entry['timestamp'], cmdrname, system, station, entry['event']) diff --git a/eddb.py b/eddb.py deleted file mode 100755 index eb3f2ad1..00000000 --- a/eddb.py +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/env python3 -# -# build databases from files systems.csv and stations.json from http://eddb.io/api -# - -import pickle -import csv -import json -import requests - -def download(filename): - r = requests.get('https://eddb.io/archive/v6/' + filename, stream=True) - print('\n%s\t%dK' % (filename, len(r.content) / 1024)) - return r - -if __name__ == "__main__": - - # Ellipsoid that encompasses most of the systems in the bubble (but not outliers like Sothis) - RX = RZ = 260 - CY = -50 - RY = 300 - - RX2 = RX * RX - RY2 = RY * RY - RZ2 = RZ * RZ - - def inbubble(x, y, z): - return (x * x)/RX2 + ((y - CY) * (y - CY))/RY2 + (z * z)/RZ2 <= 1 - - # Sphere around Jaques - JX, JY, JZ = -9530.50000, -910.28125, 19808.12500 - RJ2 = 80 * 80 # Furthest populated system is Pekoe at 50.16 Ly - - def around_jaques(x, y, z): - return ((x - JX) * (x - JX) + (y - JY) * (y - JY) + (z - JZ) * (z - JZ)) <= RJ2 - - # Sphere around outliers - RO2 = 40 * 40 - def around_outlier(cx, cy, cz, x, y, z): - return ((x - ox) * (x - ox) + (y - oy) * (y - oy) + (z - oz) * (z - oz)) <= RO2 - - # Load all EDDB-known systems into a dictionary - systems = { int(s['id']) : { - 'name' : s['name'], - 'x' : float(s['x']), - 'y' : float(s['y']), - 'z' : float(s['z']), - 'is_populated' : int(s['is_populated']), - } for s in csv.DictReader(download('systems.csv').iter_lines(decode_unicode=True)) } - #} for s in csv.DictReader(open('systems.csv')) } - print('%d\tsystems' % len(systems)) - - # Build another dict containing all systems considered to be in the - # main populated bubble (see constants above and inbubble() for - # the criteria). - # (system_id, is_populated) by system_name (ignoring duplicate names) - system_ids = { - str(s['name']) : (k, s['is_populated']) - for k,s in systems.items() if inbubble(s['x'], s['y'], s['z']) - } - print('%d\tsystems in bubble' % len(system_ids)) - - # Build another dict for systems considered to be around Colonia - extra_ids = { - str(s['name']) : (k, s['is_populated']) - for k,s in systems.items() if around_jaques(s['x'], s['y'], s['z']) - } - system_ids.update(extra_ids) - print('%d\tsystems in Colonia' % len(extra_ids)) - - # Build another dict for systems that are marked as populated, but - # didn't make it into the bubble list. - cut = { - k : s for k, s in systems.items() - if s['is_populated'] and s['name'] not in system_ids - } - print('%d\toutlying populated systems:' % len(cut)) - - # Build another dict with all the systems, populated or not, around any - # of the outliers. - extra_ids = {} - for k1,o in sorted(cut.items()): - ox, oy, oz = o['x'], o['y'], o['z'] - extra = { - str(s['name']) : (k, s['is_populated']) - for k,s in systems.items() if around_outlier(ox, oy, oz, s['x'], s['y'], s['z']) - } - print('%-30s%7d %11.5f %11.5f %11.5f %4d' % (o['name'], k1, ox, oy, oz, len(extra))) - extra_ids.update(extra) - print('\n%d\tsystems around outliers' % len(extra_ids)) - system_ids.update(extra_ids) - - # Re-build 'cut' dict to hold duplicate (name) systems - cut = { - k : s - for k,s in systems.items() if s['name'] in system_ids and system_ids[s['name']][0] != k - } - print('\n%d duplicate systems' % len(cut)) - for k,s in sorted(cut.items()): - print('%-20s%8d %8d %11.5f %11.5f %11.5f' % (s['name'], system_ids[s['name']][0], k, s['x'], s['y'], s['z'])) - - # Hack - ensure duplicate system names are pointing at the more interesting system - system_ids['Amo'] = (866, True) - system_ids['C Puppis'] = (25068, False) - system_ids['q Velorum'] = (15843, True) - system_ids['M Carinae'] = (22627, False) - system_ids['HH 17'] = (61275, False) - system_ids['K Carinae'] = (375886, False) - system_ids['d Velorum'] = (406476, False) - system_ids['L Velorum'] = (2016580, False) - system_ids['N Velorum'] = (3012033, False) - system_ids['i Velorum'] = (3387990, False) - - with open('systems.p', 'wb') as h: - pickle.dump(system_ids, h, protocol = pickle.HIGHEST_PROTOCOL) - print('\n%d saved systems' % len(system_ids)) - - # station_id by (system_id, station_name) - stations = json.loads(download('stations.json').content) # let json do the utf-8 decode - station_ids = { - (x['system_id'], x['name']) : x['id'] # Pilgrim's Ruin in HR 3005 id 70972 has U+2019 quote - for x in stations if x['max_landing_pad_size'] - } - - with open('stations.p', 'wb') as h: - pickle.dump(station_ids, h, protocol = pickle.HIGHEST_PROTOCOL) - print('\n%d saved stations' % len(station_ids)) diff --git a/edmc_data.py b/edmc_data.py new file mode 100644 index 00000000..be1db743 --- /dev/null +++ b/edmc_data.py @@ -0,0 +1,492 @@ +""" +Static data. + +For easy reference any variable should be prefixed with the name of the file it +was either in originally, or where the primary code utilising it is. +""" +from collections import OrderedDict + +# Map numeric 'demand/supply brackets' to the names as shown in-game. +commodity_bracketmap = { + 0: '', + 1: 'Low', + 2: 'Med', + 3: 'High', +} + +# Map values reported by the Companion interface to names displayed in-game. +# May be imported by plugins. +companion_category_map = { + 'Narcotics': 'Legal Drugs', + 'Slaves': 'Slavery', + 'Waste ': 'Waste', + 'NonMarketable': False, # Don't appear in the in-game market so don't report +} + +# Map suit symbol names to English localised names +companion_suit_type_map = { + 'TacticalSuit_Class1': 'Dominator Suit', +} + +# Map Coriolis's names to names displayed in the in-game shipyard. +coriolis_ship_map = { + 'Cobra Mk III': 'Cobra MkIII', + 'Cobra Mk IV': 'Cobra MkIV', + 'Krait Mk II': 'Krait MkII', + 'Viper': 'Viper MkIII', + 'Viper Mk IV': 'Viper MkIV', +} + +# Map API slot names to E:D Shipyard slot names +edshipyard_slot_map = { + 'hugehardpoint': 'H', + 'largehardpoint': 'L', + 'mediumhardpoint': 'M', + 'smallhardpoint': 'S', + 'tinyhardpoint': 'U', + 'armour': 'BH', + 'powerplant': 'RB', + 'mainengines': 'TM', + 'frameshiftdrive': 'FH', + 'lifesupport': 'EC', + 'powerdistributor': 'PC', + 'radar': 'SS', + 'fueltank': 'FS', + 'military': 'MC', +} + +# Map API module names to in-game names + +outfitting_armour_map = OrderedDict([ + ('grade1', 'Lightweight Alloy'), + ('grade2', 'Reinforced Alloy'), + ('grade3', 'Military Grade Composite'), + ('mirrored', 'Mirrored Surface Composite'), + ('reactive', 'Reactive Surface Composite'), +]) + +outfitting_weapon_map = { + 'advancedtorppylon': 'Torpedo Pylon', + 'atdumbfiremissile': 'AX Missile Rack', + 'atmulticannon': 'AX Multi-Cannon', + 'basicmissilerack': 'Seeker Missile Rack', + 'beamlaser': 'Beam Laser', + ('beamlaser', 'heat'): 'Retributor Beam Laser', + 'cannon': 'Cannon', + 'causticmissile': 'Enzyme Missile Rack', + 'drunkmissilerack': 'Pack-Hound Missile Rack', + 'dumbfiremissilerack': 'Missile Rack', + ('dumbfiremissilerack', 'advanced'): 'Advanced Missile Rack', + ('dumbfiremissilerack', 'lasso'): 'Rocket Propelled FSD Disruptor', + 'flakmortar': 'Remote Release Flak Launcher', + 'flechettelauncher': 'Remote Release Flechette Launcher', + 'guardian_gausscannon': 'Guardian Gauss Cannon', + 'guardian_plasmalauncher': 'Guardian Plasma Charger', + 'guardian_shardcannon': 'Guardian Shard Cannon', + 'minelauncher': 'Mine Launcher', + ('minelauncher', 'impulse'): 'Shock Mine Launcher', + 'mining_abrblstr': 'Abrasion Blaster', + 'mining_seismchrgwarhd': 'Seismic Charge Launcher', + 'mining_subsurfdispmisle': 'Sub-Surface Displacement Missile', + 'mininglaser': 'Mining Laser', + ('mininglaser', 'advanced'): 'Mining Lance Beam Laser', + 'multicannon': 'Multi-Cannon', + ('multicannon', 'advanced'): 'Advanced Multi-Cannon', + ('multicannon', 'strong'): 'Enforcer Cannon', + 'plasmaaccelerator': 'Plasma Accelerator', + ('plasmaaccelerator', 'advanced'): 'Advanced Plasma Accelerator', + 'plasmashockcannon': 'Shock Cannon', + 'pulselaser': 'Pulse Laser', + ('pulselaser', 'disruptor'): 'Pulse Disruptor Laser', + 'pulselaserburst': 'Burst Laser', + ('pulselaserburst', 'scatter'): 'Cytoscrambler Burst Laser', + 'railgun': 'Rail Gun', + ('railgun', 'burst'): 'Imperial Hammer Rail Gun', + 'slugshot': 'Fragment Cannon', + ('slugshot', 'range'): 'Pacifier Frag-Cannon', +} + +outfitting_missiletype_map = { + 'advancedtorppylon': 'Seeker', + 'atdumbfiremissile': 'Dumbfire', + 'basicmissilerack': 'Seeker', + 'causticmissile': 'Dumbfire', + 'drunkmissilerack': 'Swarm', + 'dumbfiremissilerack': 'Dumbfire', + 'mining_subsurfdispmisle': 'Seeker', + 'mining_seismchrgwarhd': 'Seeker', +} + +outfitting_weaponmount_map = { + 'fixed': 'Fixed', + 'gimbal': 'Gimballed', + 'turret': 'Turreted', +} + +outfitting_weaponclass_map = { + 'tiny': '0', + 'small': '1', + 'smallfree': '1', + 'medium': '2', + 'large': '3', + 'huge': '4', +} + +# There's no discernable pattern for weapon ratings, so here's a lookup table +outfitting_weaponrating_map = { + 'hpt_advancedtorppylon_fixed_small': 'I', + 'hpt_advancedtorppylon_fixed_medium': 'I', + 'hpt_advancedtorppylon_fixed_large': 'I', + 'hpt_atdumbfiremissile_fixed_medium': 'B', + 'hpt_atdumbfiremissile_fixed_large': 'A', + 'hpt_atdumbfiremissile_turret_medium': 'B', + 'hpt_atdumbfiremissile_turret_large': 'A', + 'hpt_atmulticannon_fixed_medium': 'E', + 'hpt_atmulticannon_fixed_large': 'C', + 'hpt_atmulticannon_turret_medium': 'F', + 'hpt_atmulticannon_turret_large': 'E', + 'hpt_basicmissilerack_fixed_small': 'B', + 'hpt_basicmissilerack_fixed_medium': 'B', + 'hpt_basicmissilerack_fixed_large': 'A', + 'hpt_beamlaser_fixed_small': 'E', + 'hpt_beamlaser_fixed_medium': 'D', + 'hpt_beamlaser_fixed_large': 'C', + 'hpt_beamlaser_fixed_huge': 'A', + 'hpt_beamlaser_gimbal_small': 'E', + 'hpt_beamlaser_gimbal_medium': 'D', + 'hpt_beamlaser_gimbal_large': 'C', + 'hpt_beamlaser_gimbal_huge': 'A', + 'hpt_beamlaser_turret_small': 'F', + 'hpt_beamlaser_turret_medium': 'E', + 'hpt_beamlaser_turret_large': 'D', + 'hpt_cannon_fixed_small': 'D', + 'hpt_cannon_fixed_medium': 'D', + 'hpt_cannon_fixed_large': 'C', + 'hpt_cannon_fixed_huge': 'B', + 'hpt_cannon_gimbal_small': 'E', + 'hpt_cannon_gimbal_medium': 'D', + 'hpt_cannon_gimbal_large': 'C', + 'hpt_cannon_gimbal_huge': 'B', + 'hpt_cannon_turret_small': 'F', + 'hpt_cannon_turret_medium': 'E', + 'hpt_cannon_turret_large': 'D', + 'hpt_causticmissile_fixed_medium': 'B', + 'hpt_drunkmissilerack_fixed_medium': 'B', + 'hpt_dumbfiremissilerack_fixed_small': 'B', + 'hpt_dumbfiremissilerack_fixed_medium': 'B', + 'hpt_dumbfiremissilerack_fixed_large': 'A', + 'hpt_flakmortar_fixed_medium': 'B', + 'hpt_flakmortar_turret_medium': 'B', + 'hpt_flechettelauncher_fixed_medium': 'B', + 'hpt_flechettelauncher_turret_medium': 'B', + 'hpt_guardian_gausscannon_fixed_small': 'D', + 'hpt_guardian_gausscannon_fixed_medium': 'B', + 'hpt_guardian_plasmalauncher_fixed_small': 'D', + 'hpt_guardian_plasmalauncher_fixed_medium': 'B', + 'hpt_guardian_plasmalauncher_fixed_large': 'C', + 'hpt_guardian_plasmalauncher_turret_small': 'F', + 'hpt_guardian_plasmalauncher_turret_medium': 'E', + 'hpt_guardian_plasmalauncher_turret_large': 'D', + 'hpt_guardian_shardcannon_fixed_small': 'D', + 'hpt_guardian_shardcannon_fixed_medium': 'A', + 'hpt_guardian_shardcannon_fixed_large': 'C', + 'hpt_guardian_shardcannon_turret_small': 'F', + 'hpt_guardian_shardcannon_turret_medium': 'D', + 'hpt_guardian_shardcannon_turret_large': 'D', + 'hpt_minelauncher_fixed_small': 'I', + 'hpt_minelauncher_fixed_medium': 'I', + 'hpt_mining_abrblstr_fixed_small': 'D', + 'hpt_mining_abrblstr_turret_small': 'D', + 'hpt_mining_seismchrgwarhd_fixed_medium': 'B', + 'hpt_mining_seismchrgwarhd_turret_medium': 'B', + 'hpt_mining_subsurfdispmisle_fixed_small': 'B', + 'hpt_mining_subsurfdispmisle_fixed_medium': 'B', + 'hpt_mining_subsurfdispmisle_turret_small': 'B', + 'hpt_mining_subsurfdispmisle_turret_medium': 'B', + 'hpt_mininglaser_fixed_small': 'D', + 'hpt_mininglaser_fixed_medium': 'D', + 'hpt_mininglaser_turret_small': 'D', + 'hpt_mininglaser_turret_medium': 'D', + 'hpt_multicannon_fixed_small': 'F', + 'hpt_multicannon_fixed_medium': 'E', + 'hpt_multicannon_fixed_large': 'C', + 'hpt_multicannon_fixed_huge': 'A', + 'hpt_multicannon_gimbal_small': 'G', + 'hpt_multicannon_gimbal_medium': 'F', + 'hpt_multicannon_gimbal_large': 'C', + 'hpt_multicannon_gimbal_huge': 'A', + 'hpt_multicannon_turret_small': 'G', + 'hpt_multicannon_turret_medium': 'F', + 'hpt_multicannon_turret_large': 'E', + 'hpt_plasmaaccelerator_fixed_medium': 'C', + 'hpt_plasmaaccelerator_fixed_large': 'B', + 'hpt_plasmaaccelerator_fixed_huge': 'A', + 'hpt_plasmashockcannon_fixed_small': 'D', + 'hpt_plasmashockcannon_fixed_medium': 'D', + 'hpt_plasmashockcannon_fixed_large': 'C', + 'hpt_plasmashockcannon_gimbal_small': 'E', + 'hpt_plasmashockcannon_gimbal_medium': 'D', + 'hpt_plasmashockcannon_gimbal_large': 'C', + 'hpt_plasmashockcannon_turret_small': 'F', + 'hpt_plasmashockcannon_turret_medium': 'E', + 'hpt_plasmashockcannon_turret_large': 'D', + 'hpt_pulselaser_fixed_small': 'F', + 'hpt_pulselaser_fixed_smallfree': 'F', + 'hpt_pulselaser_fixed_medium': 'E', + 'hpt_pulselaser_fixed_large': 'D', + 'hpt_pulselaser_fixed_huge': 'A', + 'hpt_pulselaser_gimbal_small': 'G', + 'hpt_pulselaser_gimbal_medium': 'F', + 'hpt_pulselaser_gimbal_large': 'E', + 'hpt_pulselaser_gimbal_huge': 'A', + 'hpt_pulselaser_turret_small': 'G', + 'hpt_pulselaser_turret_medium': 'F', + 'hpt_pulselaser_turret_large': 'F', + 'hpt_pulselaserburst_fixed_small': 'F', + 'hpt_pulselaserburst_fixed_medium': 'E', + 'hpt_pulselaserburst_fixed_large': 'D', + 'hpt_pulselaserburst_fixed_huge': 'E', + 'hpt_pulselaserburst_gimbal_small': 'G', + 'hpt_pulselaserburst_gimbal_medium': 'F', + 'hpt_pulselaserburst_gimbal_large': 'E', + 'hpt_pulselaserburst_gimbal_huge': 'E', + 'hpt_pulselaserburst_turret_small': 'G', + 'hpt_pulselaserburst_turret_medium': 'F', + 'hpt_pulselaserburst_turret_large': 'E', + 'hpt_railgun_fixed_small': 'D', + 'hpt_railgun_fixed_medium': 'B', + 'hpt_slugshot_fixed_small': 'E', + 'hpt_slugshot_fixed_medium': 'A', + 'hpt_slugshot_fixed_large': 'C', + 'hpt_slugshot_gimbal_small': 'E', + 'hpt_slugshot_gimbal_medium': 'D', + 'hpt_slugshot_gimbal_large': 'C', + 'hpt_slugshot_turret_small': 'E', + 'hpt_slugshot_turret_medium': 'D', + 'hpt_slugshot_turret_large': 'C', +} + +# Old standard weapon variants +outfitting_weaponoldvariant_map = { + 'f': 'Focussed', + 'hi': 'High Impact', + 'lh': 'Low Heat', + 'oc': 'Overcharged', + 'ss': 'Scatter Spray', +} + +outfitting_countermeasure_map = { + 'antiunknownshutdown': ('Shutdown Field Neutraliser', 'F'), + 'chafflauncher': ('Chaff Launcher', 'I'), + 'electroniccountermeasure': ('Electronic Countermeasure', 'F'), + 'heatsinklauncher': ('Heat Sink Launcher', 'I'), + 'plasmapointdefence': ('Point Defence', 'I'), + 'xenoscanner': ('Xeno Scanner', 'E'), +} + +outfitting_utility_map = { + 'cargoscanner': 'Cargo Scanner', + 'cloudscanner': 'Frame Shift Wake Scanner', + 'crimescanner': 'Kill Warrant Scanner', + 'mrascanner': 'Pulse Wave Analyser', + 'shieldbooster': 'Shield Booster', +} + +outfitting_cabin_map = { + '0': 'Prisoner Cells', + '1': 'Economy Class Passenger Cabin', + '2': 'Business Class Passenger Cabin', + '3': 'First Class Passenger Cabin', + '4': 'Luxury Class Passenger Cabin', + '5': 'Passenger Cabin', # not seen +} + +outfitting_rating_map = { + '1': 'E', + '2': 'D', + '3': 'C', + '4': 'B', + '5': 'A', +} + +# Ratings are weird for the following + +outfitting_corrosion_rating_map = { + '1': 'E', + '2': 'F', +} + +outfitting_planet_rating_map = { + '1': 'H', + '2': 'G', +} + +outfitting_fighter_rating_map = { + '1': 'D', +} + +outfitting_misc_internal_map = { + ('detailedsurfacescanner', 'tiny'): ('Detailed Surface Scanner', 'I'), + ('dockingcomputer', 'advanced'): ('Advanced Docking Computer', 'E'), + ('dockingcomputer', 'standard'): ('Standard Docking Computer', 'E'), + 'planetapproachsuite': ('Planetary Approach Suite', 'I'), + ('stellarbodydiscoveryscanner', 'standard'): ('Basic Discovery Scanner', 'E'), + ('stellarbodydiscoveryscanner', 'intermediate'): ('Intermediate Discovery Scanner', 'D'), + ('stellarbodydiscoveryscanner', 'advanced'): ('Advanced Discovery Scanner', 'C'), + 'supercruiseassist': ('Supercruise Assist', 'E'), +} + +outfitting_standard_map = { + # 'armour': handled separately + 'engine': 'Thrusters', + ('engine', 'fast'): 'Enhanced Performance Thrusters', + 'fueltank': 'Fuel Tank', + 'guardianpowerdistributor': 'Guardian Hybrid Power Distributor', + 'guardianpowerplant': 'Guardian Hybrid Power Plant', + 'hyperdrive': 'Frame Shift Drive', + 'lifesupport': 'Life Support', + # 'planetapproachsuite': handled separately + 'powerdistributor': 'Power Distributor', + 'powerplant': 'Power Plant', + 'sensors': 'Sensors', +} + +outfitting_internal_map = { + 'buggybay': 'Planetary Vehicle Hangar', + 'cargorack': 'Cargo Rack', + 'collection': 'Collector Limpet Controller', + 'corrosionproofcargorack': 'Corrosion Resistant Cargo Rack', + 'decontamination': 'Decontamination Limpet Controller', + 'fighterbay': 'Fighter Hangar', + 'fsdinterdictor': 'Frame Shift Drive Interdictor', + 'fuelscoop': 'Fuel Scoop', + 'fueltransfer': 'Fuel Transfer Limpet Controller', + 'guardianfsdbooster': 'Guardian FSD Booster', + 'guardianhullreinforcement': 'Guardian Hull Reinforcement', + 'guardianmodulereinforcement': 'Guardian Module Reinforcement', + 'guardianshieldreinforcement': 'Guardian Shield Reinforcement', + 'hullreinforcement': 'Hull Reinforcement Package', + 'metaalloyhullreinforcement': 'Meta Alloy Hull Reinforcement', + 'modulereinforcement': 'Module Reinforcement Package', + 'passengercabin': 'Passenger Cabin', + 'prospector': 'Prospector Limpet Controller', + 'refinery': 'Refinery', + 'recon': 'Recon Limpet Controller', + 'repair': 'Repair Limpet Controller', + 'repairer': 'Auto Field-Maintenance Unit', + 'resourcesiphon': 'Hatch Breaker Limpet Controller', + 'shieldcellbank': 'Shield Cell Bank', + 'shieldgenerator': 'Shield Generator', + ('shieldgenerator', 'fast'): 'Bi-Weave Shield Generator', + ('shieldgenerator', 'strong'): 'Prismatic Shield Generator', + 'unkvesselresearch': 'Research Limpet Controller', +} + +# Dashboard Flags constants +FlagsDocked = 1 << 0 # on a landing pad +FlagsLanded = 1 << 1 # on planet surface +FlagsLandingGearDown = 1 << 2 +FlagsShieldsUp = 1 << 3 +FlagsSupercruise = 1 << 4 +FlagsFlightAssistOff = 1 << 5 +FlagsHardpointsDeployed = 1 << 6 +FlagsInWing = 1 << 7 +FlagsLightsOn = 1 << 8 +FlagsCargoScoopDeployed = 1 << 9 +FlagsSilentRunning = 1 << 10 +FlagsScoopingFuel = 1 << 11 +FlagsSrvHandbrake = 1 << 12 +FlagsSrvTurret = 1 << 13 # using turret view +FlagsSrvUnderShip = 1 << 14 # turret retracted +FlagsSrvDriveAssist = 1 << 15 +FlagsFsdMassLocked = 1 << 16 +FlagsFsdCharging = 1 << 17 +FlagsFsdCooldown = 1 << 18 +FlagsLowFuel = 1 << 19 # < 25% +FlagsOverHeating = 1 << 20 # > 100%, or is this 80% now ? +FlagsHasLatLong = 1 << 21 +FlagsIsInDanger = 1 << 22 +FlagsBeingInterdicted = 1 << 23 +FlagsInMainShip = 1 << 24 +FlagsInFighter = 1 << 25 +FlagsInSRV = 1 << 26 +FlagsAnalysisMode = 1 << 27 # Hud in Analysis mode +FlagsNightVision = 1 << 28 +FlagsAverageAltitude = 1 << 29 # Altitude from Average radius +FlagsFsdJump = 1 << 30 +FlagsSrvHighBeam = 1 << 31 + +# Status.json / Dashboard flags2 +Flags2OnFoot = 1 << 0 +Flags2InTaxi = 1 << 1 # (or dropship/shuttle) +Flags2InMulticrew = 1 << 2 # (ie in someone else’s ship) +Flags2OnFootInStation = 1 << 3 +Flags2OnFootOnPlanet = 1 << 4 +Flags2AimDownSight = 1 << 5 +Flags2LowOxygen = 1 << 6 +Flags2LowHealth = 1 << 7 +Flags2Cold = 1 << 8 +Flags2Hot = 1 << 9 +Flags2VeryCold = 1 << 10 +Flags2VeryHot = 1 << 11 + +# Dashboard GuiFocus constants +GuiFocusNoFocus = 0 +GuiFocusInternalPanel = 1 # right hand side +GuiFocusExternalPanel = 2 # left hand side +GuiFocusCommsPanel = 3 # top +GuiFocusRolePanel = 4 # bottom +GuiFocusStationServices = 5 +GuiFocusGalaxyMap = 6 +GuiFocusSystemMap = 7 +GuiFocusOrrery = 8 +GuiFocusFSS = 9 +GuiFocusSAA = 10 +GuiFocusCodex = 11 + +ship_name_map = { + 'adder': 'Adder', + 'anaconda': 'Anaconda', + 'asp': 'Asp Explorer', + 'asp_scout': 'Asp Scout', + 'belugaliner': 'Beluga Liner', + 'cobramkiii': 'Cobra MkIII', + 'cobramkiv': 'Cobra MkIV', + 'clipper': 'Panther Clipper', + 'cutter': 'Imperial Cutter', + 'diamondback': 'Diamondback Scout', + 'diamondbackxl': 'Diamondback Explorer', + 'dolphin': 'Dolphin', + 'eagle': 'Eagle', + 'empire_courier': 'Imperial Courier', + 'empire_eagle': 'Imperial Eagle', + 'empire_fighter': 'Imperial Fighter', + 'empire_trader': 'Imperial Clipper', + 'federation_corvette': 'Federal Corvette', + 'federation_dropship': 'Federal Dropship', + 'federation_dropship_mkii': 'Federal Assault Ship', + 'federation_gunship': 'Federal Gunship', + 'federation_fighter': 'F63 Condor', + 'ferdelance': 'Fer-de-Lance', + 'hauler': 'Hauler', + 'independant_trader': 'Keelback', + 'independent_fighter': 'Taipan Fighter', + 'krait_mkii': 'Krait MkII', + 'krait_light': 'Krait Phantom', + 'mamba': 'Mamba', + 'orca': 'Orca', + 'python': 'Python', + 'scout': 'Taipan Fighter', + 'sidewinder': 'Sidewinder', + 'testbuggy': 'Scarab', + 'type6': 'Type-6 Transporter', + 'type7': 'Type-7 Transporter', + 'type9': 'Type-9 Heavy', + 'type9_military': 'Type-10 Defender', + 'typex': 'Alliance Chieftain', + 'typex_2': 'Alliance Crusader', + 'typex_3': 'Alliance Challenger', + 'viper': 'Viper MkIII', + 'viper_mkiv': 'Viper MkIV', + 'vulture': 'Vulture', +} diff --git a/edshipyard.py b/edshipyard.py index f3ce48a4..d709a2e1 100644 --- a/edshipyard.py +++ b/edshipyard.py @@ -1,80 +1,71 @@ -# Export ship loadout in E:D Shipyard plain text format +"""Export ship loadout in ED Shipyard plain text format.""" -import pickle -from collections import defaultdict import os -from os.path import join +import pathlib +import pickle import re import time +from collections import defaultdict +from typing import Dict, List, Union -from config import config -import companion import outfitting +import util_ships +from config import config +from edmc_data import edshipyard_slot_map as slot_map +from edmc_data import ship_name_map +from EDMCLogging import get_main_logger + +logger = get_main_logger() -from typing import Dict, Union, List __Module = Dict[str, Union[str, List[str]]] -# Map API ship names to E:D Shipyard ship names -ship_map = companion.ship_map.copy() - -ship_map.update( - { - 'cobramkiii': 'Cobra Mk III', - 'cobramkiv' : 'Cobra Mk IV', - 'viper' : 'Viper', - 'viper_mkiv': 'Viper Mk IV', - } -) - - -# Map API slot names to E:D Shipyard slot names -slot_map = { - 'hugehardpoint' : 'H', - 'largehardpoint' : 'L', - 'mediumhardpoint' : 'M', - 'smallhardpoint' : 'S', - 'tinyhardpoint' : 'U', - 'armour' : 'BH', - 'powerplant' : 'RB', - 'mainengines' : 'TM', - 'frameshiftdrive' : 'FH', - 'lifesupport' : 'EC', - 'powerdistributor' : 'PC', - 'radar' : 'SS', - 'fueltank' : 'FS', - 'military' : 'MC', -} - +# 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(join(config.respath, 'ships.p'), 'rb')) +ships = pickle.load(open(pathlib.Path(config.respath_path) / 'ships.p', 'rb')) -# Export ship loadout in E:D Shipyard plain text format -def export(data, filename=None): - def class_rating(module: __Module): +def export(data, filename=None) -> None: # noqa: C901, CCR001 + """ + Export ship loadout in E:D Shipyard plain text format. + + :param data: CAPI data. + :param filename: Override default file name. + """ + def class_rating(module: __Module) -> str: + """ + Return a string representation of the class of the given module. + + :param module: Module data dict. + :return: Rating of the module. + """ mod_class = module['class'] mod_rating = module['rating'] mod_mount = module.get('mount') - mod_guidance = module.get('guidance') + mod_guidance: str = str(module.get('guidance')) - ret = '{mod_class}{rating}'.format(mod_class=mod_class, rating=mod_rating) + ret = f'{mod_class}{mod_rating}' if 'guidance' in module: # Missiles - ret += "/{mount}{guidance}".format( - mount=mod_mount[0] if mod_mount is not None else 'F', - guidance=mod_guidance[0], - ) + if mod_mount is not None: + mount = mod_mount[0] + + else: + mount = 'F' + + guidance = mod_guidance[0] + ret += f'/{mount}{guidance}' elif 'mount' in module: # Hardpoints - ret += "/{mount}".format(mount=mod_mount) + ret += f'/{mod_mount}' elif 'Cabin' in module['name']: # Passenger cabins - ret += "/{name}".format(name=module['name'][0]) + ret += f'/{module["name"][0]}' return ret + ' ' - querytime = config.getint('querytime') or int(time.time()) + querytime = config.get_int('querytime', default=int(time.time())) loadout = defaultdict(list) mass = 0.0 @@ -97,22 +88,22 @@ def export(data, filename=None): cr = class_rating(module) mods = v.get('modifications') or v.get('WorkInProgress_modifications') or {} if mods.get('OutfittingFieldType_Mass'): - mass += (module.get('mass', 0) * mods['OutfittingFieldType_Mass']['value']) + mass += float(module.get('mass', 0.0) * mods['OutfittingFieldType_Mass']['value']) else: - mass += module.get('mass', 0) + mass += float(module.get('mass', 0.0)) # type: ignore # Specials if 'Fuel Tank' in module['name']: - fuel += 2**int(module['class']) - name = '{} (Capacity: {})'.format(module['name'], 2**int(module['class'])) + fuel += 2**int(module['class']) # type: ignore + name = f'{module["name"]} (Capacity: {2**int(module["class"])})' # type: ignore elif 'Cargo Rack' in module['name']: - cargo += 2**int(module['class']) - name = '{} (Capacity: {})'.format(module['name'], 2**int(module['class'])) + cargo += 2**int(module['class']) # type: ignore + name = f'{module["name"]} (Capacity: {2**int(module["class"])})' # type: ignore else: - name = module['name'] + name = module['name'] # type: ignore if name == 'Frame Shift Drive': fsd = module # save for range calculation @@ -123,7 +114,7 @@ def export(data, filename=None): if mods.get('OutfittingFieldType_MaxFuelPerJump'): fsd['maxfuel'] *= mods['OutfittingFieldType_MaxFuelPerJump']['value'] - jumpboost += module.get('jumpboost', 0) + jumpboost += module.get('jumpboost', 0) # type: ignore for s in slot_map: if slot.lower().startswith(s): @@ -134,13 +125,11 @@ def export(data, filename=None): if slot.lower().startswith('slot'): loadout[slot[-1]].append(cr + name) - elif __debug__ and not slot.lower().startswith('planetaryapproachsuite'): - print('EDShipyard: Unknown slot {}'.format(slot)) + elif not slot.lower().startswith('planetaryapproachsuite'): + logger.debug(f'EDShipyard: Unknown slot {slot}') except AssertionError as e: - if __debug__: - print('EDShipyard: {}'.format(e)) - + logger.debug(f'EDShipyard: {e!r}') continue # Silently skip unrecognized modules except Exception: @@ -151,40 +140,43 @@ def export(data, filename=None): ship = ship_map.get(data['ship']['name'].lower(), data['ship']['name']) if data['ship'].get('shipName') is not None: - _ships = '{}, {}'.format(ship, data['ship']['shipName']) + _ships = f'{ship}, {data["ship"]["shipName"]}' + else: _ships = ship - string = '[{}]\n'.format(_ships) + string = f'[{_ships}]\n' - SLOT_TYPES = ( + slot_types = ( 'H', 'L', 'M', 'S', 'U', None, 'BH', 'RB', 'TM', 'FH', 'EC', 'PC', 'SS', 'FS', None, 'MC', None, '9', '8', '7', '6', '5', '4', '3', '2', '1' ) - for slot in SLOT_TYPES: + for slot in slot_types: if not slot: string += '\n' elif slot in loadout: for name in loadout[slot]: - string += '{}: {}\n'.format(slot, name) + string += f'{slot}: {name}\n' - string += '---\nCargo : {} T\nFuel : {} T\n'.format(cargo, fuel) + string += f'---\nCargo : {cargo} T\nFuel : {fuel} T\n' # Add mass and range - assert data['ship']['name'].lower() in companion.ship_map, data['ship']['name'] - assert companion.ship_map[data['ship']['name'].lower()] in ships, companion.ship_map[data['ship']['name'].lower()] + assert data['ship']['name'].lower() in ship_name_map, data['ship']['name'] + assert ship_name_map[data['ship']['name'].lower()] in ships, ship_name_map[data['ship']['name'].lower()] try: - mass += ships[companion.ship_map[data['ship']['name'].lower()]]['hullMass'] - string += 'Mass : {:.2f} T empty\n {:.2f} T full\n'.format(mass, mass + fuel + cargo) + mass += ships[ship_name_map[data['ship']['name'].lower()]]['hullMass'] + string += f'Mass : {mass:.2f} T empty\n {mass + fuel + cargo:.2f} T full\n' - multiplier = pow(min(fuel, fsd['maxfuel']) / fsd['fuelmul'], 1.0 / fsd['fuelpower']) * fsd['optmass'] + multiplier = pow(min(fuel, fsd['maxfuel']) / fsd['fuelmul'], 1.0 # type: ignore + / fsd['fuelpower']) * fsd['optmass'] # type: ignore - string += 'Range : {:.2f} LY unladen\n {:.2f} LY laden\n'.format( - multiplier / (mass + fuel) + jumpboost, - multiplier / (mass + fuel + cargo) + jumpboost - ) + range_unladen = multiplier / (mass + fuel) + jumpboost + range_laden = multiplier / (mass + fuel + cargo) + jumpboost + # As of 2021-04-07 edsy.org says text import not yet implemented, so ignore the possible issue with + # a locale that uses comma for decimal separator. + string += f'Range : {range_unladen:.2f} LY unladen\n {range_laden:.2f} LY laden\n' except Exception: if __debug__: @@ -197,18 +189,17 @@ def export(data, filename=None): return # Look for last ship of this type - ship = companion.ship_file_name(data['ship'].get('shipName'), data['ship']['name']) + ship = util_ships.ship_file_name(data['ship'].get('shipName'), data['ship']['name']) 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('outdir')) if regexp.match(x)]) + oldfiles = sorted([x for x in os.listdir(config.get_str('outdir')) if regexp.match(x)]) if oldfiles: - with open(join(config.get('outdir'), oldfiles[-1]), 'rU') as h: + with (pathlib.Path(config.get_str('outdir')) / oldfiles[-1]).open('r') as h: if h.read() == string: return # same as last time - don't write # Write - filename = join(config.get('outdir'), '{}.{}.txt'.format( - ship, time.strftime('%Y-%m-%dT%H.%M.%S', time.localtime(querytime))) - ) + timestamp = time.strftime('%Y-%m-%dT%H.%M.%S', time.localtime(querytime)) + filename = pathlib.Path(config.get_str('outdir')) / f'{ship}.{timestamp}.txt' with open(filename, 'wt') as h: h.write(string) diff --git a/hotkey.py b/hotkey.py index 9b261ccc..5a72cde1 100644 --- a/hotkey.py +++ b/hotkey.py @@ -1,269 +1,424 @@ +"""Handle keyboard input for manual update triggering.""" # -*- coding: utf-8 -*- -import os -from os.path import dirname, join, normpath +import abc +import pathlib import sys -from sys import platform +import tkinter as tk +from abc import abstractmethod +from typing import Optional, Tuple, Union from config import config +from EDMCLogging import get_main_logger -if platform == 'darwin': +logger = get_main_logger() + + +class AbstractHotkeyMgr(abc.ABC): + """Abstract root class of all platforms specific HotKeyMgr.""" + + @abstractmethod + def register(self, root, keycode, modifiers) -> None: + """Register the hotkey handler.""" + pass + + @abstractmethod + def unregister(self) -> None: + """Unregister the hotkey handling.""" + pass + + @abstractmethod + def play_good(self) -> None: + """Play the 'good' sound.""" + pass + + @abstractmethod + def play_bad(self) -> None: + """Play the 'bad' sound.""" + pass + + +if sys.platform == 'darwin': import objc + from AppKit import ( + NSAlternateKeyMask, NSApplication, NSBeep, NSClearLineFunctionKey, NSCommandKeyMask, NSControlKeyMask, + NSDeleteFunctionKey, NSDeviceIndependentModifierFlagsMask, NSEvent, NSF1FunctionKey, NSF35FunctionKey, + NSFlagsChanged, NSKeyDown, NSKeyDownMask, NSKeyUp, NSNumericPadKeyMask, NSShiftKeyMask, NSSound, NSWorkspace + ) - from AppKit import NSApplication, NSWorkspace, NSBeep, NSSound, NSEvent, NSKeyDown, NSKeyUp, NSFlagsChanged, NSKeyDownMask, NSFlagsChangedMask, NSShiftKeyMask, NSControlKeyMask, NSAlternateKeyMask, NSCommandKeyMask, NSNumericPadKeyMask, NSDeviceIndependentModifierFlagsMask, NSF1FunctionKey, NSF35FunctionKey, NSDeleteFunctionKey, NSClearLineFunctionKey - class HotkeyMgr: +class MacHotkeyMgr(AbstractHotkeyMgr): + """Hot key management.""" - MODIFIERMASK = NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask|NSCommandKeyMask|NSNumericPadKeyMask - POLL = 250 - # https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSEvent_Class/#//apple_ref/doc/constant_group/Function_Key_Unicodes - DISPLAY = { 0x03: u'⌅', 0x09: u'⇥', 0xd: u'↩', 0x19: u'⇤', 0x1b: u'esc', 0x20: u'⏘', 0x7f: u'⌫', - 0xf700: u'↑', 0xf701: u'↓', 0xf702: u'←', 0xf703: u'→', - 0xf727: u'Ins', - 0xf728: u'⌦', 0xf729: u'↖', 0xf72a: u'Fn', 0xf72b: u'↘', - 0xf72c: u'⇞', 0xf72d: u'⇟', 0xf72e: u'PrtScr', 0xf72f: u'ScrollLock', - 0xf730: u'Pause', 0xf731: u'SysReq', 0xf732: u'Break', 0xf733: u'Reset', - 0xf739: u'⌧', - } - (ACQUIRE_INACTIVE, ACQUIRE_ACTIVE, ACQUIRE_NEW) = range(3) + POLL = 250 + # https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSEvent_Class/#//apple_ref/doc/constant_group/Function_Key_Unicodes + DISPLAY = { + 0x03: u'⌅', 0x09: u'⇥', 0xd: u'↩', 0x19: u'⇤', 0x1b: u'esc', 0x20: u'⏘', 0x7f: u'⌫', + 0xf700: u'↑', 0xf701: u'↓', 0xf702: u'←', 0xf703: u'→', + 0xf727: u'Ins', + 0xf728: u'⌦', 0xf729: u'↖', 0xf72a: u'Fn', 0xf72b: u'↘', + 0xf72c: u'⇞', 0xf72d: u'⇟', 0xf72e: u'PrtScr', 0xf72f: u'ScrollLock', + 0xf730: u'Pause', 0xf731: u'SysReq', 0xf732: u'Break', 0xf733: u'Reset', + 0xf739: u'⌧', + } + (ACQUIRE_INACTIVE, ACQUIRE_ACTIVE, ACQUIRE_NEW) = range(3) - def __init__(self): - self.root = None + def __init__(self): + self.MODIFIERMASK = NSShiftKeyMask | NSControlKeyMask | NSAlternateKeyMask | NSCommandKeyMask \ + | NSNumericPadKeyMask + self.root = None - self.keycode = 0 - self.modifiers = 0 + self.keycode = 0 + self.modifiers = 0 + self.activated = False + self.observer = None + + self.acquire_key = 0 + self.acquire_state = MacHotkeyMgr.ACQUIRE_INACTIVE + + self.tkProcessKeyEvent_old = None + + self.snd_good = NSSound.alloc().initWithContentsOfFile_byReference_( + pathlib.Path(config.respath_path) / 'snd_good.wav', False + ) + self.snd_bad = NSSound.alloc().initWithContentsOfFile_byReference_( + pathlib.Path(config.respath_path) / 'snd_bad.wav', False + ) + + def register(self, root: tk.Tk, keycode, modifiers) -> None: + """ + Register current hotkey for monitoring. + + :param root: parent window. + :param keycode: Key to monitor. + :param modifiers: Any modifiers to take into account. + """ + self.root = root + self.keycode = keycode + self.modifiers = modifiers + self.activated = False + + if keycode: + if not self.observer: + self.root.after_idle(self._observe) + self.root.after(MacHotkeyMgr.POLL, self._poll) + + # Monkey-patch tk (tkMacOSXKeyEvent.c) + if not self.tkProcessKeyEvent_old: + sel = b'tkProcessKeyEvent:' + cls = NSApplication.sharedApplication().class__() # type: ignore + self.tkProcessKeyEvent_old = NSApplication.sharedApplication().methodForSelector_(sel) # type: ignore + newmethod = objc.selector( # type: ignore + self.tkProcessKeyEvent, + selector=self.tkProcessKeyEvent_old.selector, + signature=self.tkProcessKeyEvent_old.signature + ) + objc.classAddMethod(cls, sel, newmethod) # type: ignore + + def tkProcessKeyEvent(self, cls, the_event): # noqa: N802 + """ + Monkey-patch tk (tkMacOSXKeyEvent.c). + + - workaround crash on OSX 10.9 & 10.10 on seeing a composing character + - notice when modifier key state changes + - keep a copy of NSEvent.charactersIgnoringModifiers, which is what we need for the hotkey + + (Would like to use a decorator but need to ensure the application is created before this is installed) + :param cls: ??? + :param the_event: tk event + :return: ??? + """ + if self.acquire_state: + if the_event.type() == NSFlagsChanged: + self.acquire_key = the_event.modifierFlags() & NSDeviceIndependentModifierFlagsMask + self.acquire_state = MacHotkeyMgr.ACQUIRE_NEW + # suppress the event by not chaining the old function + return the_event + + elif the_event.type() in (NSKeyDown, NSKeyUp): + c = the_event.charactersIgnoringModifiers() + self.acquire_key = (c and ord(c[0]) or 0) | \ + (the_event.modifierFlags() & NSDeviceIndependentModifierFlagsMask) + self.acquire_state = MacHotkeyMgr.ACQUIRE_NEW + # suppress the event by not chaining the old function + return the_event + + # replace empty characters with charactersIgnoringModifiers to avoid crash + elif the_event.type() in (NSKeyDown, NSKeyUp) and not the_event.characters(): + the_event = NSEvent.keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode_( # noqa: E501 + # noqa: E501 + the_event.type(), + the_event.locationInWindow(), + the_event.modifierFlags(), + the_event.timestamp(), + the_event.windowNumber(), + the_event.context(), + the_event.charactersIgnoringModifiers(), + the_event.charactersIgnoringModifiers(), + the_event.isARepeat(), + the_event.keyCode() + ) + return self.tkProcessKeyEvent_old(cls, the_event) + + def _observe(self): + # Must be called after root.mainloop() so that the app's message loop has been created + self.observer = NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSKeyDownMask, self._handler) + + def _poll(self): + if config.shutting_down: + return + + # No way of signalling to Tkinter from within the callback handler block that doesn't + # cause Python to crash, so poll. + if self.activated: self.activated = False - self.observer = None + self.root.event_generate('<>', when="tail") - self.acquire_key = 0 - self.acquire_state = HotkeyMgr.ACQUIRE_INACTIVE + if self.keycode or self.modifiers: + self.root.after(MacHotkeyMgr.POLL, self._poll) - self.tkProcessKeyEvent_old = None - - self.snd_good = NSSound.alloc().initWithContentsOfFile_byReference_(join(config.respath, 'snd_good.wav'), False) - self.snd_bad = NSSound.alloc().initWithContentsOfFile_byReference_(join(config.respath, 'snd_bad.wav'), False) - - def register(self, root, keycode, modifiers): - self.root = root - self.keycode = keycode - self.modifiers = modifiers - self.activated = False - - if keycode: - if not self.observer: - self.root.after_idle(self._observe) - self.root.after(HotkeyMgr.POLL, self._poll) - - # Monkey-patch tk (tkMacOSXKeyEvent.c) - if not self.tkProcessKeyEvent_old: - sel = b'tkProcessKeyEvent:' - cls = NSApplication.sharedApplication().class__() - self.tkProcessKeyEvent_old = NSApplication.sharedApplication().methodForSelector_(sel) - newmethod = objc.selector(self.tkProcessKeyEvent, selector = self.tkProcessKeyEvent_old.selector, signature = self.tkProcessKeyEvent_old.signature) - objc.classAddMethod(cls, sel, newmethod) - - # Monkey-patch tk (tkMacOSXKeyEvent.c) to: - # - workaround crash on OSX 10.9 & 10.10 on seeing a composing character - # - notice when modifier key state changes - # - keep a copy of NSEvent.charactersIgnoringModifiers, which is what we need for the hotkey - # (Would like to use a decorator but need to ensure the application is created before this is installed) - def tkProcessKeyEvent(self, cls, theEvent): - if self.acquire_state: - if theEvent.type() == NSFlagsChanged: - self.acquire_key = theEvent.modifierFlags() & NSDeviceIndependentModifierFlagsMask - self.acquire_state = HotkeyMgr.ACQUIRE_NEW - # suppress the event by not chaining the old function - return theEvent - elif theEvent.type() in (NSKeyDown, NSKeyUp): - c = theEvent.charactersIgnoringModifiers() - self.acquire_key = (c and ord(c[0]) or 0) | (theEvent.modifierFlags() & NSDeviceIndependentModifierFlagsMask) - self.acquire_state = HotkeyMgr.ACQUIRE_NEW - # suppress the event by not chaining the old function - return theEvent - - # replace empty characters with charactersIgnoringModifiers to avoid crash - elif theEvent.type() in (NSKeyDown, NSKeyUp) and not theEvent.characters(): - theEvent = NSEvent.keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode_(theEvent.type(), theEvent.locationInWindow(), theEvent.modifierFlags(), theEvent.timestamp(), theEvent.windowNumber(), theEvent.context(), theEvent.charactersIgnoringModifiers(), theEvent.charactersIgnoringModifiers(), theEvent.isARepeat(), theEvent.keyCode()) - return self.tkProcessKeyEvent_old(cls, theEvent) - - def _observe(self): - # Must be called after root.mainloop() so that the app's message loop has been created - self.observer = NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSKeyDownMask, self._handler) - - def _poll(self): - if config.shutting_down: - return - - # No way of signalling to Tkinter from within the callback handler block that doesn't - # cause Python to crash, so poll. - if self.activated: - self.activated = False - self.root.event_generate('<>', when="tail") - - if self.keycode or self.modifiers: - self.root.after(HotkeyMgr.POLL, self._poll) - - def unregister(self): - self.keycode = None - self.modifiers = None + def unregister(self) -> None: + """Remove hotkey registration.""" + self.keycode = None + self.modifiers = None + if sys.platform == 'darwin': # noqa: C901 @objc.callbackFor(NSEvent.addGlobalMonitorForEventsMatchingMask_handler_) - def _handler(self, event): + def _handler(self, event) -> None: # use event.charactersIgnoringModifiers to handle composing characters like Alt-e - if (event.modifierFlags() & HotkeyMgr.MODIFIERMASK) == self.modifiers and ord(event.charactersIgnoringModifiers()[0]) == self.keycode: - if config.getint('hotkey_always'): + if ((event.modifierFlags() & self.MODIFIERMASK) == self.modifiers + and ord(event.charactersIgnoringModifiers()[0]) == self.keycode): + if config.get_int('hotkey_always'): self.activated = True - else: # Only trigger if game client is front process + + else: # Only trigger if game client is front process front = NSWorkspace.sharedWorkspace().frontmostApplication() if front and front.bundleIdentifier() == 'uk.co.frontier.EliteDangerous': self.activated = True - def acquire_start(self): - self.acquire_state = HotkeyMgr.ACQUIRE_ACTIVE + def acquire_start(self) -> None: + """Start acquiring hotkey state via polling.""" + self.acquire_state = MacHotkeyMgr.ACQUIRE_ACTIVE self.root.after_idle(self._acquire_poll) - def acquire_stop(self): - self.acquire_state = HotkeyMgr.ACQUIRE_INACTIVE + def acquire_stop(self) -> None: + """Stop acquiring hotkey state.""" + self.acquire_state = MacHotkeyMgr.ACQUIRE_INACTIVE - def _acquire_poll(self): + def _acquire_poll(self) -> None: + """Perform a poll of current hotkey state.""" if config.shutting_down: return # No way of signalling to Tkinter from within the monkey-patched event handler that doesn't # cause Python to crash, so poll. if self.acquire_state: - if self.acquire_state == HotkeyMgr.ACQUIRE_NEW: + if self.acquire_state == MacHotkeyMgr.ACQUIRE_NEW: # Abuse tkEvent's keycode field to hold our acquired key & modifier - self.root.event_generate('', keycode = self.acquire_key) - self.acquire_state = HotkeyMgr.ACQUIRE_ACTIVE + self.root.event_generate('', keycode=self.acquire_key) + self.acquire_state = MacHotkeyMgr.ACQUIRE_ACTIVE self.root.after(50, self._acquire_poll) - def fromevent(self, event): - # Return configuration (keycode, modifiers) or None=clear or False=retain previous - (keycode, modifiers) = (event.keycode & 0xffff, event.keycode & 0xffff0000) # Set by _acquire_poll() - if keycode and not (modifiers & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask|NSCommandKeyMask)): - if keycode == 0x1b: # Esc = retain previous - self.acquire_state = HotkeyMgr.ACQUIRE_INACTIVE + def fromevent(self, event) -> Optional[Union[bool, Tuple]]: + """ + Return configuration (keycode, modifiers) or None=clear or False=retain previous. + + :param event: tk event ? + :return: False to retain previous, None to not use, else (keycode, modifiers) + """ + (keycode, modifiers) = (event.keycode & 0xffff, event.keycode & 0xffff0000) # Set by _acquire_poll() + if (keycode + and not (modifiers & (NSShiftKeyMask | NSControlKeyMask | NSAlternateKeyMask | NSCommandKeyMask))): + if keycode == 0x1b: # Esc = retain previous + self.acquire_state = MacHotkeyMgr.ACQUIRE_INACTIVE return False - elif keycode in [0x7f, ord(NSDeleteFunctionKey), ord(NSClearLineFunctionKey)]: # BkSp, Del, Clear = clear hotkey - self.acquire_state = HotkeyMgr.ACQUIRE_INACTIVE + + # BkSp, Del, Clear = clear hotkey + elif keycode in [0x7f, ord(NSDeleteFunctionKey), ord(NSClearLineFunctionKey)]: + self.acquire_state = MacHotkeyMgr.ACQUIRE_INACTIVE return None - elif keycode in [0x13, 0x20, 0x2d] or 0x61 <= keycode <= 0x7a: # don't allow keys needed for typing in System Map + + # don't allow keys needed for typing in System Map + elif keycode in [0x13, 0x20, 0x2d] or 0x61 <= keycode <= 0x7a: NSBeep() - self.acquire_state = HotkeyMgr.ACQUIRE_INACTIVE + self.acquire_state = MacHotkeyMgr.ACQUIRE_INACTIVE return None + return (keycode, modifiers) - def display(self, keycode, modifiers): - # Return displayable form + def display(self, keycode, modifiers) -> str: + """ + Return displayable form of given hotkey + modifiers. + + :param keycode: + :param modifiers: + :return: string form + """ text = '' - if modifiers & NSControlKeyMask: text += u'⌃' - if modifiers & NSAlternateKeyMask: text += u'⌥' - if modifiers & NSShiftKeyMask: text += u'⇧' - if modifiers & NSCommandKeyMask: text += u'⌘' - if (modifiers & NSNumericPadKeyMask) and keycode <= 0x7f: text += u'№' + if modifiers & NSControlKeyMask: + text += u'⌃' + + if modifiers & NSAlternateKeyMask: + text += u'⌥' + + if modifiers & NSShiftKeyMask: + text += u'⇧' + + if modifiers & NSCommandKeyMask: + text += u'⌘' + + if (modifiers & NSNumericPadKeyMask) and keycode <= 0x7f: + text += u'№' + if not keycode: pass + elif ord(NSF1FunctionKey) <= keycode <= ord(NSF35FunctionKey): - text += 'F%d' % (keycode + 1 - ord(NSF1FunctionKey)) - elif keycode in HotkeyMgr.DISPLAY: # specials - text += HotkeyMgr.DISPLAY[keycode] - elif keycode < 0x20: # control keys - text += chr(keycode+0x40) - elif keycode < 0xf700: # key char + text += f'F{keycode + 1 - ord(NSF1FunctionKey)}' + + elif keycode in MacHotkeyMgr.DISPLAY: # specials + text += MacHotkeyMgr.DISPLAY[keycode] + + elif keycode < 0x20: # control keys + text += chr(keycode + 0x40) + + elif keycode < 0xf700: # key char text += chr(keycode).upper() + else: text += u'⁈' + return text - def play_good(self): - self.snd_good.play() + def play_good(self): + """Play the 'good' sound.""" + self.snd_good.play() - def play_bad(self): - self.snd_bad.play() + def play_bad(self): + """Play the 'bad' sound.""" + self.snd_bad.play() -elif platform == 'win32': +if sys.platform == 'win32': import atexit import ctypes - from ctypes.wintypes import * import threading import winsound + from ctypes.wintypes import DWORD, HWND, LONG, LPWSTR, MSG, ULONG, WORD - RegisterHotKey = ctypes.windll.user32.RegisterHotKey - UnregisterHotKey = ctypes.windll.user32.UnregisterHotKey - MOD_ALT = 0x0001 - MOD_CONTROL = 0x0002 - MOD_SHIFT = 0x0004 - MOD_WIN = 0x0008 + RegisterHotKey = ctypes.windll.user32.RegisterHotKey + UnregisterHotKey = ctypes.windll.user32.UnregisterHotKey + MOD_ALT = 0x0001 + MOD_CONTROL = 0x0002 + MOD_SHIFT = 0x0004 + MOD_WIN = 0x0008 MOD_NOREPEAT = 0x4000 - GetMessage = ctypes.windll.user32.GetMessageW - TranslateMessage = ctypes.windll.user32.TranslateMessage - DispatchMessage = ctypes.windll.user32.DispatchMessageW + GetMessage = ctypes.windll.user32.GetMessageW + TranslateMessage = ctypes.windll.user32.TranslateMessage + DispatchMessage = ctypes.windll.user32.DispatchMessageW PostThreadMessage = ctypes.windll.user32.PostThreadMessageW - WM_QUIT = 0x0012 - WM_HOTKEY = 0x0312 - WM_APP = 0x8000 - WM_SND_GOOD = WM_APP + 1 - WM_SND_BAD = WM_APP + 2 + WM_QUIT = 0x0012 + WM_HOTKEY = 0x0312 + WM_APP = 0x8000 + WM_SND_GOOD = WM_APP + 1 + WM_SND_BAD = WM_APP + 2 - GetKeyState = ctypes.windll.user32.GetKeyState - MapVirtualKey = ctypes.windll.user32.MapVirtualKeyW - VK_BACK = 0x08 - VK_CLEAR = 0x0c - VK_RETURN = 0x0d - VK_SHIFT = 0x10 - VK_CONTROL = 0x11 - VK_MENU = 0x12 - VK_CAPITAL = 0x14 - VK_MODECHANGE= 0x1f - VK_ESCAPE = 0x1b - VK_SPACE = 0x20 - VK_DELETE = 0x2e - VK_LWIN = 0x5b - VK_RWIN = 0x5c - VK_NUMPAD0 = 0x60 - VK_DIVIDE = 0x6f - VK_F1 = 0x70 - VK_F24 = 0x87 + GetKeyState = ctypes.windll.user32.GetKeyState + MapVirtualKey = ctypes.windll.user32.MapVirtualKeyW + VK_BACK = 0x08 + VK_CLEAR = 0x0c + VK_RETURN = 0x0d + VK_SHIFT = 0x10 + VK_CONTROL = 0x11 + VK_MENU = 0x12 + VK_CAPITAL = 0x14 + VK_MODECHANGE = 0x1f + VK_ESCAPE = 0x1b + VK_SPACE = 0x20 + VK_DELETE = 0x2e + VK_LWIN = 0x5b + VK_RWIN = 0x5c + VK_NUMPAD0 = 0x60 + VK_DIVIDE = 0x6f + VK_F1 = 0x70 + VK_F24 = 0x87 VK_OEM_MINUS = 0xbd - VK_NUMLOCK = 0x90 - VK_SCROLL = 0x91 - VK_PROCESSKEY= 0xe5 + VK_NUMLOCK = 0x90 + VK_SCROLL = 0x91 + VK_PROCESSKEY = 0xe5 VK_OEM_CLEAR = 0xfe - GetForegroundWindow = ctypes.windll.user32.GetForegroundWindow - GetWindowText = ctypes.windll.user32.GetWindowTextW + GetWindowText = ctypes.windll.user32.GetWindowTextW GetWindowText.argtypes = [HWND, LPWSTR, ctypes.c_int] GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW - def WindowTitle(h): + def window_title(h) -> str: + """ + Determine the title for a window. + + :param h: Window handle. + :return: Window title. + """ if h: - l = GetWindowTextLength(h) + 1 - buf = ctypes.create_unicode_buffer(l) - if GetWindowText(h, buf, l): + title_length = GetWindowTextLength(h) + 1 + buf = ctypes.create_unicode_buffer(title_length) + if GetWindowText(h, buf, title_length): return buf.value + return '' - class MOUSEINPUT(ctypes.Structure): - _fields_ = [('dx', LONG), ('dy', LONG), ('mouseData', DWORD), ('dwFlags', DWORD), ('time', DWORD), ('dwExtraInfo', ctypes.POINTER(ULONG))] + """Mouse Input structure.""" + + _fields_ = [ + ('dx', LONG), + ('dy', LONG), + ('mouseData', DWORD), + ('dwFlags', DWORD), + ('time', DWORD), + ('dwExtraInfo', ctypes.POINTER(ULONG)) + ] class KEYBDINPUT(ctypes.Structure): - _fields_ = [('wVk', WORD), ('wScan', WORD), ('dwFlags', DWORD), ('time', DWORD), ('dwExtraInfo', ctypes.POINTER(ULONG))] + """Keyboard Input structure.""" + + _fields_ = [ + ('wVk', WORD), + ('wScan', WORD), + ('dwFlags', DWORD), + ('time', DWORD), + ('dwExtraInfo', ctypes.POINTER(ULONG)) + ] class HARDWAREINPUT(ctypes.Structure): - _fields_ = [('uMsg', DWORD), ('wParamL', WORD), ('wParamH', WORD)] + """Hardware Input structure.""" - class INPUT_union(ctypes.Union): - _fields_ = [('mi', MOUSEINPUT), ('ki', KEYBDINPUT), ('hi', HARDWAREINPUT)] + _fields_ = [ + ('uMsg', DWORD), + ('wParamL', WORD), + ('wParamH', WORD) + ] + + class INPUTUNION(ctypes.Union): + """Input union.""" + + _fields_ = [ + ('mi', MOUSEINPUT), + ('ki', KEYBDINPUT), + ('hi', HARDWAREINPUT) + ] class INPUT(ctypes.Structure): - _fields_ = [('type', DWORD), ('union', INPUT_union)] + """Input structure.""" + + _fields_ = [ + ('type', DWORD), + ('union', INPUTUNION) + ] SendInput = ctypes.windll.user32.SendInput SendInput.argtypes = [ctypes.c_uint, ctypes.POINTER(INPUT), ctypes.c_int] @@ -273,157 +428,276 @@ elif platform == 'win32': INPUT_HARDWARE = 2 - class HotkeyMgr: +class WindowsHotkeyMgr(AbstractHotkeyMgr): + """Hot key management.""" - # https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731%28v=vs.85%29.aspx - # Limit ourselves to symbols in Windows 7 Segoe UI - DISPLAY = { 0x03: 'Break', 0x08: 'Bksp', 0x09: u'↹', 0x0c: 'Clear', 0x0d: u'↵', 0x13: 'Pause', - 0x14: u'Ⓐ', 0x1b: 'Esc', - 0x20: u'⏘', 0x21: 'PgUp', 0x22: 'PgDn', 0x23: 'End', 0x24: 'Home', - 0x25: u'←', 0x26: u'↑', 0x27: u'→', 0x28: u'↓', - 0x2c: 'PrtScn', 0x2d: 'Ins', 0x2e: 'Del', 0x2f: 'Help', - 0x5d: u'▤', 0x5f: u'☾', - 0x90: u'➀', 0x91: 'ScrLk', - 0xa6: u'⇦', 0xa7: u'⇨', 0xa9: u'⊗', 0xab: u'☆', 0xac: u'⌂', 0xb4: u'✉', - } + # https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731%28v=vs.85%29.aspx + # Limit ourselves to symbols in Windows 7 Segoe UI + DISPLAY = { + 0x03: 'Break', 0x08: 'Bksp', 0x09: u'↹', 0x0c: 'Clear', 0x0d: u'↵', 0x13: 'Pause', + 0x14: u'Ⓐ', 0x1b: 'Esc', + 0x20: u'⏘', 0x21: 'PgUp', 0x22: 'PgDn', 0x23: 'End', 0x24: 'Home', + 0x25: u'←', 0x26: u'↑', 0x27: u'→', 0x28: u'↓', + 0x2c: 'PrtScn', 0x2d: 'Ins', 0x2e: 'Del', 0x2f: 'Help', + 0x5d: u'▤', 0x5f: u'☾', + 0x90: u'➀', 0x91: 'ScrLk', + 0xa6: u'⇦', 0xa7: u'⇨', 0xa9: u'⊗', 0xab: u'☆', 0xac: u'⌂', 0xb4: u'✉', + } - def __init__(self): - self.root = None - self.thread = None - self.snd_good = open(join(config.respath, 'snd_good.wav'), 'rb').read() - self.snd_bad = open(join(config.respath, 'snd_bad.wav'), 'rb').read() - atexit.register(self.unregister) + def __init__(self) -> None: + self.root: tk.Tk = None # type: ignore + self.thread: threading.Thread = None # type: ignore + with open(pathlib.Path(config.respath) / 'snd_good.wav', 'rb') as sg: + self.snd_good = sg.read() + with open(pathlib.Path(config.respath) / 'snd_bad.wav', 'rb') as sb: + self.snd_bad = sb.read() + atexit.register(self.unregister) - def register(self, root, keycode, modifiers): - self.root = root - if self.thread: - self.unregister() - if keycode or modifiers: - self.thread = threading.Thread(target = self.worker, name = 'Hotkey "%x:%x"' % (keycode,modifiers), args = (keycode,modifiers)) - self.thread.daemon = True - self.thread.start() + def register(self, root: tk.Tk, keycode, modifiers) -> None: + """Register the hotkey handler.""" + self.root = root - def unregister(self): - thread = self.thread - if thread: - self.thread = None - PostThreadMessage(thread.ident, WM_QUIT, 0, 0) - thread.join() # Wait for it to unregister hotkey and quit + if self.thread: + logger.debug('Was already registered, unregistering...') + self.unregister() - def worker(self, keycode, modifiers): + if keycode or modifiers: + logger.debug('Creating thread worker...') + self.thread = threading.Thread( + target=self.worker, + name=f'Hotkey "{keycode}:{modifiers}"', + args=(keycode, modifiers) + ) + self.thread.daemon = True + logger.debug('Starting thread worker...') + self.thread.start() + logger.debug('Done.') - # Hotkey must be registered by the thread that handles it - if not RegisterHotKey(None, 1, modifiers|MOD_NOREPEAT, keycode): - self.thread = None - return + def unregister(self) -> None: + """Unregister the hotkey handling.""" + thread = self.thread - fake = INPUT(INPUT_KEYBOARD, INPUT_union(ki = KEYBDINPUT(keycode, keycode, 0, 0, None))) + if thread: + logger.debug('Thread is/was running') + self.thread = None # type: ignore + logger.debug('Telling thread WM_QUIT') + PostThreadMessage(thread.ident, WM_QUIT, 0, 0) + logger.debug('Joining thread') + thread.join() # Wait for it to unregister hotkey and quit - msg = MSG() - while GetMessage(ctypes.byref(msg), None, 0, 0) != 0: - if msg.message == WM_HOTKEY: - if config.getint('hotkey_always') or WindowTitle(GetForegroundWindow()).startswith('Elite - Dangerous'): - if not config.shutting_down: - self.root.event_generate('<>', when="tail") - else: - # Pass the key on - UnregisterHotKey(None, 1) - SendInput(1, fake, ctypes.sizeof(INPUT)) - if not RegisterHotKey(None, 1, modifiers|MOD_NOREPEAT, keycode): - break + else: + logger.debug('No thread') + + logger.debug('Done.') + + def worker(self, keycode, modifiers) -> None: # noqa: CCR001 + """Handle hotkeys.""" + logger.debug('Begin...') + # Hotkey must be registered by the thread that handles it + if not RegisterHotKey(None, 1, modifiers | MOD_NOREPEAT, keycode): + logger.debug("We're not the right thread?") + self.thread = None # type: ignore + return + + fake = INPUT(INPUT_KEYBOARD, INPUTUNION(ki=KEYBDINPUT(keycode, keycode, 0, 0, None))) + + msg = MSG() + logger.debug('Entering GetMessage() loop...') + while GetMessage(ctypes.byref(msg), None, 0, 0) != 0: + logger.debug('Got message') + if msg.message == WM_HOTKEY: + logger.debug('WM_HOTKEY') + + if ( + config.get_int('hotkey_always') + or window_title(GetForegroundWindow()).startswith('Elite - Dangerous') + ): + if not config.shutting_down: + logger.debug('Sending event <>') + self.root.event_generate('<>', when="tail") - elif msg.message == WM_SND_GOOD: - winsound.PlaySound(self.snd_good, winsound.SND_MEMORY) # synchronous - elif msg.message == WM_SND_BAD: - winsound.PlaySound(self.snd_bad, winsound.SND_MEMORY) # synchronous else: - TranslateMessage(ctypes.byref(msg)) - DispatchMessage(ctypes.byref(msg)) + logger.debug('Passing key on') + UnregisterHotKey(None, 1) + SendInput(1, fake, ctypes.sizeof(INPUT)) + if not RegisterHotKey(None, 1, modifiers | MOD_NOREPEAT, keycode): + logger.debug("We aren't registered for this ?") + break - UnregisterHotKey(None, 1) - self.thread = None + elif msg.message == WM_SND_GOOD: + logger.debug('WM_SND_GOOD') + winsound.PlaySound(self.snd_good, winsound.SND_MEMORY) # synchronous - def acquire_start(self): - pass + elif msg.message == WM_SND_BAD: + logger.debug('WM_SND_BAD') + winsound.PlaySound(self.snd_bad, winsound.SND_MEMORY) # synchronous - def acquire_stop(self): - pass - - def fromevent(self, event): - # event.state is a pain - it shows the state of the modifiers *before* a modifier key was pressed. - # event.state *does* differentiate between left and right Ctrl and Alt and between Return and Enter - # by putting KF_EXTENDED in bit 18, but RegisterHotKey doesn't differentiate. - modifiers = ((GetKeyState(VK_MENU) & 0x8000) and MOD_ALT) | ((GetKeyState(VK_CONTROL) & 0x8000) and MOD_CONTROL) | ((GetKeyState(VK_SHIFT) & 0x8000) and MOD_SHIFT) | ((GetKeyState(VK_LWIN) & 0x8000) and MOD_WIN) | ((GetKeyState(VK_RWIN) & 0x8000) and MOD_WIN) - keycode = event.keycode - - if keycode in [ VK_SHIFT, VK_CONTROL, VK_MENU, VK_LWIN, VK_RWIN ]: - 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 - return None - elif 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) - - # See if the keycode is usable and available - if RegisterHotKey(None, 2, modifiers|MOD_NOREPEAT, keycode): - UnregisterHotKey(None, 2) - return (keycode, modifiers) else: + logger.debug('Something else') + TranslateMessage(ctypes.byref(msg)) + DispatchMessage(ctypes.byref(msg)) + + logger.debug('Exited GetMessage() loop.') + UnregisterHotKey(None, 1) + self.thread = None # type: ignore + logger.debug('Done.') + + def acquire_start(self) -> None: + """Start acquiring hotkey state via polling.""" + pass + + def acquire_stop(self) -> None: + """Stop acquiring hotkey state.""" + pass + + def fromevent(self, event) -> Optional[Union[bool, Tuple]]: # noqa: CCR001 + """ + Return configuration (keycode, modifiers) or None=clear or False=retain previous. + + event.state is a pain - it shows the state of the modifiers *before* a modifier key was pressed. + event.state *does* differentiate between left and right Ctrl and Alt and between Return and Enter + by putting KF_EXTENDED in bit 18, but RegisterHotKey doesn't differentiate. + + :param event: tk event ? + :return: False to retain previous, None to not use, else (keycode, modifiers) + """ + modifiers = ((GetKeyState(VK_MENU) & 0x8000) and MOD_ALT) \ + | ((GetKeyState(VK_CONTROL) & 0x8000) and MOD_CONTROL) \ + | ((GetKeyState(VK_SHIFT) & 0x8000) and MOD_SHIFT) \ + | ((GetKeyState(VK_LWIN) & 0x8000) and MOD_WIN) \ + | ((GetKeyState(VK_RWIN) & 0x8000) and MOD_WIN) + keycode = event.keycode + + if keycode in [VK_SHIFT, VK_CONTROL, VK_MENU, VK_LWIN, VK_RWIN]: + 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 + return None + + elif 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 - def display(self, keycode, modifiers): - text = '' - if modifiers & MOD_WIN: text += u'❖+' - if modifiers & MOD_CONTROL: text += u'Ctrl+' - if modifiers & MOD_ALT: text += u'Alt+' - if modifiers & MOD_SHIFT: text += u'⇧+' - if VK_NUMPAD0 <= keycode <= VK_DIVIDE: text += u'№' + elif (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) + + else: + winsound.MessageBeep() + return None + + def display(self, keycode, modifiers) -> str: + """ + Return displayable form of given hotkey + modifiers. + + :param keycode: + :param modifiers: + :return: string form + """ + text = '' + if modifiers & MOD_WIN: + text += u'❖+' + + if modifiers & MOD_CONTROL: + text += u'Ctrl+' + + if modifiers & MOD_ALT: + text += u'Alt+' + + if modifiers & MOD_SHIFT: + text += u'⇧+' + + if VK_NUMPAD0 <= keycode <= VK_DIVIDE: + text += u'№' + + if not keycode: + pass + + elif VK_F1 <= keycode <= VK_F24: + text += f'F{keycode + 1 - VK_F1}' + + elif keycode in WindowsHotkeyMgr.DISPLAY: # specials + text += WindowsHotkeyMgr.DISPLAY[keycode] + + else: + c = MapVirtualKey(keycode, 2) # printable ? + if not c: # oops not printable + text += u'⁈' + + elif c < 0x20: # control keys + text += chr(c + 0x40) - if not keycode: - pass - elif VK_F1 <= keycode <= VK_F24: - text += 'F%d' % (keycode + 1 - VK_F1) - elif keycode in HotkeyMgr.DISPLAY: # specials - text += HotkeyMgr.DISPLAY[keycode] else: - c = MapVirtualKey(keycode, 2) # printable ? - if not c: # oops not printable - text += u'⁈' - elif c < 0x20: # control keys - text += chr(c+0x40) - else: - text += chr(c).upper() - return text + text += chr(c).upper() - def play_good(self): - if self.thread: - PostThreadMessage(self.thread.ident, WM_SND_GOOD, 0, 0) + return text - def play_bad(self): - if self.thread: - PostThreadMessage(self.thread.ident, WM_SND_BAD, 0, 0) + def play_good(self) -> None: + """Play the 'good' sound.""" + if self.thread: + PostThreadMessage(self.thread.ident, WM_SND_GOOD, 0, 0) -else: # Linux + def play_bad(self) -> None: + """Play the 'bad' sound.""" + if self.thread: + PostThreadMessage(self.thread.ident, WM_SND_BAD, 0, 0) - class HotkeyMgr: - def register(self, root, keycode, modifiers): - pass +class LinuxHotKeyMgr(AbstractHotkeyMgr): + """ + Hot key management. - def unregister(self): - pass + Not actually implemented on Linux. It's a no-op instead. + """ - def play_good(self): - pass + def register(self, root, keycode, modifiers) -> None: + """Register the hotkey handler.""" + pass + + def unregister(self) -> None: + """Unregister the hotkey handling.""" + pass + + def play_good(self) -> None: + """Play the 'good' sound.""" + pass + + def play_bad(self) -> None: + """Play the 'bad' sound.""" + pass + + +def get_hotkeymgr() -> AbstractHotkeyMgr: + """ + Determine platform-specific HotkeyMgr. + + :param args: + :param kwargs: + :return: Appropriate class instance. + :raises ValueError: If unsupported platform. + """ + if sys.platform == 'darwin': + return MacHotkeyMgr() + + elif sys.platform == 'win32': + return WindowsHotkeyMgr() + + elif sys.platform == 'linux': + return LinuxHotKeyMgr() + + else: + raise ValueError(f'Unknown platform: {sys.platform}') - def play_bad(self): - pass # singleton -hotkeymgr = HotkeyMgr() +hotkeymgr = get_hotkeymgr() diff --git a/journal_lock.py b/journal_lock.py index 51f94f89..318eff6b 100644 --- a/journal_lock.py +++ b/journal_lock.py @@ -13,7 +13,7 @@ from EDMCLogging import get_main_logger logger = get_main_logger() -if TYPE_CHECKING: +if TYPE_CHECKING: # pragma: no cover def _(x: str) -> str: return x @@ -33,7 +33,7 @@ class JournalLock: def __init__(self) -> None: """Initialise where the journal directory and lock file are.""" - self.journal_dir: str = config.get('journaldir') or config.default_journal_dir + self.journal_dir: str = config.get_str('journaldir') or config.default_journal_dir self.journal_dir_path: Optional[pathlib.Path] = None self.set_path_from_journaldir() self.journal_dir_lockfile_name: Optional[pathlib.Path] = None @@ -42,6 +42,7 @@ class JournalLock: self.locked = False def set_path_from_journaldir(self): + """Set self.journal_dir_path from self.journal_dir.""" if self.journal_dir is None: self.journal_dir_path = None @@ -49,9 +50,25 @@ class JournalLock: try: self.journal_dir_path = pathlib.Path(self.journal_dir) - except Exception: + except Exception: # pragma: no cover logger.exception("Couldn't make pathlib.Path from journal_dir") + def open_journal_dir_lockfile(self) -> bool: + """Open journal_dir lockfile ready for locking.""" + self.journal_dir_lockfile_name = self.journal_dir_path / 'edmc-journal-lock.txt' # type: ignore + logger.trace(f'journal_dir_lockfile_name = {self.journal_dir_lockfile_name!r}') + try: + self.journal_dir_lockfile = open(self.journal_dir_lockfile_name, mode='w+', encoding='utf-8') + + # Linux CIFS read-only mount throws: OSError(30, 'Read-only file system') + # Linux no-write-perm directory throws: PermissionError(13, 'Permission denied') + except Exception as e: # For remote FS this could be any of a wide range of exceptions + logger.warning(f"Couldn't open \"{self.journal_dir_lockfile_name}\" for \"w+\"" + f" Aborting duplicate process checks: {e!r}") + return False + + return True + def obtain_lock(self) -> JournalLockResult: """ Attempt to obtain a lock on the journal directory. @@ -61,18 +78,22 @@ class JournalLock: if self.journal_dir_path is None: return JournalLockResult.JOURNALDIR_IS_NONE - self.journal_dir_lockfile_name = self.journal_dir_path / 'edmc-journal-lock.txt' - logger.trace(f'journal_dir_lockfile_name = {self.journal_dir_lockfile_name!r}') - try: - self.journal_dir_lockfile = open(self.journal_dir_lockfile_name, mode='w+', encoding='utf-8') - - # Linux CIFS read-only mount throws: OSError(30, 'Read-only file system') - # Linux no-write-perm directory throws: PermissionError(13, 'Permission denied') - except Exception as e: # For remote FS this could be any of a wide range of exceptions - logger.warning(f"Couldn't open \"{self.journal_dir_lockfile_name}\" for \"w+\"" - f" Aborting duplicate process checks: {e!r}") + if not self.open_journal_dir_lockfile(): return JournalLockResult.JOURNALDIR_READONLY + return self._obtain_lock() + + def _obtain_lock(self) -> JournalLockResult: + """ + Actual code for obtaining a lock. + + This is split out so tests can call *just* it, without the attempt + at opening the file. If we call open_journal_dir_lockfile() we + re-use self.journal_dir_lockfile and in the process close the + previous handle stored in it and thus release the lock. + + :return: LockResult - See the class Enum definition + """ if platform == 'win32': logger.trace('win32, using msvcrt') # win32 doesn't have fcntl, so we have to use msvcrt @@ -86,7 +107,7 @@ class JournalLock: f", assuming another process running: {e!r}") return JournalLockResult.ALREADY_LOCKED - else: + else: # pytest coverage only sees this on !win32 logger.trace('NOT win32, using fcntl') try: import fcntl @@ -112,7 +133,7 @@ class JournalLock: return JournalLockResult.LOCKED - def release_lock(self) -> bool: + def release_lock(self) -> bool: # noqa: CCR001 """ Release lock on journal directory. @@ -139,7 +160,7 @@ class JournalLock: else: unlocked = True - else: + else: # pytest coverage only sees this on !win32 logger.trace('NOT win32, using fcntl') try: import fcntl @@ -158,7 +179,8 @@ class JournalLock: unlocked = True # Close the file whether or not the unlocking succeeded. - self.journal_dir_lockfile.close() + if hasattr(self, 'journal_dir_lockfile'): + self.journal_dir_lockfile.close() self.journal_dir_lockfile_name = None # Avoids type hint issues, see 'declaration' in JournalLock.__init__() @@ -166,7 +188,7 @@ class JournalLock: return unlocked - class JournalAlreadyLocked(tk.Toplevel): + class JournalAlreadyLocked(tk.Toplevel): # pragma: no cover """Pop-up for when Journal directory already locked.""" def __init__(self, parent: tk.Tk, callback: Callable) -> None: @@ -230,7 +252,7 @@ class JournalLock: :param parent: - The parent tkinter window. """ - current_journaldir = config.get('journaldir') or config.default_journal_dir + current_journaldir = config.get_str('journaldir') or config.default_journal_dir if current_journaldir == self.journal_dir: return # Still the same @@ -242,9 +264,9 @@ class JournalLock: if self.obtain_lock() == JournalLockResult.ALREADY_LOCKED: # Pop-up message asking for Retry or Ignore - self.retry_popup = self.JournalAlreadyLocked(parent, self.retry_lock) + self.retry_popup = self.JournalAlreadyLocked(parent, self.retry_lock) # pragma: no cover - def retry_lock(self, retry: bool, parent: tk.Tk) -> None: + def retry_lock(self, retry: bool, parent: tk.Tk) -> None: # pragma: no cover """ Try again to obtain a lock on the Journal Directory. @@ -256,7 +278,7 @@ class JournalLock: if not retry: return - current_journaldir = config.get('journaldir') or config.default_journal_dir + current_journaldir = config.get_str('journaldir') or config.default_journal_dir self.journal_dir = current_journaldir self.set_path_from_journaldir() if self.obtain_lock() == JournalLockResult.ALREADY_LOCKED: diff --git a/killswitch.py b/killswitch.py new file mode 100644 index 00000000..aca020aa --- /dev/null +++ b/killswitch.py @@ -0,0 +1,195 @@ +"""Fetch kill switches from EDMC Repo.""" +from typing import Dict, List, NamedTuple, Optional, Union, cast + +import requests +import semantic_version + +import config +import EDMCLogging + +logger = EDMCLogging.get_main_logger() + +DEFAULT_KILLSWITCH_URL = 'https://raw.githubusercontent.com/EDCD/EDMarketConnector/releases/killswitches.json' + +_current_version: semantic_version.Version = config.appversion_nobuild() + + +class KillSwitch(NamedTuple): + """One version's set of kill switches.""" + + version: semantic_version.SimpleSpec + kills: Dict[str, str] + + +class DisabledResult(NamedTuple): + """DisabledResult is the result returned from various is_disabled calls.""" + + disabled: bool + reason: str + + +class KillSwitchSet: + """Queryable set of kill switches.""" + + def __init__(self, kill_switches: List[KillSwitch]) -> None: + self.kill_switches = kill_switches + + def get_disabled(self, id: str, *, version=_current_version) -> DisabledResult: + """ + Return whether or not 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 current EDMC version + :return: a namedtuple indicating status and reason, if any + """ + for ks in self.kill_switches: + if version not in ks.version: + continue + + return DisabledResult(id in ks.kills, ks.kills.get(id, "")) + + return DisabledResult(False, "") + + 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 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[KillSwitch]: + """ + Get all killswitch entries that apply to the given version. + + :param version: the version to check against, defaults to the current EDMC version + :return: the matching kill switches + """ + return [k for k in self.kill_switches if version in k.version] + + def __str__(self) -> str: + """Return a string representation of KillSwitchSet.""" + return f'KillSwitchSet: {str(self.kill_switches)}' + + def __repr__(self) -> str: + """Return __repr__ for KillSwitchSet.""" + return f'KillSwitchSet(kill_switches={self.kill_switches!r})' + + +KILL_SWITCH_JSON = List[Dict[str, Union[str, List[str]]]] +KILL_SWITCH_JSON_DICT = Dict[ + str, Union[ + str, # Last updated + int, # Version + KILL_SWITCH_JSON # kills + ] +] + + +def fetch_kill_switches(target=DEFAULT_KILLSWITCH_URL) -> Optional[KILL_SWITCH_JSON_DICT]: + """ + Fetch the JSON representation of our kill switches. + + :param target: the URL to fetch the kill switch list from, defaults to DEFAULT_KILLSWITCH_URL + :return: a list of dicts containing kill switch data, or None + """ + logger.info("Attempting to fetch kill switches") + try: + data = requests.get(target, timeout=10).json() + + except ValueError as e: + logger.warning(f"Failed to get kill switches, data was invalid: {e}") + return None + + except (requests.exceptions.BaseHTTPError, requests.exceptions.ConnectionError) as e: + logger.warning(f"unable to connect to {target!r}: {e}") + return None + + return data + + +def parse_kill_switches(data: KILL_SWITCH_JSON_DICT) -> List[KillSwitch]: + """ + Parse kill switch dict to List of KillSwitches. + + :param data: dict containing raw killswitch data + :return: a list of all provided killswitches + """ + last_updated = data['last_updated'] + ks_version = data['version'] + logger.info(f'Kill switches last updated {last_updated}') + + if ks_version != 1: + logger.warning(f'Unknown killswitch version {ks_version}. Bailing out') + return [] + + kill_switches = cast(KILL_SWITCH_JSON, data['kill_switches']) + out: List[KillSwitch] = [] + + for idx, ks_data in enumerate(kill_switches): + try: + ver = semantic_version.SimpleSpec(ks_data['version']) + + except ValueError as e: + logger.warning(f'could not parse killswitch idx {idx}: {e}') + continue + + ks = KillSwitch(version=ver, kills=cast(Dict[str, str], ks_data['kills'])) + out.append(ks) + + return out + + +def get_kill_switches(target=DEFAULT_KILLSWITCH_URL) -> Optional[KillSwitchSet]: + """ + Get a kill switch set object. + + :param target: the URL to fetch the killswitch JSON from, defaults to DEFAULT_KILLSWITCH_URL + :return: the KillSwitchSet for the URL, or None if there was an error + """ + if (data := fetch_kill_switches(target)) is None: + logger.warning('could not get killswitches') + return None + + return KillSwitchSet(parse_kill_switches(data)) + + +active: KillSwitchSet = KillSwitchSet([]) + + +def setup_main_list(): + """ + Set up the global set of kill switches for querying. + + Plugins should NOT call this EVER. + """ + if (data := fetch_kill_switches()) is None: + logger.warning("Unable to fetch kill switches. Setting global set to an empty set") + return + + global active + active = KillSwitchSet(parse_kill_switches(data)) + + +def get_disabled(id: str, *, version: semantic_version.Version = _current_version) -> DisabledResult: + """ + Query the global KillSwitchSet for whether or not a given ID is disabled. + + See KillSwitchSet#is_disabled for more information + """ + return active.get_disabled(id, version=version) + + +def is_disabled(id: str, *, version: semantic_version.Version = _current_version) -> bool: + """Query the global KillSwitchSet#is_disabled method.""" + return active.is_disabled(id, version=version) + + +def get_reason(id: str, *, version: semantic_version.Version = _current_version) -> str: + """Query the global KillSwitchSet#get_reason method.""" + return active.get_reason(id, version=version) + + +def kills_for_version(version: semantic_version.Version = _current_version) -> List[KillSwitch]: + """Query the global KillSwitchSet for kills matching a particular version.""" + return active.kills_for_version(version) diff --git a/l10n.py b/l10n.py index 7a181f8d..d6e4677e 100755 --- a/l10n.py +++ b/l10n.py @@ -1,27 +1,36 @@ #!/usr/bin/env python3 -# -# Localization with gettext is a pain on non-Unix systems. Use OSX-style strings files instead. -# +"""Localization with gettext is a pain on non-Unix systems. Use OSX-style strings files instead.""" -import codecs -from collections import OrderedDict +import builtins +import locale import numbers import os -from os.path import basename, dirname, exists, isfile, isdir, join, normpath +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 sys import platform -from traceback import print_exc -import builtins +from typing import TYPE_CHECKING, Dict, Iterable, Optional, Set, TextIO, Union, cast -import locale +if TYPE_CHECKING: + def _(x: str) -> str: ... + +# 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: + +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' @@ -29,17 +38,24 @@ LOCALISATION_DIR = 'L10n' if platform == 'darwin': - from Foundation import NSLocale, NSNumberFormatter, NSNumberFormatterDecimalStyle + from Foundation import ( # type: ignore # exists on Darwin + NSLocale, NSNumberFormatter, NSNumberFormatterDecimalStyle + ) elif platform == 'win32': import ctypes - from ctypes.wintypes import * + from ctypes.wintypes import BOOL, DWORD, LPCVOID, LPCWSTR, LPWSTR + if TYPE_CHECKING: + import ctypes.windll # type: ignore # Magic to make linters not complain that windll is special # https://msdn.microsoft.com/en-us/library/windows/desktop/dd318124%28v=vs.85%29.aspx MUI_LANGUAGE_ID = 4 MUI_LANGUAGE_NAME = 8 GetUserPreferredUILanguages = ctypes.windll.kernel32.GetUserPreferredUILanguages - GetUserPreferredUILanguages.argtypes = [ DWORD, ctypes.POINTER(ctypes.c_ulong), LPCVOID, ctypes.POINTER(ctypes.c_ulong) ] + GetUserPreferredUILanguages.argtypes = [ + DWORD, ctypes.POINTER(ctypes.c_ulong), LPCVOID, ctypes.POINTER(ctypes.c_ulong) + ] + GetUserPreferredUILanguages.restype = BOOL LOCALE_NAME_USER_DEFAULT = None @@ -48,135 +64,185 @@ elif platform == 'win32': GetNumberFormatEx.restype = ctypes.c_int -class Translations(object): +class _Translations: - FALLBACK = 'en' # strings in this code are in English + 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: {}} - def __init__(self): - self.translations = { None: {} } + def install_dummy(self) -> None: + """ + Install a dummy translation function. - def install_dummy(self): - # For when translation is not desired or not available - self.translations = { None: {} } - builtins.__dict__['_'] = lambda x: str(x).replace(r'\"', u'"').replace(u'{CR}', u'\n') # Promote strings to Unicode for consistency + Use when translation is not desired or not available + """ + self.translations = {None: {}} + builtins.__dict__['_'] = lambda x: str(x).replace(r'\"', '"').replace('{CR}', '\n') - def install(self, lang=None): + def install(self, lang: str = None) -> None: # noqa: CCR001 + """ + Install the translation function to the _ builtin. + + :param lang: The language to translate to, defaults to the preferred language + """ available = self.available() - available.add(Translations.FALLBACK) - + available.add(_Translations.FALLBACK) if not lang: # Choose the default language - for preferred in Locale.preferredLanguages(): + for preferred in Locale.preferred_languages(): components = preferred.split('-') if preferred in available: lang = preferred + elif '-'.join(components[0:2]) in available: - lang = '-'.join(components[0:2]) # language-script + lang = '-'.join(components[0:2]) # language-script + elif components[0] in available: - lang = components[0] # just base language + lang = components[0] # just base language + if lang: break if lang not in self.available(): self.install_dummy() - else: - self.translations = { None: self.contents(lang) } - for plugin in os.listdir(config.plugin_dir): - plugin_path = join(config.plugin_dir, plugin, LOCALISATION_DIR) - if isdir(plugin_path): - try: - self.translations[plugin] = self.contents(lang, plugin_path) - except UnicodeDecodeError as e: - print('Malformed file %s.strings in plugin %s: %s' % (lang, plugin, e)) - except: - print_exc() - builtins.__dict__['_'] = self.translate + return - def contents(self, lang, plugin_path=None): + self.translations = {None: self.contents(cast(str, lang))} + for plugin in os.listdir(config.plugin_dir_path): + plugin_path = join(config.plugin_dir_path, plugin, LOCALISATION_DIR) + if isdir(plugin_path): + try: + self.translations[plugin] = self.contents(cast(str, lang), str(plugin_path)) + + except UnicodeDecodeError as e: + logger.warning(f'Malformed file {lang}.strings in plugin {plugin}: {e}') + + except Exception: + logger.exception(f'Exception occurred while parsing {lang}.strings in plugin {plugin}') + + builtins.__dict__['_'] = self.translate + + def contents(self, lang: str, plugin_path: Optional[str] = None) -> Dict[str, str]: + """Load all the translations from a translation file.""" assert lang in self.available() translations = {} + h = self.file(lang, plugin_path) if not h: return {} - else: - for line in h: - if line.strip(): - match = Translations.TRANS_RE.match(line) - if match: - translations[match.group(1).replace(r'\"', u'"')] = match.group(2).replace(r'\"', u'"').replace(u'{CR}', u'\n') - elif __debug__ and not Translations.COMMENT_RE.match(line): - print('Bad translation: %s' % line.strip()) + + for line in h: + if line.strip(): + match = _Translations.TRANS_RE.match(line) + if match: + to_set = match.group(2).replace(r'\"', '"').replace('{CR}', '\n') + translations[match.group(1).replace(r'\"', '"')] = to_set + + elif not _Translations.COMMENT_RE.match(line): + logger.debug(f'Bad translation: {line.strip()}') + h.close() + if translations.get(LANGUAGE_ID, LANGUAGE_ID) == LANGUAGE_ID: - translations[LANGUAGE_ID] = str(lang) # Replace language name with code if missing + translations[LANGUAGE_ID] = str(lang) # Replace language name with code if missing + return translations - def translate(self, x, context=None): - if context: - context = context[len(config.plugin_dir)+1:].split(os.sep)[0] - if __debug__: - if self.translations[None] and context not in self.translations: - print('No translations for "%s"' % context) - return self.translations.get(context, {}).get(x) or self.translate(x) - else: - if __debug__: - if self.translations[None] and x not in self.translations[None]: - print('Missing translation: "%s"' % x) - return self.translations[None].get(x) or str(x).replace(r'\"', u'"').replace(u'{CR}', u'\n') + def translate(self, x: str, context: Optional[str] = None) -> str: + """ + Translate the given string to the current lang. - # Returns list of available language codes - def available(self): + :param x: The string to translate + :param context: Whether or not to search the given directory for translation files, defaults to None + :return: The translated string + """ + 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] + if self.translations[None] and context not in self.translations: + logger.debug(f'No translations for {context!r}') + + return self.translations.get(context, {}).get(x) or self.translate(x) + + if self.translations[None] and x not in self.translations[None]: + logger.debug(f'Missing translation: {x!r}') + + return self.translations[None].get(x) or str(x).replace(r'\"', '"').replace('{CR}', '\n') + + def available(self) -> Set[str]: + """Return a list of available language codes.""" path = self.respath() - if getattr(sys, 'frozen', False) and platform=='darwin': - available = set([x[:-len('.lproj')] for x in os.listdir(path) if x.endswith('.lproj') and isfile(join(x, 'Localizable.strings'))]) + if getattr(sys, 'frozen', False) and platform == 'darwin': + available = { + x[:-len('.lproj')] for x in os.listdir(path) + if x.endswith('.lproj') and isfile(join(x, 'Localizable.strings')) + } + else: - available = set([x[:-len('.strings')] for x in os.listdir(path) if x.endswith('.strings')]) + available = {x[:-len('.strings')] for x in os.listdir(path) if x.endswith('.strings')} + return available - # Available language names by code - def available_names(self): - names = OrderedDict([ - (None, _('Default')), # Appearance theme and language setting + def available_names(self) -> Dict[Optional[str], str]: + """Available language names by code.""" + names: Dict[Optional[str], str] = OrderedDict([ + (None, _('Default')), # Appearance theme and language setting ]) - names.update(sorted([(lang, self.contents(lang).get(LANGUAGE_ID, lang)) for lang in self.available()] + - [(Translations.FALLBACK, Translations.FALLBACK_NAME)], - key=lambda x: x[1])) # Sort by name + names.update(sorted( + [(lang, self.contents(lang).get(LANGUAGE_ID, lang)) for lang in self.available()] + + [(_Translations.FALLBACK, _Translations.FALLBACK_NAME)], + key=lambda x: x[1] + )) # Sort by name + return names - def respath(self): + def respath(self) -> pathlib.Path: + """Path to localisation files.""" if getattr(sys, 'frozen', False): - if platform=='darwin': - return normpath(join(dirname(sys.executable), os.pardir, 'Resources')) - else: - return join(dirname(sys.executable), LOCALISATION_DIR) + if platform == 'darwin': + return (pathlib.Path(sys.executable).parents[0] / os.pardir / 'Resources').resolve() + + return pathlib.Path(dirname(sys.executable)) / LOCALISATION_DIR + elif __file__: - return join(dirname(__file__), LOCALISATION_DIR) - else: - return LOCALISATION_DIR + return pathlib.Path(__file__).parents[0] / LOCALISATION_DIR - def file(self, lang, plugin_path=None): + return pathlib.Path(LOCALISATION_DIR) + + def file(self, lang: str, plugin_path: Optional[str] = None) -> Optional[TextIO]: + """ + Open the given lang file for reading. + + :param lang: The lang file to open (just the name of the lang) + :param plugin_path: path to plugins dir, to check for plugin based lang files, defaults to None + :return: the opened file (Note: This should be closed when done) + """ if plugin_path: - f = join(plugin_path, '%s.strings' % lang) - if exists(f): - try: - return codecs.open(f, 'r', 'utf-8') - except: - print_exc() - return None - elif getattr(sys, 'frozen', False) and platform=='darwin': - return codecs.open(join(self.respath(), '%s.lproj' % lang, 'Localizable.strings'), 'r', 'utf-16') - else: - return codecs.open(join(self.respath(), '%s.strings' % lang), 'r', 'utf-8') + f = pathlib.Path(plugin_path) / f'{lang}.strings' + if not f.exists(): + return None + + try: + return f.open('r', encoding='utf-8') + + except OSError: + logger.exception(f'could not open {f}') + + elif getattr(sys, 'frozen', False) and platform == 'darwin': + return (self.respath() / f'{lang}.lproj' / 'Localizable.strings').open('r', encoding='utf-16') + + return (self.respath() / f'{lang}.strings').open('r', encoding='utf-8') -class Locale(object): +class _Locale: + """Locale holds a few utility methods to convert data to and from localized versions.""" - def __init__(self): - if platform=='darwin': + def __init__(self) -> None: + if platform == 'darwin': self.int_formatter = NSNumberFormatter.alloc().init() self.int_formatter.setNumberStyle_(NSNumberFormatterDecimalStyle) self.float_formatter = NSNumberFormatter.alloc().init() @@ -184,99 +250,136 @@ class Locale(object): self.float_formatter.setMinimumFractionDigits_(5) self.float_formatter.setMaximumFractionDigits_(5) - def stringFromNumber(self, number, decimals=None): - # Uses the current system locale, irrespective of language choice. - # Unless `decimals` is specified, the number will be formatted with 5 decimal - # places if the input is a float, or none if the input is an int. + def stringFromNumber(self, number: Union[float, int], decimals: int = 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 + warnings.warn(DeprecationWarning('use _Locale.number_from_string instead.')) + return self.number_from_string(string) + + def preferredLanguages(self) -> Iterable[str]: # noqa: N802 + 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: + """ + Convert a number to a string. + + Uses the current system locale, irrespective of language choice. + + :param number: The number to stringify + :param decimals: The number of decimals to return, defaults to 5 if the given number is a float, otherwise None + :return: the stringified number + """ if decimals == 0 and not isinstance(number, numbers.Integral): number = int(round(number)) + if platform == 'darwin': if not decimals and isinstance(number, numbers.Integral): return self.int_formatter.stringFromNumber_(number) - else: - self.float_formatter.setMinimumFractionDigits_(decimals or 5) - self.float_formatter.setMaximumFractionDigits_(decimals or 5) - return self.float_formatter.stringFromNumber_(number) - else: - if not decimals and isinstance(number, numbers.Integral): - return locale.format('%d', number, True) - else: - return locale.format('%.*f', (decimals or 5, number), True) - def numberFromString(self, string): - # Uses the current system locale, irrespective of language choice. - # Returns None if the string is not parsable, otherwise an integer or float. - if platform=='darwin': + self.float_formatter.setMinimumFractionDigits_(decimals) + self.float_formatter.setMaximumFractionDigits_(decimals) + return self.float_formatter.stringFromNumber_(number) + + if not decimals and isinstance(number, numbers.Integral): + return locale.format('%d', number, True) + + else: + return locale.format('%.*f', (decimals, number), True) # type: ignore # It ends up working out + + def number_from_string(self, string: str) -> Union[int, float, None]: + """ + Convert a string to a number using the system locale. + + Note that this uses the current SYSTEM locale regardless of set language. + :param string: The string to convert + :return: None if the string cannot be parsed, otherwise an int or float dependant on input data. + """ + if platform == 'darwin': return self.float_formatter.numberFromString_(string) - else: - try: - return locale.atoi(string) - except: - try: - return locale.atof(string) - except: - return None - # Returns list of preferred language codes in RFC4646 format i.e. "lang[-script][-region]" - # Where lang is a lowercase 2 alpha ISO 639-1 or 3 alpha ISO 639-2 code, - # script is a capitalized 4 alpha ISO 15924 code and region is an uppercase 2 alpha ISO 3166 code - def preferredLanguages(self): + with suppress(ValueError): + return locale.atoi(string) - if platform=='darwin': + with suppress(ValueError): + return locale.atof(string) + + return None + + def preferred_languages(self) -> Iterable[str]: + """ + Return a list of preferred language codes. + + Returned data is in RFC4646 format (i.e. "lang[-script][-region]") + Where lang is a lowercase 2 alpha ISO 693-1 or 3 alpha ISO 693-2 code + Where script is a capitalized 4 alpha ISO 15924 code + Where region is an uppercase 2 alpha ISO 3166 code + + :return: The preferred language list + """ + if platform == 'darwin': return NSLocale.preferredLanguages() - elif platform=='win32': - - 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) - if (GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, ctypes.byref(num), None, ctypes.byref(size)) and size.value): - buf = ctypes.create_unicode_buffer(size.value) - if GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, ctypes.byref(num), ctypes.byref(buf), ctypes.byref(size)): - return wszarray_to_list(buf) - return [] - - else: # POSIX + elif platform != 'win32': + # POSIX lang = locale.getlocale()[0] - return lang and [lang.replace('_','-')] or [] + return lang and [lang.replace('_', '-')] or [] + + 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) + if GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, ctypes.byref(num), None, ctypes.byref(size)) and size.value: + buf = ctypes.create_unicode_buffer(size.value) + + if GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, ctypes.byref(num), ctypes.byref(buf), ctypes.byref(size)): + return wszarray_to_list(buf) + + return [] + # singletons -Locale = Locale() -Translations = Translations() +Locale = _Locale() +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]?(['"])(((? None: # TODO(A_D): A bunch of these should be switched to default values (eg '' for strings) and no longer be Optional FileSystemEventHandler.__init__(self) # futureproofing - not need for current version of watchdog - self.root = None - self.currentdir: Optional[str] = None # The actual logdir that we're monitoring + self.root: 'tkinter.Tk' = None # type: ignore # Don't use Optional[] - mypy thinks no methods + self.currentdir: Optional[str] = None # The actual logdir that we're monitoring self.logfile: Optional[str] = None - self.observer = None - self.observed = None # a watchdog ObservedWatch, or None if polling + self.observer: Optional['Observer'] = None + self.observed = None # a watchdog ObservedWatch, or None if polling self.thread: Optional[threading.Thread] = None - self.event_queue = [] # For communicating journal entries back to main thread + # For communicating journal entries back to main thread + self.event_queue: queue.Queue = queue.Queue(maxsize=0) # On startup we might be: # 1) Looking at an old journal file because the game isn't running or the user has exited to the main menu. @@ -92,45 +103,72 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below self.station: Optional[str] = None self.station_marketid: Optional[int] = None self.stationtype: Optional[str] = None - self.coordinates: Optional[Tuple[int, int, int]] = None + self.coordinates: Optional[Tuple[float, float, float]] = None self.systemaddress: Optional[int] = None + self.systempopulation: Optional[int] = None self.started: Optional[int] = None # Timestamp of the LoadGame event + self.__init_state() + + def __init_state(self) -> None: # Cmdr state shared with EDSM and plugins # If you change anything here update PLUGINS.md documentation! - self.state = { - 'Captain': None, # On a crew - 'Cargo': defaultdict(int), - 'Credits': None, - 'FID': None, # Frontier Cmdr ID - 'Horizons': None, # Does this user have Horizons? - 'Loan': None, - 'Raw': defaultdict(int), - 'Manufactured': defaultdict(int), - 'Encoded': defaultdict(int), - 'Engineers': {}, - 'Rank': {}, - 'Reputation': {}, - 'Statistics': {}, - 'Role': None, # Crew role - None, Idle, FireCon, FighterCon - 'Friends': set(), # Online friends - 'ShipID': None, - 'ShipIdent': None, - 'ShipName': None, - 'ShipType': None, - 'HullValue': None, - 'ModulesValue': None, - 'Rebuy': None, - 'Modules': None, - 'CargoJSON': None, # The raw data from the last time cargo.json was read + self.state: Dict = { + 'Captain': None, # On a crew + 'Cargo': defaultdict(int), + 'Credits': None, + 'FID': None, # Frontier Cmdr ID + 'Horizons': None, # Does this user have Horizons? + 'Loan': None, + 'Raw': defaultdict(int), + 'Manufactured': defaultdict(int), + 'Encoded': defaultdict(int), + 'Engineers': {}, + 'Rank': {}, + 'Reputation': {}, + 'Statistics': {}, + 'Role': None, # Crew role - None, Idle, FireCon, FighterCon + 'Friends': set(), # Online friends + 'ShipID': None, + 'ShipIdent': None, + 'ShipName': None, + 'ShipType': None, + 'HullValue': None, + 'ModulesValue': None, + 'Rebuy': None, + 'Modules': None, + 'CargoJSON': None, # The raw data from the last time cargo.json was read + 'Route': None, # Last plotted route from Route.json file + 'OnFoot': False, # Whether we think you're on-foot + 'Component': defaultdict(int), # Odyssey Components in Ship Locker + 'Item': defaultdict(int), # Odyssey Items in Ship Locker + 'Consumable': defaultdict(int), # Odyssey Consumables in Ship Locker + 'Data': defaultdict(int), # Odyssey Data in Ship Locker + 'BackPack': { # Odyssey BackPack contents + 'Component': defaultdict(int), # BackPack Components + 'Consumable': defaultdict(int), # BackPack Consumables + 'Item': defaultdict(int), # BackPack Items + 'Data': defaultdict(int), # Backpack Data + }, + 'SuitCurrent': None, + 'Suits': {}, + 'SuitLoadoutCurrent': None, + 'SuitLoadouts': {}, } - def start(self, root: 'tkinter.Tk'): - self.root = root - journal_dir = config.get('journaldir') or config.default_journal_dir + def start(self, root: 'tkinter.Tk') -> bool: # noqa: CCR001 + """ + Start journal monitoring. - if journal_dir is None: - journal_dir = '' + :param root: The parent Tk window. + :return: bool - False if we couldn't access/find latest Journal file. + """ + logger.debug('Begin...') + self.root = root # type: ignore + journal_dir = config.get_str('journaldir') + + if journal_dir == '' or journal_dir is None: + journal_dir = config.default_journal_dir # TODO(A_D): this is ignored for type checking due to all the different types config.get returns # When that is refactored, remove the magic comment @@ -166,31 +204,40 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below # 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. - polling = bool(config.get('journaldir')) and platform != 'win32' + polling = bool(config.get_str('journaldir')) and platform != 'win32' if not polling and not self.observer: + logger.debug('Not polling, no observer, starting an observer...') self.observer = Observer() self.observer.daemon = True self.observer.start() + logger.debug('Done') elif polling and self.observer: + logger.debug('Polling, but observer, so stopping observer...') self.observer.stop() self.observer = None + logger.debug('Done') if not self.observed and not polling: - self.observed = self.observer.schedule(self, self.currentdir) + logger.debug('Not observed and not polling, setting observed...') + self.observed = self.observer.schedule(self, self.currentdir) # type: ignore + logger.debug('Done') logger.info(f'{"Polling" if polling else "Monitoring"} Journal Folder: "{self.currentdir}"') logger.info(f'Start Journal File: "{self.logfile}"') if not self.running(): - logger.debug('Starting Journal worker') + logger.debug('Starting Journal worker thread...') self.thread = threading.Thread(target=self.worker, name='Journal worker') self.thread.daemon = True self.thread.start() + logger.debug('Done') + logger.debug('Done.') return True - def stop(self): + def stop(self) -> None: + """Stop journal monitoring.""" logger.debug('Stopping monitoring Journal') self.currentdir = None @@ -207,31 +254,60 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below self.coordinates = None self.systemaddress = None self.is_beta = False + self.state['OnFoot'] = False + if self.observed: + logger.debug('self.observed: Calling unschedule_all()') self.observed = None self.observer.unschedule_all() + logger.debug('Done') self.thread = None # Orphan the worker thread - will terminate at next poll - def close(self): + logger.debug('Done.') + + def close(self) -> None: + """Close journal monitoring.""" + logger.debug('Calling self.stop()...') self.stop() - if self.observer: - self.observer.stop() + logger.debug('Done') if self.observer: + logger.debug('Calling self.observer.stop()...') + self.observer.stop() + logger.debug('Done') + + if self.observer: + logger.debug('Joining self.observer thread...') self.observer.join() self.observer = None + logger.debug('Done') - def running(self): - return self.thread and self.thread.is_alive() + logger.debug('Done.') - def on_created(self, event): - # watchdog callback, e.g. client (re)started. + def running(self) -> bool: + """ + Determine if Journal watching is active. + + :return: bool + """ + return bool(self.thread and self.thread.is_alive()) + + def on_created(self, event: 'FileCreatedEvent') -> None: + """Watchdog callback when, e.g. client (re)started.""" if not event.is_directory and self._RE_LOGFILE.search(basename(event.src_path)): self.logfile = event.src_path - def worker(self): + def worker(self) -> None: # noqa: C901, CCR001 + """ + Watch latest Journal file. + + 1. Keep track of the latest Journal file, switching to a new one if + needs be. + 2. Read in lines from the latest Journal file and queue them up for + get_entry() to process in the main thread. + """ # Tk isn't thread-safe in general. # event_generate() is the only safe way to poke the main thread from this thread: # https://mail.python.org/pipermail/tkinter-discuss/2013-November/003522.html @@ -246,18 +322,20 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below for line in loghandle: try: - if b'"event":"Location"' in line: - logger.trace('"Location" event in the past at startup') + # if b'"event":"Location"' in line: + # logger.trace('"Location" event in the past at startup') self.parse_entry(line) # Some events are of interest even in the past except Exception as ex: - logger.debug(f'Invalid journal entry:\n{line}\n', exc_info=ex) + logger.debug(f'Invalid journal entry:\n{line!r}\n', exc_info=ex) log_pos = loghandle.tell() else: - loghandle = None + loghandle = None # type: ignore + + logger.debug('Now at end of latest file.') self.game_was_running = self.game_running() @@ -283,17 +361,18 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below entry['StationType'] = self.stationtype entry['MarketID'] = self.station_marketid - self.event_queue.append(json.dumps(entry, separators=(', ', ':'))) + self.event_queue.put(json.dumps(entry, separators=(', ', ':'))) else: # Generate null event to update the display (with possibly out-of-date info) - self.event_queue.append(None) + self.event_queue.put(None) self.live = False # Watchdog thread -- there is a way to get this by using self.observer.emitters and checking for an attribute: # watch, but that may have unforseen differences in behaviour. emitter = self.observed and self.observer._emitter_for_watch[self.observed] # Note: Uses undocumented attribute + logger.debug('Entering loop...') while True: # Check whether new log file started, e.g. client (re)started. @@ -335,13 +414,14 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below logger.info("We're not meant to be running, exiting...") return # Terminate - if b'"event":"Location"' in line: - logger.trace('Found "Location" event, appending to event_queue') + # if b'"event":"Location"' in line: + # logger.trace('Found "Location" event, adding to event_queue') - self.event_queue.append(line) + self.event_queue.put(line) - if self.event_queue: + if not self.event_queue.empty(): if not config.shutting_down: + # logger.trace('Sending <>') self.root.event_generate('<>', when="tail") log_pos = loghandle.tell() @@ -351,16 +431,21 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below # Check whether we're still supposed to be running if threading.current_thread() != self.thread: logger.info("We're not meant to be running, exiting...") + if loghandle: + loghandle.close() + return # Terminate if self.game_was_running: if not self.game_running(): logger.info('Detected exit from game, synthesising ShutDown event') - self.event_queue.append( - '{{ "timestamp":"{}", "event":"ShutDown" }}'.format(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime())) + timestamp = strftime('%Y-%m-%dT%H:%M:%SZ', gmtime()) + self.event_queue.put( + f'{{ "timestamp":"{timestamp}", "event":"ShutDown" }}' ) if not config.shutting_down: + # logger.trace('Sending <>') self.root.event_generate('<>', when="tail") self.game_was_running = False @@ -368,7 +453,19 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below else: self.game_was_running = self.game_running() - def parse_entry(self, line: str): + logger.debug('Done.') + + def parse_entry(self, line: bytes) -> MutableMapping[str, Any]: # noqa: C901, CCR001 + """ + Parse a Journal JSON line. + + This augments some events, sets internal state in reaction to many and + loads some extra files, e.g. Cargo.json, as necessary. + + :param line: bytes - The entry being parsed. Yes, this is bytes, not str. + We rely on json.loads() dealing with this properly. + :return: Dict of the processed event. + """ # TODO(A_D): a bunch of these can be simplified to use if itertools.product and filters if line is None: return {'event': None} # Fake startup event @@ -396,36 +493,14 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below self.coordinates = None self.systemaddress = None self.started = None - self.state = { - 'Captain': None, - 'Cargo': defaultdict(int), - 'Credits': None, - 'FID': None, - 'Horizons': None, - 'Loan': None, - 'Raw': defaultdict(int), - 'Manufactured': defaultdict(int), - 'Encoded': defaultdict(int), - 'Engineers': {}, - 'Rank': {}, - 'Reputation': {}, - 'Statistics': {}, - 'Role': None, - 'Friends': set(), - 'ShipID': None, - 'ShipIdent': None, - 'ShipName': None, - 'ShipType': None, - 'HullValue': None, - 'ModulesValue': None, - 'Rebuy': None, - 'Modules': None, - } + self.__init_state() elif event_type == 'Commander': self.live = True # First event in 3.0 elif event_type == 'LoadGame': + # alpha4 + # Odyssey: bool self.cmdr = entry['Commander'] # 'Open', 'Solo', 'Group', or None for CQC (and Training - but no LoadGame event) self.mode = entry.get('GameMode') @@ -452,6 +527,8 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below 'Statistics': {}, 'Role': None, }) + if entry.get('Ship') is not None and self._RE_SHIP_ONFOOT.search(entry['Ship']): + self.state['OnFoot'] = True elif event_type == 'NewCommander': self.cmdr = entry['Name'] @@ -475,6 +552,8 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below self.state['Rebuy'] = None self.state['Modules'] = None + self.state['Credits'] -= entry.get('ShipPrice', 0) + elif event_type == 'ShipyardSwap': self.state['ShipID'] = entry['ShipID'] self.state['ShipIdent'] = None @@ -525,8 +604,21 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below 'Value': entry['BuyPrice'], } + self.state['Credits'] -= entry.get('BuyPrice', 0) + + elif event_type == 'ModuleRetrieve': + self.state['Credits'] -= entry.get('Cost', 0) + elif event_type == 'ModuleSell': self.state['Modules'].pop(entry['Slot'], None) + self.state['Credits'] += entry.get('SellPrice', 0) + + elif event_type == 'ModuleSellRemote': + self.state['Credits'] += entry.get('SellPrice', 0) + + elif event_type == 'ModuleStore': + self.state['Modules'].pop(entry['Slot'], None) + self.state['Credits'] -= entry.get('Cost', 0) elif event_type == 'ModuleSwap': to_item = self.state['Modules'].get(entry['ToSlot']) @@ -546,32 +638,100 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below self.stationtype = None self.stationservices = None - elif event_type in ('Location', 'FSDJump', 'Docked', 'CarrierJump'): + elif event_type == 'Embark': + # This event is logged when a player (on foot) gets into a ship or SRV + # Parameters: + # • SRV: true if getting into SRV, false if getting into a ship + # • Taxi: true when boarding a taxi transposrt ship + # • Multicrew: true when boarding another player’s vessel + # • ID: player’s ship ID (if players own vessel) + # • StarSystem + # • SystemAddress + # • Body + # • BodyID + # • OnStation: bool + # • OnPlanet: bool + # • StationName (if at a station) + # • StationType + # • MarketID + self.station = None + if entry.get('OnStation'): + self.station = entry.get('StationName', '') + + self.state['OnFoot'] = False + + elif event_type == 'Disembark': + # This event is logged when the player steps out of a ship or SRV + # + # Parameters: + # • SRV: true if getting out of SRV, false if getting out of a ship + # • Taxi: true when getting out of a taxi transposrt ship + # • Multicrew: true when getting out of another player’s vessel + # • ID: player’s ship ID (if players own vessel) + # • StarSystem + # • SystemAddress + # • Body + # • BodyID + # • OnStation: bool + # • OnPlanet: bool + # • StationName (if at a station) + # • StationType + # • MarketID + + if entry.get('OnStation', False): + self.station = entry.get('StationName', '') + + else: + self.station = None + + self.state['OnFoot'] = True + + elif event_type == 'DropshipDeploy': + # We're definitely on-foot now + self.state['OnFoot'] = True + + elif event_type == 'Docked': + self.station = entry.get('StationName') # May be None + self.station_marketid = entry.get('MarketID') # May be None + self.stationtype = entry.get('StationType') # May be None + self.stationservices = entry.get('StationServices') # None under E:D < 2.4 + + elif event_type in ('Location', 'FSDJump', 'CarrierJump'): + # alpha4 - any changes ? + # Location: + # New in Odyssey: + # • Taxi: bool + # • Multicrew: bool + # • InSRV: bool + # • OnFoot: bool if event_type in ('Location', 'CarrierJump'): self.planet = entry.get('Body') if entry.get('BodyType') == 'Planet' else None - if event_type == 'Location': - logger.trace('"Location" event') + # if event_type == 'Location': + # logger.trace('"Location" event') elif event_type == 'FSDJump': self.planet = None if 'StarPos' in entry: - self.coordinates = tuple(entry['StarPos']) - - elif self.system != entry['StarSystem']: - self.coordinates = None # Docked event doesn't include coordinates + self.coordinates = tuple(entry['StarPos']) # type: ignore self.systemaddress = entry.get('SystemAddress') - if event_type in ('Location', 'FSDJump', 'CarrierJump'): - self.systempopulation = entry.get('Population') + self.systempopulation = entry.get('Population') self.system = 'CQC' if entry['StarSystem'] == 'ProvingGround' else entry['StarSystem'] + self.station = entry.get('StationName') # May be None + # If on foot in-station 'Docked' is false, but we have a + # 'BodyType' of 'Station', and the 'Body' is the station name + # NB: No MarketID + if entry.get('BodyType') and entry['BodyType'] == 'Station': + self.station = entry.get('Body') + self.station_marketid = entry.get('MarketID') # May be None self.stationtype = entry.get('StationType') # May be None - self.stationservices = entry.get('StationServices') # None under E:D < 2.4 + self.stationservices = entry.get('StationServices') # None in Odyssey for on-foot 'Location' elif event_type == 'ApproachBody': self.planet = entry['Body'] @@ -627,10 +787,473 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below self.state['Cargo'].update({self.canonicalise(x['Name']): x['Count'] for x in clean}) + elif event_type == 'CargoTransfer': + for c in entry['Transfers']: + name = self.canonicalise(c['Type']) + if c['Direction'] == 'toship': + self.state['Cargo'][name] += c['Count'] + + else: + # So it's *from* the ship + self.state['Cargo'][name] -= c['Count'] + + elif event_type == 'ShipLockerMaterials': + # This event has the current totals, so drop any current data + self.state['Component'] = defaultdict(int) + self.state['Consumable'] = defaultdict(int) + self.state['Item'] = defaultdict(int) + self.state['Data'] = defaultdict(int) + # TODO: Really we need a full BackPackMaterials event at the same time. + # In lieu of that, empty the backpack. This will explicitly + # be wrong if Cmdr relogs at a Settlement with anything in + # backpack. + # Still no BackPackMaterials at the same time in 4.0.0.31 + self.state['BackPack']['Component'] = defaultdict(int) + self.state['BackPack']['Consumable'] = defaultdict(int) + self.state['BackPack']['Item'] = defaultdict(int) + self.state['BackPack']['Data'] = defaultdict(int) + + clean_components = self.coalesce_cargo(entry['Components']) + self.state['Component'].update( + {self.canonicalise(x['Name']): x['Count'] for x in clean_components} + ) + + clean_consumables = self.coalesce_cargo(entry['Consumables']) + self.state['Consumable'].update( + {self.canonicalise(x['Name']): x['Count'] for x in clean_consumables} + ) + + clean_items = self.coalesce_cargo(entry['Items']) + self.state['Item'].update( + {self.canonicalise(x['Name']): x['Count'] for x in clean_items} + ) + + clean_data = self.coalesce_cargo(entry['Data']) + self.state['Data'].update( + {self.canonicalise(x['Name']): x['Count'] for x in clean_data} + ) + + elif event_type == 'BackPackMaterials': + # alpha4 - + # Lists the contents of the backpack, eg when disembarking from ship + + # Assume this reflects the current state when written + self.state['BackPack']['Component'] = defaultdict(int) + self.state['BackPack']['Consumable'] = defaultdict(int) + self.state['BackPack']['Item'] = defaultdict(int) + self.state['BackPack']['Data'] = defaultdict(int) + + clean_components = self.coalesce_cargo(entry['Components']) + self.state['BackPack']['Component'].update( + {self.canonicalise(x['Name']): x['Count'] for x in clean_components} + ) + + clean_consumables = self.coalesce_cargo(entry['Consumables']) + self.state['BackPack']['Consumable'].update( + {self.canonicalise(x['Name']): x['Count'] for x in clean_consumables} + ) + + clean_items = self.coalesce_cargo(entry['Items']) + self.state['BackPack']['Item'].update( + {self.canonicalise(x['Name']): x['Count'] for x in clean_items} + ) + + clean_data = self.coalesce_cargo(entry['Data']) + self.state['BackPack']['Data'].update( + {self.canonicalise(x['Name']): x['Count'] for x in clean_data} + ) + + elif event_type == 'BuyMicroResources': + # Buying from a Pioneer Supplies, goes directly to ShipLocker. + # One event per Item, not an array. + category = self.category(entry['Category']) + name = self.canonicalise(entry['Name']) + self.state[category][name] += entry['Count'] + + self.state['Credits'] -= entry.get('Price', 0) + + elif event_type == 'SellMicroResources': + # Selling to a Bar Tender on-foot. + self.state['Credits'] += entry.get('Price', 0) + # One event per whole sale, so it's an array. + for mr in entry['MicroResources']: + category = self.category(mr['Category']) + name = self.canonicalise(mr['Name']) + self.state[category][name] -= mr['Count'] + + elif event_type == 'TradeMicroResources': + # Trading some MicroResources for another at a Bar Tender + # 'Offered' is what we traded away + for offer in entry['Offered']: + category = self.category(offer['Category']) + name = self.canonicalise(offer['Name']) + self.state[category][name] -= offer['Count'] + + # For a single item name received + category = self.category(entry['Category']) + name = self.canonicalise(entry['Received']) + self.state[category][name] += entry['Count'] + + elif event_type == 'TransferMicroResources': + # Moving Odyssey MicroResources between ShipLocker and BackPack + for mr in entry['Transfers']: + category = self.category(mr['Category']) + name = self.canonicalise(mr['Name']) + + if mr['Direction'] == 'ToShipLocker': + self.state[category][name] += mr['Count'] + self.state['BackPack'][category][name] -= mr['Count'] + + elif mr['Direction'] == 'ToBackpack': + self.state[category][name] -= mr['Count'] + self.state['BackPack'][category][name] += mr['Count'] + + else: + logger.warning(f'TransferMicroResources with unexpected Direction {mr["Direction"]=}: {mr=}') + + # Paranoia check to see if anything has gone negative. + # As of Odyssey Alpha Phase 1 Hotfix 2 keeping track of BackPack + # materials is impossible when used/picked up anyway. + for c in self.state['BackPack']: + for m in self.state['BackPack'][c]: + if self.state['BackPack'][c][m] < 0: + self.state['BackPack'][c][m] = 0 + + elif event_type == 'CollectItems': + # alpha4 + # When picking up items from the ground + # Parameters: + # • Name + # • Type + # • OwnerID + for i in self.state['BackPack'][entry['Type']]: + if i == entry['Name']: + self.state['BackPack'][entry['Type']][i] += entry['Count'] + + elif event_type == 'DropItems': + # alpha4 + # Parameters: + # • Name + # • Type + # • OwnerID + # • MissionID + # • Count + for i in self.state['BackPack'][entry['Type']]: + if i == entry['Name']: + self.state['BackPack'][entry['Type']][i] -= entry['Count'] + # Paranoia in case we lost track + if self.state['BackPack'][entry['Type']][i] < 0: + self.state['BackPack'][entry['Type']][i] = 0 + + elif event_type == 'UseConsumable': + # alpha4 + # When using an item from the player’s inventory (backpack) + # + # Parameters: + # • Name + # • Type + for c in self.state['BackPack']['Consumable']: + if c == entry['Name']: + self.state['BackPack']['Consumable'][c] -= 1 + # Paranoia in case we lost track + if self.state['BackPack']['Consumable'][c] < 0: + self.state['BackPack']['Consumable'][c] = 0 + + elif event_type == 'SwitchSuitLoadout': + loadoutid = entry['LoadoutID'] + new_slot = self.suit_loadout_id_from_loadoutid(loadoutid) + # If this application is run with the latest Journal showing such an event then we won't + # yet have the CAPI data, so no idea about Suits or Loadouts. + if self.state['Suits'] and self.state['SuitLoadouts']: + try: + self.state['SuitLoadoutCurrent'] = self.state['SuitLoadouts'][f'{new_slot}'] + + except KeyError: + logger.debug(f"KeyError getting suit loadout after switch, bad slot: {new_slot} ({loadoutid})") + self.state['SuitCurrent'] = None + self.state['SuitLoadoutCurrent'] = None + + else: + try: + new_suitid = self.state['SuitLoadoutCurrent']['suit']['suitId'] + + except KeyError: + logger.debug(f"KeyError getting switched-to suit ID from slot {new_slot} ({loadoutid})") + + else: + try: + self.state['SuitCurrent'] = self.state['Suits'][f'{new_suitid}'] + + except KeyError: + logger.debug(f"KeyError getting switched-to suit from slot {new_slot} ({loadoutid}") + + elif event_type == 'CreateSuitLoadout': + # We know we won't have data for this new one + # Parameters: + # • SuitID + # • SuitName + # • LoadoutID + # • LoadoutName + # alpha4: + # { "timestamp":"2021-04-29T09:37:08Z", "event":"CreateSuitLoadout", "SuitID":1698364940285172, + # "SuitName":"tacticalsuit_class1", "SuitName_Localised":"Dominator Suit", "LoadoutID":4293000001, + # "LoadoutName":"Dom L/K/K", "Modules":[ + # { + # "SlotName":"PrimaryWeapon1", + # "SuitModuleID":1698364962722310, + # "ModuleName":"wpn_m_assaultrifle_laser_fauto", + # "ModuleName_Localised":"TK Aphelion" + # }, + # { "SlotName":"PrimaryWeapon2", + # "SuitModuleID":1698364956302993, "ModuleName":"wpn_m_assaultrifle_kinetic_fauto", + # "ModuleName_Localised":"Karma AR-50" }, { "SlotName":"SecondaryWeapon", + # "SuitModuleID":1698292655291850, "ModuleName":"wpn_s_pistol_kinetic_sauto", + # "ModuleName_Localised":"Karma P-15" } ] } + new_loadout = { + 'loadoutSlotId': self.suit_loadout_id_from_loadoutid(entry['LoadoutID']), + 'suit': { + 'name': entry['SuitName'], + 'locName': entry.get('SuitName_Localised', entry['SuitName']), + 'suitId': entry['SuitID'], + }, + 'name': entry['LoadoutName'], + 'slots': self.suit_loadout_slots_array_to_dict(entry['Modules']), + } + self.state['SuitLoadouts'][new_loadout['loadoutSlotId']] = new_loadout + + elif event_type == 'DeleteSuitLoadout': + # alpha4: + # { "timestamp":"2021-04-29T10:32:27Z", "event":"DeleteSuitLoadout", "SuitID":1698365752966423, + # "SuitName":"explorationsuit_class1", "SuitName_Localised":"Artemis Suit", "LoadoutID":4293000003, + # "LoadoutName":"Loadout 1" } + + if self.state['SuitLoadouts']: + loadout_id = self.suit_loadout_id_from_loadoutid(entry['LoadoutID']) + try: + self.state['SuitLoadouts'].pop(f'{loadout_id}') + + except KeyError: + # This should no longer happen, as we're now handling CreateSuitLoadout properly + logger.debug(f"loadout slot id {loadout_id} doesn't exist, not in last CAPI pull ?") + + elif event_type == 'RenameSuitLoadout': + # alpha4 + # Parameters: + # • SuitID + # • SuitName + # • LoadoutID + # • Loadoutname + # alpha4: + # { "timestamp":"2021-04-29T10:35:55Z", "event":"RenameSuitLoadout", "SuitID":1698365752966423, + # "SuitName":"explorationsuit_class1", "SuitName_Localised":"Artemis Suit", "LoadoutID":4293000003, + # "LoadoutName":"Art L/K" } + if self.state['SuitLoadouts']: + loadout_id = self.suit_loadout_id_from_loadoutid(entry['LoadoutID']) + try: + self.state['SuitLoadouts'][loadout_id]['name'] = entry['LoadoutName'] + + except KeyError: + logger.debug(f"loadout slot id {loadout_id} doesn't exist, not in last CAPI pull ?") + + elif event_type == 'BuySuit': + # alpha4 : + # { "timestamp":"2021-04-29T09:03:37Z", "event":"BuySuit", "Name":"UtilitySuit_Class1", + # "Name_Localised":"Maverick Suit", "Price":150000, "SuitID":1698364934364699 } + self.state['Suits'][entry['SuitID']] = { + 'name': entry['Name'], + 'locName': entry.get('Name_Localised', entry['Name']), + 'id': None, # Is this an FDev ID for suit type ? + 'suitId': entry['SuitID'], + 'slots': [], + } + + # update credits + if price := entry.get('Price') is None: + logger.error(f"BuySuit didn't contain Price: {entry}") + + else: + self.state['Credits'] -= price + + elif event_type == 'SellSuit': + # Remove from known suits + # As of Odyssey Alpha Phase 2, Hotfix 5 (4.0.0.13) this isn't possible as this event + # doesn't contain the specific suit ID as per CAPI `suits` dict. + # alpha4 + # This event is logged when a player sells a flight suit + # + # Parameters: + # • Name + # • Price + # • SuitID + # alpha4: + # { "timestamp":"2021-04-29T09:15:51Z", "event":"SellSuit", "SuitID":1698364937435505, + # "Name":"explorationsuit_class1", "Name_Localised":"Artemis Suit", "Price":90000 } + if self.state['Suits']: + try: + self.state['Suits'].pop(entry['SuitID']) + + except KeyError: + logger.debug(f"SellSuit for a suit we didn't know about? {entry['SuitID']}") + + # update credits total + if price := entry.get('Price') is None: + logger.error(f"SellSuit didn't contain Price: {entry}") + + else: + self.state['Credits'] += price + + elif event_type == 'UpgradeSuit': + # alpha4 + # This event is logged when the player upgrades their flight suit + # + # Parameters: + # • Name + # • SuitID + # • Class + # • Cost + # Update credits total ? It shouldn't even involve credits! + # Actual alpha4 - need to grind mats + # if self.state['Suits']: + pass + + elif event_type == 'LoadoutEquipModule': + # alpha4: + # { "timestamp":"2021-04-29T11:11:13Z", "event":"LoadoutEquipModule", "LoadoutName":"Dom L/K/K", + # "SuitID":1698364940285172, "SuitName":"tacticalsuit_class1", "SuitName_Localised":"Dominator Suit", + # "LoadoutID":4293000001, "SlotName":"PrimaryWeapon2", "ModuleName":"wpn_m_assaultrifle_laser_fauto", + # "ModuleName_Localised":"TK Aphelion", "SuitModuleID":1698372938719590 } + if self.state['SuitLoadouts']: + loadout_id = self.suit_loadout_id_from_loadoutid(entry['LoadoutID']) + try: + self.state['SuitLoadouts'][loadout_id]['slots'][entry['SlotName']] = { + 'name': entry['ModuleName'], + 'locName': entry.get('ModuleName_Localised', entry['ModuleName']), + 'id': None, + 'weaponrackId': entry['SuitModuleID'], + 'locDescription': '', + } + + except KeyError: + logger.error(f"LoadoutEquipModule: {entry}") + + elif event_type == 'LoadoutRemoveModule': + # alpha4 - triggers if selecting an already-equipped weapon into a different slot + # { "timestamp":"2021-04-29T11:11:13Z", "event":"LoadoutRemoveModule", "LoadoutName":"Dom L/K/K", + # "SuitID":1698364940285172, "SuitName":"tacticalsuit_class1", "SuitName_Localised":"Dominator Suit", + # "LoadoutID":4293000001, "SlotName":"PrimaryWeapon1", "ModuleName":"wpn_m_assaultrifle_laser_fauto", + # "ModuleName_Localised":"TK Aphelion", "SuitModuleID":1698372938719590 } + if self.state['SuitLoadouts']: + loadout_id = self.suit_loadout_id_from_loadoutid(entry['LoadoutID']) + try: + self.state['SuitLoadouts'][loadout_id]['slots'].pop(entry['SlotName']) + + except KeyError: + logger.error(f"LoadoutRemoveModule: {entry}") + + elif event_type == 'BuyWeapon': + # alpha4 + # { "timestamp":"2021-04-29T11:10:51Z", "event":"BuyWeapon", "Name":"Wpn_M_AssaultRifle_Laser_FAuto", + # "Name_Localised":"TK Aphelion", "Price":125000, "SuitModuleID":1698372938719590 } + # update credits + if price := entry.get('Price') is None: + logger.error(f"BuyWeapon didn't contain Price: {entry}") + + else: + self.state['Credits'] -= price + + elif event_type == 'SellWeapon': + # We're not actually keeping track of all owned weapons, only those in + # Suit Loadouts. + # alpha4: + # { "timestamp":"2021-04-29T10:50:34Z", "event":"SellWeapon", "Name":"wpn_m_assaultrifle_laser_fauto", + # "Name_Localised":"TK Aphelion", "Price":75000, "SuitModuleID":1698364962722310 } + + # We need to look over all Suit Loadouts for ones that used this specific weapon + # and update them to entirely empty that slot. + for sl in self.state['SuitLoadouts']: + for w in self.state['SuitLoadouts'][sl]['slots']: + if self.state['SuitLoadouts'][sl]['slots'][w]['weaponrackId'] == entry['SuitModuleID']: + self.state['SuitLoadouts'][sl]['slots'].pop(w) + # We've changed the dict, so iteration breaks, but also the weapon + # could only possibly have been here once. + break + + # Update credits total + if price := entry.get('Price') is None: + logger.error(f"SellWeapon didn't contain Price: {entry}") + + else: + self.state['Credits'] += price + + elif event_type == 'UpgradeWeapon': + # We're not actually keeping track of all owned weapons, only those in + # Suit Loadouts. + # alpha4 - credits? Shouldn't cost any! + pass + + elif event_type == 'ScanOrganic': + # Nothing of interest to our state. + pass + + elif event_type == 'SellOrganicData': + for bd in entry['BioData']: + self.state['Credits'] += bd.get('Value', 0) + bd.get('Bonus', 0) + + elif event_type == 'BookDropship': + self.state['Credits'] -= entry.get('Cost', 0) + # Technically we *might* now not be OnFoot. + # The problem is that this event is recorded both for signing up for + # an on-foot CZ, and when you use the Dropship to return after the + # CZ completes. + # + # In the first case we're still in-station and thus still on-foot. + # + # In the second case we should instantly be in the Dropship and thus + # not still on-foot, BUT it doesn't really matter as the next significant + # event is going to be Disembark to on-foot anyway. + + elif event_type == 'BookTaxi': + self.state['Credits'] -= entry.get('Cost', 0) + + elif event_type == 'CancelDropship': + self.state['Credits'] += entry.get('Refund', 0) + + elif event_type == 'CancelTaxi': + self.state['Credits'] += entry.get('Refund', 0) + + elif event_type == 'NavRoute': + # Added in ED 3.7 - multi-hop route details in NavRoute.json + with open(join(self.currentdir, 'NavRoute.json'), 'rb') as rf: # type: ignore + try: + entry = json.load(rf) + + except json.JSONDecodeError: + logger.exception('Failed decoding NavRoute.json', exc_info=True) + + else: + self.state['NavRoute'] = entry + + elif event_type == 'ModuleInfo': + with open(join(self.currentdir, 'ModulesInfo.json'), 'rb') as mf: # type: ignore + try: + entry = json.load(mf) + + except json.JSONDecodeError: + logger.exception('Failed decoding ModulesInfo.json', exc_info=True) + + else: + self.state['ModuleInfo'] = entry + elif event_type in ('CollectCargo', 'MarketBuy', 'BuyDrones', 'MiningRefined'): commodity = self.canonicalise(entry['Type']) self.state['Cargo'][commodity] += entry.get('Count', 1) + if event_type == 'BuyDrones': + self.state['Credits'] -= entry.get('TotalCost', 0) + + elif event_type == 'MarketBuy': + self.state['Credits'] -= entry.get('TotalCost', 0) + elif event_type in ('EjectCargo', 'MarketSell', 'SellDrones'): commodity = self.canonicalise(entry['Type']) cargo = self.state['Cargo'] @@ -638,6 +1261,12 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below if cargo[commodity] <= 0: cargo.pop(commodity) + if event_type == 'MarketSell': + self.state['Credits'] += entry.get('TotalSale', 0) + + elif event_type == 'SellDrones': + self.state['Credits'] += entry.get('TotalSale', 0) + elif event_type == 'SearchAndRescue': for item in entry.get('Items', []): commodity = self.canonicalise(item['Name']) @@ -719,6 +1348,8 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below module['Engineering'].pop('ExperimentalEffect_Localised', None) elif event_type == 'MissionCompleted': + self.state['Credits'] += entry.get('Reward', 0) + for reward in entry.get('CommodityReward', []): commodity = self.canonicalise(reward['Name']) self.state['Cargo'][commodity] += reward.get('Count', 1) @@ -777,6 +1408,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below self.stationservices = None self.coordinates = None self.systemaddress = None + self.state['OnFoot'] = False elif event_type == 'ChangeCrewRole': self.state['Role'] = entry['Role'] @@ -792,6 +1424,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below self.stationservices = None self.coordinates = None self.systemaddress = None + # TODO: on_foot: Will we get an event after this to know ? elif event_type == 'Friends': if entry['Status'] in ('Online', 'Added'): @@ -800,16 +1433,109 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below else: self.state['Friends'].discard(entry['Name']) + # Try to keep Credits total updated + elif event_type in ('MultiSellExplorationData', 'SellExplorationData'): + self.state['Credits'] += entry.get('TotalEarnings', 0) + + elif event_type == 'BuyExplorationData': + self.state['Credits'] -= entry.get('Cost', 0) + + elif event_type == 'BuyTradeData': + self.state['Credits'] -= entry.get('Cost', 0) + + elif event_type == 'BuyAmmo': + self.state['Credits'] -= entry.get('Cost', 0) + + elif event_type == 'CommunityGoalReward': + self.state['Credits'] += entry.get('Reward', 0) + + elif event_type == 'CrewHire': + self.state['Credits'] -= entry.get('Cost', 0) + + elif event_type == 'FetchRemoteModule': + self.state['Credits'] -= entry.get('TransferCost', 0) + + elif event_type == 'MissionAbandoned': + # Is this paid at this point, or just a fine to pay later ? + # self.state['Credits'] -= entry.get('Fine', 0) + pass + + elif event_type in ('PayBounties', 'PayFines', 'PayLegacyFines'): + self.state['Credits'] -= entry.get('Amount', 0) + + elif event_type == 'RedeemVoucher': + self.state['Credits'] += entry.get('Amount', 0) + + elif event_type in ('RefuelAll', 'RefuelPartial', 'Repair', 'RepairAll', 'RestockVehicle'): + self.state['Credits'] -= entry.get('Cost', 0) + + elif event_type == 'SellShipOnRebuy': + self.state['Credits'] += entry.get('ShipPrice', 0) + + elif event_type == 'ShipyardSell': + self.state['Credits'] += entry.get('ShipPrice', 0) + + elif event_type == 'ShipyardTransfer': + self.state['Credits'] -= entry.get('TransferPrice', 0) + + elif event_type == 'PowerplayFastTrack': + self.state['Credits'] -= entry.get('Cost', 0) + + elif event_type == 'PowerplaySalary': + self.state['Credits'] += entry.get('Amount', 0) + + elif event_type == 'SquadronCreated': + # v30 docs don't actually say anything about credits cost + pass + + elif event_type == 'CarrierBuy': + self.state['Credits'] -= entry.get('Price', 0) + + elif event_type == 'CarrierBankTransfer': + if (newbal := entry.get('PlayerBalance')): + self.state['Credits'] = newbal + + elif event_type == 'CarrierDecommission': + # v30 doc says nothing about citing the refund amount + pass + + elif event_type == 'NpcCrewPaidWage': + self.state['Credits'] -= entry.get('Amount', 0) + + elif event_type == 'Resurrect': + self.state['Credits'] -= entry.get('Cost', 0) + return entry + except Exception as ex: - logger.debug(f'Invalid journal entry:\n{line}\n', exc_info=ex) + logger.debug(f'Invalid journal entry:\n{line!r}\n', exc_info=ex) return {'event': None} - # Commodities, Modules and Ships can appear in different forms e.g. "$HNShockMount_Name;", "HNShockMount", - # and "hnshockmount", "$int_cargorack_size6_class1_name;" and "Int_CargoRack_Size6_Class1", - # "python" and "Python", etc. - # This returns a simple lowercased name e.g. 'hnshockmount', 'int_cargorack_size6_class1', 'python', etc - def canonicalise(self, item: Optional[str]): + def suit_loadout_id_from_loadoutid(self, journal_loadoutid: int) -> int: + """ + Determine the CAPI-oriented numeric slot id for a Suit Loadout. + + :param journal_loadoutid: Journal `LoadoutID` integer value. + :return: + """ + # Observed LoadoutID in SwitchSuitLoadout events are, e.g. + # 4293000005 for CAPI slot 5. + # This *might* actually be "lower 6 bits", but maybe it's not. + slotid = journal_loadoutid - 4293000000 + return slotid + + def canonicalise(self, item: Optional[str]) -> str: + """ + Produce canonical name for a ship module. + + Commodities, Modules and Ships can appear in different forms e.g. "$HNShockMount_Name;", "HNShockMount", + and "hnshockmount", "$int_cargorack_size6_class1_name;" and "Int_CargoRack_Size6_Class1", + "python" and "Python", etc. + This returns a simple lowercased name e.g. 'hnshockmount', 'int_cargorack_size6_class1', 'python', etc + + :param item: str - 'Found' name of the item. + :return: str - The canonical name. + """ if not item: return '' @@ -821,7 +1547,13 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below return item - def category(self, item: str): + def category(self, item: str) -> str: + """ + Determine the category of an item. + + :param item: str - The item in question. + :return: str - The category for this item. + """ match = self._RE_CATEGORY.match(item) if match: @@ -829,7 +1561,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below return item.capitalize() - def get_entry(self) -> Union[OrderedDictT[str, Any], None]: + def get_entry(self) -> Optional[MutableMapping[str, Any]]: """ Pull the next Journal event from the event_queue. @@ -839,62 +1571,71 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below logger.debug('Called whilst self.thread is None, returning') return None - if not self.event_queue: - logger.trace('Called with no event_queue') + # logger.trace('Begin') + if self.event_queue.empty() and self.game_running(): + logger.error('event_queue is empty whilst game_running, this should not happen, returning') return None - else: - entry = self.parse_entry(self.event_queue.pop(0)) + # logger.trace('event_queue NOT empty') + entry = self.parse_entry(self.event_queue.get_nowait()) - if entry['event'] == 'Location': - logger.trace('"Location" event') + # if entry['event'] == 'Location': + # logger.trace('"Location" event') - if not self.live and entry['event'] not in (None, 'Fileheader'): - # Game not running locally, but Journal has been updated - self.live = True - if self.station: - entry = OrderedDict([ - ('timestamp', strftime('%Y-%m-%dT%H:%M:%SZ', gmtime())), - ('event', 'StartUp'), - ('Docked', True), - ('MarketID', self.station_marketid), - ('StationName', self.station), - ('StationType', self.stationtype), - ('StarSystem', self.system), - ('StarPos', self.coordinates), - ('SystemAddress', self.systemaddress), - ]) + if not self.live and entry['event'] not in (None, 'Fileheader'): + # Game not running locally, but Journal has been updated + self.live = True + if self.station: + entry = OrderedDict([ + ('timestamp', strftime('%Y-%m-%dT%H:%M:%SZ', gmtime())), + ('event', 'StartUp'), + ('Docked', True), + ('MarketID', self.station_marketid), + ('StationName', self.station), + ('StationType', self.stationtype), + ('StarSystem', self.system), + ('StarPos', self.coordinates), + ('SystemAddress', self.systemaddress), + ]) - else: - entry = OrderedDict([ - ('timestamp', strftime('%Y-%m-%dT%H:%M:%SZ', gmtime())), - ('event', 'StartUp'), - ('Docked', False), - ('StarSystem', self.system), - ('StarPos', self.coordinates), - ('SystemAddress', self.systemaddress), - ]) + else: + entry = OrderedDict([ + ('timestamp', strftime('%Y-%m-%dT%H:%M:%SZ', gmtime())), + ('event', 'StartUp'), + ('Docked', False), + ('StarSystem', self.system), + ('StarPos', self.coordinates), + ('SystemAddress', self.systemaddress), + ]) - if entry['event'] == 'Location': - logger.trace('Appending "Location" event to event_queue') + # if entry['event'] == 'Location': + # logger.trace('Appending "Location" event to event_queue') - self.event_queue.append(json.dumps(entry, separators=(', ', ':'))) + self.event_queue.put(json.dumps(entry, separators=(', ', ':'))) - elif self.live and entry['event'] == 'Music' and entry.get('MusicTrack') == 'MainMenu': - self.event_queue.append( - '{{ "timestamp":"{}", "event":"ShutDown" }}'.format(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime())) - ) + elif self.live and entry['event'] == 'Music' and entry.get('MusicTrack') == 'MainMenu': + ts = strftime('%Y-%m-%dT%H:%M:%SZ', gmtime()) + self.event_queue.put( + f'{{ "timestamp":"{ts}", "event":"ShutDown" }}' + ) - return entry + return entry - def game_running(self): + def game_running(self) -> bool: # noqa: CCR001 + """ + Determine if the game is currently running. + + TODO: Implement on Linux + + :return: bool - True if the game is running. + """ if platform == 'darwin': for app in NSWorkspace.sharedWorkspace().runningApplications(): if app.bundleIdentifier() == 'uk.co.frontier.EliteDangerous': return True elif platform == 'win32': - def WindowTitle(h): + def WindowTitle(h): # noqa: N802 # type: ignore if h: length = GetWindowTextLength(h) + 1 buf = ctypes.create_unicode_buffer(length) @@ -902,7 +1643,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below return buf.value return None - def callback(hWnd, lParam): + def callback(hWnd, lParam): # noqa: N803 name = WindowTitle(hWnd) if name and name.startswith('Elite - Dangerous'): handle = GetProcessHandleFromHwnd(hWnd) @@ -916,8 +1657,15 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below return False - # Return a subset of the received data describing the current ship as a Loadout event - def ship(self, timestamped=True): + def ship(self, timestamped=True) -> Optional[MutableMapping[str, Any]]: + """ + Produce a subset of data for the current ship. + + Return a subset of the received data describing the current ship as a Loadout event. + + :param timestamped: bool - Whether to add a 'timestamp' member. + :return: dict + """ if not self.state['Modules']: return None @@ -926,7 +1674,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below 'PowerDistributor', 'Radar', 'FuelTank' ) - d = OrderedDict() + d: MutableMapping[str, Any] = OrderedDict() if timestamped: d['timestamp'] = strftime('%Y-%m-%dT%H:%M:%SZ', gmtime()) @@ -960,8 +1708,15 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below return d - # Export ship loadout as a Loadout event - def export_ship(self, filename=None): + def export_ship(self, filename=None) -> None: # noqa: C901, CCR001 + """ + Export ship loadout as a Loadout event. + + Writes either to the specified filename or to a formatted filename based on + the ship name and a date+timestamp. + + :param filename: Name of file to write to, if not default. + """ # TODO(A_D): Some type checking has been disabled in here due to config.get getting weird outputs string = json.dumps(self.ship(False), ensure_ascii=False, indent=2, separators=(',', ': ')) # pretty print if filename: @@ -988,31 +1743,39 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below return - ship = ship_file_name(self.state['ShipName'], self.state['ShipType']) + 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('outdir')) if regexp.match(x))) # type: ignore + oldfiles = sorted((x for x in listdir(config.get_str('outdir')) if regexp.match(x))) # type: ignore if oldfiles: try: - with open(join(config.get('outdir'), oldfiles[-1]), 'rU', encoding='utf-8') as h: # type: ignore + with open(join(config.get_str('outdir'), oldfiles[-1]), 'r', encoding='utf-8') as h: # type: ignore 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('outdir'), oldfiles[-1]), 'rU') as h: # type: ignore + with open(join(config.get_str('outdir'), oldfiles[-1]), 'r') as h: # type: ignore if h.read() == string: return # same as last time - don't write except OSError: logger.exception("OSError reading old ship loadout default encoding.") + except ValueError: + # User was on $OtherEncoding, updated windows to be sane and use utf8 everywhere, thus + # the above open() fails, likely with a UnicodeDecodeError, which subclasses UnicodeError which + # subclasses ValueError, this catches ValueError _instead_ of UnicodeDecodeError just to be sure + # that if some other encoding error crops up we grab it too. + logger.exception('ValueError when reading old ship loadout default encoding') + except OSError: logger.exception("OSError reading old ship loadout with default encoding") # Write + ts = strftime('%Y-%m-%dT%H.%M.%S', localtime(time())) filename = join( # type: ignore - config.get('outdir'), '{}.{}.txt'.format(ship, strftime('%Y-%m-%dT%H.%M.%S', localtime(time()))) + config.get_str('outdir'), f'{ship}.{ts}.txt' ) try: @@ -1068,6 +1831,29 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below return out + def suit_loadout_slots_array_to_dict(self, loadout: dict) -> dict: + """ + Return a CAPI-style Suit loadout from a Journal style dict. + + :param loadout: e.g. Journal 'CreateSuitLoadout'->'Modules'. + :return: CAPI-style dict for a suit loadout. + """ + loadout_slots = {x['SlotName']: x for x in loadout} + slots = {} + for s in ('PrimaryWeapon1', 'PrimaryWeapon2', 'SecondaryWeapon'): + if loadout_slots.get(s) is None: + continue + + slots[s] = { + 'name': loadout_slots[s]['ModuleName'], + 'id': None, # FDevID ? + 'weaponrackId': loadout_slots[s]['SuitModuleID'], + 'locName': loadout_slots[s].get('ModuleName_Localised', loadout_slots[s]['ModuleName']), + 'locDescription': '', + } + + return slots + # singleton monitor = EDLogs() diff --git a/outfitting.py b/outfitting.py index 061cb4f3..e59aa8d0 100644 --- a/outfitting.py +++ b/outfitting.py @@ -1,377 +1,88 @@ -from collections import OrderedDict +"""Code dealing with ship outfitting.""" + import pickle +from collections import OrderedDict from os.path import join -import time +from typing import Optional +from typing import OrderedDict as OrderedDictT -import companion 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 EDMCLogging import get_main_logger - -# Map API module names to in-game names - -armour_map = OrderedDict([ - ('grade1', 'Lightweight Alloy'), - ('grade2', 'Reinforced Alloy'), - ('grade3', 'Military Grade Composite'), - ('mirrored', 'Mirrored Surface Composite'), - ('reactive', 'Reactive Surface Composite'), -]) - -weapon_map = { - 'advancedtorppylon' : 'Torpedo Pylon', - 'atdumbfiremissile' : 'AX Missile Rack', - 'atmulticannon' : 'AX Multi-Cannon', - 'basicmissilerack' : 'Seeker Missile Rack', - 'beamlaser' : 'Beam Laser', - ('beamlaser','heat') : 'Retributor Beam Laser', - 'cannon' : 'Cannon', - 'causticmissile' : 'Enzyme Missile Rack', - 'drunkmissilerack' : 'Pack-Hound Missile Rack', - 'dumbfiremissilerack' : 'Missile Rack', - ('dumbfiremissilerack', 'advanced') : 'Advanced Missile Rack', - ('dumbfiremissilerack', 'lasso') : 'Rocket Propelled FSD Disruptor', - 'flakmortar' : 'Remote Release Flak Launcher', - 'flechettelauncher' : 'Remote Release Flechette Launcher', - 'guardian_gausscannon' : 'Guardian Gauss Cannon', - 'guardian_plasmalauncher' : 'Guardian Plasma Charger', - 'guardian_shardcannon' : 'Guardian Shard Cannon', - 'minelauncher' : 'Mine Launcher', - ('minelauncher','impulse') : 'Shock Mine Launcher', - 'mining_abrblstr' : 'Abrasion Blaster', - 'mining_seismchrgwarhd' : 'Seismic Charge Launcher', - 'mining_subsurfdispmisle' : 'Sub-Surface Displacement Missile', - 'mininglaser' : 'Mining Laser', - ('mininglaser','advanced') : 'Mining Lance Beam Laser', - 'multicannon' : 'Multi-Cannon', - ('multicannon','advanced') : 'Advanced Multi-Cannon', - ('multicannon','strong') : 'Enforcer Cannon', - 'plasmaaccelerator' : 'Plasma Accelerator', - ('plasmaaccelerator','advanced') : 'Advanced Plasma Accelerator', - 'plasmashockcannon' : 'Shock Cannon', - 'pulselaser' : 'Pulse Laser', - ('pulselaser','disruptor') : 'Pulse Disruptor Laser', - 'pulselaserburst' : 'Burst Laser', - ('pulselaserburst','scatter') : 'Cytoscrambler Burst Laser', - 'railgun' : 'Rail Gun', - ('railgun','burst') : 'Imperial Hammer Rail Gun', - 'slugshot' : 'Fragment Cannon', - ('slugshot','range') : 'Pacifier Frag-Cannon', -} - -missiletype_map = { - 'advancedtorppylon' : 'Seeker', - 'atdumbfiremissile' : 'Dumbfire', - 'basicmissilerack' : 'Seeker', - 'causticmissile' : 'Dumbfire', - 'drunkmissilerack' : 'Swarm', - 'dumbfiremissilerack' : 'Dumbfire', - 'mining_subsurfdispmisle' : 'Seeker', - 'mining_seismchrgwarhd' : 'Seeker', -} - -weaponmount_map = { - 'fixed' : 'Fixed', - 'gimbal' : 'Gimballed', - 'turret' : 'Turreted', -} - -weaponclass_map = { - 'tiny' : '0', - 'small' : '1', - 'smallfree' : '1', - 'medium' : '2', - 'large' : '3', - 'huge' : '4', -} - -# There's no discernable pattern for weapon ratings, so here's a lookup table -weaponrating_map = { - 'hpt_advancedtorppylon_fixed_small' : 'I', - 'hpt_advancedtorppylon_fixed_medium': 'I', - 'hpt_advancedtorppylon_fixed_large' : 'I', - 'hpt_atdumbfiremissile_fixed_medium': 'B', - 'hpt_atdumbfiremissile_fixed_large' : 'A', - 'hpt_atdumbfiremissile_turret_medium': 'B', - 'hpt_atdumbfiremissile_turret_large' : 'A', - 'hpt_atmulticannon_fixed_medium' : 'E', - 'hpt_atmulticannon_fixed_large' : 'C', - 'hpt_atmulticannon_turret_medium' : 'F', - 'hpt_atmulticannon_turret_large' : 'E', - 'hpt_basicmissilerack_fixed_small' : 'B', - 'hpt_basicmissilerack_fixed_medium' : 'B', - 'hpt_basicmissilerack_fixed_large' : 'A', - 'hpt_beamlaser_fixed_small' : 'E', - 'hpt_beamlaser_fixed_medium' : 'D', - 'hpt_beamlaser_fixed_large': 'C', - 'hpt_beamlaser_fixed_huge': 'A', - 'hpt_beamlaser_gimbal_small': 'E', - 'hpt_beamlaser_gimbal_medium': 'D', - 'hpt_beamlaser_gimbal_large': 'C', - 'hpt_beamlaser_gimbal_huge': 'A', - 'hpt_beamlaser_turret_small': 'F', - 'hpt_beamlaser_turret_medium': 'E', - 'hpt_beamlaser_turret_large': 'D', - 'hpt_cannon_fixed_small': 'D', - 'hpt_cannon_fixed_medium': 'D', - 'hpt_cannon_fixed_large': 'C', - 'hpt_cannon_fixed_huge': 'B', - 'hpt_cannon_gimbal_small': 'E', - 'hpt_cannon_gimbal_medium': 'D', - 'hpt_cannon_gimbal_large': 'C', - 'hpt_cannon_gimbal_huge': 'B', - 'hpt_cannon_turret_small': 'F', - 'hpt_cannon_turret_medium': 'E', - 'hpt_cannon_turret_large': 'D', - 'hpt_causticmissile_fixed_medium': 'B', - 'hpt_drunkmissilerack_fixed_medium': 'B', - 'hpt_dumbfiremissilerack_fixed_small': 'B', - 'hpt_dumbfiremissilerack_fixed_medium': 'B', - 'hpt_dumbfiremissilerack_fixed_large': 'A', - 'hpt_flakmortar_fixed_medium': 'B', - 'hpt_flakmortar_turret_medium': 'B', - 'hpt_flechettelauncher_fixed_medium': 'B', - 'hpt_flechettelauncher_turret_medium': 'B', - 'hpt_guardian_gausscannon_fixed_small': 'D', - 'hpt_guardian_gausscannon_fixed_medium': 'B', - 'hpt_guardian_plasmalauncher_fixed_small': 'D', - 'hpt_guardian_plasmalauncher_fixed_medium': 'B', - 'hpt_guardian_plasmalauncher_fixed_large': 'C', - 'hpt_guardian_plasmalauncher_turret_small': 'F', - 'hpt_guardian_plasmalauncher_turret_medium': 'E', - 'hpt_guardian_plasmalauncher_turret_large': 'D', - 'hpt_guardian_shardcannon_fixed_small': 'D', - 'hpt_guardian_shardcannon_fixed_medium': 'A', - 'hpt_guardian_shardcannon_fixed_large': 'C', - 'hpt_guardian_shardcannon_turret_small': 'F', - 'hpt_guardian_shardcannon_turret_medium': 'D', - 'hpt_guardian_shardcannon_turret_large': 'D', - 'hpt_minelauncher_fixed_small': 'I', - 'hpt_minelauncher_fixed_medium': 'I', - 'hpt_mining_abrblstr_fixed_small' : 'D', - 'hpt_mining_abrblstr_turret_small' : 'D', - 'hpt_mining_seismchrgwarhd_fixed_medium' : 'B', - 'hpt_mining_seismchrgwarhd_turret_medium' : 'B', - 'hpt_mining_subsurfdispmisle_fixed_small' : 'B', - 'hpt_mining_subsurfdispmisle_fixed_medium' : 'B', - 'hpt_mining_subsurfdispmisle_turret_small' : 'B', - 'hpt_mining_subsurfdispmisle_turret_medium' : 'B', - 'hpt_mininglaser_fixed_small': 'D', - 'hpt_mininglaser_fixed_medium': 'D', - 'hpt_mininglaser_turret_small': 'D', - 'hpt_mininglaser_turret_medium': 'D', - 'hpt_multicannon_fixed_small': 'F', - 'hpt_multicannon_fixed_medium': 'E', - 'hpt_multicannon_fixed_large': 'C', - 'hpt_multicannon_fixed_huge': 'A', - 'hpt_multicannon_gimbal_small': 'G', - 'hpt_multicannon_gimbal_medium': 'F', - 'hpt_multicannon_gimbal_large': 'C', - 'hpt_multicannon_gimbal_huge': 'A', - 'hpt_multicannon_turret_small': 'G', - 'hpt_multicannon_turret_medium': 'F', - 'hpt_multicannon_turret_large': 'E', - 'hpt_plasmaaccelerator_fixed_medium': 'C', - 'hpt_plasmaaccelerator_fixed_large': 'B', - 'hpt_plasmaaccelerator_fixed_huge': 'A', - 'hpt_plasmashockcannon_fixed_small': 'D', - 'hpt_plasmashockcannon_fixed_medium': 'D', - 'hpt_plasmashockcannon_fixed_large': 'C', - 'hpt_plasmashockcannon_gimbal_small': 'E', - 'hpt_plasmashockcannon_gimbal_medium': 'D', - 'hpt_plasmashockcannon_gimbal_large': 'C', - 'hpt_plasmashockcannon_turret_small': 'F', - 'hpt_plasmashockcannon_turret_medium': 'E', - 'hpt_plasmashockcannon_turret_large': 'D', - 'hpt_pulselaser_fixed_small': 'F', - 'hpt_pulselaser_fixed_smallfree': 'F', - 'hpt_pulselaser_fixed_medium': 'E', - 'hpt_pulselaser_fixed_large': 'D', - 'hpt_pulselaser_fixed_huge': 'A', - 'hpt_pulselaser_gimbal_small': 'G', - 'hpt_pulselaser_gimbal_medium': 'F', - 'hpt_pulselaser_gimbal_large': 'E', - 'hpt_pulselaser_gimbal_huge': 'A', - 'hpt_pulselaser_turret_small': 'G', - 'hpt_pulselaser_turret_medium': 'F', - 'hpt_pulselaser_turret_large': 'F', - 'hpt_pulselaserburst_fixed_small': 'F', - 'hpt_pulselaserburst_fixed_medium': 'E', - 'hpt_pulselaserburst_fixed_large': 'D', - 'hpt_pulselaserburst_fixed_huge': 'E', - 'hpt_pulselaserburst_gimbal_small': 'G', - 'hpt_pulselaserburst_gimbal_medium': 'F', - 'hpt_pulselaserburst_gimbal_large': 'E', - 'hpt_pulselaserburst_gimbal_huge': 'E', - 'hpt_pulselaserburst_turret_small': 'G', - 'hpt_pulselaserburst_turret_medium': 'F', - 'hpt_pulselaserburst_turret_large': 'E', - 'hpt_railgun_fixed_small': 'D', - 'hpt_railgun_fixed_medium': 'B', - 'hpt_slugshot_fixed_small': 'E', - 'hpt_slugshot_fixed_medium': 'A', - 'hpt_slugshot_fixed_large': 'C', - 'hpt_slugshot_gimbal_small': 'E', - 'hpt_slugshot_gimbal_medium': 'D', - 'hpt_slugshot_gimbal_large': 'C', - 'hpt_slugshot_turret_small': 'E', - 'hpt_slugshot_turret_medium': 'D', - 'hpt_slugshot_turret_large': 'C', -} - -# Old standard weapon variants -weaponoldvariant_map = { - 'f' : 'Focussed', - 'hi' : 'High Impact', - 'lh' : 'Low Heat', - 'oc' : 'Overcharged', - 'ss' : 'Scatter Spray', -} - -countermeasure_map = { - 'antiunknownshutdown' : ('Shutdown Field Neutraliser', 'F'), - 'chafflauncher' : ('Chaff Launcher', 'I'), - 'electroniccountermeasure' : ('Electronic Countermeasure', 'F'), - 'heatsinklauncher' : ('Heat Sink Launcher', 'I'), - 'plasmapointdefence' : ('Point Defence', 'I'), - 'xenoscanner' : ('Xeno Scanner', 'E'), -} - -utility_map = { - 'cargoscanner' : 'Cargo Scanner', - 'cloudscanner' : 'Frame Shift Wake Scanner', - 'crimescanner' : 'Kill Warrant Scanner', - 'mrascanner' : 'Pulse Wave Analyser', - 'shieldbooster' : 'Shield Booster', -} - -cabin_map = { - '0': 'Prisoner Cells', - '1': 'Economy Class Passenger Cabin', - '2': 'Business Class Passenger Cabin', - '3': 'First Class Passenger Cabin', - '4': 'Luxury Class Passenger Cabin', - '5': 'Passenger Cabin', # not seen -} - -rating_map = { - '1': 'E', - '2': 'D', - '3': 'C', - '4': 'B', - '5': 'A', -} - -# Ratings are weird for the following - -corrosion_rating_map = { - '1': 'E', - '2': 'F', -} - -planet_rating_map = { - '1': 'H', - '2': 'G', -} - -fighter_rating_map = { - '1': 'D', -} - -misc_internal_map = { - ('detailedsurfacescanner', 'tiny') : ('Detailed Surface Scanner', 'I'), - ('dockingcomputer', 'advanced') : ('Advanced Docking Computer', 'E'), - ('dockingcomputer', 'standard') : ('Standard Docking Computer', 'E'), - 'planetapproachsuite' : ('Planetary Approach Suite', 'I'), - ('stellarbodydiscoveryscanner', 'standard') : ('Basic Discovery Scanner', 'E'), - ('stellarbodydiscoveryscanner', 'intermediate') : ('Intermediate Discovery Scanner', 'D'), - ('stellarbodydiscoveryscanner', 'advanced') : ('Advanced Discovery Scanner', 'C'), - 'supercruiseassist' : ('Supercruise Assist', 'E'), -} - -standard_map = { - # 'armour' : handled separately - 'engine' : 'Thrusters', - ('engine','fast') : 'Enhanced Performance Thrusters', - 'fueltank' : 'Fuel Tank', - 'guardianpowerdistributor' : 'Guardian Hybrid Power Distributor', - 'guardianpowerplant' : 'Guardian Hybrid Power Plant', - 'hyperdrive' : 'Frame Shift Drive', - 'lifesupport' : 'Life Support', - # 'planetapproachsuite' : handled separately - 'powerdistributor' : 'Power Distributor', - 'powerplant' : 'Power Plant', - 'sensors' : 'Sensors', -} - -internal_map = { - 'buggybay' : 'Planetary Vehicle Hangar', - 'cargorack' : 'Cargo Rack', - 'collection' : 'Collector Limpet Controller', - 'corrosionproofcargorack' : 'Corrosion Resistant Cargo Rack', - 'decontamination' : 'Decontamination Limpet Controller', - 'fighterbay' : 'Fighter Hangar', - 'fsdinterdictor' : 'Frame Shift Drive Interdictor', - 'fuelscoop' : 'Fuel Scoop', - 'fueltransfer' : 'Fuel Transfer Limpet Controller', - 'guardianfsdbooster' : 'Guardian FSD Booster', - 'guardianhullreinforcement' : 'Guardian Hull Reinforcement', - 'guardianmodulereinforcement': 'Guardian Module Reinforcement', - 'guardianshieldreinforcement': 'Guardian Shield Reinforcement', - 'hullreinforcement' : 'Hull Reinforcement Package', - 'metaalloyhullreinforcement' : 'Meta Alloy Hull Reinforcement', - 'modulereinforcement' : 'Module Reinforcement Package', - 'passengercabin' : 'Passenger Cabin', - 'prospector' : 'Prospector Limpet Controller', - 'refinery' : 'Refinery', - 'recon' : 'Recon Limpet Controller', - 'repair' : 'Repair Limpet Controller', - 'repairer' : 'Auto Field-Maintenance Unit', - 'resourcesiphon' : 'Hatch Breaker Limpet Controller', - 'shieldcellbank' : 'Shield Cell Bank', - 'shieldgenerator' : 'Shield Generator', - ('shieldgenerator','fast') : 'Bi-Weave Shield Generator', - ('shieldgenerator','strong') : 'Prismatic Shield Generator', - 'unkvesselresearch' : 'Research Limpet Controller', -} - +logger = get_main_logger() # Module mass, FSD data etc -moduledata = OrderedDict() +moduledata: OrderedDictT = OrderedDict() -# Given a module description from the Companion API returns a description of the module in the form of a -# dict { category, name, [mount], [guidance], [ship], rating, class } using the same terms found in the -# English langauge game. For fitted modules, dict also includes { enabled, priority }. -# ship_map tells us what ship names to use for Armour - i.e. EDDN schema names or in-game names. -# -# Returns None if the module is user-specific (i.e. decal, paintjob, kit) or PP-specific in station outfitting. -# (Given the ad-hocery in this implementation a big lookup table might have been simpler and clearer). -def lookup(module, ship_map, entitled=False): +def lookup(module, ship_map, entitled=False) -> Optional[dict]: # noqa: C901, CCR001 + """ + Produce a standard dict description of the given module. + Given a module description from the Companion API returns a description of the module in the form of a + dict { category, name, [mount], [guidance], [ship], rating, class } using the same terms found in the + English language game. For fitted modules, dict also includes { enabled, priority }. + ship_name_map tells us what ship names to use for Armour - i.e. EDDN schema names or in-game names. + + Given the ad-hocery in this implementation a big lookup table might have been simpler and clearer. + + :param module: module dict, e.g. from CAPI lastStarport->modules. + :param ship_map: dict mapping symbols to English names. + :param entitled: Whether to report modules that require e.g. Horizons. + :return: None if the module is user-specific (i.e. decal, paintjob, kit) or PP-specific in station outfitting. + """ # Lazily populate if not moduledata: - moduledata.update(pickle.load(open(join(config.respath, 'modules.p'), 'rb'))) + moduledata.update(pickle.load(open(join(config.respath_path, 'modules.p'), 'rb'))) - # if not module.get('category'): raise AssertionError('%s: Missing category' % module['id']) # only present post 1.3, and not present in ship loadout - if not module.get('name'): raise AssertionError('%s: Missing name' % module['id']) + if not module.get('name'): + raise AssertionError(f'{module["id"]}') name = module['name'].lower().split('_') - new = { 'id': module['id'], 'symbol': module['name'] } + new = {'id': module['id'], 'symbol': module['name']} # 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 + name = module['name'].lower().rsplit('_', 2) # Armour is ship-specific, and ship names can have underscores new['category'] = 'standard' new['name'] = armour_map[name[2]] - new['ship'] = ship_map[name[0]] # Generate error on unknown ship + new['ship'] = ship_map[name[0]] # Generate error on unknown ship new['class'] = '1' new['rating'] = 'I' # Skip uninteresting stuff - some no longer present in ED 3.1 cAPI data - elif name[0] in ['bobble', 'decal', 'nameplate', 'paintjob', 'enginecustomisation', 'voicepack', 'weaponcustomisation'] or name[1].startswith('shipkit') : + elif (name[0] in [ + 'bobble', + 'decal', + 'nameplate', + 'paintjob', + 'enginecustomisation', + 'voicepack', + 'weaponcustomisation' + ] + or name[1].startswith('shipkit')): return None - # Shouldn't be listing player-specific paid stuff or broker/powerplay-specific modules in outfitting, other than Horizons + # Shouldn't be listing player-specific paid stuff or broker/powerplay-specific modules in outfitting, + # other than Horizons elif not entitled and module.get('sku') and module['sku'] != 'ELITE_HORIZONS_V_PLANETARY_LANDINGS': return None @@ -380,152 +91,194 @@ def lookup(module, ship_map, entitled=False): return None # Countermeasures - e.g. Hpt_PlasmaPointDefence_Turret_Tiny - elif name[0]=='hpt' and name[1] in countermeasure_map: + elif name[0] == 'hpt' and name[1] in countermeasure_map: new['category'] = 'utility' - new['name'], new['rating'] = countermeasure_map[len(name)>4 and (name[1],name[4]) or name[1]] + new['name'], new['rating'] = countermeasure_map[len(name) > 4 and (name[1], name[4]) or name[1]] new['class'] = weaponclass_map[name[-1]] # Utility - e.g. Hpt_CargoScanner_Size0_Class1 - elif name[0]=='hpt' and name[1] in utility_map: + elif name[0] == 'hpt' and name[1] in utility_map: new['category'] = 'utility' - new['name'] = utility_map[len(name)>4 and (name[1],name[4]) or name[1]] - if not name[2].startswith('size') or not name[3].startswith('class'): raise AssertionError('%s: Unknown class/rating "%s/%s"' % (module['id'], name[2], name[3])) + new['name'] = utility_map[len(name) > 4 and (name[1], name[4]) or name[1]] + if not name[2].startswith('size') or not name[3].startswith('class'): + raise AssertionError(f'{module["id"]}: Unknown class/rating "{name[2]}/{name[3]}"') + new['class'] = str(name[2][4:]) new['rating'] = rating_map[name[3][5:]] # Hardpoints - e.g. Hpt_Slugshot_Fixed_Medium - elif name[0]=='hpt': + elif name[0] == 'hpt': # Hack 'Guardian' and 'Mining' prefixes if len(name) > 3 and name[3] in weaponmount_map: prefix = name.pop(1) - name[1] = '%s_%s' % (prefix, name[1]) - if name[1] not in weapon_map: raise AssertionError('%s: Unknown weapon "%s"' % (module['id'], name[0])) - if name[2] not in weaponmount_map: raise AssertionError('%s: Unknown weapon mount "%s"' % (module['id'], name[2])) - if name[3] not in weaponclass_map: raise AssertionError('%s: Unknown weapon class "%s"' % (module['id'], name[3])) + name[1] = f'{prefix}_{name[1]}' + + if name[1] not in weapon_map: + raise AssertionError(f'{module["id"]}: Unknown weapon "{name[0]}"') + + if name[2] not in weaponmount_map: + raise AssertionError(f'{module["id"]}: Unknown weapon mount "{name[2]}"') + + if name[3] not in weaponclass_map: + raise AssertionError(f'{module["id"]}: Unknown weapon class "{name[3]}"') new['category'] = 'hardpoint' - if len(name)>4: - if name[4] in weaponoldvariant_map: # Old variants e.g. Hpt_PulseLaserBurst_Turret_Large_OC - new['name'] = weapon_map[name[1]] + ' ' + weaponoldvariant_map[name[4]] + if len(name) > 4: + if name[4] in weaponoldvariant_map: # Old variants e.g. Hpt_PulseLaserBurst_Turret_Large_OC + new['name'] = weapon_map[name[1]] + ' ' + weaponoldvariant_map[name[4]] new['rating'] = '?' + elif '_'.join(name[:4]) not in weaponrating_map: - raise AssertionError('%s: Unknown weapon rating "%s"' % (module['id'], module['name'])) - else: # PP faction-specific weapons e.g. Hpt_Slugshot_Fixed_Large_Range - new['name'] = weapon_map[(name[1],name[4])] - new['rating'] = weaponrating_map['_'.join(name[:4])] # assumes same rating as base weapon + raise AssertionError(f'{module["id"]}: Unknown weapon rating "{module["name"]}"') + + else: + # PP faction-specific weapons e.g. Hpt_Slugshot_Fixed_Large_Range + new['name'] = weapon_map[(name[1], name[4])] + new['rating'] = weaponrating_map['_'.join(name[:4])] # assumes same rating as base weapon + elif module['name'].lower() not in weaponrating_map: - raise AssertionError('%s: Unknown weapon rating "%s"' % (module['id'], module['name'])) + raise AssertionError(f'{module["id"]}: Unknown weapon rating "{module["name"]}"') + else: - new['name'] = weapon_map[name[1]] - new['rating'] = weaponrating_map[module['name'].lower()] # no obvious rule - needs lookup table + new['name'] = weapon_map[name[1]] + new['rating'] = weaponrating_map[module['name'].lower()] # no obvious rule - needs lookup table + new['mount'] = weaponmount_map[name[2]] - if name[1] in missiletype_map: # e.g. Hpt_DumbfireMissileRack_Fixed_Small + if name[1] in missiletype_map: + # e.g. Hpt_DumbfireMissileRack_Fixed_Small new['guidance'] = missiletype_map[name[1]] + new['class'] = weaponclass_map[name[3]] - elif name[0]!='int': - raise AssertionError('%s: Unknown prefix "%s"' % (module['id'], name[0])) + elif name[0] != 'int': + raise AssertionError(f'{module["id"]}: Unknown prefix "{name[0]}"') - # Miscellaneous Class 1 - e.g. Int_PlanetApproachSuite, Int_StellarBodyDiscoveryScanner_Advanced, Int_DockingComputer_Standard + # Miscellaneous Class 1 + # e.g. Int_PlanetApproachSuite, Int_StellarBodyDiscoveryScanner_Advanced, Int_DockingComputer_Standard elif name[1] in misc_internal_map: new['category'] = 'internal' new['name'], new['rating'] = misc_internal_map[name[1]] new['class'] = '1' - elif len(name) > 2 and (name[1],name[2]) in misc_internal_map: + + elif len(name) > 2 and (name[1], name[2]) in misc_internal_map: # Reported category is not necessarily helpful. e.g. "Int_DockingComputer_Standard" has category "utility" new['category'] = 'internal' - new['name'], new['rating'] = misc_internal_map[(name[1],name[2])] + new['name'], new['rating'] = misc_internal_map[(name[1], name[2])] new['class'] = '1' - # Standard & Internal else: - if name[1] == 'dronecontrol': # e.g. Int_DroneControl_Collection_Size1_Class1 + # Standard & Internal + if name[1] == 'dronecontrol': # e.g. Int_DroneControl_Collection_Size1_Class1 name.pop(0) - elif name[-1] == 'free': # Starter Sidewinder or Freagle modules - just treat them like vanilla modules + + elif name[-1] == 'free': # Starter Sidewinder or Freagle modules - just treat them like vanilla modules name.pop() - if name[1] in standard_map: # e.g. Int_Engine_Size2_Class1, Int_ShieldGenerator_Size8_Class5_Strong + if name[1] in standard_map: # e.g. Int_Engine_Size2_Class1, Int_ShieldGenerator_Size8_Class5_Strong new['category'] = 'standard' - new['name'] = standard_map[len(name)>4 and (name[1],name[4]) or name[1]] - elif name[1] in internal_map: # e.g. Int_CargoRack_Size8_Class1 + new['name'] = standard_map[len(name) > 4 and (name[1], name[4]) or name[1]] + + elif name[1] in internal_map: # e.g. Int_CargoRack_Size8_Class1 new['category'] = 'internal' if name[1] == 'passengercabin': new['name'] = cabin_map[name[3][5:]] - else: - new['name'] = internal_map[len(name)>4 and (name[1],name[4]) or name[1]] - else: - raise AssertionError('%s: Unknown module "%s"' % (module['id'], name[1])) - if len(name) < 4 and name[1] == 'unkvesselresearch': # Hack! No size or class. - (new['class'], new['rating']) = ('1', 'E') - elif len(name) < 4 and name[1] == 'resourcesiphon': # Hack! 128066402 has no size or class. - (new['class'], new['rating']) = ('1', 'I') - elif len(name) < 4 and name[1] in ['guardianpowerdistributor', 'guardianpowerplant']: # Hack! No class. - (new['class'], new['rating']) = (str(name[2][4:]), 'A') - elif len(name) < 4 and name[1] in ['guardianfsdbooster']: # Hack! No class. - (new['class'], new['rating']) = (str(name[2][4:]), 'H') + else: + new['name'] = internal_map[len(name) > 4 and (name[1], name[4]) or name[1]] + else: - if len(name) < 3: raise AssertionError('%s: length < 3]' % (name)) - if not name[2].startswith('size') or not name[3].startswith('class'): raise AssertionError('%s: Unknown class/rating "%s/%s"' % (module['id'], name[2], name[3])) + raise AssertionError(f'{module["id"]}: Unknown module "{name[1]}"') + + if len(name) < 4 and name[1] == 'unkvesselresearch': # Hack! No size or class. + (new['class'], new['rating']) = ('1', 'E') + + elif len(name) < 4 and name[1] == 'resourcesiphon': # Hack! 128066402 has no size or class. + (new['class'], new['rating']) = ('1', 'I') + + elif len(name) < 4 and name[1] in ['guardianpowerdistributor', 'guardianpowerplant']: # Hack! No class. + (new['class'], new['rating']) = (str(name[2][4:]), 'A') + + elif len(name) < 4 and name[1] in ['guardianfsdbooster']: # Hack! No class. + (new['class'], new['rating']) = (str(name[2][4:]), 'H') + + else: + if len(name) < 3: + raise AssertionError(f'{name}: length < 3]') + + if not name[2].startswith('size') or not name[3].startswith('class'): + raise AssertionError(f'{module["id"]}: Unknown class/rating "{name[2]}/{name[3]}"') + new['class'] = str(name[2][4:]) - new['rating'] = (name[1]=='buggybay' and planet_rating_map or - name[1]=='fighterbay' and fighter_rating_map or - name[1]=='corrosionproofcargorack' and corrosion_rating_map or + new['rating'] = (name[1] == 'buggybay' and planet_rating_map or + name[1] == 'fighterbay' and fighter_rating_map or + name[1] == 'corrosionproofcargorack' and corrosion_rating_map or rating_map)[name[3][5:]] # Disposition of fitted modules if 'on' in module and 'priority' in module: - new['enabled'], new['priority'] = module['on'], module['priority'] # priority is zero-based + new['enabled'], new['priority'] = module['on'], module['priority'] # priority is zero-based # Entitlements if not module.get('sku'): pass + else: new['entitlement'] = module['sku'] # Extra module data if module['name'].endswith('_free'): - key = module['name'][:-5].lower() # starter modules - treated like vanilla modules + key = module['name'][:-5].lower() # starter modules - treated like vanilla modules + else: key = module['name'].lower() + if __debug__: m = moduledata.get(key, {}) if not m: - print('No data for module %s' % key) + print(f'No data for module {key}') + elif new['name'] == 'Frame Shift Drive': assert 'mass' in m and 'optmass' in m and 'maxfuel' in m and 'fuelmul' in m and 'fuelpower' in m, m + else: assert 'mass' in m, m + 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('%s: failed to set %s' % (module['id'], thing)) + 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}') + if new['category'] == 'hardpoint' and not new.get('mount'): - raise AssertionError('%s: failed to set %s' % (module['id'], 'mount')) + raise AssertionError(f'{module["id"]}: failed to set mount') return new -def export(data, filename): - - querytime = config.getint('querytime') or int(time.time()) +def export(data, filename) -> None: + """ + Export given data about module availability. + :param data: CAPI data to export. + :param filename: Filename to export into. + """ assert data['lastSystem'].get('name') assert data['lastStarport'].get('name') header = 'System,Station,Category,Name,Mount,Guidance,Ship,Class,Rating,FDevID,Date\n' - rowheader = '%s,%s' % (data['lastSystem']['name'], data['lastStarport']['name']) + rowheader = f'{data["lastSystem"]["name"]},{data["lastStarport"]["name"]}' - h = open(filename, 'wt') - h.write(header) - for v in list(data['lastStarport'].get('modules', {}).values()): - try: - m = lookup(v, companion.ship_map) - if m: - h.write('%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n' % (rowheader, m['category'], m['name'], m.get('mount',''), m.get('guidance',''), m.get('ship',''), m['class'], m['rating'], m['id'], data['timestamp'])) - except AssertionError as e: - if __debug__: print('Outfitting: %s' % e) # Silently skip unrecognized modules - except: - if __debug__: raise - h.close() + with open(filename, 'wt') as h: + h.write(header) + for v in list(data['lastStarport'].get('modules', {}).values()): + try: + m = lookup(v, ship_name_map) + if m: + h.write(f'{rowheader}, {m["category"]}, {m["name"]}, {m.get("mount","")},' + f'{m.get("guidance","")}, {m.get("ship","")}, {m["class"]}, {m["rating"]},' + f'{m["id"]}, {data["timestamp"]}\n') + + except AssertionError as e: + # Log unrecognised modules + logger.debug('Outfitting', exc_info=e) diff --git a/plug.py b/plug.py index 755fec1c..eea96ea7 100644 --- a/plug.py +++ b/plug.py @@ -19,55 +19,6 @@ import logging logger = get_main_logger() -# Dashboard Flags constants -FlagsDocked = 1 << 0 # on a landing pad -FlagsLanded = 1 << 1 # on planet surface -FlagsLandingGearDown = 1 << 2 -FlagsShieldsUp = 1 << 3 -FlagsSupercruise = 1 << 4 -FlagsFlightAssistOff = 1 << 5 -FlagsHardpointsDeployed = 1 << 6 -FlagsInWing = 1 << 7 -FlagsLightsOn = 1 << 8 -FlagsCargoScoopDeployed = 1 << 9 -FlagsSilentRunning = 1 << 10 -FlagsScoopingFuel = 1 << 11 -FlagsSrvHandbrake = 1 << 12 -FlagsSrvTurret = 1 << 13 # using turret view -FlagsSrvUnderShip = 1 << 14 # turret retracted -FlagsSrvDriveAssist = 1 << 15 -FlagsFsdMassLocked = 1 << 16 -FlagsFsdCharging = 1 << 17 -FlagsFsdCooldown = 1 << 18 -FlagsLowFuel = 1 << 19 # <25% -FlagsOverHeating = 1 << 20 # > 100% -FlagsHasLatLong = 1 << 21 -FlagsIsInDanger = 1 << 22 -FlagsBeingInterdicted = 1 << 23 -FlagsInMainShip = 1 << 24 -FlagsInFighter = 1 << 25 -FlagsInSRV = 1 << 26 -FlagsAnalysisMode = 1 << 27 # Hud in Analysis mode -FlagsNightVision = 1 << 28 -FlagsAverageAltitude = 1 << 29 # Altitude from Average radius -FlagsFsdJump = 1 << 30 -FlagsSrvHighBeam = 1 << 31 - -# Dashboard GuiFocus constants -GuiFocusNoFocus = 0 -GuiFocusInternalPanel = 1 # right hand side -GuiFocusExternalPanel = 2 # left hand side -GuiFocusCommsPanel = 3 # top -GuiFocusRolePanel = 4 # bottom -GuiFocusStationServices = 5 -GuiFocusGalaxyMap = 6 -GuiFocusSystemMap = 7 -GuiFocusOrrery = 8 -GuiFocusFSS = 9 -GuiFocusSAA = 10 -GuiFocusCodex = 11 - - # List of loaded Plugins PLUGINS = [] PLUGINS_not_py3 = [] @@ -173,10 +124,10 @@ def load_plugins(master): last_error['root'] = master internal = [] - for name in sorted(os.listdir(config.internal_plugin_dir)): + 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, name), logger) + 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 as e: @@ -188,9 +139,9 @@ def load_plugins(master): found = [] # Load any plugins that are also packages first - for name in sorted(os.listdir(config.plugin_dir), - key = lambda n: (not os.path.isfile(os.path.join(config.plugin_dir, n, '__init__.py')), n.lower())): - if not os.path.isdir(os.path.join(config.plugin_dir, name)) or name[0] in ['.', '_']: + 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'): name, discard = name.rsplit('.', 1) @@ -198,14 +149,14 @@ def load_plugins(master): else: try: # Add plugin's folder to load path in case plugin has internal package dependencies - sys.path.append(os.path.join(config.plugin_dir, name)) + 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 plugin_logger = EDMCLogging.get_plugin_logger(name) - found.append(Plugin(name, os.path.join(config.plugin_dir, name, 'load.py'), plugin_logger)) + found.append(Plugin(name, os.path.join(config.plugin_dir_path, name, 'load.py'), plugin_logger)) except Exception as e: logger.exception(f'Failure loading found Plugin "{name}"') pass @@ -307,8 +258,8 @@ def notify_journal_entry(cmdr, is_beta, system, station, entry, state): :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'): - logger.trace('Notifying plugins of "Location" event') + # if entry['event'] in ('Location'): + # logger.trace('Notifying plugins of "Location" event') error = None for plugin in PLUGINS: @@ -371,7 +322,6 @@ def show_error(err): :param err: .. versionadded:: 2.3.7 """ - if config.shutting_down: logger.info(f'Called during shutdown: "{str(err)}"') return diff --git a/plugins/coriolis.py b/plugins/coriolis.py index 21077886..89504173 100644 --- a/plugins/coriolis.py +++ b/plugins/coriolis.py @@ -8,10 +8,10 @@ import io # Migrate settings from <= 3.01 from config import config -if not config.get('shipyard_provider') and config.getint('shipyard'): +if not config.get_str('shipyard_provider') and config.get_int('shipyard'): config.set('shipyard_provider', 'Coriolis') -config.delete('shipyard') +config.delete('shipyard', suppress=True) def plugin_start3(_): diff --git a/plugins/eddb.py b/plugins/eddb.py index c0ef35fc..cd51b49c 100644 --- a/plugins/eddb.py +++ b/plugins/eddb.py @@ -24,15 +24,23 @@ import sys -from typing import Any, Optional, TYPE_CHECKING +from typing import TYPE_CHECKING, Any, Optional + import requests +import EDMCLogging +import killswitch +import plug +from companion import CAPIData from config import config if TYPE_CHECKING: from tkinter import Tk +logger = EDMCLogging.get_main_logger() + + STATION_UNDOCKED: str = '×' # "Station" name to display when not docked = U+00D7 this: Any = sys.modules[__name__] # For holding module globals @@ -45,6 +53,7 @@ this.system_population: Optional[int] = None this.station_link: 'Optional[Tk]' = None this.station: Optional[str] = None this.station_marketid: Optional[int] = None +this.on_foot = False def system_url(system_name: str) -> str: @@ -63,6 +72,7 @@ def station_url(system_name: str, station_name: str) -> str: return system_url(system_name) + def plugin_start3(plugin_dir): return 'eddb' @@ -82,7 +92,18 @@ def prefs_changed(cmdr, is_beta): # through correctly. We don't want a static string. pass + def journal_entry(cmdr, is_beta, system, station, entry, state): + if (ks := killswitch.get_disabled('plugins.eddb.journal')).disabled: + logger.warning(f'Journal processing for EDDB has been disabled: {ks.reason}') + plug.show_error('EDDB Journal processing disabled. See Log') + return + + elif (ks := killswitch.get_disabled(f'plugins.eddb.journal.event.{entry["event"]}')).disabled: + logger.warning(f'Processing of event {entry["event"]} has been disabled: {ks.reason}') + return + + this.on_foot = state['OnFoot'] # Always update our system address even if we're not currently the provider for system or station, but dont update # on events that contain "future" data, such as FSDTarget if entry['event'] in ('Location', 'Docked', 'CarrierJump', 'FSDJump'): @@ -96,21 +117,31 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): this.system_population = pop this.station = entry.get('StationName') or this.station + # on_foot station detection + if entry['event'] == 'Location' and entry['BodyType'] == 'Station': + this.station = entry['Body'] + this.station_marketid = entry.get('MarketID') or this.station_marketid # We might pick up StationName in DockingRequested, make sure we clear it if leaving if entry['event'] in ('Undocked', 'FSDJump', 'SupercruiseEntry'): this.station = None this.station_marketid = None + if entry['event'] == 'Embark' and not entry.get('OnStation'): + # If we're embarking OnStation to a Taxi/Dropship we'll also get an + # Undocked event. + this.station = None + this.station_marketid = None + # Only actually change URLs if we are current provider. - if config.get('system_provider') == 'eddb': + if config.get_str('system_provider') == 'eddb': this.system_link['text'] = this.system # 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() # But only actually change the URL if we are current station provider. - if config.get('station_provider') == 'eddb': + if config.get_str('station_provider') == 'eddb': text = this.station if not text: if this.system_population is not None and this.system_population > 0: @@ -125,7 +156,7 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): this.station_link.update_idletasks() -def cmdr_data(data, is_beta): +def cmdr_data(data: CAPIData, is_beta): # 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'] @@ -138,14 +169,14 @@ def cmdr_data(data, is_beta): this.station = data['lastStarport']['name'] # Override standard URL functions - if config.get('system_provider') == 'eddb': + if config.get_str('system_provider') == 'eddb': this.system_link['text'] = this.system # 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('station_provider') == 'eddb': - if data['commander']['docked']: + if config.get_str('station_provider') == 'eddb': + if data['commander']['docked'] or this.on_foot and this.station: this.station_link['text'] = this.station elif data['lastStarport']['name'] and data['lastStarport']['name'] != "": diff --git a/plugins/eddn.py b/plugins/eddn.py index 464eae46..d700ba2b 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -1,4 +1,4 @@ -# Export to EDDN +"""Handle exporting data to EDDN.""" import itertools import json @@ -10,22 +10,25 @@ from collections import OrderedDict from os import SEEK_SET from os.path import join from platform import system -from typing import TYPE_CHECKING, Any, AnyStr, Dict, Iterator, List, Mapping, MutableMapping, Optional, Tuple +from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Mapping, MutableMapping, Optional from typing import OrderedDict as OrderedDictT -from typing import Sequence, TextIO +from typing import TextIO, Tuple import requests +import killswitch import myNotebook as nb # noqa: N813 -from companion import category_map -from config import applongname, appversion, config +import plug +from companion import CAPIData, category_map +from config import applongname, appversion_nobuild, config from EDMCLogging import get_main_logger +from monitor import monitor from myNotebook import Frame from prefs import prefsVersion from ttkHyperlinkLabel import HyperlinkLabel if sys.platform != 'win32': - from fcntl import lockf, LOCK_EX, LOCK_NB + from fcntl import LOCK_EX, LOCK_NB, lockf if TYPE_CHECKING: @@ -34,18 +37,43 @@ if TYPE_CHECKING: logger = get_main_logger() -this: Any = sys.modules[__name__] # For holding module globals -# Track location to add to Journal events -this.systemaddress = None -this.coordinates = None -this.planet = None +class This: + """Holds module globals.""" + + def __init__(self): + # Track if we're on foot + self.on_foot = False + # Track location to add to Journal events + self.systemaddress: Optional[str] = None + self.coordinates: Optional[Tuple] = None + self.planet: Optional[str] = None + + # Avoid duplicates + self.marketId: Optional[str] = None + self.commodities: Optional[List[OrderedDictT[str, Any]]] = None + self.outfitting: Optional[Tuple[bool, List[str]]] = None + self.shipyard: Optional[Tuple[bool, List[Mapping[str, Any]]]] = None + + # For the tkinter parent window, so we can call update_idletasks() + self.parent: tk.Tk + + # To hold EDDN class instance + self.eddn: EDDN + + # tkinter UI bits. + self.eddn_station: tk.IntVar + self.eddn_station_button: nb.Checkbutton + + self.eddn_system: tk.IntVar + self.eddn_system_button: nb.Checkbutton + + self.eddn_delay: tk.IntVar + self.eddn_delay_button: nb.Checkbutton + + +this = This() -# Avoid duplicates -this.marketId = None -this.commodities = None -this.outfitting: Optional[Tuple[bool, MutableMapping[str, Any]]] = None -this.shipyard = None HORIZ_SKU = 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' @@ -53,6 +81,8 @@ HORIZ_SKU = 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' # TODO: a good few of these methods are static or could be classmethods. they should be created as such. class EDDN: + """EDDN Data export.""" + # SERVER = 'http://localhost:8081' # testing SERVER = 'https://eddn.edcd.io:4430' UPLOAD = f'{SERVER}/upload/' @@ -70,7 +100,7 @@ class EDDN: def load_journal_replay(self) -> bool: """ - Load cached journal entries from disk + Load cached journal entries from disk. :return: a bool indicating success """ @@ -100,9 +130,7 @@ class EDDN: return True def flush(self): - """ - flush flushes the replay file, clearing any data currently there that is not in the replaylog list - """ + """Flush the replay file, clearing any data currently there that is not in the replaylog list.""" self.replayfile.seek(0, SEEK_SET) self.replayfile.truncate() for line in self.replaylog: @@ -111,28 +139,35 @@ class EDDN: self.replayfile.flush() def close(self): - """ - close closes the replay file - """ + """Close down the EDDN class instance.""" + logger.debug('Closing replayfile...') if self.replayfile: self.replayfile.close() self.replayfile = None + logger.debug('Done.') + + logger.debug('Closing EDDN requests.Session.') + self.session.close() def send(self, cmdr: str, msg: Mapping[str, Any]) -> None: """ - Send sends an update to EDDN + Send sends an update to EDDN. - :param cmdr: the CMDR to use as the uploader ID - :param msg: the payload to send + :param cmdr: the CMDR to use as the uploader ID. + :param msg: the payload to send. """ + if (res := killswitch.get_disabled('plugins.eddn.send')).disabled: + logger.warning(f"eddn.send has been disabled via killswitch. Returning. ({res.reason})") + return + uploader_id = cmdr - to_send: OrderedDictT[str, str] = OrderedDict([ + to_send: OrderedDictT[str, OrderedDict[str, Any]] = OrderedDict([ ('$schemaRef', msg['$schemaRef']), ('header', OrderedDict([ ('softwareName', f'{applongname} [{system() if sys.platform != "darwin" else "Mac OS"}]'), - ('softwareVersion', appversion), + ('softwareVersion', str(appversion_nobuild())), ('uploaderID', uploader_id), ])), ('message', msg['message']), @@ -162,14 +197,12 @@ Msg:\n{msg}''' r.raise_for_status() - def sendreplay(self) -> None: - """ - sendreplay updates EDDN with cached journal lines - """ + def sendreplay(self) -> None: # noqa: CCR001 + """Send cached Journal lines to EDDN.""" if not self.replayfile: return # Probably closing app - status: Dict[str, Any] = self.parent.children['status'] + status: tk.Widget = self.parent.children['status'] if not self.replaylog: status['text'] = '' @@ -230,9 +263,10 @@ Msg:\n{msg}''' self.parent.after(self.REPLAYPERIOD, self.sendreplay) - def export_commodities(self, data: Mapping[str, Any], is_beta: bool) -> None: + def export_commodities(self, data: Mapping[str, Any], is_beta: bool) -> None: # noqa: CCR001 """ - export_commodities updates EDDN with the commodities on the current (lastStarport) station. + Update EDDN with the commodities on the current (lastStarport) station. + Once the send is complete, this.commodities is updated with the new data. :param data: a dict containing the starport data @@ -290,15 +324,28 @@ Msg:\n{msg}''' this.commodities = commodities 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. + + Principally this catches where the supplied CAPI data either doesn't + contain expected elements, or they're not of the expected type (e.g. + a list instead of a dict). + + :param data: The raw CAPI data. + :return: Sanity-checked data. + """ modules: Dict[str, Any] = data['lastStarport'].get('modules') if modules is None or not isinstance(modules, dict): if modules is None: logger.debug('modules was None. FC or Damaged Station?') + elif isinstance(modules, list): if len(modules) == 0: logger.debug('modules is empty list. FC or Damaged Station?') + else: logger.error(f'modules is non-empty list: {modules!r}') + else: logger.error(f'modules was not None, a list, or a dict! type = {type(modules)}') # Set a safe value @@ -308,6 +355,7 @@ Msg:\n{msg}''' 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)}') # Set a safe value @@ -315,9 +363,10 @@ Msg:\n{msg}''' return modules, ships - def export_outfitting(self, data: Mapping[str, Any], is_beta: bool) -> None: + def export_outfitting(self, data: CAPIData, is_beta: bool) -> None: """ - export_outfitting updates EDDN with the current (lastStarport) station's outfitting options, if any. + Update EDDN with the current (lastStarport) station's outfitting options, if any. + Once the send is complete, this.outfitting is updated with the given data. :param data: dict containing the outfitting data @@ -331,7 +380,7 @@ Msg:\n{msg}''' data['lastStarport'].get('economies', {}), modules, ships - ) + ) to_search: Iterator[Mapping[str, Any]] = filter( lambda m: self.MODULE_RE.search(m['name']) and m.get('sku') in (None, HORIZ_SKU) and @@ -342,6 +391,7 @@ Msg:\n{msg}''' outfitting: List[str] = sorted( self.MODULE_RE.sub(lambda match: match.group(0).capitalize(), mod['name'].lower()) for mod in to_search ) + # Don't send empty modules list - schema won't allow it if outfitting and this.outfitting != (horizons, outfitting): self.send(data['commander']['name'], { @@ -358,10 +408,11 @@ Msg:\n{msg}''' this.outfitting = (horizons, outfitting) - def export_shipyard(self, data: Dict[str, Any], is_beta: bool) -> None: + def export_shipyard(self, data: CAPIData, is_beta: bool) -> None: """ - export_shipyard updates EDDN with the current (lastStarport) station's outfitting options, if any. - once the send is complete, this.shipyard is updated to the new data. + Update EDDN with the current (lastStarport) station's outfitting options, if any. + + Once the send is complete, this.shipyard is updated to the new data. :param data: dict containing the shipyard data :param is_beta: whether or not we are in beta mode @@ -372,12 +423,12 @@ Msg:\n{msg}''' data['lastStarport'].get('economies', {}), modules, ships - ) + ) shipyard: List[Mapping[str, Any]] = sorted( itertools.chain( (ship['name'].lower() for ship in (ships['shipyard_list'] or {}).values()), - ships['unavailable_list'] + (ship['name'].lower() for ship in ships['unavailable_list'] or {}), ) ) # Don't send empty ships list - shipyard data is only guaranteed present if user has visited the shipyard. @@ -398,15 +449,16 @@ Msg:\n{msg}''' def export_journal_commodities(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]) -> None: """ - export_journal_commodities updates EDDN with the commodities list on the current station (lastStarport) from - data in the journal. As a side effect, it also updates this.commodities with the data + Update EDDN with Journal commodities data from the current station (lastStarport). + + As a side effect, it also updates this.commodities with the data. :param cmdr: The commander to send data under :param is_beta: whether or not we're in beta mode :param entry: the journal entry containing the commodities data """ items: List[Mapping[str, Any]] = entry.get('Items') or [] - commodities: Sequence[OrderedDictT[AnyStr, Any]] = sorted((OrderedDict([ + commodities: List[OrderedDictT[str, Any]] = sorted((OrderedDict([ ('name', self.canonicalise(commodity['Name'])), ('meanPrice', commodity['MeanPrice']), ('buyPrice', commodity['BuyPrice']), @@ -435,12 +487,13 @@ Msg:\n{msg}''' ]), }) - this.commodities: OrderedDictT[str, Any] = commodities + this.commodities = commodities def export_journal_outfitting(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]) -> None: """ - export_journal_outfitting updates EDDN with station outfitting based on a journal entry. As a side effect, - it also updates this.outfitting with the data + Update EDDN with Journal oufitting data from the current station (lastStarport). + + As a side effect, it also updates this.outfitting with the data. :param cmdr: The commander to send data under :param is_beta: Whether or not we're in beta mode @@ -472,8 +525,9 @@ Msg:\n{msg}''' def export_journal_shipyard(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]) -> None: """ - export_journal_shipyard updates EDDN with station shipyard data based on a journal entry. As a side effect, - this.shipyard is updated with the data. + Update EDDN with Journal shipyard data from the current station (lastStarport). + + As a side effect, this.shipyard is updated with the data. :param cmdr: the commander to send this update under :param is_beta: Whether or not we're in beta mode @@ -496,12 +550,13 @@ Msg:\n{msg}''' ]), }) - this.shipyard = (horizons, shipyard) + # this.shipyard = (horizons, shipyard) def export_journal_entry(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]) -> None: """ - export_journal_entry updates EDDN with a line from the journal. Additionally if additional lines are cached, - it may send those as well. + Update EDDN with an event from the journal. + + Additionally if additional lines are cached, it may send those as well. :param cmdr: the commander under which this upload is made :param is_beta: whether or not we are in beta mode @@ -515,23 +570,28 @@ Msg:\n{msg}''' if self.replayfile or self.load_journal_replay(): # Store the entry self.replaylog.append(json.dumps([cmdr, msg])) - self.replayfile.write(f'{self.replaylog[-1]}\n') + self.replayfile.write(f'{self.replaylog[-1]}\n') # type: ignore if ( entry['event'] == 'Docked' or (entry['event'] == 'Location' and entry['Docked']) or not - (config.getint('output') & config.OUT_SYS_DELAY) + (config.get_int('output') & config.OUT_SYS_DELAY) ): self.parent.after(self.REPLAYPERIOD, self.sendreplay) # Try to send this and previous entries else: # Can't access replay file! Send immediately. - status: MutableMapping[str, str] = self.parent.children['status'] - status['text'] = _('Sending data to EDDN...') + self.parent.children['status']['text'] = _('Sending data to EDDN...') self.parent.update_idletasks() self.send(cmdr, msg) - status['text'] = '' + self.parent.children['status']['text'] = '' def canonicalise(self, item: str) -> str: + """ + Canonicalise the given commodity name. + + :param item: Name of an commodity we want the canonical name for. + :return: The canonical name for this commodity. + """ match = self.CANONICALISE_RE.match(item) return match and match.group(1) or item @@ -539,27 +599,52 @@ Msg:\n{msg}''' # Plugin callbacks def plugin_start3(plugin_dir: str) -> str: + """ + Start this plugin. + + :param plugin_dir: `str` - The full path to this plugin's directory. + :return: `str` - Name of this plugin to use in UI. + """ return 'EDDN' def plugin_app(parent: tk.Tk) -> None: + """ + Set up any plugin-specific UI. + + In this case we need the tkinter parent in order to later call + `update_idletasks()` on it. + + TODO: Re-work the whole replaylog and general sending to EDDN so this isn't + necessary. + + :param parent: tkinter parent frame. + """ this.parent = parent this.eddn = EDDN(parent) # Try to obtain exclusive lock on journal cache, even if we don't need it yet if not this.eddn.load_journal_replay(): # Shouldn't happen - don't bother localizing - this.status['text'] = 'Error: Is another copy of this app already running?' + this.parent.children['status']['text'] = 'Error: Is another copy of this app already running?' def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: + """ + Set up Preferences pane for this plugin. + + :param parent: tkinter parent to attach to. + :param cmdr: `str` - Name of current Cmdr. + :param is_beta: `bool` - True if this is a beta version of the Game. + :return: The tkinter frame we created. + """ PADX = 10 # noqa: N806 BUTTONX = 12 # noqa: N806 # indent Checkbuttons and Radiobuttons - if prefsVersion.shouldSetDefaults('0.0.0.0', not bool(config.getint('output'))): + if prefsVersion.shouldSetDefaults('0.0.0.0', not bool(config.get_int('output'))): output: int = (config.OUT_MKT_EDDN | config.OUT_SYS_EDDN) # default settings else: - output: int = config.getint('output') + output = config.get_int('output') eddnframe = nb.Frame(parent) @@ -603,15 +688,27 @@ def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: def prefsvarchanged(event=None) -> None: + """ + Handle changes to EDDN Preferences. + + :param event: tkinter event ? + """ this.eddn_station_button['state'] = tk.NORMAL this.eddn_system_button['state'] = tk.NORMAL this.eddn_delay_button['state'] = this.eddn.replayfile and this.eddn_system.get() and tk.NORMAL or tk.DISABLED def prefs_changed(cmdr: str, is_beta: bool) -> None: + """ + Handle when Preferences have been changed. + + :param cmdr: `str` - Name of current Cmdr. + :param is_beta: `bool` - True if this is a beta version of the Game. + """ config.set( 'output', - (config.getint('output') & (config.OUT_MKT_TD | config.OUT_MKT_CSV | config.OUT_SHIP | config.OUT_MKT_MANUAL)) + + (config.get_int('output') + & (config.OUT_MKT_TD | config.OUT_MKT_CSV | config.OUT_SHIP | config.OUT_MKT_MANUAL)) + (this.eddn_station.get() and config.OUT_MKT_EDDN) + (this.eddn_system.get() and config.OUT_SYS_EDDN) + (this.eddn_delay.get() and config.OUT_SYS_DELAY) @@ -619,12 +716,40 @@ def prefs_changed(cmdr: str, is_beta: bool) -> None: def plugin_stop() -> None: + """Handle stopping this plugin.""" + logger.debug('Calling this.eddn.close()') this.eddn.close() + logger.debug('Done.') -def journal_entry( # noqa: C901 - cmdr: str, is_beta: bool, system: str, station: str, entry: MutableMapping[str, Any], state: Mapping[str, Any] +def journal_entry( # noqa: C901, CCR001 + cmdr: str, + is_beta: bool, + system: str, + station: str, + entry: MutableMapping[str, Any], + state: Mapping[str, Any] ) -> Optional[str]: + """ + Process a new Journal entry. + + :param cmdr: `str` - Name of currennt Cmdr. + :param is_beta: `bool` - True if this is a beta version of the Game. + :param system: `str` - Name of system Cmdr is in. + :param station: `str` - Name of station Cmdr is docked at, if applicable. + :param entry: `dict` - The data for this Journal entry. + :param state: `dict` - Current `monitor.state` data. + :return: `str` - Error message, or `None` if no errors. + """ + if (ks := killswitch.get_disabled("plugins.eddn.journal")).disabled: + logger.warning(f"EDDN journal handler has been disabled via killswitch: {ks.reason}") + plug.show_error("EDDN journal handler disabled. See Log.") + return None + + elif (ks := killswitch.get_disabled(f'plugins.eddn.journal.event.{entry["event"]}')).disabled: + logger.warning(f'Handling of event {entry["event"]} disabled via killswitch: {ks.reason}') + return None + # Recursively filter '*_Localised' keys from dict def filter_localised(d: Mapping[str, Any]) -> OrderedDictT[str, Any]: filtered: OrderedDictT[str, Any] = OrderedDict() @@ -643,21 +768,22 @@ def journal_entry( # noqa: C901 return filtered + this.on_foot = state['OnFoot'] # Track location if entry['event'] in ('Location', 'FSDJump', 'Docked', 'CarrierJump'): if entry['event'] in ('Location', 'CarrierJump'): - this.planet: Optional[str] = entry.get('Body') if entry.get('BodyType') == 'Planet' else None + this.planet = entry.get('Body') if entry.get('BodyType') == 'Planet' else None elif entry['event'] == 'FSDJump': - this.planet: Optional[str] = None + this.planet = None if 'StarPos' in entry: - this.coordinates: Optional[Tuple[int, int, int]] = tuple(entry['StarPos']) + this.coordinates = tuple(entry['StarPos']) elif this.systemaddress != entry.get('SystemAddress'): - this.coordinates: Optional[Tuple[int, int, int]] = None # Docked event doesn't include coordinates + this.coordinates = None # Docked event doesn't include coordinates - this.systemaddress: Optional[str] = entry.get('SystemAddress') + this.systemaddress = entry.get('SystemAddress') # type: ignore elif entry['event'] == 'ApproachBody': this.planet = entry['Body'] @@ -666,7 +792,7 @@ def journal_entry( # noqa: C901 this.planet = None # Send interesting events to EDDN, but not when on a crew - if (config.getint('output') & config.OUT_SYS_EDDN and not state['Captain'] and + if (config.get_int('output') & config.OUT_SYS_EDDN and not state['Captain'] and (entry['event'] in ('Location', 'FSDJump', 'Docked', 'Scan', 'SAASignalsFound', 'CarrierJump')) and ('StarPos' in entry or this.coordinates)): @@ -740,7 +866,7 @@ def journal_entry( # noqa: C901 logger.debug('Failed in export_journal_entry', exc_info=e) return str(e) - elif (config.getint('output') & config.OUT_MKT_EDDN and not state['Captain'] and + elif (config.get_int('output') & config.OUT_MKT_EDDN and not state['Captain'] and entry['event'] in ('Market', 'Outfitting', 'Shipyard')): # Market.json, Outfitting.json or Shipyard.json to process @@ -749,7 +875,12 @@ def journal_entry( # noqa: C901 this.commodities = this.outfitting = this.shipyard = None this.marketId = entry['MarketID'] - path = pathlib.Path(str(config.get('journaldir') or config.default_journal_dir)) / f'{entry["event"]}.json' + journaldir = config.get_str('journaldir') + if journaldir is None or journaldir == '': + journaldir = config.default_journal_dir + + path = pathlib.Path(journaldir) / f'{entry["event"]}.json' + with path.open('rb') as f: entry = json.load(f) if entry['event'] == 'Market': @@ -769,9 +900,19 @@ def journal_entry( # noqa: C901 logger.debug(f'Failed exporting {entry["event"]}', exc_info=e) return str(e) + return None -def cmdr_data(data: Mapping[str, Any], is_beta: bool) -> str: - if data['commander'].get('docked') and config.getint('output') & config.OUT_MKT_EDDN: + +def cmdr_data(data: CAPIData, is_beta: bool) -> Optional[str]: # noqa: CCR001 + """ + Process new CAPI data. + + :param data: CAPI data to process. + :param is_beta: bool - True if this is a beta version of the Game. + :return: str - Error message, or `None` if no errors. + """ + if (data['commander'].get('docked') or (this.on_foot and monitor.station) + and config.get_int('output') & config.OUT_MKT_EDDN): try: if this.marketId != data['lastStarport']['id']: this.commodities = this.outfitting = this.shipyard = None @@ -798,11 +939,21 @@ def cmdr_data(data: Mapping[str, Any], is_beta: bool) -> str: logger.debug('Failed exporting data', exc_info=e) return str(e) + return None + MAP_STR_ANY = Mapping[str, Any] def is_horizons(economies: MAP_STR_ANY, modules: MAP_STR_ANY, ships: MAP_STR_ANY) -> bool: + """ + Indicate if the supplied data indicates a player has Horizons access. + + :param economies: Economies of where the Cmdr is docked. + :param modules: Modules available at the docked station. + :param ships: Ships available at the docked station. + :return: bool - True if the Cmdr has Horizons access. + """ economies_colony = False modules_horizons = False ship_horizons = False diff --git a/plugins/edsm.py b/plugins/edsm.py index e9fbd46c..43a3c8ff 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -9,15 +9,17 @@ # 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. +from companion import CAPIData import json import sys import tkinter as tk from queue import Queue from threading import Thread -from typing import TYPE_CHECKING, Any, List, Mapping, MutableMapping, Optional, Tuple +from typing import TYPE_CHECKING, Any, List, Mapping, MutableMapping, Optional, Tuple, cast import requests +import killswitch import myNotebook as nb # noqa: N813 import plug from config import applongname, appversion, config @@ -53,6 +55,7 @@ this.system_population: Optional[int] = None this.station_link: tk.Tk = None this.station: Optional[str] = None this.station_marketid: Optional[int] = None # Frontier MarketID +this.on_foot = False STATION_UNDOCKED: str = '×' # "Station" name to display when not docked = U+00D7 __cleanup = str.maketrans({' ': None, '\n': None}) IMG_KNOWN_B64 = """ @@ -123,29 +126,31 @@ def plugin_start3(plugin_dir: str) -> str: this._IMG_ERROR = tk.PhotoImage(data=IMG_ERR_B64) # BBC Mode 5 '?' # Migrate old settings - if not config.get('edsm_cmdrs'): - if isinstance(config.get('cmdrs'), list) and config.get('edsm_usernames') and config.get('edsm_apikeys'): + if not config.get_list('edsm_cmdrs'): + if isinstance(config.get_list('cmdrs'), list) and config.get_list('edsm_usernames') and config.get_list('edsm_apikeys'): # Migrate <= 2.34 settings - config.set('edsm_cmdrs', config.get('cmdrs')) + config.set('edsm_cmdrs', config.get_list('cmdrs')) - elif config.get('edsm_cmdrname'): + elif config.get_list('edsm_cmdrname'): # Migrate <= 2.25 settings. edsm_cmdrs is unknown at this time - config.set('edsm_usernames', [config.get('edsm_cmdrname') or '']) - config.set('edsm_apikeys', [config.get('edsm_apikey') or '']) + config.set('edsm_usernames', [config.get_str('edsm_cmdrname', default='')]) + config.set('edsm_apikeys', [config.get_str('edsm_apikey', default='')]) - config.delete('edsm_cmdrname') - config.delete('edsm_apikey') + config.delete('edsm_cmdrname', suppress=True) + config.delete('edsm_apikey', suppress=True) - if config.getint('output') & 256: + if config.get_int('output') & 256: # Migrate <= 2.34 setting config.set('edsm_out', 1) - config.delete('edsm_autoopen') - config.delete('edsm_historical') + config.delete('edsm_autoopen', suppress=True) + config.delete('edsm_historical', suppress=True) + logger.debug('Starting worker thread...') this.thread = Thread(target=worker, name='EDSM worker') this.thread.daemon = True this.thread.start() + logger.debug('Done.') return 'EDSM' @@ -158,13 +163,16 @@ def plugin_app(parent: tk.Tk) -> None: def plugin_stop() -> None: - """Plugin exit hook.""" + """Stop this plugin.""" + logger.debug('Signalling queue to close...') # Signal thread to close and wait for it this.queue.put(None) this.thread.join() this.thread = None + this.session.close() # Suppress 'Exception ignored in: ' errors # TODO: this is bad. this._IMG_KNOWN = this._IMG_UNKNOWN = this._IMG_NEW = this._IMG_ERROR = None + logger.debug('Done.') def plugin_prefs(parent: tk.Tk, cmdr: str, is_beta: bool) -> tk.Frame: @@ -184,7 +192,7 @@ def plugin_prefs(parent: tk.Tk, cmdr: str, is_beta: bool) -> tk.Frame: underline=True ).grid(columnspan=2, padx=PADX, sticky=tk.W) # Don't translate - this.log = tk.IntVar(value=config.getint('edsm_out') and 1) + this.log = tk.IntVar(value=config.get_int('edsm_out') and 1) this.log_button = nb.Checkbutton( frame, text=_('Send flight log and Cmdr status to EDSM'), variable=this.log, command=prefsvarchanged ) @@ -284,9 +292,10 @@ def prefs_changed(cmdr: str, is_beta: bool) -> None: if cmdr and not is_beta: # TODO: remove this when config is rewritten. - cmdrs: List[str] = list(config.get('edsm_cmdrs') or []) - usernames: List[str] = list(config.get('edsm_usernames') or []) - apikeys: List[str] = list(config.get('edsm_apikeys') or []) + 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 cmdr in cmdrs: idx = cmdrs.index(cmdr) usernames.extend([''] * (1 + idx - len(usernames))) @@ -314,15 +323,15 @@ def credentials(cmdr: str) -> Optional[Tuple[str, str]]: if not cmdr: return None - cmdrs = config.get('edsm_cmdrs') + cmdrs = config.get_list('edsm_cmdrs') if not cmdrs: # Migrate from <= 2.25 cmdrs = [cmdr] config.set('edsm_cmdrs', cmdrs) - if cmdr in cmdrs and config.get('edsm_usernames') and config.get('edsm_apikeys'): + if cmdr in cmdrs and config.get_list('edsm_usernames') and config.get_list('edsm_apikeys'): idx = cmdrs.index(cmdr) - return (config.get('edsm_usernames')[idx], config.get('edsm_apikeys')[idx]) + return (config.get_list('edsm_usernames')[idx], config.get_list('edsm_apikeys')[idx]) else: return None @@ -332,14 +341,24 @@ def journal_entry( cmdr: str, is_beta: bool, system: str, station: str, entry: MutableMapping[str, Any], state: Mapping[str, Any] ) -> None: """Journal Entry hook.""" - if entry['event'] in ('CarrierJump', 'FSDJump', 'Location', 'Docked'): - logger.trace(f'''{entry["event"]} -Commander: {cmdr} -System: {system} -Station: {station} -state: {state!r} -entry: {entry!r}''' - ) + if (ks := killswitch.get_disabled('plugins.edsm.journal')).disabled: + logger.warning(f'EDSM Journal handler disabled via killswitch: {ks.reason}') + plug.show_error('EDSM Handler disabled. See Log.') + return + + elif (ks := killswitch.get_disabled(f'plugins.edsm.journal.event.{entry["event"]}')).disabled: + logger.warning(f'Handling of event {entry["event"]} has been disabled via killswitch: {ks.reason}') + return + + this.on_foot = state['OnFoot'] + # if entry['event'] in ('CarrierJump', 'FSDJump', 'Location', 'Docked'): + # logger.trace(f'''{entry["event"]} +# Commander: {cmdr} +# System: {system} +# Station: {station} +# state: {state!r} +# entry: {entry!r}''' +# ) # Always update our system address even if we're not currently the provider for system or station, but dont update # on events that contain "future" data, such as FSDTarget if entry['event'] in ('Location', 'Docked', 'CarrierJump', 'FSDJump'): @@ -353,13 +372,23 @@ entry: {entry!r}''' this.system_population = pop this.station = entry.get('StationName', this.station) - this.station_marketid = entry.get('MarketID', this.station) + # on_foot station detection + if entry['event'] == 'Location' and entry['BodyType'] == 'Station': + this.station = entry['Body'] + + this.station_marketid = entry.get('MarketID', this.station_marketid) # We might pick up StationName in DockingRequested, make sure we clear it if leaving if entry['event'] in ('Undocked', 'FSDJump', 'SupercruiseEntry'): this.station = None this.station_marketid = None - if config.get('station_provider') == 'EDSM': + if entry['event'] == 'Embark' and not entry.get('OnStation'): + # If we're embarking OnStation to a Taxi/Dropship we'll also get an + # Undocked event. + this.station = None + this.station_marketid = None + + if config.get_str('station_provider') == 'EDSM': to_set = this.station if not this.station: if this.system_population and this.system_population > 0: @@ -405,7 +434,7 @@ entry: {entry!r}''' # Send interesting events to EDSM if ( - config.getint('edsm_out') and not is_beta and not this.multicrew and credentials(cmdr) and + config.get_int('edsm_out') and not is_beta and not this.multicrew and credentials(cmdr) and entry['event'] not in this.discardedEvents ): # Introduce transient states into the event @@ -430,15 +459,15 @@ entry: {entry!r}''' materials.update(transient) this.queue.put((cmdr, materials)) - if entry['event'] in ('CarrierJump', 'FSDJump', 'Location', 'Docked'): - logger.trace(f'''{entry["event"]} -Queueing: {entry!r}''' - ) + # if entry['event'] in ('CarrierJump', 'FSDJump', 'Location', 'Docked'): + # logger.trace(f'''{entry["event"]} +# Queueing: {entry!r}''' +# ) this.queue.put((cmdr, entry)) # Update system data -def cmdr_data(data: Mapping[str, Any], is_beta: bool) -> None: +def cmdr_data(data: CAPIData, is_beta: bool) -> None: """CAPI Entry Hook.""" system = data['lastSystem']['name'] @@ -455,14 +484,14 @@ def cmdr_data(data: Mapping[str, Any], is_beta: bool) -> None: # TODO: Fire off the EDSM API call to trigger the callback for the icons - if config.get('system_provider') == 'EDSM': + if config.get_str('system_provider') == 'EDSM': this.system_link['text'] = this.system # 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('station_provider') == 'EDSM': - if data['commander']['docked']: + if config.get_str('station_provider') == 'EDSM': + if data['commander']['docked'] or this.on_foot and this.station: this.station_link['text'] = this.station elif data['lastStarport']['name'] and data['lastStarport']['name'] != "": @@ -485,10 +514,11 @@ def cmdr_data(data: Mapping[str, Any], is_beta: bool) -> None: # Worker thread def worker() -> None: """ - Upload worker. + Handle uploading events to EDSM API. Processes `this.queue` until the queued item is None. """ + logger.debug('Starting...') pending = [] # Unsent events closing = False @@ -496,11 +526,18 @@ def worker() -> None: item: Optional[Tuple[str, Mapping[str, Any]]] = this.queue.get() if item: (cmdr, entry) = item + else: + logger.debug('Empty queue message, setting closing = True') closing = True # Try to send any unsent events before we close retrying = 0 while retrying < 3: + if (res := killswitch.get_disabled("plugins.edsm.worker")).disabled: + logger.warning( + f'EDSM worker has been disabled via kill switch. Not uploading data. ({res.reason})' + ) + break try: if TYPE_CHECKING: # Tell the type checker that these two are bound. @@ -517,6 +554,7 @@ def worker() -> None: r = this.session.get('https://www.edsm.net/api-journal-v1/discard', timeout=_TIMEOUT) r.raise_for_status() this.discardedEvents = set(r.json()) + this.discardedEvents.discard('Docked') # should_send() assumes that we send 'Docked' events if not this.discardedEvents: logger.error( @@ -529,14 +567,14 @@ def worker() -> None: pending = list(filter(lambda x: x['event'] not in this.discardedEvents, pending)) if should_send(pending): - if any(p for p in pending if p['event'] in ('CarrierJump', 'FSDJump', 'Location', 'Docked')): - logger.trace("pending has at least one of " - "('CarrierJump', 'FSDJump', 'Location', 'Docked')" - " and it passed should_send()") - for p in pending: - if p['event'] in ('Location'): - logger.trace('"Location" event in pending passed should_send(), ' - f'timestamp: {p["timestamp"]}') + # if any(p for p in pending if p['event'] in ('CarrierJump', 'FSDJump', 'Location', 'Docked')): + # logger.trace("pending has at least one of " + # "('CarrierJump', 'FSDJump', 'Location', 'Docked')" + # " and it passed should_send()") + # for p in pending: + # if p['event'] in ('Location'): + # logger.trace('"Location" event in pending passed should_send(), ' + # f'timestamp: {p["timestamp"]}') creds = credentials(cmdr) # TODO: possibly unbound if creds is None: @@ -547,29 +585,29 @@ def worker() -> None: 'commanderName': username.encode('utf-8'), 'apiKey': apikey, 'fromSoftware': applongname, - 'fromSoftwareVersion': appversion, + 'fromSoftwareVersion': str(appversion()), 'message': json.dumps(pending, ensure_ascii=False).encode('utf-8'), } - if any(p for p in pending if p['event'] in ('CarrierJump', 'FSDJump', 'Location', 'Docked')): - data_elided = data.copy() - data_elided['apiKey'] = '' - logger.trace( - "pending has at least one of " - "('CarrierJump', 'FSDJump', 'Location', 'Docked')" - " Attempting API call with the following events:" - ) + # if any(p for p in pending if p['event'] in ('CarrierJump', 'FSDJump', 'Location', 'Docked')): + # data_elided = data.copy() + # data_elided['apiKey'] = '' + # logger.trace( + # "pending has at least one of " + # "('CarrierJump', 'FSDJump', 'Location', 'Docked')" + # " Attempting API call with the following events:" + # ) - for p in pending: - logger.trace(f"Event: {p!r}") - if p['event'] in ('Location'): - logger.trace('Attempting API call for "Location" event with timestamp: ' - f'{p["timestamp"]}') + # for p in pending: + # logger.trace(f"Event: {p!r}") + # if p['event'] in ('Location'): + # logger.trace('Attempting API call for "Location" event with timestamp: ' + # f'{p["timestamp"]}') - logger.trace(f'Overall POST data (elided) is:\n{data_elided}') + # logger.trace(f'Overall POST data (elided) is:\n{data_elided}') r = this.session.post('https://www.edsm.net/api-journal-v1', data=data, timeout=_TIMEOUT) - logger.trace(f'API response content: {r.content}') + # logger.trace(f'API response content: {r.content}') r.raise_for_status() reply = r.json() msg_num = reply['msgnum'] @@ -586,10 +624,12 @@ def worker() -> None: else: if msg_num // 100 == 1: - logger.trace('Overall OK') + # logger.trace('Overall OK') + pass elif msg_num // 100 == 5: - logger.trace('Event(s) not currently processed, but saved for later') + # logger.trace('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}') @@ -598,9 +638,8 @@ def worker() -> None: if not closing and e['event'] in ('StartUp', 'Location', 'FSDJump', 'CarrierJump'): # Update main window's system status this.lastlookup = r - + # calls update_status in main thread if not config.shutting_down: - # calls update_status in main thread this.system_link.event_generate('<>', when="tail") if r['msgnum'] // 100 != 1: @@ -610,6 +649,7 @@ def worker() -> None: pending = [] break # No exception, so assume success + except Exception as e: logger.debug(f'Attempt to send API events: retrying == {retrying}', exc_info=e) retrying += 1 @@ -618,8 +658,11 @@ def worker() -> None: plug.show_error(_("Error: Can't connect to EDSM")) if closing: + logger.debug('closing, so returning.') return + logger.debug('Done.') + def should_send(entries: List[Mapping[str, Any]]) -> bool: """ diff --git a/plugins/inara.py b/plugins/inara.py index 47eaf6dd..4f76b603 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -1,26 +1,23 @@ """Inara Sync.""" -import dataclasses import json -import sys +import threading import time import tkinter as tk -# For new impl from collections import OrderedDict, defaultdict, deque from operator import itemgetter -from queue import Queue from threading import Lock, Thread -from typing import ( - TYPE_CHECKING, Any, AnyStr, Callable, Deque, Dict, List, Mapping, MutableMapping, NamedTuple, Optional -) +from typing import TYPE_CHECKING, Any, Callable, Deque, Dict, List, Mapping, NamedTuple, Optional from typing import OrderedDict as OrderedDictT from typing import Sequence, Union, cast import requests +import killswitch import myNotebook as nb # noqa: N813 import plug import timeout_session +from companion import CAPIData from config import applongname, appversion, config from EDMCLogging import get_main_logger from ttkHyperlinkLabel import HyperlinkLabel @@ -37,58 +34,16 @@ FAKE = ('CQC', 'Training', 'Destination') # Fake systems that shouldn't be sent CREDIT_RATIO = 1.05 # Update credits if they change by 5% over the course of a session -this: Any = sys.modules[__name__] # For holding module globals -this.session = timeout_session.new_session() -this.queue = Queue() # Items to be sent to Inara by worker thread -this.lastlocation = None # eventData from the last Commander's Flight Log event -this.lastship = None # eventData from the last addCommanderShip or setCommanderShip event - -# Cached Cmdr state -this.events: List[OrderedDictT[str, Any]] = [] # Unsent events -this.event_lock = Lock -this.cmdr: Optional[str] = None -this.FID: Optional[str] = None # Frontier ID -this.multicrew: bool = False # don't send captain's ship info to Inara while on a crew -this.newuser: bool = False # just entered API Key - send state immediately -this.newsession: bool = True # starting a new session - wait for Cargo event -this.undocked: bool = False # just undocked -this.suppress_docked = False # Skip initial Docked event if started docked -this.cargo: Optional[OrderedDictT[str, Any]] = None -this.materials: Optional[OrderedDictT[str, Any]] = None -this.lastcredits: int = 0 # Send credit update soon after Startup / new game -this.storedmodules: Optional[OrderedDictT[str, Any]] = None -this.loadout: Optional[OrderedDictT[str, Any]] = None -this.fleet: Optional[List[OrderedDictT[str, Any]]] = None -this.shipswap: bool = False # just swapped ship - -# last time we updated, if unset in config this is 0, which means an instant update -LAST_UPDATE_CONF_KEY = 'inara_last_update' -EVENT_COLLECT_TIME = 31 # Minimum time to take collecting events before requesting a send -WORKER_WAIT_TIME = 35 # Minimum time for worker to wait between sends - -this.timer_run = True - - -# Main window clicks -this.system_link = None -this.system = None -this.system_address = None -this.system_population = None -this.station_link = None -this.station = None -this.station_marketid = None -STATION_UNDOCKED: str = '×' # "Station" name to display when not docked = U+00D7 - - +# These need to be defined above This class Credentials(NamedTuple): """Credentials holds the set of credentials required to identify an inara API payload to inara.""" - cmdr: str - fid: str + cmdr: Optional[str] + fid: Optional[str] api_key: str -EVENT_DATA = Union[Mapping[AnyStr, Any], Sequence[Mapping[AnyStr, Any]]] +EVENT_DATA = Union[Mapping[str, Any], Sequence[Mapping[str, Any]]] class Event(NamedTuple): @@ -99,16 +54,52 @@ class Event(NamedTuple): data: EVENT_DATA -@dataclasses.dataclass -class NewThis: - """ - NewThis is where the plugin stores all of its data. +class This: + """Holds module globals.""" - It is named NewThis as it is currently being migrated to. Once migration is complete it will be renamed to This. - """ + def __init__(self): + self.session = timeout_session.new_session() + self.thread: Thread + self.lastlocation = None # eventData from the last Commander's Flight Log event + self.lastship = None # eventData from the last addCommanderShip or setCommanderShip event - events: Dict[Credentials, Deque[Event]] = dataclasses.field(default_factory=lambda: defaultdict(deque)) - event_lock: Lock = dataclasses.field(default_factory=Lock) # protects events, for use when rewriting events + # Cached Cmdr state + self.cmdr: Optional[str] = None + self.FID: Optional[str] = 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.lastcredits: 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.shipswap: bool = False # just swapped ship + self.on_foot = False + + self.timer_run = True + + # Main window clicks + self.system_link: tk.Widget = None # type: ignore + self.system: Optional[str] = None # type: ignore + self.system_address: Optional[str] = None # type: ignore + self.system_population: Optional[int] = None + self.station_link: tk.Widget = None # type: ignore + self.station = None + self.station_marketid = None + + # Prefs UI + self.log: 'tk.IntVar' + self.log_button: nb.Checkbutton + self.label: HyperlinkLabel + self.apikey: nb.Entry + self.apikey_label: HyperlinkLabel + + 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: """ @@ -125,7 +116,15 @@ class NewThis: self.events[key].extend(filter(predicate, tmp)) -new_this = NewThis() +this = This() +# last time we updated, if unset in config this is 0, which means an instant update +LAST_UPDATE_CONF_KEY = 'inara_last_update' +EVENT_COLLECT_TIME = 31 # Minimum time to take collecting events before requesting a send +WORKER_WAIT_TIME = 35 # Minimum time for worker to wait between sends + +STATION_UNDOCKED: str = '×' # "Station" name to display when not docked = U+00D7 + + TARGET_URL = 'https://inara.cz/inapi/v1/' @@ -164,10 +163,16 @@ def station_url(system_name: str, station_name: str) -> str: def plugin_start3(plugin_dir: str) -> str: - """Plugin start Hook.""" + """ + Start this plugin. + + Start the worker thread to handle sending to Inara API. + """ + logger.debug('Starting worker thread...') this.thread = Thread(target=new_worker, name='Inara worker') this.thread.daemon = True this.thread.start() + logger.debug('Done.') return 'Inara' @@ -182,33 +187,35 @@ def plugin_app(parent: tk.Tk) -> None: def plugin_stop() -> None: """Plugin shutdown hook.""" - # Signal thread to close and wait for it - this.queue.put(None) - # this.thread.join() - # this.thread = None + logger.debug('We have no way to ask new_worker to stop, but...') + # The Newthis/new_worker doesn't have a method to ask the new_worker to + # stop. We're relying on it being a daemon thread and thus exiting when + # there are no non-daemon (i.e. main) threads running. this.timer_run = False + logger.debug('Done.') + def plugin_prefs(parent: tk.Tk, cmdr: str, is_beta: bool) -> tk.Frame: """Plugin Preferences UI hook.""" - PADX = 10 - BUTTONX = 12 # indent Checkbuttons and Radiobuttons - PADY = 2 # close spacing + x_padding = 10 + x_button_padding = 12 # indent Checkbuttons and Radiobuttons + y_padding = 2 # close spacing 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=PADX, sticky=tk.W) # Don't translate + ).grid(columnspan=2, padx=x_padding, sticky=tk.W) # Don't translate - this.log = tk.IntVar(value=config.getint('inara_out') and 1) + this.log = tk.IntVar(value=config.get_int('inara_out') and 1) this.log_button = nb.Checkbutton( frame, text=_('Send flight log and Cmdr status to Inara'), variable=this.log, command=prefsvarchanged ) - this.log_button.grid(columnspan=2, padx=BUTTONX, pady=(5, 0), sticky=tk.W) + this.log_button.grid(columnspan=2, padx=x_button_padding, pady=(5, 0), sticky=tk.W) nb.Label(frame).grid(sticky=tk.W) # big spacer @@ -221,12 +228,12 @@ def plugin_prefs(parent: tk.Tk, cmdr: str, is_beta: bool) -> tk.Frame: underline=True ) - this.label.grid(columnspan=2, padx=PADX, sticky=tk.W) + this.label.grid(columnspan=2, padx=x_padding, sticky=tk.W) this.apikey_label = nb.Label(frame, text=_('API Key')) # Inara setting - this.apikey_label.grid(row=12, padx=PADX, sticky=tk.W) + this.apikey_label.grid(row=12, padx=x_padding, sticky=tk.W) this.apikey = nb.Entry(frame) - this.apikey.grid(row=12, column=1, padx=PADX, pady=PADY, sticky=tk.EW) + this.apikey.grid(row=12, column=1, padx=x_padding, pady=y_padding, sticky=tk.EW) prefs_cmdr_changed(cmdr, is_beta) @@ -243,7 +250,7 @@ def prefs_cmdr_changed(cmdr: str, is_beta: bool) -> None: if cred: this.apikey.insert(0, cred) - state = tk.DISABLED + state: str = tk.DISABLED if cmdr and not is_beta and this.log.get(): state = tk.NORMAL @@ -265,14 +272,14 @@ def prefsvarchanged(): def prefs_changed(cmdr: str, is_beta: bool) -> None: """Preferences window closed hook.""" - changed = config.getint('inara_out') != this.log.get() + changed = config.get_int('inara_out') != this.log.get() config.set('inara_out', this.log.get()) if cmdr and not is_beta: this.cmdr = cmdr this.FID = None - cmdrs = config.get('inara_cmdrs') or [] - apikeys = config.get('inara_apikeys') or [] + cmdrs = config.get_list('inara_cmdrs', default=[]) + apikeys = config.get_list('inara_apikeys', default=[]) if cmdr in cmdrs: idx = cmdrs.index(cmdr) apikeys.extend([''] * (1 + idx - len(apikeys))) @@ -293,7 +300,7 @@ def prefs_changed(cmdr: str, is_beta: bool) -> None: ) -def credentials(cmdr: str) -> Optional[str]: +def credentials(cmdr: Optional[str]) -> Optional[str]: """ Get the credentials for the current commander. @@ -303,18 +310,31 @@ def credentials(cmdr: str) -> Optional[str]: if not cmdr: return None - cmdrs = config.get('inara_cmdrs') or [] - if cmdr in cmdrs and config.get('inara_apikeys'): - return config.get('inara_apikeys')[cmdrs.index(cmdr)] + 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)] else: return None -def journal_entry( +def journal_entry( # noqa: C901, CCR001 cmdr: str, is_beta: bool, system: str, station: str, entry: Dict[str, Any], state: Dict[str, Any] -) -> None: - """Journal entry hook.""" +) -> str: + """ + Journal entry hook. + + :return: str - empty if no error, else error string. + """ + if (ks := killswitch.get_disabled('plugins.inara.journal')).disabled: + logger.warning(f'INARA support has been disabled via killswitch: {ks.reason}') + plug.show_error('INARA disabled. See Log.') + return '' + + elif (ks := killswitch.get_disabled(f'plugins.inara.journal.event.{entry["event"]}')).disabled: + logger.warning(f'event {entry["event"]} processing has been disabled via killswitch: {ks.reason}') + + this.on_foot = state['OnFoot'] event_name: str = entry['event'] this.cmdr = cmdr this.FID = state['FID'] @@ -365,13 +385,23 @@ def journal_entry( this.system_population = pop this.station = entry.get('StationName', this.station) + # on_foot station detection + if entry['event'] == 'Location' and entry['BodyType'] == 'Station': + this.station = entry['Body'] + this.station_marketid = entry.get('MarketID', this.station_marketid) or this.station_marketid # We might pick up StationName in DockingRequested, make sure we clear it if leaving if event_name in ('Undocked', 'FSDJump', 'SupercruiseEntry'): this.station = None this.station_marketid = None - if config.getint('inara_out') and not is_beta and not this.multicrew and credentials(cmdr): + if entry['event'] == 'Embark' and not entry.get('OnStation'): + # If we're embarking OnStation to a Taxi/Dropship we'll also get an + # Undocked event. + this.station = None + this.station_marketid = None + + if config.get_int('inara_out') and not is_beta and not this.multicrew and credentials(cmdr): current_creds = Credentials(this.cmdr, this.FID, str(credentials(this.cmdr))) try: # Dump starting state to Inara @@ -389,17 +419,19 @@ def journal_entry( ] ) - 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 - ] - ) + # 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[Mapping[str, Any]] = [] + to_send_list: List[Mapping[str, Any]] = [] for k, v in state['Engineers'].items(): e = {'engineerName': k} if isinstance(v, tuple): @@ -408,12 +440,12 @@ def journal_entry( else: e['rankStage'] = v - to_send.append(e) + to_send_list.append(e) new_add_event( 'setCommanderRankEngineer', entry['timestamp'], - to_send, + to_send_list, ) # Update location @@ -428,7 +460,7 @@ def journal_entry( # Update ship if state['ShipID']: # Unknown if started in Fighter or SRV - cur_ship = { + cur_ship: Dict[str, Any] = { 'shipType': state['ShipType'], 'shipGameID': state['ShipID'], 'shipName': state['ShipName'], @@ -461,17 +493,17 @@ def journal_entry( elif event_name == 'EngineerProgress' and 'Engineer' in entry: # TODO: due to this var name being used above, the types are weird - to_send = {'engineerName': entry['Engineer']} + to_send_dict = {'engineerName': entry['Engineer']} if 'Rank' in entry: - to_send['rankValue'] = entry['Rank'] + to_send_dict['rankValue'] = entry['Rank'] else: - to_send['rankStage'] = entry['Progress'] + to_send_dict['rankStage'] = entry['Progress'] new_add_event( 'setCommanderRankEngineer', entry['timestamp'], - to_send + to_send_dict ) # PowerPlay status change @@ -498,7 +530,7 @@ def journal_entry( # Ship change if event_name == 'Loadout' and this.shipswap: - cur_ship: Dict[str, Any] = { + cur_ship = { 'shipType': state['ShipType'], 'shipGameID': state['ShipID'], 'shipName': state['ShipName'], # Can be None @@ -609,14 +641,15 @@ def journal_entry( # Ignore the following 'Docked' event this.suppress_docked = True - cargo = [{'itemName': k, 'itemCount': state['Cargo'][k]} for k in sorted(state['Cargo'])] + 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 if this.cargo != cargo: new_add_event('setCommanderInventoryCargo', entry['timestamp'], cargo) this.cargo = cargo - materials: List[Mapping[str, Any]] = [] + 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])] @@ -707,8 +740,8 @@ def journal_entry( # Fleet if event_name == 'StoredShips': - fleet = sorted( - [{ + fleet: List[OrderedDictT[str, Any]] = sorted( + [OrderedDict({ 'shipType': x['ShipType'], 'shipGameID': x['ShipID'], 'shipName': x.get('Name'), @@ -716,21 +749,21 @@ def journal_entry( 'starsystemName': entry['StarSystem'], 'stationName': entry['StationName'], 'marketID': entry['MarketID'], - } for x in entry['ShipsHere']] + - [{ + }) for x in entry['ShipsHere']] + + [OrderedDict({ 'shipType': x['ShipType'], 'shipGameID': x['ShipID'], 'shipName': x.get('Name'), 'isHot': x['Hot'], 'starsystemName': x.get('StarSystem'), # Not present for ships in transit 'marketID': x.get('ShipMarketID'), # " - } for x in entry['ShipsRemote']], + }) for x in entry['ShipsRemote']], key=itemgetter('shipGameID') ) if this.fleet != fleet: this.fleet = fleet - new_this.filter_events(current_creds, lambda e: e.name != 'setCommanderShip') + this.filter_events(current_creds, lambda e: e.name != 'setCommanderShip') # this.events = [x for x in this.events if x['eventName'] != 'setCommanderShip'] # Remove any unsent for ship in this.fleet: @@ -742,9 +775,11 @@ def journal_entry( if this.loadout != loadout: this.loadout = loadout - new_this.filter_events( + this.filter_events( current_creds, - lambda e: e.name != 'setCommanderShipLoadout' or e.data['shipGameID'] != this.loadout['shipGameID'] + lambda e: ( + e.name != 'setCommanderShipLoadout' + or cast(dict, e.data)['shipGameID'] != cast(dict, this.loadout)['shipGameID']) ) new_add_event('setCommanderShipLoadout', entry['timestamp'], this.loadout) @@ -752,7 +787,7 @@ def journal_entry( # Stored modules if event_name == 'StoredModules': items = {mod['StorageSlot']: mod for mod in entry['Items']} # Impose an order - modules = [] + modules: List[OrderedDictT[str, Any]] = [] for slot in sorted(items): item = items[slot] module: OrderedDictT[str, Any] = OrderedDict([ @@ -782,14 +817,14 @@ def journal_entry( # Only send on change this.storedmodules = modules # Remove any unsent - new_this.filter_events(current_creds, lambda e: e.name != 'setCommanderStorageModules') + this.filter_events(current_creds, lambda e: e.name != 'setCommanderStorageModules') # this.events = list(filter(lambda e: e['eventName'] != 'setCommanderStorageModules', this.events)) new_add_event('setCommanderStorageModules', entry['timestamp'], this.storedmodules) # Missions if event_name == 'MissionAccepted': - data = OrderedDict([ + data: OrderedDictT[str, Any] = OrderedDict([ ('missionName', entry['Name']), ('missionGameID', entry['MissionID']), ('influenceGain', entry['Influence']), @@ -899,7 +934,7 @@ def journal_entry( new_add_event('addCommanderCombatInterdicted', entry['timestamp'], data) elif event_name == 'Interdiction': - data: OrderedDictT[str, Any] = OrderedDict([ + data = OrderedDict([ ('starsystemName', system), ('isPlayer', entry['IsPlayer']), ('isSuccess', entry['Success']), @@ -940,7 +975,7 @@ def journal_entry( # Community Goals if event_name == 'CommunityGoal': # Remove any unsent - new_this.filter_events( + this.filter_events( current_creds, lambda e: e.name not in ('setCommunityGoal', 'setCommanderCommunityGoalProgress') ) @@ -950,7 +985,7 @@ def journal_entry( # )) for goal in entry['CurrentGoals']: - data: MutableMapping[str, Any] = OrderedDict([ + data = OrderedDict([ ('communitygoalGameID', goal['CGID']), ('communitygoalName', goal['Title']), ('starsystemName', goal['SystemName']), @@ -973,7 +1008,7 @@ def journal_entry( new_add_event('setCommunityGoal', entry['timestamp'], data) - data: MutableMapping[str, Any] = OrderedDict([ + data = OrderedDict([ ('communitygoalGameID', goal['CGID']), ('contribution', goal['PlayerContribution']), ('percentileBand', goal['PlayerPercentileBand']), @@ -1012,13 +1047,13 @@ def journal_entry( this.newuser = False # Only actually change URLs if we are current provider. - if config.get('system_provider') == 'Inara': + if config.get_str('system_provider') == 'Inara': this.system_link['text'] = this.system # 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('station_provider') == 'Inara': + if config.get_str('station_provider') == 'Inara': to_set: str = cast(str, this.station) if not to_set: if this.system_population is not None and this.system_population > 0: @@ -1031,8 +1066,10 @@ def journal_entry( # through correctly. We don't want a static string. this.station_link.update_idletasks() + return '' # No error -def cmdr_data(data, is_beta): + +def cmdr_data(data: CAPIData, is_beta): # noqa: CCR001 """CAPI event hook.""" this.cmdr = data['commander']['name'] @@ -1047,14 +1084,14 @@ def cmdr_data(data, is_beta): this.station = data['lastStarport']['name'] # Override standard URL functions - if config.get('system_provider') == 'Inara': + if config.get_str('system_provider') == 'Inara': this.system_link['text'] = this.system # 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('station_provider') == 'Inara': - if data['commander']['docked']: + if config.get_str('station_provider') == 'Inara': + if data['commander']['docked'] or this.on_foot and this.station: this.station_link['text'] = this.station elif data['lastStarport']['name'] and data['lastStarport']['name'] != "": @@ -1067,9 +1104,9 @@ def cmdr_data(data, is_beta): # through correctly. We don't want a static string. this.station_link.update_idletasks() - if config.getint('inara_out') and not is_beta and not this.multicrew and credentials(this.cmdr): + if config.get_int('inara_out') and not is_beta and not this.multicrew and credentials(this.cmdr): if not (CREDIT_RATIO > this.lastcredits / data['commander']['credits'] > 1/CREDIT_RATIO): - new_this.filter_events( + this.filter_events( Credentials(this.cmdr, this.FID, str(credentials(this.cmdr))), lambda e: e.name != 'setCommanderCredits' ) @@ -1084,10 +1121,10 @@ def cmdr_data(data, is_beta): } ) - this.lastcredits = float(data['commander']['credits']) + this.lastcredits = int(data['commander']['credits']) -def make_loadout(state: Dict[str, Any]) -> OrderedDictT[str, Any]: +def make_loadout(state: Dict[str, Any]) -> OrderedDictT[str, Any]: # noqa: CCR001 """ Construct an inara loadout from an event. @@ -1183,18 +1220,23 @@ def new_add_event( key = Credentials(str(cmdr), str(fid), api_key) # this fails type checking due to `this` weirdness, hence str() - with new_this.event_lock: - new_this.events[key].append(Event(name, timestamp, data)) + with this.event_lock: + this.events[key].append(Event(name, timestamp, data)) def new_worker(): """ - Queue worker. + Handle sending events to the Inara API. Will only ever send one message per WORKER_WAIT_TIME, regardless of status. """ + 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})") + continue + for creds, event_list in events.items(): if not event_list: continue @@ -1202,7 +1244,7 @@ def new_worker(): data = { 'header': { 'appName': applongname, - 'appVersion': appversion, + 'appVersion': str(appversion()), 'APIkey': creds.api_key, 'commanderName': creds.cmdr, 'commanderFrontierID': creds.fid @@ -1216,6 +1258,8 @@ def new_worker(): time.sleep(WORKER_WAIT_TIME) + logger.debug('Done.') + def get_events(clear: bool = True) -> Dict[Credentials, List[Event]]: """ @@ -1225,8 +1269,8 @@ def get_events(clear: bool = True) -> Dict[Credentials, List[Event]]: :return: the frozen event list """ out: Dict[Credentials, List[Event]] = {} - with new_this.event_lock: - for key, events in new_this.events.items(): + with this.event_lock: + for key, events in this.events.items(): out[key] = list(events) if clear: events.clear() @@ -1252,7 +1296,7 @@ def try_send_data(url: str, data: Mapping[str, Any]) -> None: return -def send_data(url: str, data: Mapping[str, Any]) -> bool: +def send_data(url: str, data: Mapping[str, Any]) -> bool: # noqa: CCR001 """ Write a set of events to the inara API. @@ -1293,22 +1337,20 @@ def send_data(url: str, data: Mapping[str, Any]) -> bool: 'setCommanderTravelLocation' ): this.lastlocation = reply_event.get('eventData', {}) - + # calls update_location in main thread if not config.shutting_down: - # calls update_location in main thread this.system_link.event_generate('<>', when="tail") elif data_event['eventName'] in ['addCommanderShip', 'setCommanderShip']: this.lastship = reply_event.get('eventData', {}) - + # calls update_ship in main thread if not config.shutting_down: - # calls update_ship in main thread this.system_link.event_generate('<>', when="tail") return True # regardless of errors above, we DID manage to send it, therefore inform our caller as such -def update_location(event: Dict[str, Any] = None) -> None: +def update_location(event=None) -> None: """ Update other plugins with our response to system and station changes. @@ -1319,12 +1361,12 @@ def update_location(event: Dict[str, Any] = None) -> None: plug.invoke(plugin, None, 'inara_notify_location', this.lastlocation) -def inara_notify_location(eventData: Dict[str, Any]) -> None: +def inara_notify_location(event_data) -> None: """Unused.""" pass -def update_ship(event: Dict[str, Any] = None) -> None: +def update_ship(event=None) -> None: """ Update other plugins with our response to changing. diff --git a/prefs.py b/prefs.py index e9c3afab..65a018a1 100644 --- a/prefs.py +++ b/prefs.py @@ -14,7 +14,7 @@ from typing import TYPE_CHECKING, Any, Callable, Optional, Type, Union import myNotebook as nb # noqa: N813 import plug -from config import applongname, appversion, config +from config import applongname, appversion_nobuild, config from EDMCLogging import edmclogger, get_main_logger from hotkey import hotkeymgr from l10n import Translations @@ -85,7 +85,7 @@ class PrefsVersion: """ # config.get('PrefsVersion') is the version preferences we last saved for - pv = config.getint('PrefsVersion') + pv = config.get_int('PrefsVersion') # If no PrefsVersion yet exists then return oldTest if not pv: return oldTest @@ -195,14 +195,15 @@ elif platform == 'win32': pass # https://msdn.microsoft.com/en-us/library/windows/desktop/bb762115 - BIF_RETURNONLYFSDIRS = 0x00000001 - BIF_USENEWUI = 0x00000050 - BFFM_INITIALIZED = 1 - BFFM_SETSELECTION = 0x00000467 + BIF_RETURNONLYFSDIRS = 0x00000001 + BIF_USENEWUI = 0x00000050 + BFFM_INITIALIZED = 1 + BFFM_SETSELECTION = 0x00000467 BrowseCallbackProc = ctypes.WINFUNCTYPE(ctypes.c_int, HWND, ctypes.c_uint, LPARAM, LPARAM) class BROWSEINFO(ctypes.Structure): - _fields_ = [("hwndOwner", HWND), ("pidlRoot", LPVOID), ("pszDisplayName", LPWSTR), ("lpszTitle", LPCWSTR), ("ulFlags", UINT), ("lpfn", BrowseCallbackProc), ("lParam", LPCWSTR), ("iImage", ctypes.c_int)] + _fields_ = [("hwndOwner", HWND), ("pidlRoot", LPVOID), ("pszDisplayName", LPWSTR), ("lpszTitle", LPCWSTR), + ("ulFlags", UINT), ("lpfn", BrowseCallbackProc), ("lParam", LPCWSTR), ("iImage", ctypes.c_int)] CalculatePopupWindowPosition = None if not is_wine: @@ -326,11 +327,11 @@ class PreferencesDialog(tk.Toplevel): output_frame = nb.Frame(root_notebook) output_frame.columnconfigure(0, weight=1) - if prefsVersion.shouldSetDefaults('0.0.0.0', not bool(config.getint('output'))): + if prefsVersion.shouldSetDefaults('0.0.0.0', not bool(config.get_int('output'))): output = config.OUT_SHIP # default settings else: - output = config.getint('output') + output = config.get_int('output') row = AutoInc(start=1) @@ -376,7 +377,7 @@ class PreferencesDialog(tk.Toplevel): self.out_auto_button.grid(columnspan=2, padx=self.BUTTONX, pady=(5, 0), sticky=tk.W, row=row.get()) self.outdir = tk.StringVar() - self.outdir.set(str(config.get('outdir'))) + self.outdir.set(str(config.get_str('outdir'))) 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 @@ -407,7 +408,12 @@ class PreferencesDialog(tk.Toplevel): row = AutoInc(start=1) self.logdir = tk.StringVar() - self.logdir.set(str(config.get('journaldir') or config.default_journal_dir or '')) + default = config.default_journal_dir if config.default_journal_dir_path is not None else '' + logdir = config.get_str('journaldir') + if logdir is None or logdir == '': + logdir = default + + self.logdir.set(logdir) self.logdir_entry = nb.Entry(config_frame, takefocus=False) # Location of the new Journal file in E:D 2.2 @@ -425,13 +431,13 @@ class PreferencesDialog(tk.Toplevel): ) self.logbutton.grid(column=3, padx=self.PADX, pady=self.PADY, sticky=tk.EW, row=row.get()) - if config.default_journal_dir: + if config.default_journal_dir_path: # Appearance theme and language setting nb.Button( config_frame, text=_('Default'), command=self.logdir_reset, - state=tk.NORMAL if config.get('journaldir') else tk.DISABLED + state=tk.NORMAL if config.get_str('journaldir') else tk.DISABLED ).grid(column=2, pady=self.PADY, sticky=tk.EW, row=row.get()) if platform in ('darwin', 'win32'): @@ -439,10 +445,10 @@ class PreferencesDialog(tk.Toplevel): columnspan=4, padx=self.PADX, pady=self.PADY*4, sticky=tk.EW, row=row.get() ) - self.hotkey_code = config.getint('hotkey_code') - self.hotkey_mods = config.getint('hotkey_mods') - self.hotkey_only = tk.IntVar(value=not config.getint('hotkey_always')) - self.hotkey_play = tk.IntVar(value=not config.getint('hotkey_mute')) + 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 # Hotkey/Shortcut settings prompt on OSX @@ -509,7 +515,7 @@ class PreferencesDialog(tk.Toplevel): ttk.Separator(config_frame, orient=tk.HORIZONTAL).grid( columnspan=4, padx=self.PADX, pady=self.PADY*4, sticky=tk.EW, row=row.get() ) - self.disable_autoappupdatecheckingame = tk.IntVar(value=config.getint('disable_autoappupdatecheckingame')) + self.disable_autoappupdatecheckingame = tk.IntVar(value=config.get_int('disable_autoappupdatecheckingame')) self.disable_autoappupdatecheckingame_btn = nb.Checkbutton( config_frame, text=_('Disable Automatic Application Updates Check when in-game'), @@ -531,8 +537,8 @@ class PreferencesDialog(tk.Toplevel): with row as cur_row: self.shipyard_provider = tk.StringVar( value=str( - config.get('shipyard_provider') in plug.provides('shipyard_url') - and config.get('shipyard_provider') or 'EDSY') + config.get_str('shipyard_provider') in plug.provides('shipyard_url') + and config.get_str('shipyard_provider', default='EDSY')) ) # Setting to decide which ship outfitting website to link to - either E:D Shipyard or Coriolis nb.Label(config_frame, text=_('Shipyard')).grid(padx=self.PADX, pady=2*self.PADY, sticky=tk.W, row=cur_row) @@ -543,7 +549,7 @@ class PreferencesDialog(tk.Toplevel): self.shipyard_button.configure(width=15) self.shipyard_button.grid(column=1, sticky=tk.W, row=cur_row) # Option for alternate URL opening - self.alt_shipyard_open = tk.IntVar(value=config.getint('use_alt_shipyard_open')) + self.alt_shipyard_open = tk.IntVar(value=config.get_int('use_alt_shipyard_open')) self.alt_shipyard_open_btn = nb.Checkbutton( config_frame, text=_('Use alternate URL method'), @@ -554,7 +560,7 @@ class PreferencesDialog(tk.Toplevel): self.alt_shipyard_open_btn.grid(column=2, sticky=tk.W, row=cur_row) with row as cur_row: - system_provider = config.get('system_provider') + system_provider = config.get_str('system_provider') self.system_provider = tk.StringVar( value=str(system_provider if system_provider in plug.provides('system_url') else 'EDSM') ) @@ -571,7 +577,7 @@ class PreferencesDialog(tk.Toplevel): self.system_button.grid(column=1, sticky=tk.W, row=cur_row) with row as cur_row: - station_provider = config.get('station_provider') + station_provider = config.get_str('station_provider') self.station_provider = tk.StringVar( value=str(station_provider if station_provider in plug.provides('station_url') else 'eddb') ) @@ -599,7 +605,7 @@ class PreferencesDialog(tk.Toplevel): text=_('Log Level') ).grid(padx=self.PADX, pady=2*self.PADY, sticky=tk.W, row=cur_row) - current_loglevel = config.get('loglevel') + current_loglevel = config.get_str('loglevel') if not current_loglevel: current_loglevel = logging.getLevelName(logging.INFO) @@ -628,10 +634,11 @@ class PreferencesDialog(tk.Toplevel): def __setup_appearance_tab(self, notebook: Notebook) -> None: self.languages = Translations.available_names() # Appearance theme and language setting - self.lang = tk.StringVar(value=self.languages.get(config.get('language'), _('Default'))) - self.always_ontop = tk.BooleanVar(value=bool(config.getint('always_ontop'))) - self.theme = tk.IntVar(value=config.getint('theme')) - self.theme_colors = [config.get('dark_text'), config.get('dark_highlight')] + self.lang = tk.StringVar(value=self.languages.get(config.get_str('language'), _('Default'))) + self.always_ontop = tk.BooleanVar(value=bool(config.get_int('always_ontop'))) + # self.minimize_system_tray = tk.BooleanVar(value=config.get_bool('minimize_system_tray')) + self.theme = tk.IntVar(value=config.get_int('theme')) + self.theme_colors = [config.get_str('dark_text'), config.get_str('dark_highlight')] self.theme_prompts = [ _('Normal text'), # Dark theme color setting _('Highlighted text'), # Dark theme color setting @@ -715,7 +722,7 @@ class PreferencesDialog(tk.Toplevel): ) self.ui_scale = tk.IntVar() - self.ui_scale.set(config.getint('ui_scale')) + self.ui_scale.set(config.get_int('ui_scale')) self.uiscale_bar = tk.Scale( appearance_frame, variable=self.ui_scale, # TODO: intvar, but annotated as DoubleVar @@ -733,9 +740,48 @@ class PreferencesDialog(tk.Toplevel): 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) + # 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() + ) + + with row as cur_row: + nb.Label(appearance_frame, text=_("Main window transparency")).grid( + padx=self.PADX, pady=self.PADY*2, 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 + self.transparency_bar = tk.Scale( + appearance_frame, + variable=self.transparency, # type: ignore # Its accepted as an intvar + orient=tk.HORIZONTAL, + length=300 * (float(theme.startup_ui_scale) / 100.0 * theme.default_ui_scale), # type: ignore # runtime + from_=100, + to=5, + tickinterval=10, + resolution=5, + command=lambda _: self.parent.wm_attributes("-alpha", self.transparency.get() / 100) + ) + + nb.Label( + appearance_frame, + text=_( + "100 means fully opaque.{CR}" + "Window is updated in real time" + ).format(CR='\n') + ).grid( + column=3, + padx=self.PADX, + pady=self.PADY*2, + sticky=tk.E, + row=cur_row + ) + + self.transparency_bar.grid(column=1, sticky=tk.W, row=cur_row) + # Always on top 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.PADY*4, sticky=tk.EW, row=row.get() ) self.ontop_button = nb.Checkbutton( @@ -746,6 +792,14 @@ class PreferencesDialog(tk.Toplevel): ) self.ontop_button.grid(columnspan=3, padx=self.BUTTONX, sticky=tk.W, row=row.get()) # Appearance setting + # if platform == 'win32': + # nb.Checkbutton( + # appearance_frame, + # 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 + nb.Label(appearance_frame).grid(sticky=tk.W) # big spacer notebook.add(appearance_frame, text=_('Appearance')) # Tab heading in settings @@ -897,14 +951,14 @@ class PreferencesDialog(tk.Toplevel): def browsecallback(hwnd, uMsg, lParam, lpData): # set initial folder if uMsg == BFFM_INITIALIZED and lpData: - ctypes.windll.user32.SendMessageW(hwnd, BFFM_SETSELECTION, 1, lpData); + ctypes.windll.user32.SendMessageW(hwnd, BFFM_SETSELECTION, 1, lpData) return 0 browseInfo = BROWSEINFO() browseInfo.lpszTitle = title browseInfo.ulFlags = BIF_RETURNONLYFSDIRS | BIF_USENEWUI browseInfo.lpfn = BrowseCallbackProc(browsecallback) - browseInfo.lParam = pathvar.get().startswith('~') and join(config.home, + browseInfo.lParam = pathvar.get().startswith('~') and join(config.home_path, pathvar.get()[2:]) or pathvar.get() ctypes.windll.ole32.CoInitialize(None) pidl = ctypes.windll.shell32.SHBrowseForFolderW(ctypes.byref(browseInfo)) @@ -981,7 +1035,7 @@ class PreferencesDialog(tk.Toplevel): def logdir_reset(self) -> None: """Reset the log dir to the default.""" - if config.default_journal_dir: + if config.default_journal_dir_path: self.logdir.set(config.default_journal_dir) self.outvarchanged() @@ -1077,23 +1131,23 @@ class PreferencesDialog(tk.Toplevel): def apply(self) -> None: """Update the config with the options set on the dialog.""" - config.set('PrefsVersion', prefsVersion.stringToSerial(appversion)) + config.set('PrefsVersion', prefsVersion.stringToSerial(appversion_nobuild())) config.set( 'output', (self.out_td.get() and config.OUT_MKT_TD) + (self.out_csv.get() and config.OUT_MKT_CSV) + (config.OUT_MKT_MANUAL if not self.out_auto.get() else 0) + (self.out_ship.get() and config.OUT_SHIP) + - (config.getint('output') & (config.OUT_MKT_EDDN | config.OUT_SYS_EDDN | config.OUT_SYS_DELAY)) + (config.get_int('output') & (config.OUT_MKT_EDDN | config.OUT_SYS_EDDN | config.OUT_SYS_DELAY)) ) config.set( 'outdir', - join(config.home, self.outdir.get()[2:]) if self.outdir.get().startswith('~') else self.outdir.get() + join(config.home_path, self.outdir.get()[2:]) if self.outdir.get().startswith('~') else self.outdir.get() ) logdir = self.logdir.get() - if config.default_journal_dir and logdir.lower() == config.default_journal_dir.lower(): + if config.default_journal_dir_path and logdir.lower() == config.default_journal_dir.lower(): config.set('journaldir', '') # default location else: @@ -1113,10 +1167,12 @@ class PreferencesDialog(tk.Toplevel): lang_codes = {v: k for k, v in self.languages.items()} # Codes by name config.set('language', lang_codes.get(self.lang.get()) or '') # or '' used here due to Default being None above - Translations.install(config.get('language') or None) # type: ignore # This sets self in weird ways. + Translations.install(config.get_str('language', default=None)) # type: ignore # This sets self in weird ways. config.set('ui_scale', self.ui_scale.get()) + config.set('ui_transparency', self.transparency.get()) config.set('always_ontop', self.always_ontop.get()) + # config.set('minimize_system_tray', self.minimize_system_tray.get()) config.set('theme', self.theme.get()) config.set('dark_text', self.theme_colors[0]) config.set('dark_highlight', self.theme_colors[1]) @@ -1136,7 +1192,7 @@ class PreferencesDialog(tk.Toplevel): self.after_cancel(self.cmdrchanged_alarm) self.cmdrchanged_alarm = None - self.parent.wm_attributes('-topmost', 1 if config.getint('always_ontop') else 0) + self.parent.wm_attributes('-topmost', 1 if config.get_int('always_ontop') else 0) self.destroy() if platform == 'darwin': diff --git a/protocol.py b/protocol.py index dcaa8b99..e9c7c4f7 100644 --- a/protocol.py +++ b/protocol.py @@ -1,39 +1,51 @@ -# edmc: protocol handler for cAPI authorisation +"""protocol handler for cAPI authorisation.""" - -import threading -import urllib.request, urllib.error, urllib.parse +import os import sys +import threading +import urllib.error +import urllib.parse +import urllib.request +from typing import TYPE_CHECKING, Optional -from config import appname, config -from constants import protocolhandler_redirect +from config import config +from constants import appname, protocolhandler_redirect from EDMCLogging import get_main_logger +if TYPE_CHECKING: + import tkinter + logger = get_main_logger() +is_wine = False + if sys.platform == 'win32': - from ctypes import * - from ctypes.wintypes import * + from ctypes import windll # type: ignore try: - is_wine = windll.ntdll.wine_get_version - except: - is_wine = False - - -class GenericProtocolHandler(object): - - def __init__(self): - self.redirect = protocolhandler_redirect # Base redirection URL - self.master = None - self.lastpayload = None - - def start(self, master): - self.master = master - - def close(self): + if windll.ntdll.wine_get_version: + is_wine = True + except Exception: pass - def event(self, url): + +class GenericProtocolHandler: + """Base Protocol Handler.""" + + def __init__(self) -> None: + self.redirect = protocolhandler_redirect # Base redirection URL + self.master: 'tkinter.Tk' = None # type: ignore + self.lastpayload = None + + def start(self, master: 'tkinter.Tk') -> None: + """Start Protocol Handler.""" + self.master = master + + def close(self) -> None: + """Stop / Close Protocol Handler.""" + pass + + def event(self, url) -> None: + """Generate an auth event.""" self.lastpayload = url logger.trace(f'Payload: {self.lastpayload}') @@ -42,212 +54,336 @@ class GenericProtocolHandler(object): self.master.event_generate('<>', when="tail") -if sys.platform == 'darwin' and getattr(sys, 'frozen', False): - +if sys.platform == 'darwin' and getattr(sys, 'frozen', False): # noqa: C901 # its guarding ALL macos stuff. import struct - import objc - from AppKit import NSAppleEventManager, NSObject - kInternetEventClass = kAEGetURL = struct.unpack('>l', b'GURL')[0] - keyDirectObject = struct.unpack('>l', b'----')[0] + import objc # type: ignore + from AppKit import NSAppleEventManager, NSObject # type: ignore - class ProtocolHandler(GenericProtocolHandler): + kInternetEventClass = kAEGetURL = struct.unpack('>l', b'GURL')[0] # noqa: N816 # API names + keyDirectObject = struct.unpack('>l', b'----')[0] # noqa: N816 # API names - POLL = 100 # ms + class DarwinProtocolHandler(GenericProtocolHandler): + """ + MacOS protocol handler implementation. - def start(self, master): + Uses macOS event stuff. + """ + + POLL = 100 # ms + + def start(self, master: 'tkinter.Tk') -> None: + """Start Protocol Handler.""" GenericProtocolHandler.start(self, master) - self.lasturl = None + self.lasturl: Optional[str] = None self.eventhandler = EventHandler.alloc().init() - def poll(self): - # No way of signalling to Tkinter from within the callback handler block that doesn't cause Python to crash, so poll. + def poll(self) -> None: + """Poll event until URL is updated.""" + # No way of signalling to Tkinter from within the callback handler block that doesn't cause Python to crash, + # so poll. TODO: Resolved? if self.lasturl and self.lasturl.startswith(self.redirect): self.event(self.lasturl) self.lasturl = None class EventHandler(NSObject): + """Handle NSAppleEventManager IPC stuff.""" - def init(self): + def init(self) -> None: + """ + Init method for handler. + + (I'd assume this is related to the subclassing of NSObject for why its not __init__) + """ self = objc.super(EventHandler, self).init() - NSAppleEventManager.sharedAppleEventManager().setEventHandler_andSelector_forEventClass_andEventID_(self, 'handleEvent:withReplyEvent:', kInternetEventClass, kAEGetURL) + NSAppleEventManager.sharedAppleEventManager().setEventHandler_andSelector_forEventClass_andEventID_( + self, + 'handleEvent:withReplyEvent:', + kInternetEventClass, + kAEGetURL + ) return self - def handleEvent_withReplyEvent_(self, event, replyEvent): - protocolhandler.lasturl = urllib.parse.unquote(event.paramDescriptorForKeyword_(keyDirectObject).stringValue()).strip() - protocolhandler.master.after(ProtocolHandler.POLL, protocolhandler.poll) + def handleEvent_withReplyEvent_(self, event, replyEvent) -> None: # noqa: N802 N803 # Required to override + """Actual event handling from NSAppleEventManager.""" + protocolhandler.lasturl = urllib.parse.unquote( # type: ignore # Its going to be a DPH in this code + event.paramDescriptorForKeyword_(keyDirectObject).stringValue() + ).strip() + + protocolhandler.master.after(DarwinProtocolHandler.POLL, protocolhandler.poll) # type: ignore -elif sys.platform == 'win32' and getattr(sys, 'frozen', False) and not is_wine and not config.auth_force_localserver: +elif (config.auth_force_edmc_protocol + or ( + sys.platform == 'win32' + and getattr(sys, 'frozen', False) + and not is_wine + and not config.auth_force_localserver + )): + # spell-checker: words HBRUSH HICON WPARAM wstring WNDCLASS HMENU HGLOBAL + from ctypes import windll # type: ignore + from ctypes import 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, LPVOID, LPWSTR, MSG, + UINT, WPARAM + ) class WNDCLASS(Structure): - _fields_ = [('style', UINT), - ('lpfnWndProc', WINFUNCTYPE(c_long, HWND, UINT, WPARAM, LPARAM)), - ('cbClsExtra', INT), - ('cbWndExtra', INT), - ('hInstance', HINSTANCE), - ('hIcon', HICON), - ('hCursor', c_void_p), - ('hbrBackground', HBRUSH), - ('lpszMenuName', LPCWSTR), - ('lpszClassName', LPCWSTR) + """ + A WNDCLASS structure. + + Ref: + + """ + + _fields_ = [ + ('style', UINT), + ('lpfnWndProc', WINFUNCTYPE(c_long, HWND, UINT, WPARAM, LPARAM)), + ('cbClsExtra', INT), + ('cbWndExtra', INT), + ('hInstance', HINSTANCE), + ('hIcon', HICON), + ('hCursor', c_void_p), + ('hbrBackground', HBRUSH), + ('lpszMenuName', LPCWSTR), + ('lpszClassName', LPCWSTR) ] - CW_USEDEFAULT = 0x80000000 + CW_USEDEFAULT = 0x80000000 - CreateWindowEx = windll.user32.CreateWindowExW - CreateWindowEx.argtypes = [DWORD, LPCWSTR, LPCWSTR, DWORD, INT, INT, INT, INT, HWND, HMENU, HINSTANCE, LPVOID] - CreateWindowEx.restype = HWND - RegisterClass = windll.user32.RegisterClassW - RegisterClass.argtypes = [POINTER(WNDCLASS)] - DefWindowProc = windll.user32.DefWindowProcW - GetParent = windll.user32.GetParent + CreateWindowExW = windll.user32.CreateWindowExW + CreateWindowExW.argtypes = [DWORD, LPCWSTR, LPCWSTR, DWORD, INT, INT, INT, INT, HWND, HMENU, HINSTANCE, LPVOID] + CreateWindowExW.restype = HWND + RegisterClassW = windll.user32.RegisterClassW + RegisterClassW.argtypes = [POINTER(WNDCLASS)] + DefWindowProcW = windll.user32.DefWindowProcW + GetParent = windll.user32.GetParent SetForegroundWindow = windll.user32.SetForegroundWindow - GetMessage = windll.user32.GetMessageW - TranslateMessage = windll.user32.TranslateMessage - DispatchMessage = windll.user32.DispatchMessageW - PostThreadMessage = windll.user32.PostThreadMessageW - SendMessage = windll.user32.SendMessageW - SendMessage.argtypes = [HWND, UINT, WPARAM, LPARAM] - PostMessage = windll.user32.PostMessageW - PostMessage.argtypes = [HWND, UINT, WPARAM, LPARAM] + GetMessageW = windll.user32.GetMessageW + TranslateMessage = windll.user32.TranslateMessage + DispatchMessageW = windll.user32.DispatchMessageW + PostThreadMessageW = windll.user32.PostThreadMessageW + SendMessageW = windll.user32.SendMessageW + SendMessageW.argtypes = [HWND, UINT, WPARAM, LPARAM] + PostMessageW = windll.user32.PostMessageW + PostMessageW.argtypes = [HWND, UINT, WPARAM, LPARAM] - WM_QUIT = 0x0012 - WM_DDE_INITIATE = 0x03E0 - WM_DDE_TERMINATE = 0x03E1 - WM_DDE_ACK = 0x03E4 - WM_DDE_EXECUTE = 0x03E8 + WM_QUIT = 0x0012 + # https://docs.microsoft.com/en-us/windows/win32/dataxchg/wm-dde-initiate + WM_DDE_INITIATE = 0x03E0 + WM_DDE_TERMINATE = 0x03E1 + WM_DDE_ACK = 0x03E4 + WM_DDE_EXECUTE = 0x03E8 - PackDDElParam = windll.user32.PackDDElParam + PackDDElParam = windll.user32.PackDDElParam PackDDElParam.argtypes = [UINT, LPARAM, LPARAM] - GlobalAddAtom = windll.kernel32.GlobalAddAtomW - GlobalAddAtom.argtypes = [LPWSTR] - GlobalAddAtom.restype = ATOM - GlobalGetAtomName = windll.kernel32.GlobalGetAtomNameW - GlobalGetAtomName.argtypes = [ATOM, LPWSTR, INT] - GlobalGetAtomName.restype = UINT - GlobalLock = windll.kernel32.GlobalLock + GlobalAddAtomW = windll.kernel32.GlobalAddAtomW + GlobalAddAtomW.argtypes = [LPWSTR] + GlobalAddAtomW.restype = ATOM + GlobalGetAtomNameW = windll.kernel32.GlobalGetAtomNameW + GlobalGetAtomNameW.argtypes = [ATOM, LPWSTR, INT] + GlobalGetAtomNameW.restype = UINT + GlobalLock = windll.kernel32.GlobalLock GlobalLock.argtypes = [HGLOBAL] GlobalLock.restype = LPVOID - GlobalUnlock = windll.kernel32.GlobalUnlock + GlobalUnlock = windll.kernel32.GlobalUnlock GlobalUnlock.argtypes = [HGLOBAL] GlobalUnlock.restype = BOOL - + # Windows Message handler stuff (IPC) + # https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms633573(v=vs.85) @WINFUNCTYPE(c_long, HWND, UINT, WPARAM, LPARAM) - def WndProc(hwnd, message, wParam, lParam): + def WndProc(hwnd: HWND, message: UINT, wParam, lParam): # noqa: N803 N802 + """ + Deal with DDE requests. + + :param hwnd: Window handle + :param message: The message being sent + :param wParam: Additional Message Information (depends on message type) + :param lParam: Also additional message information + :return: ??? + """ + if message != WM_DDE_INITIATE: + # Not a DDE init message, bail and tell windows to do the default + # https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-defwindowproca?redirectedfrom=MSDN + return DefWindowProcW(hwnd, message, wParam, lParam) + service = create_unicode_buffer(256) topic = create_unicode_buffer(256) - if message == WM_DDE_INITIATE: - if ((lParam & 0xffff == 0 or (GlobalGetAtomName(lParam & 0xffff, service, 256) and service.value == appname)) and - (lParam >> 16 == 0 or (GlobalGetAtomName(lParam >> 16, topic, 256) and topic.value.lower() == 'system'))): - SendMessage(wParam, WM_DDE_ACK, hwnd, PackDDElParam(WM_DDE_ACK, GlobalAddAtom(appname), GlobalAddAtom('System'))) - return 0 - return DefWindowProc(hwnd, message, wParam, lParam) + # Note that lParam is 32 bits, and broken into two 16 bit words. This will break on 64bit as the math is + # wrong + lparam_low = lParam & 0xFFFF # if nonzero, the target application for which a conversation is requested + lparam_high = lParam >> 16 # if nonzero, the topic of said conversation + # if either of the words are nonzero, they contain + # atoms https://docs.microsoft.com/en-us/windows/win32/dataxchg/about-atom-tables + # which we can read out as shown below, and then compare. - class ProtocolHandler(GenericProtocolHandler): + target_is_valid = lparam_low == 0 or ( + GlobalGetAtomNameW(lparam_low, service, 256) and service.value == appname + ) - def __init__(self): - GenericProtocolHandler.__init__(self) - self.thread = None + topic_is_valid = lparam_high == 0 or ( + GlobalGetAtomNameW(lparam_high, topic, 256) and topic.value.lower() == 'system' + ) - def start(self, master): - GenericProtocolHandler.start(self, master) + if target_is_valid and topic_is_valid: + # if everything is happy, send an acknowledgement of the DDE request + SendMessageW( + wParam, WM_DDE_ACK, hwnd, PackDDElParam(WM_DDE_ACK, GlobalAddAtomW(appname), GlobalAddAtomW('System')) + ) + + return 0 + + class WindowsProtocolHandler(GenericProtocolHandler): + """ + Windows implementation of GenericProtocolHandler. + + This works by using windows Dynamic Data Exchange to pass messages between processes + https://en.wikipedia.org/wiki/Dynamic_Data_Exchange + """ + + def __init__(self) -> None: + super().__init__() + self.thread: Optional[threading.Thread] = None + + def start(self, master: 'tkinter.Tk') -> None: + """Start the DDE thread.""" + super().start(master) self.thread = threading.Thread(target=self.worker, name='DDE worker') self.thread.daemon = True self.thread.start() - def close(self): + def close(self) -> None: + """Stop the DDE thread.""" thread = self.thread if thread: self.thread = None - PostThreadMessage(thread.ident, WM_QUIT, 0, 0) - thread.join() # Wait for it to quit + PostThreadMessageW(thread.ident, WM_QUIT, 0, 0) + thread.join() # Wait for it to quit - def worker(self): + def worker(self) -> None: + """Start a DDE server.""" wndclass = WNDCLASS() - wndclass.style = 0 - wndclass.lpfnWndProc = WndProc - wndclass.cbClsExtra = 0 - wndclass.cbWndExtra = 0 - wndclass.hInstance = windll.kernel32.GetModuleHandleW(0) - wndclass.hIcon = None - wndclass.hCursor = None - wndclass.hbrBackground = None - wndclass.lpszMenuName = None - wndclass.lpszClassName = 'DDEServer' + wndclass.style = 0 + wndclass.lpfnWndProc = WndProc + wndclass.cbClsExtra = 0 + wndclass.cbWndExtra = 0 + wndclass.hInstance = windll.kernel32.GetModuleHandleW(0) + wndclass.hIcon = None + wndclass.hCursor = None + wndclass.hbrBackground = None + wndclass.lpszMenuName = None + wndclass.lpszClassName = 'DDEServer' + + if not RegisterClassW(byref(wndclass)): + print('Failed to register Dynamic Data Exchange for cAPI') + return + + # https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw + hwnd = CreateWindowExW( + 0, # dwExStyle + wndclass.lpszClassName, # lpClassName + "DDE Server", # lpWindowName + 0, # dwStyle + CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, # X, Y, nWidth, nHeight + self.master.winfo_id(), # hWndParent # Don't use HWND_MESSAGE since the window won't get DDE broadcasts + None, # hMenu + wndclass.hInstance, # hInstance + None # lpParam + ) + + msg = MSG() + # Calls GetMessageW: https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmessagew + while GetMessageW(byref(msg), None, 0, 0) != 0: + logger.trace(f'DDE message of type: {msg.message}') + if msg.message == WM_DDE_EXECUTE: + # GlobalLock does some sort of "please dont move this?" + # https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globallock + args = wstring_at(GlobalLock(msg.lParam)).strip() + GlobalUnlock(msg.lParam) # Unlocks the GlobalLock-ed object + + if args.lower().startswith('open("') and args.endswith('")'): + logger.trace(f'args are: {args}') + url = urllib.parse.unquote(args[6:-2]).strip() + if url.startswith(self.redirect): + logger.debug(f'Message starts with {self.redirect}') + self.event(url) + + SetForegroundWindow(GetParent(self.master.winfo_id())) # raise app window + # Send back a WM_DDE_ACK. this is _required_ with WM_DDE_EXECUTE + PostMessageW(msg.wParam, WM_DDE_ACK, hwnd, PackDDElParam(WM_DDE_ACK, 0x80, msg.lParam)) - if RegisterClass(byref(wndclass)): - hwnd = CreateWindowEx(0, - wndclass.lpszClassName, - "DDE Server", - 0, - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, - self.master.winfo_id(), # Don't use HWND_MESSAGE since the window won't get DDE broadcasts - None, - wndclass.hInstance, - None) - msg = MSG() - while GetMessage(byref(msg), None, 0, 0) != 0: - logger.trace(f'DDE message of type: {msg.message}') - if msg.message == WM_DDE_EXECUTE: - args = wstring_at(GlobalLock(msg.lParam)).strip() - GlobalUnlock(msg.lParam) - if args.lower().startswith('open("') and args.endswith('")'): - logger.trace(f'args are: {args}') - url = urllib.parse.unquote(args[6:-2]).strip() - logger.trace(f'Parsed url: {url}') - if url.startswith(self.redirect): - logger.debug(f'Message starts with {self.redirect}') - self.event(url) - SetForegroundWindow(GetParent(self.master.winfo_id())) # raise app window - PostMessage(msg.wParam, WM_DDE_ACK, hwnd, PackDDElParam(WM_DDE_ACK, 0x80, msg.lParam)) - else: - PostMessage(msg.wParam, WM_DDE_ACK, hwnd, PackDDElParam(WM_DDE_ACK, 0, msg.lParam)) - elif msg.message == WM_DDE_TERMINATE: - PostMessage(msg.wParam, WM_DDE_TERMINATE, hwnd, 0) else: - TranslateMessage(byref(msg)) - DispatchMessage(byref(msg)) - else: - print('Failed to register DDE for cAPI') + # Send back a WM_DDE_ACK. this is _required_ with WM_DDE_EXECUTE + PostMessageW(msg.wParam, WM_DDE_ACK, hwnd, PackDDElParam(WM_DDE_ACK, 0, msg.lParam)) -else: # Linux / Run from source + elif msg.message == WM_DDE_TERMINATE: + PostMessageW(msg.wParam, WM_DDE_TERMINATE, hwnd, 0) - from http.server import HTTPServer, BaseHTTPRequestHandler + else: + TranslateMessage(byref(msg)) # "Translates virtual key messages into character messages" ??? + DispatchMessageW(byref(msg)) - class ProtocolHandler(GenericProtocolHandler): - def __init__(self): - GenericProtocolHandler.__init__(self) +else: # Linux / Run from source + + from http.server import BaseHTTPRequestHandler, HTTPServer + + class LinuxProtocolHandler(GenericProtocolHandler): + """ + Implementation of GenericProtocolHandler. + + This implementation uses a localhost HTTP server + """ + + def __init__(self) -> None: + super().__init__() self.httpd = HTTPServer(('localhost', 0), HTTPRequestHandler) - self.redirect = 'http://localhost:%d/auth' % self.httpd.server_port - logger.trace(f'Web server listening on {self.redirect}') - self.thread = None + self.redirect = f'http://localhost:{self.httpd.server_port}/auth' + if not os.getenv("EDMC_NO_UI"): + logger.info(f'Web server listening on {self.redirect}') - def start(self, master): + self.thread: Optional[threading.Thread] = None + + def start(self, master) -> None: + """Start the HTTP server thread.""" GenericProtocolHandler.start(self, master) self.thread = threading.Thread(target=self.worker, name='OAuth worker') self.thread.daemon = True self.thread.start() - def close(self): + def close(self) -> None: + """Shutdown the HTTP server thread.""" thread = self.thread if thread: + logger.debug('Thread') self.thread = None - if self.httpd: - self.httpd.shutdown() - thread.join() # Wait for it to quit - def worker(self): + if self.httpd: + logger.info('Shutting down httpd') + self.httpd.shutdown() + + logger.info('Joining thread') + thread.join() # Wait for it to quit + + else: + logger.debug('No thread') + + logger.debug('Done.') + + def worker(self) -> None: + """HTTP Worker.""" + # TODO: This should probably be more ephemeral, and only handle one request, as its all we're expecting self.httpd.serve_forever() class HTTPRequestHandler(BaseHTTPRequestHandler): + """Simple HTTP server to handle IPC from protocol handler.""" - def parse(self): + def parse(self) -> bool: + """Parse a request.""" logger.trace(f'Got message on path: {self.path}') url = urllib.parse.unquote(self.path) if url.startswith('/auth'): @@ -256,25 +392,43 @@ else: # Linux / Run from source self.send_response(200) return True else: - self.send_response(404) # Not found + self.send_response(404) # Not found return False - def do_HEAD(self): + def do_HEAD(self) -> None: # noqa: N802 # Required to override + """Handle HEAD Request.""" self.parse() self.end_headers() - def do_GET(self): + def do_GET(self) -> None: # noqa: N802 # Required to override + """Handle GET Request.""" if self.parse(): self.send_header('Content-Type', 'text/html') self.end_headers() - self.wfile.write('{}'.format('Authentication successful').encode('utf-8')) - self.wfile.write('

{}

'.format('Authentication successful').encode('utf-8')) + self.wfile.write('Authentication successful'.encode('utf-8')) + self.wfile.write('

Authentication successful

'.encode('utf-8')) else: self.end_headers() def log_request(self, code, size=None): + """Override to prevent logging.""" pass # singleton -protocolhandler = ProtocolHandler() +protocolhandler: GenericProtocolHandler + +if sys.platform == 'darwin' and getattr(sys, 'frozen', False): + protocolhandler = DarwinProtocolHandler() # pyright: reportUnboundVariable=false + +elif ( + sys.platform == 'win32' + and config.auth_force_edmc_protocol or ( + getattr(sys, 'frozen', False) + and not is_wine + and not config.auth_force_localserver + ) + ): + protocolhandler = WindowsProtocolHandler() +else: + protocolhandler = LinuxProtocolHandler() diff --git a/pyproject.toml b/pyproject.toml index 5b2d299b..35ab26e4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,3 +4,9 @@ max_line_length = 120 [tool.isort] multi_line_output = 5 line_length = 119 + +[tool.pytest.ini_options] +testpaths = ["tests"] # Search for tests in tests/ + +[tool.coverage.run] +omit = ["venv/*"] # when running pytest --cov, dont report coverage in venv directories diff --git a/requirements-dev.txt b/requirements-dev.txt index e2ea8f11..cfa41fe6 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,27 +1,41 @@ +# So that you don't get warnings like: +# Using legacy 'setup.py install' for flake8-annotations-coverage, since package 'wheel' is not installed. +wheel + # Static analysis tools -flake8==3.8.3 -flake8-annotations-coverage==0.0.4 +flake8==3.9.2 +flake8-annotations-coverage==0.0.5 flake8-cognitive-complexity==0.1.0 -flake8-comprehensions==3.2.3 -flake8-docstrings==1.5.0 -isort==5.5.2 +flake8-comprehensions==3.5.0 +flake8-docstrings==1.6.0 +isort==5.8.0 flake8-isort==4.0.0 -flake8-json==19.8.0 -flake8-noqa==1.0.5 +flake8-json==21.1.0 +flake8-noqa==1.1.0 flake8-polyfill==1.0.2 flake8-use-fstring==1.1 +mypy==0.812 pep8-naming==0.11.1 +safety==1.10.3 # Code formatting tools -autopep8==1.5.4 +autopep8==1.5.7 # HTML changelogs grip==4.5.2 # Packaging # We only need py2exe on windows. -py2exe==0.10.0.2; sys_platform == 'win32' +py2exe==0.10.4.0; sys_platform == 'win32' + +# Testing +pytest==6.2.4 +pytest-cov==2.11.1 # Pytest code coverage support +coverage[toml]==5.5 # pytest-cov dep. This is here to ensure that it includes TOML support for pyproject.toml configs +# For manipulating folder permissions and the like. +pywin32==300; sys_platform == 'win32' + # All of the normal requirements -r requirements.txt diff --git a/requirements.txt b/requirements.txt index a7079592..ee9255db 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,8 @@ -certifi==2019.9.11 +certifi==2020.12.5 requests==2.25.1 -watchdog==0.10.3 +watchdog==2.1.1 +# Commented out because this doesn't package well with py2exe +# infi.systray==0.1.12; sys_platform == 'win32' # argh==0.26.2 watchdog dep # pyyaml==5.3.1 watchdog dep semantic-version==2.8.5 diff --git a/setup.py b/setup.py index e3868777..372b4477 100755 --- a/setup.py +++ b/setup.py @@ -1,43 +1,61 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ -This is a setup.py script generated by py2applet +Script to build to .exe and .msi package. -Usage: - python setup.py py2app +.exe build is via py2exe on win32. +.msi packaging utilises Windows SDK. """ -from distutils.core import setup import codecs import os -from os.path import exists, isdir, join import platform import re import shutil import sys +from distutils.core import setup +from os.path import exists, isdir, join from tempfile import gettempdir -import semantic_version +from typing import Any, Generator, Set -from config import appname as APPNAME, applongname as APPLONGNAME, appcmdname as APPCMDNAME, appversion as VERSION, copyright as COPYRIGHT -from config import update_feed, update_interval +from config import ( + appcmdname, applongname, appname, appversion, appversion_nobuild, copyright, git_shorthash_from_head, update_feed, + update_interval +) +from constants import GITVERSION_FILE -if sys.version_info[0:2] != (3, 7): +if sys.version_info[0:2] != (3, 9): raise AssertionError(f'Unexpected python version {sys.version}') -if sys.platform=='win32': - assert platform.architecture()[0]=='32bit', 'Assumes a Python built for 32bit' - import py2exe +########################################################################### +# Retrieve current git short hash and store in file GITVERSION_FILE +git_shorthash = git_shorthash_from_head() +if git_shorthash is None: + exit(-1) + +with open(GITVERSION_FILE, 'w+', encoding='utf-8') as gvf: + gvf.write(git_shorthash) + +print(f'Git short hash: {git_shorthash}') +########################################################################### + +if sys.platform == 'win32': + assert platform.architecture()[0] == '32bit', 'Assumes a Python built for 32bit' + import py2exe # noqa: F401 # Yes, this *is* used dist_dir = 'dist.win32' -elif sys.platform=='darwin': + +elif sys.platform == 'darwin': dist_dir = 'dist.macosx' + else: - assert False, 'Unsupported platform %s' % sys.platform + assert False, f'Unsupported platform {sys.platform}' # Split version, as py2exe wants the 'base' for version -semver = semantic_version.Version.coerce(VERSION) -BASEVERSION = str(semver.truncate('patch')) +semver = appversion() +appversion_str = str(semver) +base_appversion = str(semver.truncate('patch')) -if dist_dir and len(dist_dir)>1 and isdir(dist_dir): +if dist_dir and len(dist_dir) > 1 and isdir(dist_dir): shutil.rmtree(dist_dir) # "Developer ID Application" name for signing @@ -45,97 +63,152 @@ macdeveloperid = None # Windows paths WIXPATH = r'C:\Program Files (x86)\WiX Toolset v3.11\bin' -SDKPATH = r'C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x86' +SDKPATH = r'C:\Program Files (x86)\Windows Kits\10\bin\10.0.19041.0\x86' # OSX paths SPARKLE = '/Library/Frameworks/Sparkle.framework' -# Patch py2app recipe enumerator to skip the sip recipe since it's too enthusiastic - we'll list additional Qt modules explicitly -if sys.platform=='darwin': - from py2app import recipes +if sys.platform == 'darwin': + # Patch py2app recipe enumerator to skip the sip recipe since it's too + # enthusiastic - we'll list additional Qt modules explicitly import py2app.build_app - def iterRecipes(module=recipes): + from py2app import recipes + + # NB: 'Any' is because I don't have MacOS docs + def iter_recipes(module=recipes) -> Generator[str, Any]: + """Enumerate recipes via alternate method.""" for name in dir(module): - if name.startswith('_') or name=='sip': + if name.startswith('_') or name == 'sip': continue check = getattr(getattr(module, name), 'check', None) if check is not None: yield (name, check) - py2app.build_app.iterRecipes = iterRecipes + + py2app.build_app.iterRecipes = iter_recipes APP = 'EDMarketConnector.py' APPCMD = 'EDMC.py' -SHORTVERSION = ''.join(VERSION.split('.')[:3]) -PLUGINS = [ 'plugins/coriolis.py', 'plugins/eddb.py', 'plugins/eddn.py', 'plugins/edsm.py', 'plugins/edsy.py', 'plugins/inara.py' ] +PLUGINS = [ + 'plugins/coriolis.py', + 'plugins/eddb.py', + 'plugins/eddn.py', + 'plugins/edsm.py', + 'plugins/edsy.py', + 'plugins/inara.py', +] -if sys.platform=='darwin': - OPTIONS = { 'py2app': - {'dist_dir': dist_dir, - 'optimize': 2, - 'packages': [ - 'requests', - 'sqlite3', # Included for plugins - ], - 'includes': [ - 'shutil', # Included for plugins - 'zipfile', # Included for plugins - ], - 'frameworks': [ 'Sparkle.framework' ], - 'excludes': [ 'distutils', '_markerlib', 'PIL', 'pkg_resources', 'simplejson', 'unittest' ], - 'iconfile': '%s.icns' % APPNAME, - 'include_plugins': [('plugins', x) for x in PLUGINS], - 'resources': [ 'commodity.csv', 'rare_commodity.csv', 'snd_good.wav', 'snd_bad.wav', 'modules.p', 'ships.p', 'stations.p', 'systems.p'], - 'site_packages': False, - 'plist': { - 'CFBundleName': APPLONGNAME, - 'CFBundleIdentifier': 'uk.org.marginal.%s' % APPNAME.lower(), - 'CFBundleLocalizations': sorted(set([x[:-len('.lproj')] for x in os.listdir(join(SPARKLE, 'Resources')) if x.endswith('.lproj')]) | set([x[:-len('.strings')] for x in os.listdir('L10n') if x.endswith('.strings')])), # https://github.com/sparkle-project/Sparkle/issues/238 - 'CFBundleShortVersionString': VERSION, - 'CFBundleVersion': VERSION, - 'CFBundleURLTypes': [ - { - 'CFBundleTypeRole': 'Viewer', - 'CFBundleURLName': 'uk.org.marginal.%s.URLScheme' % APPNAME.lower(), - 'CFBundleURLSchemes': ['edmc'], - } - ], - 'LSMinimumSystemVersion': '10.10', - 'NSAppleScriptEnabled': True, - 'NSHumanReadableCopyright': COPYRIGHT, - 'SUEnableAutomaticChecks': True, - 'SUShowReleaseNotes': True, - 'SUAllowsAutomaticUpdates': False, - 'SUFeedURL': update_feed, - 'SUScheduledCheckInterval': update_interval, - }, - 'graph': True, # output dependency graph in dist - } +if sys.platform == 'darwin': + def get_cfbundle_localizations() -> Set: + """ + Build a set of the localisation files. + + See https://github.com/sparkle-project/Sparkle/issues/238 + """ + return sorted( + ( + [x[:-len('.lproj')] for x in os.listdir(join(SPARKLE, 'Resources')) if x.endswith('.lproj')] + ) | ( + [x[:-len('.strings')] for x in os.listdir('L10n') if x.endswith('.strings')] + ) + ) + + OPTIONS = { + 'py2app': { + 'dist_dir': dist_dir, + 'optimize': 2, + 'packages': [ + 'requests', + 'sqlite3', # Included for plugins + ], + 'includes': [ + 'shutil', # Included for plugins + 'zipfile', # Included for plugins + ], + 'frameworks': [ + 'Sparkle.framework' + ], + 'excludes': [ + 'distutils', + '_markerlib', + 'PIL', + 'pkg_resources', + 'simplejson', + 'unittest' + ], + 'iconfile': f'{appname}.icns', + 'include_plugins': [ + ('plugins', x) for x in PLUGINS + ], + 'resources': [ + 'commodity.csv', + 'rare_commodity.csv', + 'snd_good.wav', + 'snd_bad.wav', + 'modules.p', + 'ships.p', + ], + 'site_packages': False, + 'plist': { + 'CFBundleName': applongname, + 'CFBundleIdentifier': f'uk.org.marginal.{appname.lower()}', + 'CFBundleLocalizations': get_cfbundle_localizations(), + 'CFBundleShortVersionString': appversion_str, + 'CFBundleVersion': appversion_str, + 'CFBundleURLTypes': [ + { + 'CFBundleTypeRole': 'Viewer', + 'CFBundleURLName': f'uk.org.marginal.{appname.lower()}.URLScheme', + 'CFBundleURLSchemes': [ + 'edmc' + ], + } + ], + 'LSMinimumSystemVersion': '10.10', + 'NSAppleScriptEnabled': True, + 'NSHumanReadableCopyright': copyright, + 'SUEnableAutomaticChecks': True, + 'SUShowReleaseNotes': True, + 'SUAllowsAutomaticUpdates': False, + 'SUFeedURL': update_feed, + 'SUScheduledCheckInterval': update_interval, + }, + 'graph': True, # output dependency graph in dist + } } DATA_FILES = [] -elif sys.platform=='win32': - OPTIONS = { 'py2exe': - {'dist_dir': dist_dir, - 'optimize': 2, - 'packages': [ - 'requests', - 'sqlite3', # Included for plugins - ], - 'includes': [ - 'dataclasses', - 'shutil', # Included for plugins - 'timeout_session', - 'zipfile', # Included for plugins - ], - 'excludes': [ 'distutils', '_markerlib', 'optparse', 'PIL', 'pkg_resources', 'simplejson', 'unittest' ], - } +elif sys.platform == 'win32': + OPTIONS = { + 'py2exe': { + 'dist_dir': dist_dir, + 'optimize': 2, + 'packages': [ + 'sqlite3', # Included for plugins + ], + 'includes': [ + 'dataclasses', + 'shutil', # Included for plugins + 'timeout_session', + 'zipfile', # Included for plugins + ], + 'excludes': [ + 'distutils', + '_markerlib', + 'optparse', + 'PIL', + 'pkg_resources', + 'simplejson', + 'unittest' + ], + } } DATA_FILES = [ ('', [ + '.gitversion', # Contains git short hash 'WinSparkle.dll', - 'WinSparkle.pdb', # For debugging - don't include in package + 'WinSparkle.pdb', # For debugging - don't include in package 'EUROCAPS.TTF', 'Changelog.md', 'commodity.csv', @@ -144,82 +217,103 @@ elif sys.platform=='win32': 'snd_bad.wav', 'modules.p', 'ships.p', - 'stations.p', - 'systems.p', - '%s.VisualElementsManifest.xml' % APPNAME, - '%s.ico' % APPNAME, - '%s/DLLs/sqlite3.dll' % (sys.base_prefix), + f'{appname}.VisualElementsManifest.xml', + f'{appname}.ico', 'EDMarketConnector - TRACE.bat', 'EDMarketConnector - localserver-auth.bat', + 'EDMarketConnector - reset-ui.bat', ]), - ('L10n', [join('L10n',x) for x in os.listdir('L10n') if x.endswith('.strings')]), + ('L10n', [join('L10n', x) for x in os.listdir('L10n') if x.endswith('.strings')]), ('plugins', PLUGINS), ] setup( - name = APPLONGNAME, - version = VERSION, - windows = [ {'dest_base': APPNAME, - 'script': APP, - 'icon_resources': [(0, '%s.ico' % APPNAME)], - 'company_name': 'EDCD', # WinSparkle - 'product_name': APPNAME, # WinSparkle - 'version': BASEVERSION, - 'product_version': VERSION, - 'copyright': COPYRIGHT, - 'other_resources': [(24, 1, open(APPNAME+'.manifest').read())], - } ], - console = [ {'dest_base': APPCMDNAME, - 'script': APPCMD, - 'company_name': 'EDCD', - 'product_name': APPNAME, - 'version': BASEVERSION, - 'product_version': VERSION, - 'copyright': COPYRIGHT, - 'other_resources': [(24, 1, open(APPCMDNAME+'.manifest').read())], - } ], - data_files = DATA_FILES, - options = OPTIONS, + name=applongname, + version=appversion_str, + windows=[ + { + 'dest_base': appname, + 'script': APP, + 'icon_resources': [(0, f'{appname}.ico')], + 'company_name': 'EDCD', # Used by WinSparkle + 'product_name': appname, # Used by WinSparkle + 'version': base_appversion, + 'product_version': appversion_str, + 'copyright': copyright, + 'other_resources': [(24, 1, open(f'{appname}.manifest').read())], + } + ], + console=[ + { + 'dest_base': appcmdname, + 'script': APPCMD, + 'company_name': 'EDCD', + 'product_name': appname, + 'version': base_appversion, + 'product_version': appversion_str, + 'copyright': copyright, + 'other_resources': [(24, 1, open(f'{appcmdname}.manifest').read())], + } + ], + data_files=DATA_FILES, + options=OPTIONS, ) -PKG = None +package_filename = None if sys.platform == 'darwin': - if isdir('%s/%s.app' % (dist_dir, APPLONGNAME)): # from CFBundleName - os.rename('%s/%s.app' % (dist_dir, APPLONGNAME), '%s/%s.app' % (dist_dir, APPNAME)) + if isdir(f'{dist_dir}/{applongname}.app'): # from CFBundleName + os.rename(f'{dist_dir}/{applongname}.app', f'{dist_dir}/{appname}.app') # Generate OSX-style localization files for x in os.listdir('L10n'): if x.endswith('.strings'): lang = x[:-len('.strings')] - path = '%s/%s.app/Contents/Resources/%s.lproj' % (dist_dir, APPNAME, lang) + path = f'{dist_dir}/{appname}.app/Contents/Resources/{lang}.lproj' os.mkdir(path) - codecs.open('%s/Localizable.strings' % path, 'w', 'utf-16').write(codecs.open('L10n/%s' % x, 'r', 'utf-8').read()) + codecs.open( + f'{path}/Localizable.strings', + 'w', + 'utf-16' + ).write(codecs.open(f'L10n/{x}', 'r', 'utf-8').read()) if macdeveloperid: - os.system('codesign --deep -v -s "Developer ID Application: %s" %s/%s.app' % (macdeveloperid, dist_dir, APPNAME)) - # Make zip for distribution, preserving signature - PKG = '%s_mac_%s.zip' % (APPNAME, VERSION) - os.system('cd %s; ditto -ck --keepParent --sequesterRsrc %s.app ../%s; cd ..' % (dist_dir, APPNAME, PKG)) -elif sys.platform == 'win32': - os.system(r'"%s\candle.exe" -out %s\ %s.wxs' % (WIXPATH, dist_dir, APPNAME)) - if not exists('%s/%s.wixobj' % (dist_dir, APPNAME)): - raise AssertionError('No %s/%s.wixobj: candle.exe failed?' % (dist_dir, APPNAME)) + os.system(f'codesign --deep -v -s "Developer ID Application: {macdeveloperid}" {dist_dir}/{appname}.app') - PKG = '%s_win_%s.msi' % (APPNAME, VERSION) - import subprocess - os.system(r'"%s\light.exe" -sacl -spdb -sw1076 %s\%s.wixobj -out %s' % (WIXPATH, dist_dir, APPNAME, PKG)) - if not exists(PKG): - raise AssertionError('light.exe failed, no %s' % (PKG)) + # Make zip for distribution, preserving signature + package_filename = f'{appname}_mac_{appversion_nobuild()}.zip' + os.system(f'cd {dist_dir}; ditto -ck --keepParent --sequesterRsrc {appname}.app ../{package_filename}; cd ..') + +elif sys.platform == 'win32': + os.system(rf'"{WIXPATH}\candle.exe" -out {dist_dir}\ {appname}.wxs') + + if not exists(f'{dist_dir}/{appname}.wixobj'): + raise AssertionError(f'No {dist_dir}/{appname}.wixobj: candle.exe failed?') + + package_filename = f'{appname}_win_{appversion_nobuild()}.msi' + os.system(rf'"{WIXPATH}\light.exe" -sacl -spdb -sw1076 {dist_dir}\{appname}.wixobj -out {package_filename}') + + if not exists(package_filename): + raise AssertionError(f'light.exe failed, no {package_filename}') # Seriously, this is how you make Windows Installer use the user's display language for its dialogs. What a crock. # http://www.geektieguy.com/2010/03/13/create-a-multi-lingual-multi-language-msi-using-wix-and-custom-build-scripts - lcids = [int(x) for x in re.search(r'Languages\s*=\s*"(.+?)"', open('%s.wxs' % APPNAME).read()).group(1).split(',')] - assert lcids[0]==1033, 'Default language is %d, should be 1033 (en_US)' % lcids[0] - shutil.copyfile(PKG, join(gettempdir(), '%s_1033.msi' % APPNAME)) + lcids = [ + int(x) for x in re.search( # type: ignore + r'Languages\s*=\s*"(.+?)"', + open(f'{appname}.wxs').read() + ).group(1).split(',') + ] + assert lcids[0] == 1033, f'Default language is {lcids[0]}, should be 1033 (en_US)' + shutil.copyfile(package_filename, join(gettempdir(), f'{appname}_1033.msi')) for lcid in lcids[1:]: - shutil.copyfile(join(gettempdir(), '%s_1033.msi' % APPNAME), join(gettempdir(), '%s_%d.msi' % (APPNAME, lcid))) - os.system(r'cscript /nologo "%s\WiLangId.vbs" %s\%s_%d.msi Product %d' % (SDKPATH, gettempdir(), APPNAME, lcid, lcid)) # Don't care about codepage because the displayed strings come from msiexec not our msi - os.system(r'"%s\MsiTran.Exe" -g %s\%s_1033.msi %s\%s_%d.msi %s\%d.mst' % (SDKPATH, gettempdir(), APPNAME, gettempdir(), APPNAME, lcid, gettempdir(), lcid)) - os.system(r'cscript /nologo "%s\WiSubStg.vbs" %s %s\%d.mst %d' % (SDKPATH, PKG, gettempdir(), lcid, lcid)) + shutil.copyfile( + join(gettempdir(), f'{appname}_1033.msi'), + join(gettempdir(), f'{appname}_{lcid}.msi') + ) + # Don't care about codepage because the displayed strings come from msiexec not our msi + os.system(rf'cscript /nologo "{SDKPATH}\WiLangId.vbs" {gettempdir()}\{appname}_{lcid}.msi Product {lcid}') + os.system(rf'"{SDKPATH}\MsiTran.Exe" -g {gettempdir()}\{appname}_1033.msi {gettempdir()}\{appname}_{lcid}.msi {gettempdir()}\{lcid}.mst') # noqa: E501 # Not going to get shorter + os.system(rf'cscript /nologo "{SDKPATH}\WiSubStg.vbs" {package_filename} {gettempdir()}\{lcid}.mst {lcid}') + else: raise AssertionError('Unsupported platform') diff --git a/ships.p b/ships.p index e709617a..d289497c 100644 Binary files a/ships.p and b/ships.p differ diff --git a/shipyard.py b/shipyard.py index fe31d33e..78961ad7 100644 --- a/shipyard.py +++ b/shipyard.py @@ -2,13 +2,13 @@ import time -from companion import ship_map from config import config +from edmc_data import ship_name_map def export(data, filename): - querytime = config.getint('querytime') or int(time.time()) + querytime = config.get_int('querytime', default=int(time.time())) assert data['lastSystem'].get('name') assert data['lastStarport'].get('name') @@ -19,6 +19,6 @@ def export(data, filename): h = open(filename, 'wt') h.write(header) - for (name,fdevid) in [(ship_map.get(ship['name'].lower(), ship['name']), ship['id']) for ship in list((data['lastStarport']['ships'].get('shipyard_list') or {}).values()) + data['lastStarport']['ships'].get('unavailable_list')]: + for (name,fdevid) in [(ship_name_map.get(ship['name'].lower(), ship['name']), ship['id']) for ship in list((data['lastStarport']['ships'].get('shipyard_list') or {}).values()) + data['lastStarport']['ships'].get('unavailable_list')]: h.write('%s,%s,%s,%s\n' % (rowheader, name, fdevid, data['timestamp'])) h.close() diff --git a/stats.py b/stats.py index c8b3daa0..fcd514cc 100644 --- a/stats.py +++ b/stats.py @@ -1,135 +1,163 @@ -from collections import OrderedDict +"""CMDR Status information.""" import csv -from sys import platform -from functools import partial -import time -if __debug__: - from traceback import print_exc - import tkinter as tk +from sys import platform from tkinter import ttk -import myNotebook as nb +from typing import TYPE_CHECKING, Any, AnyStr, Dict, List, NamedTuple, Optional, Sequence, cast import companion -from companion import ship_map +import EDMCLogging +import myNotebook as nb # noqa: N813 +from edmc_data import ship_name_map from l10n import Locale from monitor import monitor -import prefs -if platform=='win32': +logger = EDMCLogging.get_main_logger() + +if TYPE_CHECKING: + def _(x: str) -> str: ... + +if platform == 'win32': import ctypes - from ctypes.wintypes import * + from ctypes.wintypes import HWND, POINT, RECT, SIZE, UINT + if TYPE_CHECKING: + import ctypes.windll # type: ignore # Fake this into existing, its really a magic dll thing + try: CalculatePopupWindowPosition = ctypes.windll.user32.CalculatePopupWindowPosition - CalculatePopupWindowPosition.argtypes = [ctypes.POINTER(POINT), ctypes.POINTER(SIZE), UINT, ctypes.POINTER(RECT), ctypes.POINTER(RECT)] + CalculatePopupWindowPosition.argtypes = [ + ctypes.POINTER(POINT), ctypes.POINTER(SIZE), UINT, ctypes.POINTER(RECT), ctypes.POINTER(RECT) + ] GetParent = ctypes.windll.user32.GetParent GetParent.argtypes = [HWND] GetWindowRect = ctypes.windll.user32.GetWindowRect GetWindowRect.argtypes = [HWND, ctypes.POINTER(RECT)] - except: # Not supported under Wine 4.0 + + except Exception: # Not supported under Wine 4.0 CalculatePopupWindowPosition = None -def status(data): +def status(data: Dict[str, Any]) -> List[List[str]]: + """ + Get the current status of the cmdr referred to by data. + + :param data: Data to generate status from + :return: Status information about the given cmdr + """ # StatsResults assumes these three things are first - res = [ [_('Cmdr'), data['commander']['name']], - [_('Balance'), str(data['commander'].get('credits', 0))], # Cmdr stats - [_('Loan'), str(data['commander'].get('debt', 0))], # Cmdr stats + res = [ + [_('Cmdr'), data['commander']['name']], + [_('Balance'), str(data['commander'].get('credits', 0))], # Cmdr stats + [_('Loan'), str(data['commander'].get('debt', 0))], # Cmdr stats ] - RANKS = [ # in output order - (_('Combat') , 'combat'), # Ranking - (_('Trade') , 'trade'), # Ranking - (_('Explorer') , 'explore'), # Ranking - (_('CQC') , 'cqc'), # Ranking - (_('Federation') , 'federation'), # Ranking - (_('Empire') , 'empire'), # Ranking - (_('Powerplay') , 'power'), # Ranking - # ??? , 'crime'), # Ranking - # ??? , 'service'), # Ranking + RANKS = [ # noqa: N806 # Its a constant, just needs to be updated at runtime + # in output order + (_('Combat'), 'combat'), # Ranking + (_('Trade'), 'trade'), # Ranking + (_('Explorer'), 'explore'), # Ranking + (_('CQC'), 'cqc'), # Ranking + (_('Federation'), 'federation'), # Ranking + (_('Empire'), 'empire'), # Ranking + (_('Powerplay'), 'power'), # Ranking + # ??? , 'crime'), # Ranking + # ??? , 'service'), # Ranking ] - RANK_NAMES = { - + RANK_NAMES = { # noqa: N806 # Its a constant, just needs to be updated at runtime # http://elite-dangerous.wikia.com/wiki/Pilots_Federation#Ranks - 'combat' : [_('Harmless'), # Combat rank - _('Mostly Harmless'), # Combat rank - _('Novice'), # Combat rank - _('Competent'), # Combat rank - _('Expert'), # Combat rank - _('Master'), # Combat rank - _('Dangerous'), # Combat rank - _('Deadly'), # Combat rank - _('Elite')], # Top rank - 'trade' : [_('Penniless'), # Trade rank - _('Mostly Penniless'), # Trade rank - _('Peddler'), # Trade rank - _('Dealer'), # Trade rank - _('Merchant'), # Trade rank - _('Broker'), # Trade rank - _('Entrepreneur'), # Trade rank - _('Tycoon'), # Trade rank - _('Elite')], # Top rank - 'explore' : [_('Aimless'), # Explorer rank - _('Mostly Aimless'), # Explorer rank - _('Scout'), # Explorer rank - _('Surveyor'), # Explorer rank - _('Trailblazer'), # Explorer rank - _('Pathfinder'), # Explorer rank - _('Ranger'), # Explorer rank - _('Pioneer'), # Explorer rank - _('Elite')], # Top rank - 'cqc' : [_('Helpless'), # CQC rank - _('Mostly Helpless'), # CQC rank - _('Amateur'), # CQC rank - _('Semi Professional'), # CQC rank - _('Professional'), # CQC rank - _('Champion'), # CQC rank - _('Hero'), # CQC rank - _('Gladiator'), # CQC rank - _('Elite')], # Top rank + 'combat': [ + _('Harmless'), # Combat rank + _('Mostly Harmless'), # Combat rank + _('Novice'), # Combat rank + _('Competent'), # Combat rank + _('Expert'), # Combat rank + _('Master'), # Combat rank + _('Dangerous'), # Combat rank + _('Deadly'), # Combat rank + _('Elite'), # Top rank + ], + 'trade': [ + _('Penniless'), # Trade rank + _('Mostly Penniless'), # Trade rank + _('Peddler'), # Trade rank + _('Dealer'), # Trade rank + _('Merchant'), # Trade rank + _('Broker'), # Trade rank + _('Entrepreneur'), # Trade rank + _('Tycoon'), # Trade rank + _('Elite') # Top rank + ], + 'explore': [ + _('Aimless'), # Explorer rank + _('Mostly Aimless'), # Explorer rank + _('Scout'), # Explorer rank + _('Surveyor'), # Explorer rank + _('Trailblazer'), # Explorer rank + _('Pathfinder'), # Explorer rank + _('Ranger'), # Explorer rank + _('Pioneer'), # Explorer rank + _('Elite') # Top rank + ], + 'cqc': [ + _('Helpless'), # CQC rank + _('Mostly Helpless'), # CQC rank + _('Amateur'), # CQC rank + _('Semi Professional'), # CQC rank + _('Professional'), # CQC rank + _('Champion'), # CQC rank + _('Hero'), # CQC rank + _('Gladiator'), # CQC rank + _('Elite') # Top rank + ], # http://elite-dangerous.wikia.com/wiki/Federation#Ranks - 'federation' : [_('None'), # No rank - _('Recruit'), # Federation rank - _('Cadet'), # Federation rank - _('Midshipman'), # Federation rank - _('Petty Officer'), # Federation rank - _('Chief Petty Officer'), # Federation rank - _('Warrant Officer'), # Federation rank - _('Ensign'), # Federation rank - _('Lieutenant'), # Federation rank - _('Lieutenant Commander'), # Federation rank - _('Post Commander'), # Federation rank - _('Post Captain'), # Federation rank - _('Rear Admiral'), # Federation rank - _('Vice Admiral'), # Federation rank - _('Admiral')], # Federation rank + 'federation': [ + _('None'), # No rank + _('Recruit'), # Federation rank + _('Cadet'), # Federation rank + _('Midshipman'), # Federation rank + _('Petty Officer'), # Federation rank + _('Chief Petty Officer'), # Federation rank + _('Warrant Officer'), # Federation rank + _('Ensign'), # Federation rank + _('Lieutenant'), # Federation rank + _('Lieutenant Commander'), # Federation rank + _('Post Commander'), # Federation rank + _('Post Captain'), # Federation rank + _('Rear Admiral'), # Federation rank + _('Vice Admiral'), # Federation rank + _('Admiral') # Federation rank + ], # http://elite-dangerous.wikia.com/wiki/Empire#Ranks - 'empire' : [_('None'), # No rank - _('Outsider'), # Empire rank - _('Serf'), # Empire rank - _('Master'), # Empire rank - _('Squire'), # Empire rank - _('Knight'), # Empire rank - _('Lord'), # Empire rank - _('Baron'), # Empire rank - _('Viscount'), # Empire rank - _('Count'), # Empire rank - _('Earl'), # Empire rank - _('Marquis'), # Empire rank - _('Duke'), # Empire rank - _('Prince'), # Empire rank - _('King')], # Empire rank + 'empire': [ + _('None'), # No rank + _('Outsider'), # Empire rank + _('Serf'), # Empire rank + _('Master'), # Empire rank + _('Squire'), # Empire rank + _('Knight'), # Empire rank + _('Lord'), # Empire rank + _('Baron'), # Empire rank + _('Viscount'), # Empire rank + _('Count'), # Empire rank + _('Earl'), # Empire rank + _('Marquis'), # Empire rank + _('Duke'), # Empire rank + _('Prince'), # Empire rank + _('King') # Empire rank + ], # http://elite-dangerous.wikia.com/wiki/Ratings - 'power' : [_('None'), # No rank - _('Rating 1'), # Power rank - _('Rating 2'), # Power rank - _('Rating 3'), # Power rank - _('Rating 4'), # Power rank - _('Rating 5')], # Power rank + 'power': [ + _('None'), # No rank + _('Rating 1'), # Power rank + _('Rating 2'), # Power rank + _('Rating 3'), # Power rank + _('Rating 4'), # Power rank + _('Rating 5') # Power rank + ], } ranks = data['commander'].get('rank', {}) @@ -137,51 +165,112 @@ def status(data): rank = ranks.get(thing) names = RANK_NAMES[thing] if isinstance(rank, int): - res.append([title, rank < len(names) and names[rank] or ('Rank %d' % rank)]) + res.append([title, names[rank] if rank < len(names) else f'Rank {rank}']) + else: - res.append([title, _('None')]) # No rank + res.append([title, _('None')]) # No rank return res -def export_status(data, filename): - h = csv.writer(open(filename, 'w')) - h.writerow(['Category', 'Value']) - for thing in status(data): - h.writerow([x for x in thing]) +def export_status(data: Dict[str, Any], filename: AnyStr) -> None: + """ + Export status data to a CSV file. + + :param data: The data to generate the file from + :param filename: The target file + """ + with open(filename, 'w') as f: + h = csv.writer(f) + h.writerow(('Category', 'Value')) + for thing in status(data): + h.writerow(list(thing)) -# Returns id,name,shipName,system,station,value -def ships(data): +class ShipRet(NamedTuple): + """ShipRet is a NamedTuple containing the return data from stats.ships.""" - ships = companion.listify(data.get('ships')) - current = data['commander'].get('currentShipId') + id: str + type: str + name: str + system: str + station: str + value: str + + +def ships(companion_data: Dict[str, Any]) -> List[ShipRet]: + """ + Return a list of 5 tuples of ship information. + + :param data: [description] + :return: A 5 tuple of strings containing: Ship ID, Ship Type Name (internal), Ship Name, System, Station, and Value + """ + ships: List[Dict[str, Any]] = companion.listify(cast(list, companion_data.get('ships'))) + current = companion_data['commander'].get('currentShipId') if isinstance(current, int) and current < len(ships) and ships[current]: - ships.insert(0, ships.pop(current)) # Put current ship first + ships.insert(0, ships.pop(current)) # Put current ship first - if not data['commander'].get('docked'): + if not companion_data['commander'].get('docked'): + out: List[ShipRet] = [] # Set current system, not last docked - return ([ (str(ships[0]['id']), ship_map.get(ships[0]['name'].lower(), ships[0]['name']), ships[0].get('shipName', ''), data['lastSystem']['name'], '', str(ships[0]['value']['total'])) ] + - [ (str(ship['id']), ship_map.get(ship['name'].lower(), ship['name']), ship.get('shipName', ''), ship['starsystem']['name'], ship['station']['name'], str(ship['value']['total'])) for ship in ships[1:] if ship]) + out.append(ShipRet( + id=str(ships[0]['id']), + type=ship_name_map.get(ships[0]['name'].lower(), ships[0]['name']), + name=str(ships[0].get('shipName', '')), + system=companion_data['lastSystem']['name'], + station='', + value=str(ships[0]['value']['total']) + )) + out.extend( + ShipRet( + id=str(ship['id']), + type=ship_name_map.get(ship['name'].lower(), ship['name']), + name=ship.get('shipName', ''), + system=ship['starsystem']['name'], + station=ship['station']['name'], + value=str(ship['value']['total']) + ) for ship in ships[1:] if ship + ) - return [ (str(ship['id']), ship_map.get(ship['name'].lower(), ship['name']), ship.get('shipName', ''), ship['starsystem']['name'], ship['station']['name'], str(ship['value']['total'])) for ship in ships if ship] + return out -def export_ships(data, filename): - h = csv.writer(open(filename, 'w')) - h.writerow(['Id', 'Ship', 'Name', 'System', 'Station', 'Value']) - for thing in ships(data): - h.writerow([x for x in thing]) + return [ + ShipRet( + id=str(ship['id']), + type=ship_name_map.get(ship['name'].lower(), ship['name']), + name=ship.get('shipName', ''), + system=ship['starsystem']['name'], + station=ship['station']['name'], + value=str(ship['value']['total']) + ) for ship in ships if ship is not None + ] + + +def export_ships(companion_data: Dict[str, Any], filename: AnyStr) -> None: + """ + Export the current ships to a CSV file. + + :param companion_data: Data from which to generate the ship list + :param filename: The target file + """ + with open(filename, 'w') as f: + h = csv.writer(f) + h.writerow(['Id', 'Ship', 'Name', 'System', 'Station', 'Value']) + for thing in ships(companion_data): + h.writerow(list(thing)) class StatsDialog(): + """Status dialog containing all of the current cmdr's stats.""" - def __init__(self, app): - self.parent = app.w - self.status = app.status + def __init__(self, parent: tk.Tk, status: tk.Label) -> None: + self.parent: tk.Tk = parent + self.status = status self.showstats() - def showstats(self): + def showstats(self) -> None: + """Show the status window for the current cmdr.""" if not monitor.cmdr: return @@ -190,47 +279,59 @@ class StatsDialog(): try: data = companion.session.profile() + except companion.ServerError as e: self.status['text'] = str(e) return + except Exception as e: - if __debug__: print_exc() + logger.exception("error while attempting to show status") self.status['text'] = str(e) return - if not data.get('commander') or not data['commander'].get('name','').strip(): - self.status['text'] = _("Who are you?!") # Shouldn't happen - elif not data.get('lastSystem') or not data['lastSystem'].get('name','').strip() or not data.get('lastStarport') or not data['lastStarport'].get('name','').strip(): - self.status['text'] = _("Where are you?!") # Shouldn't happen - elif not data.get('ship') or not data['ship'].get('modules') or not data['ship'].get('name','').strip(): - self.status['text'] = _("What are you flying?!") # Shouldn't happen + if not data.get('commander') or not data['commander'].get('name', '').strip(): + self.status['text'] = _("Who are you?!") # Shouldn't happen + + elif ( + not data.get('lastSystem') + or not data['lastSystem'].get('name', '').strip() + or not data.get('lastStarport') + or not data['lastStarport'].get('name', '').strip() + ): + self.status['text'] = _("Where are you?!") # Shouldn't happen + + elif not data.get('ship') or not data['ship'].get('modules') or not data['ship'].get('name', '').strip(): + self.status['text'] = _("What are you flying?!") # Shouldn't happen + else: self.status['text'] = '' StatsResults(self.parent, data) class StatsResults(tk.Toplevel): + """Status window.""" - def __init__(self, parent, data): + def __init__(self, parent: tk.Tk, data: Dict[str, Any]) -> None: tk.Toplevel.__init__(self, parent) self.parent = parent stats = status(data) - self.title(' '.join(stats[0])) # assumes first thing is player name + self.title(' '.join(stats[0])) # assumes first thing is player name if parent.winfo_viewable(): self.transient(parent) # position over parent - if platform!='darwin' or parent.winfo_rooty()>0: # http://core.tcl.tk/tk/tktview/c84f660833546b1b84e7 - self.geometry("+%d+%d" % (parent.winfo_rootx(), parent.winfo_rooty())) + if platform != 'darwin' or parent.winfo_rooty() > 0: # http://core.tcl.tk/tk/tktview/c84f660833546b1b84e7 + self.geometry(f"+{parent.winfo_rootx()}+{parent.winfo_rooty()}") # remove decoration self.resizable(tk.FALSE, tk.FALSE) - if platform=='win32': + if platform == 'win32': self.attributes('-toolwindow', tk.TRUE) - elif platform=='darwin': + + elif platform == 'darwin': # http://wiki.tcl.tk/13428 parent.call('tk::unsupported::MacWindowStyle', 'style', self, 'utility') @@ -241,30 +342,35 @@ class StatsResults(tk.Toplevel): page = self.addpage(notebook) for thing in stats[1:3]: - self.addpagerow(page, [thing[0], self.credits(int(thing[1]))]) # assumes things two and three are money + self.addpagerow(page, [thing[0], self.credits(int(thing[1]))]) # assumes things two and three are money + for thing in stats[3:]: self.addpagerow(page, thing) - ttk.Frame(page).grid(pady=5) # bottom spacer - notebook.add(page, text=_('Status')) # Status dialog title + + ttk.Frame(page).grid(pady=5) # bottom spacer + notebook.add(page, text=_('Status')) # Status dialog title page = self.addpage(notebook, [ - _('Ship'), # Status dialog subtitle + _('Ship'), # Status dialog subtitle '', - _('System'), # Main window - _('Station'), # Status dialog subtitle - _('Value'), # Status dialog subtitle - CR value of ship + _('System'), # Main window + _('Station'), # Status dialog subtitle + _('Value'), # Status dialog subtitle - CR value of ship ]) - shiplist = ships(data) - for thing in shiplist: - self.addpagerow(page, list(thing[1:-1]) + [self.credits(int(thing[-1]))]) # skip id, last item is money - ttk.Frame(page).grid(pady=5) # bottom spacer - notebook.add(page, text=_('Ships')) # Status dialog title - if platform!='darwin': + shiplist = ships(data) + for ship_data in shiplist: + # skip id, last item is money + self.addpagerow(page, list(ship_data[1:-1]) + [self.credits(int(ship_data[-1]))]) + + ttk.Frame(page).grid(pady=5) # bottom spacer + notebook.add(page, text=_('Ships')) # Status dialog title + + if platform != 'darwin': buttonframe = ttk.Frame(frame) - buttonframe.grid(padx=10, pady=(0,10), sticky=tk.NSEW) + buttonframe.grid(padx=10, pady=(0, 10), sticky=tk.NSEW) # type: ignore # the tuple is supported buttonframe.columnconfigure(0, weight=1) - ttk.Label(buttonframe).grid(row=0, column=0) # spacer + ttk.Label(buttonframe).grid(row=0, column=0) # spacer ttk.Button(buttonframe, text='OK', command=self.destroy).grid(row=0, column=1, sticky=tk.E) # wait for window to appear on screen before calling grab_set @@ -275,37 +381,71 @@ class StatsResults(tk.Toplevel): if platform == 'win32' and CalculatePopupWindowPosition: position = RECT() GetWindowRect(GetParent(self.winfo_id()), position) - if CalculatePopupWindowPosition(POINT(parent.winfo_rootx(), parent.winfo_rooty()), - SIZE(position.right - position.left, position.bottom - position.top), - 0x10000, None, position): - self.geometry("+%d+%d" % (position.left, position.top)) + if CalculatePopupWindowPosition( + POINT(parent.winfo_rootx(), parent.winfo_rooty()), + # - is evidently supported on the C side + SIZE(position.right - position.left, position.bottom - position.top), # type: ignore + 0x10000, None, position + ): + self.geometry(f"+{position.left}+{position.top}") + + def addpage(self, parent, header: List[str] = None, align: Optional[str] = None) -> tk.Frame: + """ + Add a page to the StatsResults screen. + + :param parent: The parent widget to put this under + :param header: The headers for the table, defaults to an empty list + :param align: Alignment to use for this page, defaults to None + :return: The Frame that was created + """ + if header is None: + header = [] - def addpage(self, parent, header=[], align=None): page = nb.Frame(parent) page.grid(pady=10, sticky=tk.NSEW) page.columnconfigure(0, weight=1) if header: self.addpageheader(page, header, align=align) + return page - def addpageheader(self, parent, header, align=None): + def addpageheader(self, parent: tk.Frame, header: Sequence[str], align: Optional[str] = None) -> None: + """ + Add the column headers to the page, followed by a separator. + + :param parent: The parent widget to add this to + :param header: The headers to add to the page + :param align: The alignment of the page, defaults to None + """ self.addpagerow(parent, header, align=align) ttk.Separator(parent, orient=tk.HORIZONTAL).grid(columnspan=len(header), padx=10, pady=2, sticky=tk.EW) - def addpagespacer(self, parent): + def addpagespacer(self, parent) -> None: + """Add a spacer to the page.""" self.addpagerow(parent, ['']) - def addpagerow(self, parent, content, align=None): + def addpagerow(self, parent: tk.Frame, content: Sequence[str], align: Optional[str] = None): + """ + Add a single row to parent. + + :param parent: The widget to add the data to + :param content: The columns of the row to add + :param align: The alignment of the data, defaults to tk.W + """ + row = -1 # To silence unbound warnings for i in range(len(content)): label = nb.Label(parent, text=content[i]) if i == 0: label.grid(padx=10, sticky=tk.W) row = parent.grid_size()[1]-1 - elif align is None and i == len(content) - 1: # Assumes last column right justified if unspecified + + elif align is None and i == len(content) - 1: # Assumes last column right justified if unspecified label.grid(row=row, column=i, padx=10, sticky=tk.E) + else: label.grid(row=row, column=i, padx=10, sticky=align or tk.W) - def credits(self, value): - return Locale.stringFromNumber(value, 0) + ' Cr' - + def credits(self, value: int) -> str: + """Localised string of given int, including a trailing ` Cr`.""" + # TODO: Locale is a class, this calls an instance method on it with an int as its `self` + return Locale.string_from_number(value, 0) + ' Cr' # type: ignore diff --git a/td.py b/td.py index ba4e5465..13c32edd 100644 --- a/td.py +++ b/td.py @@ -11,6 +11,7 @@ import time from config import applongname, appversion, config +# These are specific to Trade Dangerous, so don't move to edmc_data.py demandbracketmap = { 0: '?', 1: 'L', 2: 'M', @@ -22,9 +23,9 @@ stockbracketmap = { 0: '-', def export(data): - querytime = config.getint('querytime') or int(time.time()) + querytime = config.get_int('querytime', default=int(time.time())) - filename = join(config.get('outdir'), '%s.%s.%s.prices' % (data['lastSystem']['name'].strip(), data['lastStarport']['name'].strip(), time.strftime('%Y-%m-%dT%H.%M.%S', time.localtime(querytime)))) + filename = join(config.get_str('outdir'), '%s.%s.%s.prices' % (data['lastSystem']['name'].strip(), data['lastStarport']['name'].strip(), time.strftime('%Y-%m-%dT%H.%M.%S', time.localtime(querytime)))) timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(data['timestamp'], '%Y-%m-%dT%H:%M:%SZ')) @@ -34,7 +35,7 @@ def export(data): '#\n# \n\n' '@ {system}/{starport}\n'.format( appname=applongname, - appversion=appversion, + appversion=appversion(), platform=platform == 'darwin' and "Mac OS" or system(), cmdr=data['commander']['name'].strip(), system=data['lastSystem']['name'].strip(), diff --git a/tests/EDMCLogging.py/test_logging_classvar.py b/tests/EDMCLogging.py/test_logging_classvar.py new file mode 100644 index 00000000..3bedb0f5 --- /dev/null +++ b/tests/EDMCLogging.py/test_logging_classvar.py @@ -0,0 +1,45 @@ +"""Test that logging works correctly from a class-definition caller.""" +import sys + +sys.path += "../" # Dont ask me why for this one it breaks, it just does. +from typing import TYPE_CHECKING # noqa: E402 + +from EDMCLogging import get_plugin_logger # noqa: E402 + +if TYPE_CHECKING: + from _pytest.logging import LogCaptureFixture + +logger = get_plugin_logger('EDMCLogging.py') + + +class ClassVarLogger: + """Test class with logger attached.""" + + @classmethod + def set_logger(cls, logger) -> None: + """Set the passed logger onto the _class_.""" + ClassVarLogger.logger = logger # type: ignore + + +def log_stuff(msg: str) -> None: + """Wrap logging in another function.""" + ClassVarLogger.logger.debug(msg) # type: ignore # its there + + +def test_class_logger(caplog: 'LogCaptureFixture') -> None: + """ + Test that logging from a class variable doesn't explode. + + In writting a plugin that uses a class variable to hold the logger, EDMCLoggings cleverness to extract data + regarding the qualified name of a function falls flat, as a class variable does not have a qualname, and at the time + we did not check for its existence before using it. + """ + 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 + + # Dont move these, it relies on the line numbres. + assert 'EDMarketConnector.EDMCLogging.py:test_logging_classvar.py:37 test' in caplog.text + assert 'EDMarketConnector.EDMCLogging.py:test_logging_classvar.py:38 test2' in caplog.text + assert 'EDMarketConnector.EDMCLogging.py:test_logging_classvar.py:25 test3' in caplog.text diff --git a/tests/config.py/_old_config.py b/tests/config.py/_old_config.py new file mode 100644 index 00000000..b1609975 --- /dev/null +++ b/tests/config.py/_old_config.py @@ -0,0 +1,500 @@ +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 sys import platform +from typing import TYPE_CHECKING, Optional, Union + +from config import applongname, appname, update_interval +from EDMCLogging import get_main_logger + +logger = get_main_logger() + +if platform == 'darwin': + from Foundation import ( # type: ignore + NSApplicationSupportDirectory, NSBundle, NSDocumentDirectory, NSSearchPathForDirectoriesInDomains, + NSUserDefaults, NSUserDomainMask + ) + +elif platform == 'win32': + import ctypes + import uuid + from ctypes.wintypes import DWORD, HANDLE, HKEY, LONG, LPCVOID, LPCWSTR + if TYPE_CHECKING: + import ctypes.windll # type: ignore + + FOLDERID_Documents = uuid.UUID('{FDD39AD0-238F-46AF-ADB4-6C85480369C7}') + FOLDERID_LocalAppData = uuid.UUID('{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}') + FOLDERID_Profile = uuid.UUID('{5E6C858F-0E22-4760-9AFE-EA3317B67173}') + FOLDERID_SavedGames = uuid.UUID('{4C5C32FF-BB9D-43b0-B5B4-2D72E54EAAA4}') + + SHGetKnownFolderPath = ctypes.windll.shell32.SHGetKnownFolderPath + SHGetKnownFolderPath.argtypes = [ctypes.c_char_p, DWORD, HANDLE, ctypes.POINTER(ctypes.c_wchar_p)] + + CoTaskMemFree = ctypes.windll.ole32.CoTaskMemFree + CoTaskMemFree.argtypes = [ctypes.c_void_p] + + # winreg in Python <= 3.7.4 handles REG_MULTI_SZ incorrectly, so do this instead. https://bugs.python.org/issue32587 + HKEY_CURRENT_USER = 0x80000001 + KEY_ALL_ACCESS = 0x000F003F + REG_CREATED_NEW_KEY = 0x00000001 + REG_OPENED_EXISTING_KEY = 0x00000002 + REG_SZ = 1 + REG_DWORD = 4 + REG_MULTI_SZ = 7 + + REG_RESERVED_ALWAYS_ZERO = 0 + + RegCreateKeyEx = ctypes.windll.advapi32.RegCreateKeyExW + RegCreateKeyEx.restype = LONG + RegCreateKeyEx.argtypes = [ + HKEY, LPCWSTR, DWORD, LPCVOID, DWORD, DWORD, LPCVOID, ctypes.POINTER(HKEY), ctypes.POINTER(DWORD) + ] + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegQueryValueEx = ctypes.windll.advapi32.RegQueryValueExW + RegQueryValueEx.restype = LONG + RegQueryValueEx.argtypes = [HKEY, LPCWSTR, LPCVOID, ctypes.POINTER(DWORD), LPCVOID, ctypes.POINTER(DWORD)] + + RegSetValueEx = ctypes.windll.advapi32.RegSetValueExW + RegSetValueEx.restype = LONG + RegSetValueEx.argtypes = [HKEY, LPCWSTR, LPCVOID, DWORD, LPCVOID, DWORD] + + RegCopyTree = ctypes.windll.advapi32.RegCopyTreeW + RegCopyTree.restype = LONG + RegCopyTree.argtypes = [HKEY, LPCWSTR, HKEY] + + RegDeleteKey = ctypes.windll.advapi32.RegDeleteTreeW + RegDeleteKey.restype = LONG + RegDeleteKey.argtypes = [HKEY, LPCWSTR] + + RegDeleteValue = ctypes.windll.advapi32.RegDeleteValueW + RegDeleteValue.restype = LONG + RegDeleteValue.argtypes = [HKEY, LPCWSTR] + + def known_folder_path(guid: uuid.UUID) -> Optional[str]: + """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)): + return None + retval = buf.value # copy data + CoTaskMemFree(buf) # and free original + return retval + +elif platform == 'linux': + import codecs + from configparser import RawConfigParser + + +class OldConfig(): + """Object that holds all configuration data.""" + + OUT_MKT_EDDN = 1 + # OUT_MKT_BPC = 2 # No longer supported + OUT_MKT_TD = 4 + OUT_MKT_CSV = 8 + OUT_SHIP = 16 + # OUT_SHIP_EDS = 16 # Replaced by OUT_SHIP + # OUT_SYS_FILE = 32 # No longer supported + # OUT_STAT = 64 # No longer available + # OUT_SHIP_CORIOLIS = 128 # Replaced by OUT_SHIP + OUT_STATION_ANY = OUT_MKT_EDDN | OUT_MKT_TD | OUT_MKT_CSV + # OUT_SYS_EDSM = 256 # Now a plugin + # OUT_SYS_AUTO = 512 # Now always automatic + OUT_MKT_MANUAL = 1024 + OUT_SYS_EDDN = 2048 + OUT_SYS_DELAY = 4096 + + if platform == 'darwin': # noqa: C901 # It's gating *all* the functions + + def __init__(self): + self.app_dir = join( + NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], appname + ) + if not isdir(self.app_dir): + mkdir(self.app_dir) + + self.plugin_dir = join(self.app_dir, 'plugins') + if not isdir(self.plugin_dir): + mkdir(self.plugin_dir) + + if getattr(sys, 'frozen', False): + self.internal_plugin_dir = normpath(join(dirname(sys.executable), pardir, 'Library', 'plugins')) + self.respath = normpath(join(dirname(sys.executable), pardir, 'Resources')) + self.identifier = NSBundle.mainBundle().bundleIdentifier() + + else: + self.internal_plugin_dir = join(dirname(__file__), 'plugins') + self.respath = dirname(__file__) + # Don't use Python's settings if interactive + self.identifier = f'uk.org.marginal.{appname.lower()}' + NSBundle.mainBundle().infoDictionary()['CFBundleIdentifier'] = self.identifier + + self.default_journal_dir = join( + NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], + 'Frontier Developments', + 'Elite Dangerous' + ) + self.home = expanduser('~') + + self.defaults = NSUserDefaults.standardUserDefaults() + self.settings = dict(self.defaults.persistentDomainForName_(self.identifier) or {}) # make writeable + + # Check out_dir exists + 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]: + """Look up a string configuration value.""" + val = self.settings.get(key) + if val is None: + return default + + elif isinstance(val, str): + return str(val) + + elif isinstance(val, list): + return list(val) # make writeable + + else: + return default + + def getint(self, key: str, default: int = 0) -> int: + """Look up an integer configuration value.""" + try: + return int(self.settings.get(key, default)) # should already be int, but check by casting + + except ValueError as e: + logger.error(f"Failed to int({key=})", exc_info=e) + return default + + except Exception as e: + logger.debug('The exception type is ...', exc_info=e) + return default + + def set(self, key: str, val: Union[int, str, list]) -> None: + """Set value on the specified configuration key.""" + self.settings[key] = val + + def delete(self, key: str) -> None: + """Delete the specified configuration key.""" + self.settings.pop(key, None) + + def save(self) -> None: + """Save current configuration to disk.""" + self.defaults.setPersistentDomain_forName_(self.settings, self.identifier) + self.defaults.synchronize() + + def close(self) -> None: + """Close the configuration.""" + self.save() + self.defaults = None + + elif platform == 'win32': + + def __init__(self): + self.app_dir = join(known_folder_path(FOLDERID_LocalAppData), appname) # type: ignore # Not going to change + if not isdir(self.app_dir): + mkdir(self.app_dir) + + self.plugin_dir = join(self.app_dir, 'plugins') + if not isdir(self.plugin_dir): + mkdir(self.plugin_dir) + + if getattr(sys, 'frozen', False): + self.internal_plugin_dir = join(dirname(sys.executable), 'plugins') + self.respath = dirname(sys.executable) + + else: + self.internal_plugin_dir = join(dirname(__file__), 'plugins') + self.respath = dirname(__file__) + + # expanduser in Python 2 on Windows doesn't handle non-ASCII - http://bugs.python.org/issue13207 + self.home = known_folder_path(FOLDERID_Profile) or r'\\' + + journaldir = known_folder_path(FOLDERID_SavedGames) + if journaldir: + self.default_journal_dir = join(journaldir, 'Frontier Developments', 'Elite Dangerous') + + else: + self.default_journal_dir = None + + self.identifier = applongname + self.hkey = HKEY() + disposition = DWORD() + if RegCreateKeyEx( + HKEY_CURRENT_USER, + r'Software\Marginal\EDMarketConnector', + 0, + None, + 0, + KEY_ALL_ACCESS, + None, + ctypes.byref(self.hkey), + ctypes.byref(disposition) + ): + raise Exception() + + # set WinSparkle defaults - https://github.com/vslavik/winsparkle/wiki/Registry-Settings + edcdhkey = HKEY() + if RegCreateKeyEx( + HKEY_CURRENT_USER, + r'Software\EDCD\EDMarketConnector', + 0, + None, + 0, + KEY_ALL_ACCESS, + None, + ctypes.byref(edcdhkey), + ctypes.byref(disposition) + ): + raise Exception() + + sparklekey = HKEY() + if not RegCreateKeyEx( + edcdhkey, + 'WinSparkle', + 0, + None, + 0, + KEY_ALL_ACCESS, + None, + ctypes.byref(sparklekey), + ctypes.byref(disposition) + ): + if disposition.value == REG_CREATED_NEW_KEY: + buf = ctypes.create_unicode_buffer('1') + RegSetValueEx(sparklekey, 'CheckForUpdates', 0, 1, buf, len(buf) * 2) + + buf = ctypes.create_unicode_buffer(str(update_interval)) + 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 + 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]: + """Look up a string configuration value.""" + key_type = DWORD() + key_size = DWORD() + # Only strings are handled here. + if ( + RegQueryValueEx( + self.hkey, + key, + 0, + ctypes.byref(key_type), + None, + ctypes.byref(key_size) + ) + or key_type.value not in [REG_SZ, REG_MULTI_SZ] + ): + return default + + buf = ctypes.create_unicode_buffer(int(key_size.value / 2)) + if RegQueryValueEx(self.hkey, key, 0, ctypes.byref(key_type), buf, ctypes.byref(key_size)): + return default + + elif key_type.value == REG_MULTI_SZ: + return list(ctypes.wstring_at(buf, len(buf)-2).split('\x00')) + + else: + return str(buf.value) + + def getint(self, key: str, default: int = 0) -> int: + """Look up an integer configuration value.""" + key_type = DWORD() + key_size = DWORD(4) + key_val = DWORD() + if ( + RegQueryValueEx( + self.hkey, + key, + 0, + ctypes.byref(key_type), + ctypes.byref(key_val), + ctypes.byref(key_size) + ) + or key_type.value != REG_DWORD + ): + return default + + else: + return key_val.value + + def set(self, key: str, val: Union[int, str, list]) -> None: + """Set value on the specified configuration key.""" + if isinstance(val, str): + buf = ctypes.create_unicode_buffer(val) + RegSetValueEx(self.hkey, key, 0, REG_SZ, buf, len(buf)*2) + + elif isinstance(val, numbers.Integral): + RegSetValueEx(self.hkey, key, 0, REG_DWORD, ctypes.byref(DWORD(val)), 4) + + elif isinstance(val, list): + # null terminated non-empty strings + string_val = '\x00'.join([str(x) or ' ' for x in val] + ['']) + buf = ctypes.create_unicode_buffer(string_val) + RegSetValueEx(self.hkey, key, 0, REG_MULTI_SZ, buf, len(buf)*2) + + else: + raise NotImplementedError() + + def delete(self, key: str) -> None: + """Delete the specified configuration key.""" + RegDeleteValue(self.hkey, key) + + def save(self) -> None: + """Save current configuration to disk.""" + pass # Redundant since registry keys are written immediately + + def close(self) -> None: + """Close the configuration.""" + RegCloseKey(self.hkey) + self.hkey = None + + elif platform == 'linux': + SECTION = 'config' + + def __init__(self): + + # http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html + self.app_dir = join(getenv('XDG_DATA_HOME', expanduser('~/.local/share')), appname) + if not isdir(self.app_dir): + makedirs(self.app_dir) + + self.plugin_dir = join(self.app_dir, 'plugins') + if not isdir(self.plugin_dir): + mkdir(self.plugin_dir) + + self.internal_plugin_dir = join(dirname(__file__), 'plugins') + self.default_journal_dir = None + self.home = expanduser('~') + self.respath = dirname(__file__) + self.identifier = f'uk.org.marginal.{appname.lower()}' + + self.filename = join(getenv('XDG_CONFIG_HOME', expanduser('~/.config')), appname, f'{appname}.ini') + if not isdir(dirname(self.filename)): + makedirs(dirname(self.filename)) + + self.config = RawConfigParser(comment_prefixes=('#',)) + try: + with codecs.open(self.filename, 'r') as h: + self.config.read_file(h) + + except Exception as e: + logger.debug('Reading config failed, assuming we\'re making a new one...', exc_info=e) + self.config.add_section(self.SECTION) + + 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]: + """Look up a string configuration value.""" + try: + val = self.config.get(self.SECTION, key) + if '\n' in val: # list + # ConfigParser drops the last entry if blank, + # 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) + + except NoOptionError: + logger.debug(f'attempted to get key {key} that does not exist') + return default + + except Exception as e: + logger.debug('And the exception type is...', exc_info=e) + return default + + def getint(self, key: str, default: int = 0) -> int: + """Look up an integer configuration value.""" + try: + return self.config.getint(self.SECTION, key) + + except ValueError as e: + logger.error(f"Failed to int({key=})", exc_info=e) + + except NoOptionError: + logger.debug(f'attempted to get key {key} that does not exist') + + except Exception: + logger.exception(f'unexpected exception while attempting to access {key}') + + return default + + def set(self, key: str, val: Union[int, str, list]) -> None: + """Set value on the specified configuration key.""" + if isinstance(val, bool): + self.config.set(self.SECTION, key, val and '1' or '0') # type: ignore # Not going to change + + 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, list): + self.config.set(self.SECTION, key, '\n'.join([self._escape(x) for x in val] + [';'])) + + else: + raise NotImplementedError() + + def delete(self, key: str) -> None: + """Delete the specified configuration key.""" + self.config.remove_option(self.SECTION, key) + + def save(self) -> None: + """Save current configuration to disk.""" + with codecs.open(self.filename, 'w', 'utf-8') as h: + self.config.write(h) + + def close(self) -> None: + """Close the configuration.""" + self.save() + self.config = None + + def _escape(self, val: str) -> str: + """Escape a string for storage.""" + return str(val).replace('\\', '\\\\').replace('\n', '\\n').replace(';', '\\;') + + def _unescape(self, val: str) -> str: + """Un-escape a string from storage.""" + chars = list(val) + i = 0 + while i < len(chars): + if chars[i] == '\\': + chars.pop(i) + if chars[i] == 'n': + chars[i] = '\n' + i += 1 + return ''.join(chars) + + else: + def __init__(self): + raise NotImplementedError('Implement me') + + # Common + + def get_password(self, account: str) -> None: + """Legacy password retrieval.""" + warnings.warn("password subsystem is no longer supported", DeprecationWarning) + + def set_password(self, account: str, password: str) -> None: + """Legacy password setting.""" + warnings.warn("password subsystem is no longer supported", DeprecationWarning) + + def delete_password(self, account: str) -> None: + """Legacy password deletion.""" + warnings.warn("password subsystem is no longer supported", DeprecationWarning) + + +old_config = OldConfig() diff --git a/tests/config.py/test_config.py b/tests/config.py/test_config.py new file mode 100644 index 00000000..0d10a3c2 --- /dev/null +++ b/tests/config.py/test_config.py @@ -0,0 +1,231 @@ +"""Test the config system.""" +from __future__ import annotations + +import contextlib +import itertools +import pathlib +import random +import string +import sys +from typing import Any, Iterable, List, cast + +import pytest +from pytest import mark + +# isort: split + +sys.path += [str(pathlib.Path(__file__).parent.parent.resolve()), "."] +print(sys.path) + +from _old_config import old_config # noqa: E402 + +from config import LinuxConfig, config # noqa: E402 + + +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) + + +_fuzz_generators = { # Type annotating this would be a nightmare. + int: lambda i: random.randint(min(0, i), max(0, i)), + # This doesn't cover unicode, or random bytes. Use them at your own peril + str: lambda l: "".join(random.choice(string.ascii_letters + string.digits + '\r\n') for _ in range(l)), + bool: lambda _: bool(random.choice((True, False))), + list: _fuzz_list, +} + + +def _get_fuzz(_type: Any, num_values=50, value_length=(0, 10)) -> list: + return [_fuzz_generators[_type](random.randint(*value_length)) for _ in range(num_values)] + + +int_tests = [0, 1, 2, 3, (1 << 32)-1, -1337] + +string_tests = [ + "test", "", "this\nis\na\ntest", "orange sidewinder", "needs \\ more backslashes\\", "\\; \\n", r"\\\\ \\\\; \\\\n", + r"entry with escapes \\ \\; \\n" +] + +list_tests = [ + ["test"], + ["multiple", "entries"], + ["multiple", "entries", "with", "", "blanks"], + ["entry", "that ends", "in a", ""], + ["entry with \n", "newlines\nin", "weird\nplaces"], + [r"entry with escapes \\ \\; \\n"], + [r"\\\\ \\\\; \\\\n"] +] +bool_tests = [True, False] + +big_int = int(0xFFFFFFFF) # 32 bit int + + +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)] + + +def _build_test_list(static_data, random_data, random_id_name='random_test_{i}') -> Iterable: + return itertools.chain(static_data, _make_params(random_data, id_name=random_id_name)) + + +class TestNewConfig: + """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.""" + if isinstance(config, LinuxConfig) and config.config is not None: + config.config.read(config.filename) + + @mark.parametrize("i", _build_test_list(int_tests, _get_fuzz(int, value_length=(-big_int, big_int)))) + def test_ints(self, i: int) -> None: + """Save int and then unpack it again.""" + if sys.platform == 'win32': + i = abs(i) + + name = f"int_test_{i}" + config.set(name, i) + config.save() + self.__update_linuxconfig() + assert i == config.get_int(name) + config.delete(name) + + @mark.parametrize("string", _build_test_list(string_tests, _get_fuzz(str, value_length=(0, 512)))) + def test_string(self, string: str) -> None: + """Save a string and then ask for it back.""" + name = f'str_test_{hash(string)}' + config.set(name, string) + config.save() + self.__update_linuxconfig() + assert string == config.get_str(name) + config.delete(name) + + @mark.parametrize("lst", _build_test_list(list_tests, _get_fuzz(list))) + 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) + + config.save() + self.__update_linuxconfig() + + assert lst == config.get_list(name) + + config.delete(name) + + @mark.parametrize('b', bool_tests) + def test_bool(self, b: bool) -> None: + """Save a bool and ask for it back.""" + name = str(b) + config.set(name, b) + config.save() + self.__update_linuxconfig() + assert b == config.get_bool(name) + config.delete(name) + + def test_get_no_error(self) -> None: + """Regression test to ensure that get() doesn't throw a TypeError.""" + name = 'test-get' + config.set(name, '1337') + config.save() + self.__update_linuxconfig() + with pytest.deprecated_call(): + res = config.get(name) + + assert res == '1337' + config.delete(name) + config.save() + + +class TestOldNewConfig: + """Tests going through the old config and out the new config.""" + + KEY_PREFIX = 'oldnew_' + + def teardown_method(self) -> None: + """ + Teardown for all config tests to save out configs. + + It is expected that tests have cleaned up whatever keys they have aded. + This is here to ensure that a save out happens for configs that need it. + """ + old_config.save() + config.save() + + def cleanup_entry(self, entry: str) -> None: + """Remove the given key, on both sides if on linux.""" + config.delete(entry) + if sys.platform == 'linux': + old_config.delete(entry) + + def __update_linuxconfig(self) -> None: + """On linux config uses ConfigParser, which doesn't update from disk changes. Force the update here.""" + if isinstance(config, LinuxConfig) and config.config is not None: + config.config.read(config.filename) + + @mark.parametrize("i", _build_test_list(int_tests, _get_fuzz(int, 50, (-big_int, big_int)))) + def test_int(self, i: int) -> None: + """Save an int though the old config, recall it using the new config.""" + if sys.platform == 'win32': + i = abs(i) + + name = self.KEY_PREFIX + f'int_{i}' + old_config.set(name, i) + old_config.save() + + self.__update_linuxconfig() + + res = config.get_int(name) + with contextlib.ExitStack() as stack: + stack.callback(self.cleanup_entry, name) + assert res == i + + @mark.parametrize("string", _build_test_list(string_tests, _get_fuzz(str, value_length=(0, 512)))) + def test_string(self, string: str) -> None: + """Save a string though the old config, recall it using the new config.""" + string = string.replace("\r", "") # The old config does _not_ support \r in its entries. We do. + name = self.KEY_PREFIX + f'string_{hash(string)}' + old_config.set(name, string) + old_config.save() + + self.__update_linuxconfig() + + res = config.get_str(name) + with contextlib.ExitStack() as stack: + stack.callback(self.cleanup_entry, name) + assert res == string + + @mark.parametrize("lst", _build_test_list(list_tests, _get_fuzz(list))) + 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': + # old conf on windows replaces empty entries with spaces as a workaround for a bug. New conf does not + # So insert those spaces here, to ensure that it works otherwise. + lst = [e if len(e) > 0 else ' ' for e in lst] + + name = self.KEY_PREFIX + f'list_test_{ hash("".join(lst)) }' + old_config.set(name, lst) + old_config.save() + + self.__update_linuxconfig() + + res = config.get_list(name) + with contextlib.ExitStack() as stack: + stack.callback(self.cleanup_entry, name) + assert res == lst + + @mark.skipif(sys.platform == 'win32', reason="Old Windows config does not support bool types") + @mark.parametrize("b", bool_tests) + def test_bool(self, b: bool) -> None: + """Save a bool though the old config, recall it using the new config.""" + name = str(b) + old_config.set(name, b) + old_config.save() + self.__update_linuxconfig() + with contextlib.ExitStack() as stack: + stack.callback(self.cleanup_entry, name) + assert config.get_bool(name) == b diff --git a/tests/journal_lock.py/test_journal_lock.py b/tests/journal_lock.py/test_journal_lock.py new file mode 100644 index 00000000..75a6be1f --- /dev/null +++ b/tests/journal_lock.py/test_journal_lock.py @@ -0,0 +1,361 @@ +""" +Tests for journal_lock.py code. + +Tests: + - Is file actually locked after obtain_lock(). Problem: We opened the + file in a manner which means nothing else can open it. Also I assume + that the same process will either be allowed to lock it 'again' or + overwrite the lock. + + Expected failures if: + + 1. Lock already held (elsewhere). + 2. Can't open lock file 'w+'. + 3. Path to lock file doesn't exist. + 4. journaldir is None (default on Linux). + + - Does release_lock() work? Easier to test, if it's worked.... + 1. return True if not locked. + 2. return True if locked, but successful unlock. + 3. return False otherwise. + + - JournalLock.set_path_from_journaldir + 1. When journaldir is None. + 2. Succeeds otherwise? + + - Can any string to pathlib.Path result in an invalid path for other + operations? + + - Not sure about testing JournalAlreadyLocked class. +""" +import multiprocessing as mp +import os +import pathlib +import sys + +import pytest +# Import as other names else they get picked up when used as fixtures +from _pytest import monkeypatch as _pytest_monkeypatch +from _pytest import tmpdir as _pytest_tmpdir +from py._path.local import LocalPath as py_path_local_LocalPath + +from config import config +from journal_lock import JournalLock, JournalLockResult + + +########################################################################### +# For some tests (at least on Linux) we need another process to already +# hold the lock. +# This is at top level due to multiprocessing.Process wanting to +# pickle its arguments, other_process_lock() being one of them. +def other_process_lock(continue_q: mp.Queue, exit_q: mp.Queue, lockfile: pathlib.Path): + """ + Obtain the lock in a sub-process. + + :param continue_q: Write to this when parent should continue. + :param exit_q: When there's an item in this, exit. + :param lockfile: Path where the lockfile should be. + """ + with open(lockfile / 'edmc-journal-lock.txt', mode='w+') as lf: + print(f'sub-process: Opened {lockfile} for read...') + # This needs to be kept in sync with journal_lock.py:_obtain_lock() + if not _obtain_lock('sub-process', lf): + print('sub-process: Failed to get lock, so returning') + return + + print('sub-process: Got lock, telling main process to go...') + continue_q.put('go', timeout=5) + # Wait for signal to exit + print('sub-process: Waiting for exit signal...') + exit_q.get(block=True, timeout=None) + + +def _obtain_lock(prefix: str, filehandle) -> bool: + """ + Obtain the JournalLock. + + :param prefix: str - what to prefix output with. + :param filehandle: File handle already open on the lockfile. + :return: bool - True if we obtained the lock. + """ + if sys.platform == 'win32': + print(f'{prefix}: On win32') + import msvcrt + try: + print(f'{prefix}: Trying msvcrt.locking() ...') + msvcrt.locking(filehandle.fileno(), msvcrt.LK_NBLCK, 4096) + + except Exception as e: + print(f'{prefix}: Unable to lock file: {e!r}') + return False + + else: + import fcntl + + print(f'{prefix}: Not win32, using fcntl') + try: + fcntl.flock(filehandle, fcntl.LOCK_EX | fcntl.LOCK_NB) + + except Exception as e: + print(f'{prefix}: Unable to lock file: {e!r}') + return False + + return True +########################################################################### + + +class TestJournalLock: + """JournalLock test class.""" + + @pytest.fixture + def mock_journaldir(self, monkeypatch: _pytest_monkeypatch, tmpdir: _pytest_tmpdir) -> py_path_local_LocalPath: + """Fixture for mocking config.get_str('journaldir').""" + def get_str(key: str, *, default: str = None) -> str: + """Mock config.*Config get_str to provide fake journaldir.""" + if key == 'journaldir': + return tmpdir + + print('Other key, calling up ...') + return config.get_str(key) # Call the non-mocked + + with monkeypatch.context() as m: + m.setattr(config, "get_str", get_str) + yield tmpdir + + @pytest.fixture + def mock_journaldir_changing( + self, + monkeypatch: _pytest_monkeypatch, + tmpdir_factory: _pytest_tmpdir.TempdirFactory + ) -> py_path_local_LocalPath: + """Fixture for mocking config.get_str('journaldir').""" + def get_str(key: str, *, default: str = None) -> str: + """Mock config.*Config get_str to provide fake journaldir.""" + if key == 'journaldir': + return tmpdir_factory.mktemp("changing") + + print('Other key, calling up ...') + return config.get_str(key) # Call the non-mocked + + with monkeypatch.context() as m: + m.setattr(config, "get_str", get_str) + yield tmpdir_factory + + ########################################################################### + # Tests against JournalLock.__init__() + def test_journal_lock_init(self, mock_journaldir: py_path_local_LocalPath): + """Test JournalLock instantiation.""" + tmpdir = mock_journaldir + + jlock = JournalLock() + # Check members are properly initialised. + assert jlock.journal_dir == tmpdir + assert jlock.journal_dir_path is not None + assert jlock.journal_dir_lockfile_name is None + + ########################################################################### + # Tests against JournalLock.set_path_from_journaldir() + def test_path_from_journaldir_with_none(self): + """Test JournalLock.set_path_from_journaldir() with None.""" + jlock = JournalLock() + + # Check that 'None' is handled correctly. + jlock.journal_dir = None + jlock.set_path_from_journaldir() + assert jlock.journal_dir_path is None + + def test_path_from_journaldir_with_tmpdir(self, mock_journaldir: py_path_local_LocalPath): + """Test JournalLock.set_path_from_journaldir() with tmpdir.""" + tmpdir = mock_journaldir + + jlock = JournalLock() + + # Check that an actual journaldir is handled correctly. + jlock.journal_dir = tmpdir + jlock.set_path_from_journaldir() + assert isinstance(jlock.journal_dir_path, pathlib.Path) + + ########################################################################### + # Tests against JournalLock.obtain_lock() + def test_obtain_lock_with_none(self): + """Test JournalLock.obtain_lock() with None.""" + jlock = JournalLock() + + # Check that 'None' is handled correctly. + jlock.journal_dir = None + jlock.set_path_from_journaldir() + assert jlock.journal_dir_path is None + locked = jlock.obtain_lock() + assert locked == JournalLockResult.JOURNALDIR_IS_NONE + + def test_obtain_lock_with_tmpdir(self, mock_journaldir: py_path_local_LocalPath): + """Test JournalLock.obtain_lock() with tmpdir.""" + jlock = JournalLock() + + # Check that an actual journaldir is handled correctly. + locked = jlock.obtain_lock() + assert locked == JournalLockResult.LOCKED + assert jlock.locked + + def test_obtain_lock_with_tmpdir_ro(self, mock_journaldir: py_path_local_LocalPath): + """Test JournalLock.obtain_lock() with read-only tmpdir.""" + tmpdir = mock_journaldir + + # Make tmpdir read-only ? + if sys.platform == 'win32': + # Ref: + import ntsecuritycon as con + import win32security + + # Fetch user details + winuser, domain, type = win32security.LookupAccountName("", os.environ.get('USERNAME')) + # Fetch the current security of tmpdir for that user. + sd = win32security.GetFileSecurity(str(tmpdir), win32security.DACL_SECURITY_INFORMATION) + dacl = sd.GetSecurityDescriptorDacl() # instead of dacl = win32security.ACL() + + # Add Write to Denied list + # con.FILE_WRITE_DATA results in a 'Special permissions' being + # listed on Properties > Security for the user in the 'Deny' column. + # Clicking through to 'Advanced' shows a 'Deny' for + # 'Create files / write data'. + dacl.AddAccessDeniedAce(win32security.ACL_REVISION, con.FILE_WRITE_DATA, winuser) + # Apply that change. + sd.SetSecurityDescriptorDacl(1, dacl, 0) # may not be necessary + win32security.SetFileSecurity(str(tmpdir), win32security.DACL_SECURITY_INFORMATION, sd) + + else: + import stat + os.chmod(tmpdir, stat.S_IRUSR | stat.S_IXUSR) + + jlock = JournalLock() + + # Check that an actual journaldir is handled correctly. + locked = jlock.obtain_lock() + + # Revert permissions for test cleanup + if sys.platform == 'win32': + # We can reuse winuser etc from before + import pywintypes + + # We have to call GetAce() until we find one that looks like what + # we added. + i = 0 + ace = dacl.GetAce(i) + while ace: + if ace[0] == (con.ACCESS_DENIED_ACE_TYPE, 0) and ace[1] == con.FILE_WRITE_DATA: + # Delete the Ace that we added + dacl.DeleteAce(i) + # Apply that change. + sd.SetSecurityDescriptorDacl(1, dacl, 0) # may not be necessary + win32security.SetFileSecurity(str(tmpdir), win32security.DACL_SECURITY_INFORMATION, sd) + break + + i += 1 + try: + ace = dacl.GetAce(i) + + except pywintypes.error: + print("Couldn't find the Ace we added, so can't remove") + break + + else: + os.chmod(tmpdir, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) + + assert locked == JournalLockResult.JOURNALDIR_READONLY + + def test_obtain_lock_already_locked(self, mock_journaldir: py_path_local_LocalPath): + """Test JournalLock.obtain_lock() with tmpdir.""" + continue_q: mp.Queue = mp.Queue() + exit_q: mp.Queue = mp.Queue() + locker = mp.Process(target=other_process_lock, + args=(continue_q, exit_q, mock_journaldir) + ) + print('Starting sub-process other_process_lock()...') + locker.start() + # Wait for the sub-process to have locked + print('Waiting for "go" signal from sub-process...') + continue_q.get(block=True, timeout=5) + + print('Attempt actual lock test...') + # Now attempt to lock with to-test code + jlock = JournalLock() + second_attempt = jlock.obtain_lock() + # Fails on Linux, because flock(2) is per process, so we'd need to + # use multiprocessing to test this. + assert second_attempt == JournalLockResult.ALREADY_LOCKED + print('Telling sub-process to quit...') + exit_q.put('quit') + print('Waiting for sub-process...') + locker.join() + print('Done.') + + ########################################################################### + # Tests against JournalLock.release_lock() + def test_release_lock(self, mock_journaldir: py_path_local_LocalPath): + """Test JournalLock.release_lock().""" + # First actually obtain the lock, and check it worked + jlock = JournalLock() + jlock.obtain_lock() + assert jlock.locked + + # Now release the lock + assert jlock.release_lock() + + # And finally check it actually IS unlocked. + with open(mock_journaldir / 'edmc-journal-lock.txt', mode='w+') as lf: + assert _obtain_lock('release-lock', lf) + + def test_release_lock_not_locked(self, mock_journaldir: py_path_local_LocalPath): + """Test JournalLock.release_lock() when not locked.""" + jlock = JournalLock() + assert jlock.release_lock() + + def test_release_lock_lie_locked(self, mock_journaldir: py_path_local_LocalPath): + """Test JournalLock.release_lock() when not locked, but lie we are.""" + jlock = JournalLock() + jlock.locked = True + assert jlock.release_lock() is False + + ########################################################################### + # Tests against JournalLock.update_lock() + def test_update_lock( + self, + mock_journaldir_changing: py_path_local_LocalPath): + """ + Test JournalLock.update_lock(). + + NB: This uses mock_journaldir_changing so that each subsequent call + to config.get_str('journaldir') gets a new, unique, path. + This should mean that the call to update_lock() switches to a new + journaldir. + """ + # First actually obtain the lock, and check it worked + jlock = JournalLock() + jlock.obtain_lock() + assert jlock.locked + + # Now store the 'current' journaldir for reference and attempt + # to update to a new one. + old_journaldir = jlock.journal_dir + jlock.update_lock(None) # type: ignore + assert jlock.journal_dir != old_journaldir + assert jlock.locked + + def test_update_lock_same(self, mock_journaldir: py_path_local_LocalPath): + """ + Test JournalLock.update_lock(). + + Due to using 'static' mock_journaldir this should 'work', because the + directory is still the same. + """ + # First actually obtain the lock, and check it worked + jlock = JournalLock() + jlock.obtain_lock() + assert jlock.locked + + # Now store the 'current' journaldir for reference and attempt + # to update to a new one. + old_journaldir = jlock.journal_dir + jlock.update_lock(None) # type: ignore + assert jlock.journal_dir == old_journaldir + assert jlock.locked diff --git a/theme.py b/theme.py index d56b7798..d05a52e6 100644 --- a/theme.py +++ b/theme.py @@ -6,26 +6,25 @@ # import os -from sys import platform -from os.path import join - import tkinter as tk -from tkinter import ttk +from os.path import join +from sys import platform from tkinter import font as tkFont -from ttkHyperlinkLabel import HyperlinkLabel +from tkinter import ttk -from config import appname, applongname, config +from config import applongname, appname, config +from ttkHyperlinkLabel import HyperlinkLabel if __debug__: from traceback import print_exc if platform == "linux": - from ctypes import * + from ctypes import POINTER, c_char_p, c_int, c_long, c_uint, c_ulong, c_void_p, cdll, Structure, byref if platform == 'win32': import ctypes - from ctypes.wintypes import LPCWSTR, DWORD, LPCVOID + from ctypes.wintypes import DWORD, LPCVOID, LPCWSTR AddFontResourceEx = ctypes.windll.gdi32.AddFontResourceExW AddFontResourceEx.restypes = [LPCWSTR, DWORD, LPCVOID] FR_PRIVATE = 0x10 @@ -33,10 +32,11 @@ if platform == 'win32': AddFontResourceEx(join(config.respath, u'EUROCAPS.TTF'), FR_PRIVATE, 0) elif platform == 'linux': + # pyright: reportUnboundVariable=false XID = c_ulong # from X.h: typedef unsigned long XID Window = XID Atom = c_ulong - Display = c_void_p # Opaque + Display = c_void_p # Opaque PropModeReplace = 0 PropModePrepend = 1 @@ -207,21 +207,21 @@ class _Theme(object): style.theme_use('clam') # Default dark theme colors - if not config.get('dark_text'): + if not config.get_str('dark_text'): config.set('dark_text', '#ff8000') # "Tangerine" in OSX color picker - if not config.get('dark_highlight'): + if not config.get_str('dark_highlight'): config.set('dark_highlight', 'white') if theme: # Dark - (r, g, b) = root.winfo_rgb(config.get('dark_text')) + (r, g, b) = root.winfo_rgb(config.get_str('dark_text')) self.current = { 'background' : 'grey4', # OSX inactive dark titlebar color - 'foreground' : config.get('dark_text'), - 'activebackground' : config.get('dark_text'), + 'foreground' : config.get_str('dark_text'), + 'activebackground' : config.get_str('dark_text'), 'activeforeground' : 'grey4', 'disabledforeground' : '#%02x%02x%02x' % (int(r/384), int(g/384), int(b/384)), - 'highlight' : config.get('dark_highlight'), + 'highlight' : config.get_str('dark_highlight'), # Font only supports Latin 1 / Supplement / Extended, and a few General Punctuation and Mathematical Operators 'font' : (theme > 1 and not 0x250 < ord(_('Cmdr')[0]) < 0x3000 and tkFont.Font(family='Euro Caps', size=10, weight=tkFont.NORMAL) or @@ -309,7 +309,7 @@ class _Theme(object): # Apply configured theme def apply(self, root): - theme = config.getint('theme') + theme = config.get_int('theme') self._colors(root, theme) # Apply colors @@ -338,7 +338,7 @@ class _Theme(object): self.active = theme if platform == 'darwin': - from AppKit import NSApplication, NSAppearance, NSMiniaturizableWindowMask, NSResizableWindowMask + from AppKit import NSAppearance, NSApplication, NSMiniaturizableWindowMask, NSResizableWindowMask root.update_idletasks() # need main window to be created appearance = NSAppearance.appearanceNamed_(theme and 'NSAppearanceNameDarkAqua' or diff --git a/ttkHyperlinkLabel.py b/ttkHyperlinkLabel.py index 627a987f..c731ffac 100644 --- a/ttkHyperlinkLabel.py +++ b/ttkHyperlinkLabel.py @@ -1,15 +1,14 @@ -from sys import platform -import webbrowser - import tkinter as tk -from tkinter import ttk +import webbrowser +from sys import platform from tkinter import font as tkFont +from tkinter import ttk if platform == 'win32': import subprocess - import ctypes - from ctypes.wintypes import * - from winreg import CloseKey, OpenKeyEx, QueryValueEx, HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, KEY_READ, REG_SZ, REG_MULTI_SZ + from winreg import ( + HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, CloseKey, OpenKeyEx, QueryValueEx + ) # A clickable ttk Label # diff --git a/update.py b/update.py index de7eb8cd..00fe9e6d 100644 --- a/update.py +++ b/update.py @@ -9,7 +9,8 @@ if TYPE_CHECKING: import tkinter as tk # ensure registry is set up on Windows before we start -from config import appname, appversion, appversion_nobuild, config, update_feed +from config import appname, appversion_nobuild, config, update_feed + class EDMCVersion(object): """ @@ -29,6 +30,7 @@ class EDMCVersion(object): self.title: str = title self.sv: semantic_version.base.Version = sv + class Updater(object): """ Updater class to handle checking for updates, whether using internal code @@ -79,7 +81,7 @@ class Updater(object): # NB: It 'accidentally' supports pre-release due to how it # splits and compares strings: # - self.updater.win_sparkle_set_app_build_version(appversion_nobuild) + self.updater.win_sparkle_set_app_build_version(str(appversion_nobuild())) # set up shutdown callback global root @@ -175,7 +177,7 @@ class Updater(object): ) # Look for any remaining version greater than appversion - simple_spec = semantic_version.SimpleSpec('>' + appversion) + simple_spec = semantic_version.SimpleSpec(f'>{appversion_nobuild()}') newversion = simple_spec.select(items.keys()) if newversion: diff --git a/util_ships.py b/util_ships.py new file mode 100644 index 00000000..204e21f5 --- /dev/null +++ b/util_ships.py @@ -0,0 +1,15 @@ +"""Utility functions relating to ships.""" +from edmc_data import ship_name_map + +def ship_file_name(ship_name: str, ship_type: str) -> str: + """Return a ship name suitable for a filename.""" + name = str(ship_name or ship_name_map.get(ship_type.lower(), ship_type)).strip() + if name.endswith('.'): + name = name[:-2] + + 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 + '_' + + return name.translate({ord(x): u'_' for x in ('\0', '<', '>', ':', '"', '/', '\\', '|', '?', '*')})