Merge branch 'stable' into releases

This commit is contained in:
Athanasius committed 2021-05-12 16:51:58 +01:00
commit 02fe3c8ee7
88 files changed
+9665 -3786

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
[run]
omit =
# The tests themselves
tests/*
# Any venv files
venv/*
+2 -3
View File
@@ -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.
@@ -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 }}
##################################################################
+21 -16
View File
@@ -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
+12 -8
View File
@@ -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
+3 -3
View File
@@ -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
+6
View File
@@ -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
+19 -12
View File
@@ -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 <file>
- repo: https://gitlab.com/pycqa/flake8
rev: ''
hooks:
- id: flake8
### # flake8 --show-source <file>
### - 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 <file>
- 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
+1
View File
@@ -0,0 +1 @@
3.9.5
+378
View File
@@ -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_<type>()` function:
* `config.get_list(<key>)`
* `config.get_str(<key>)`
* `config.get_bool(<key>)`
* `config.get_int(<key>)`
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
===
+29 -3
View File
@@ -1,3 +1,6 @@
<!--
vim: textwidth=79 wrapmargin=79
-->
# 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).
---
+12 -9
View File
@@ -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()
+111 -68
View File
@@ -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:
<file/module>.<classA>[.classB....].<function>
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"<property {name} on {class_name}>"
else:
caller_qualname = f"<property {name} on {class_name}>"
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 == '<module>':
caller_class_names = '<none>'
caller_qualname = value_dict['__name__']
# It's a call from the top level module file
elif frame_info.function == '<module>':
caller_class_names = '<none>'
caller_qualname = value_dict['__name__']
elif frame_info.function != '':
caller_class_names = '<none>'
caller_qualname = frame_info.function
elif frame_info.function != '':
caller_class_names = '<none>'
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()
+1
View File
@@ -0,0 +1 @@
EDMarketConnector.exe --reset-ui
+606 -244
View File
File diff suppressed because it is too large. Load diff
+37 -13
View File
@@ -113,12 +113,18 @@
<File Id="EDMarketConnector.exe" KeyPath="yes" Source="SourceDir\EDMarketConnector.exe" />
<Shortcut Id="MainExeShortcut" Directory="ProgramMenuFolder" Name="$(var.PRODUCTLONGNAME)" Description="Downloads station data from Elite: Dangerous" WorkingDirectory="INSTALLDIR" Icon="EDMarketConnector.exe" IconIndex="0" Advertise="yes" />
</Component>
<Component Guid="*">
<File KeyPath="yes" Source="SourceDir\_asyncio.pyd" />
</Component>
<Component Guid="{842DC919-EC3D-48EF-A6B3-9A81608E0FB9}">
<File KeyPath="yes" Source="SourceDir\_bz2.pyd" />
</Component>
<Component Guid="{433C38E1-F736-4546-AA83-FCD8B0AAA39B}">
<File KeyPath="yes" Source="SourceDir\_ctypes.pyd" />
</Component>
<Component Guid="*">
<File KeyPath="yes" Source="SourceDir\_decimal.pyd" />
</Component>
<Component Guid="*">
<File KeyPath="yes" Source="SourceDir\_elementtree.pyd" />
</Component>
@@ -128,6 +134,12 @@
<Component Guid="*">
<File KeyPath="yes" Source="SourceDir\_lzma.pyd" />
</Component>
<Component Guid="*">
<File KeyPath="yes" Source="SourceDir\_multiprocessing.pyd" />
</Component>
<Component Guid="*">
<File KeyPath="yes" Source="SourceDir\_overlapped.pyd" />
</Component>
<Component Guid="*">
<File KeyPath="yes" Source="SourceDir\_queue.pyd" />
</Component>
@@ -140,6 +152,9 @@
<Component Guid="{2EA8F0B6-A104-4D31-99F0-3535ACDC26A9}">
<File KeyPath="yes" Source="SourceDir\_ssl.pyd" />
</Component>
<Component Guid="*">
<File KeyPath="yes" Source="SourceDir\_testcapi.pyd" />
</Component>
<Component Guid="{D2F0CDD2-E934-419F-BC99-445E8FD3AF24}">
<File KeyPath="yes" Source="SourceDir\_tkinter.pyd" />
</Component>
@@ -167,6 +182,9 @@
<Component Guid="*">
<File KeyPath="yes" Source="SourceDir\libcrypto-1_1.dll" />
</Component>
<Component Guid="*">
<File KeyPath="yes" Source="SourceDir\libffi-7.dll" />
</Component>
<Component Guid="{A18814B6-B491-42AB-A433-2AD66A823AD7}">
<File KeyPath="yes" Source="SourceDir\library.zip" />
</Component>
@@ -179,8 +197,8 @@
<Component Guid="{87A99AAA-792F-4092-9D00-5106D99D00AD}">
<File KeyPath="yes" Source="SourceDir\pyexpat.pyd" />
</Component>
<Component Guid="{685773F2-78E4-4A16-BE0D-C7AB9575C856}">
<File KeyPath="yes" Source="SourceDir\python37.dll" />
<Component Guid="*">
<File KeyPath="yes" Source="SourceDir\python39.dll" />
</Component>
<Component Guid="*">
<File KeyPath="yes" Source="SourceDir\rare_commodity.csv" />
@@ -200,12 +218,6 @@
<Component Guid="*">
<File KeyPath="yes" Source="SourceDir\sqlite3.dll" />
</Component>
<Component Guid="*">
<File KeyPath="yes" Source="SourceDir\stations.p" />
</Component>
<Component Guid="*">
<File KeyPath="yes" Source="SourceDir\systems.p" />
</Component>
<Component Guid="{30EEAD30-A43B-4A31-A209-450A8AD17AC2}">
<File KeyPath="yes" Source="SourceDir\tcl86t.dll" />
</Component>
@@ -227,6 +239,12 @@
<Component Id="EDMarketConnector_localserver_auth.bat" Guid="*">
<File KeyPath="yes" Source="SourceDir\EDMarketConnector - localserver-auth.bat" />
</Component>
<Component Id="EDMarketConnector_localserver_resetui.bat" Guid="*">
<File KeyPath="yes" Source="SourceDir\EDMarketConnector - reset-ui.bat" />
</Component>
<Component Id="gitversion" Guid="*">
<File KeyPath="yes" Source="SourceDir\.gitversion" />
</Component>
<Directory Id="L10n" Name="L10n">
<Component Guid="*">
<File KeyPath="yes" Source="SourceDir\L10n\cs.strings" />
@@ -543,15 +561,21 @@
<Feature Id='Complete' Level='1'>
<ComponentRef Id="RegistryEntries" />
<ComponentRef Id="MainExecutable" />
<ComponentRef Id="gitversion" />
<ComponentRef Id="_asyncio.pyd" />
<ComponentRef Id="_bz2.pyd" />
<ComponentRef Id="_ctypes.pyd" />
<ComponentRef Id="_decimal.pyd" />
<ComponentRef Id="_elementtree.pyd" />
<ComponentRef Id="_hashlib.pyd" />
<ComponentRef Id="_lzma.pyd" />
<ComponentRef Id="_multiprocessing.pyd" />
<ComponentRef Id="_overlapped.pyd" />
<ComponentRef Id="_queue.pyd" />
<ComponentRef Id="_socket.pyd" />
<ComponentRef Id="_sqlite3.pyd" />
<ComponentRef Id="_ssl.pyd" />
<ComponentRef Id="_testcapi.pyd" />
<ComponentRef Id="_tkinter.pyd" />
<ComponentRef Id="cacert.pem" />
<ComponentRef Id="ChangeLog.md" />
@@ -568,18 +592,19 @@
<ComponentRef Id="hu.strings" />
<ComponentRef Id="it.strings" />
<ComponentRef Id="ja.strings" />
<ComponentRef Id="ko.strings" />
<ComponentRef Id="libcrypto_1_1.dll" />
<ComponentRef Id="libffi_7.dll" />
<ComponentRef Id="library.zip" />
<ComponentRef Id="libssl_1_1.dll" />
<ComponentRef Id="ko.strings" />
<ComponentRef Id="lv.strings" />
<ComponentRef Id="modules.p" />
<ComponentRef Id="lv.strings" />
<ComponentRef Id="nl.strings" />
<ComponentRef Id="pl.strings" />
<ComponentRef Id="pt_BR.strings" />
<ComponentRef Id="pt_PT.strings" />
<ComponentRef Id="pyexpat.pyd" />
<ComponentRef Id="python37.dll" />
<ComponentRef Id="python39.dll" />
<ComponentRef Id="rare_commodity.csv" />
<ComponentRef Id="ru.strings" />
<ComponentRef Id="select.pyd" />
@@ -590,9 +615,7 @@
<ComponentRef Id="snd_good.wav" />
<ComponentRef Id="snd_bad.wav" />
<ComponentRef Id="sqlite3.dll" />
<ComponentRef Id="stations.p" />
<ComponentRef Id="sv_SE.strings" />
<ComponentRef Id="systems.p" />
<ComponentRef Id="tcl86t.dll" />
<ComponentRef Id="tk86t.dll" />
<ComponentRef Id="uk.strings" />
@@ -601,6 +624,7 @@
<ComponentRef Id="WinSparkle.dll" />
<ComponentRef Id="EDMarketConnector_TRACE.bat" />
<ComponentRef Id="EDMarketConnector_localserver_auth.bat" />
<ComponentRef Id="EDMarketConnector_localserver_resetui.bat" />
<ComponentRef Id="zh_CN.strings" />
<ComponentRef Id="auto.tcl" />
<ComponentRef Id="clock.tcl" />
+48 -21
View File
@@ -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í";
+48 -21
View File
@@ -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";
+48 -21
View File
@@ -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";
+64 -11
View File
@@ -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";
+60 -18
View File
@@ -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";
+9 -13
View File
@@ -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";
-1
View File
@@ -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";
+20 -23
View File
@@ -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";
+48 -21
View File
@@ -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" = "ログレベル";
+48 -21
View File
@@ -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" = "로깅 수준";
-1
View File
@@ -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";
+9 -13
View File
@@ -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";
+48 -21
View File
@@ -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";
+63 -18
View File
@@ -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";
+48 -21
View File
@@ -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";
+48 -21
View File
@@ -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" = "Уровень лога";
-1
View File
@@ -429,4 +429,3 @@
/* Shortcut settings prompt on OSX. [prefs.py] */
"{APP} needs permission to use shortcuts" = "{APP} potrebuje dovoljenja za uporabo bližnjic";
+48 -21
View File
@@ -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";
+48 -21
View File
@@ -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";
+9 -13
View File
@@ -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";
+64 -11
View File
@@ -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} необхідні дозволи для використання ярликів";
+42 -21
View File
@@ -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" = "诊断模式";
+353 -80
View File
@@ -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 `<<Quit>>` 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.
+4 -11
View File
@@ -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.
+32 -30
View File
@@ -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__":
+44 -39
View File
@@ -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)
+281 -110
View File
@@ -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),
'<unknown error>'
)
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<id>'
# 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),
'<unknown error>'
)
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 = '<unknown system>'
try:
if data['commander'].get('docked'):
station = f'.{data["lastStarport"]["name"]}'
else:
station = ''
except (KeyError, ValueError):
station = '<unknown 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
+1000 -382
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -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'
+30 -42
View File
@@ -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()
+110 -47
View File
@@ -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('<<DashboardEvent>>', when="tail")
except Exception:
logger.exception('Reading Status.json')
logger.exception('Processing Status.json')
# singleton
dashboard = Dashboard()
+62
View File
@@ -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.
+58 -12
View File
@@ -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_<version>.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 `<enclosure ...` that is like:
<enclosure
url="https://github.com/EDCD/EDMarketConnector/releases/download/Release/4.2.3/EDMarketConnector_win_4.2.3.msi"
sparkle:os="windows"
sparkle:installerArguments="/passive LAUNCH=yes"
sparkle:version="4.2.3"
length="11382784"
type="application/octet-stream"
/>
## 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.
+21
View File
@@ -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`.
+1 -1
View File
@@ -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:
+66 -8
View File
@@ -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'])
-127
View File
@@ -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))
+492
View File
@@ -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',
}
+76 -85
View File
@@ -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)
+582 -308
View File
File diff suppressed because it is too large. Load diff
+44 -22
View File
@@ -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:
+195
View File
@@ -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)
+270 -167
View File
@@ -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]?(['"])(((?<!\\)\\\1|.)+?)\1\)[^#]*(#.+)?''') # match a single line python literal
seen = {}
for f in (sorted([x for x in os.listdir('.') if x.endswith('.py')]) +
sorted([join('plugins', x) for x in isdir('plugins') and os.listdir('plugins') or [] if x.endswith('.py')])):
with codecs.open(f, 'r', 'utf-8') as h:
regexp = re.compile(r'''_\([ur]?(['"])(((?<!\\)\\\1|.)+?)\1\)[^#]*(#.+)?''') # match a single line python literal
seen: Dict[str, str] = {}
for f in (
sorted(x for x in os.listdir('.') if x.endswith('.py')) +
sorted(join('plugins', x) for x in (os.listdir('plugins') if isdir('plugins') else []) if x.endswith('.py'))
):
with open(f, 'r', encoding='utf-8') as h:
lineno = 0
for line in h:
lineno += 1
match = regexp.search(line)
if match and not seen.get(match.group(2)): # only record first commented instance of a string
seen[match.group(2)] = (match.group(4) and (match.group(4)[1:].strip()) + '. ' or '') + '[%s]' % basename(f)
if match and not seen.get(match.group(2)): # only record first commented instance of a string
seen[match.group(2)] = (
(match.group(4) and (match.group(4)[1:].strip()) + '. ' or '') + f'[{basename(f)}]'
)
if seen:
if not isdir(LOCALISATION_DIR):
os.mkdir(LOCALISATION_DIR)
template = codecs.open(join(LOCALISATION_DIR, 'en.template'), 'w', 'utf-8')
template.write('/* Language name */\n"%s" = "%s";\n\n' % (LANGUAGE_ID, 'English'))
for thing in sorted(seen, key=str.lower):
if seen[thing]:
template.write('/* %s */\n' % (seen[thing]))
template.write('"%s" = "%s";\n\n' % (thing, thing))
template.close()
target_path = pathlib.Path(LOCALISATION_DIR) / 'en.template.new'
target_path.parent.mkdir(exist_ok=True)
with target_path.open('w', encoding='utf-8') as target_file:
target_file.write(f'/* Language name */\n"{LANGUAGE_ID}" = "English";\n\n')
for thing in sorted(seen, key=str.lower):
if seen[thing]:
target_file.write(f'/* {seen[thing]} */\n')
target_file.write(f'"{thing}" = "{thing}";\n\n')
+6 -5
View File
@@ -8,6 +8,7 @@ import time
from config import config
import companion
import util_ships
def export(data, filename=None):
@@ -20,17 +21,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) + '\.\d\d\d\d\-\d\d\-\d\dT\d\d\.\d\d\.\d\d\.txt')
oldfiles = sorted([x for x in os.listdir(config.get('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 open(join(config.get_str('outdir'), oldfiles[-1]), 'rU') as h:
if h.read() == string:
return # same as last time - don't write
querytime = config.getint('querytime') or int(time.time())
querytime = config.get_int('querytime', default=int(time.time()))
# Write
filename = join(config.get('outdir'), '%s.%s.txt' % (ship, time.strftime('%Y-%m-%dT%H.%M.%S', time.localtime(querytime))))
filename = join(config.get_str('outdir'), '%s.%s.txt' % (ship, time.strftime('%Y-%m-%dT%H.%M.%S', time.localtime(querytime))))
with open(filename, 'wt') as h:
h.write(string)
BIN
View File
Binary file not shown.
+952 -166
View File
File diff suppressed because it is too large. Load diff
+172 -419
View File
@@ -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)
+9 -59
View File
@@ -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
+2 -2
View File
@@ -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(_):
+38 -7
View File
@@ -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'] != "":
+226 -75
View File
@@ -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
+111 -68
View File
@@ -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: <function Image.__del__ at ...>' 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'] = '<elided>'
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'] = '<elided>'
# 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('<<EDSMStatus>>', 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:
"""
+188 -146
View File
@@ -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('<<InaraLocation>>', when="tail")
elif data_event['eventName'] in ['addCommanderShip', 'setCommanderShip']:
this.lastship = reply_event.get('eventData', {})
# calls update_ship in main thread
if not config.shutting_down:
# calls update_ship in main thread
this.system_link.event_generate('<<InaraShip>>', 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.
+95 -39
View File
@@ -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':
+319 -165
View File
@@ -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('<<CompanionAuthEvent>>', 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: <https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-wndclassa>
<https://docs.microsoft.com/en-us/windows/win32/intl/registering-window-classes>
"""
_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('<html><head><title>{}</title></head>'.format('Authentication successful').encode('utf-8'))
self.wfile.write('<body><p>{}</p></body>'.format('Authentication successful').encode('utf-8'))
self.wfile.write('<html><head><title>Authentication successful</title></head>'.encode('utf-8'))
self.wfile.write('<body><p>Authentication successful</p></body>'.encode('utf-8'))
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()
+6
View File
@@ -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
+23 -9
View File
@@ -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
+4 -2
View File
@@ -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
+233 -139
View File
@@ -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')
BIN
View File
Binary file not shown.
+3 -3
View File
@@ -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()
+307 -167
View File
@@ -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
+4 -3
View File
@@ -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# <item name> <sellCR> <buyCR> <demand> <stock> <timestamp>\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(),
@@ -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
+500
View File
@@ -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()
+231
View File
@@ -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
+361
View File
@@ -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: <https://stackoverflow.com/a/12168268>
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
+17 -17
View File
@@ -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
+6 -7
View File
@@ -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
#
+5 -3
View File
@@ -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:
# <https://github.com/vslavik/winsparkle/issues/214>
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:
+15
View File
@@ -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', '<', '>', ':', '"', '/', '\\', '|', '?', '*')})