Merge branch 'stable' into releases

This commit is contained in:
Athanasius committed 2021-05-27 15:28:14 +01:00
commit 8a4c31f2dc
18 files changed
+395 -74

No files matched your search

+48
View File
@@ -17,6 +17,54 @@ This is the master changelog for Elite Dangerous Market Connector. Entries are
in the source (it's not distributed with the Windows installer) for the
currently used version in a given branch.
Release 5.0.3
===
* You can now click on a 'cell' in the "File" > "Status" popup to copy that
text to the clipboard. This was a relatively easy, and non-intrusive, code
change. We'll look at richer, fuller, copy functionality in the future.
* Suit names, for all grades, should now be displaying as just the relevant
word, never a symbol, and with the redundant 'suit' word(s) from all
languages removed. Note that Frontier have *not* translated the
following, so neither do we: "Artemis", "Dominator", "Maverick". The 'Flight
Suit' should, approximately, use the Frontier-supplied translation for
'Flight' in this context. In essence the displayed name is now as short
as possible whilst disambiguating the suit names from each other.
Bug Fixes
---
* The check for "source, but with extra changes?" in appversion will now
not cause an error if the "git" command isn't available. Also, the extra
text added to the build number is now ".DIRTY".
* Actually properly handle the "you just made progress" version of the
`EngineerProgress` Journal event, so that it doesn't throw errors.
Plugin Developers
---
* The backpack and ship locker tracking of micro-resources **might** now
actually be correct with respect to 'reality' in-game. This is in part
thanks to Frontier changes to some events in 4.0.0.200.
* Suit names will now only be sourced from Journal events if the
application didn't (yet) have the equivalent CAPI data.
* The displayed Suit name is stored in an extra "edmcName" key within
`state['Suits']` and `state['SuitCurrent']`. What was found in the
Journal or CAPI data is still present in the "name" and "locName" values.
* The "language", "gameversion" and "build" values from the "Fileheader" event
are all now stored in `state[]` fields. See [PLUGINS.md](./PLUGINS.md) for
updated documentation.
* We have a new [Contributing.md](./Contributing.md) policy of adding
comments in a defined format when we add or change code such that there's a
'hack', 'magic' or 'workaround' in play. You might find some of this
enlightening going forwards.
Release 5.0.2
===
+15
View File
@@ -325,6 +325,21 @@ literals.
Doc strings are preferred on all new modules, functions, classes, and methods, as they help others understand your code.
We use the `sphinx` formatting style, which for pycharm users is the default.
### Mark hacks and workarounds with a specific comment
We often write hacks or workarounds to make EDMC work on a given version or around a specific bug.
Please mark all hacks, workarounds, magic with one of the following comments, where applicable:
```
# HACK $elite-version-number | $date: $description
# MAGIC $elite-version-number | $date: $description
# WORKAROUND $elite-version-number | $date: $description
```
The description should cover exactly why the hack is needed, what it does, what is required / expected for it to be removed.
Please be verbose here, more info about weird choices is always prefered over magic that we struggle to understand in six months.
Additionally, if your hack is over around 5 lines, please include a `# HACK END` or similar comment to indicate the end of the hack.
---
## Git commit conventions
+2 -2
View File
@@ -629,7 +629,7 @@ class AppWindow(object):
self.suit['text'] = f'<{_("Unknown")}>'
return
suitname = suit['locName']
suitname = suit['edmcName']
if (suitloadout := monitor.state.get('SuitLoadoutCurrent')) is None:
self.suit['text'] = ''
@@ -927,7 +927,7 @@ class AppWindow(object):
if monitor.state.get('SuitCurrent') is not None:
if (loadout := data.get('loadout')) is not None:
if (suit := loadout.get('suit')) is not None:
if (suitname := suit.get('locName')) is not None:
if (suitname := suit.get('edmcName')) is not None:
# We've been paranoid about loadout->suit->suitname, now just assume loadouts is there
loadout_name = index_possibly_sparse_list(
data['loadouts'], loadout['loadoutSlotId']
+6
View File
@@ -230,6 +230,12 @@
/* Section heading in settings. [prefs.py] */
"File location" = "Cesta k souboru";
/* Failures to access Frontier CAPI endpoints [companion.py] */
"Frontier CAPI query failure" = "Dotaz na Frontier CAPI selhal";
/* Server errors from Frontier CAPI server [companion.py] */
"Frontier CAPI server error" = "Chyba Frontier CAPI serveru";
/* CQC rank. [stats.py] */
"Gladiator" = "Gladiator";
+6
View File
@@ -230,6 +230,12 @@
/* Section heading in settings. [prefs.py] */
"File location" = "Speicherort";
/* Failures to access Frontier CAPI endpoints [companion.py] */
"Frontier CAPI query failure" = "Frontier CAPI Anfrage gescheitert";
/* Server errors from Frontier CAPI server [companion.py] */
"Frontier CAPI server error" = "Frontier CAPI Server-Fehler";
/* CQC rank. [stats.py] */
"Gladiator" = "Gladiator";
+6
View File
@@ -230,6 +230,12 @@
/* Section heading in settings. [prefs.py] */
"File location" = "Localización de archivos";
/* Failures to access Frontier CAPI endpoints [companion.py] */
"Frontier CAPI query failure" = "Fallo de consulta del CAPI de Frontier";
/* Server errors from Frontier CAPI server [companion.py] */
"Frontier CAPI server error" = "Error de servidor CAPI de Frontier";
/* CQC rank. [stats.py] */
"Gladiator" = "Gladiador";
+21
View File
@@ -124,6 +124,15 @@
/* Location of the new Journal file in E:D 2.2. [EDMarketConnector.py] */
"E:D journal file location" = "E:D lokikirjan tiedostosijainti";
/* When EDDB functionality has been killswitched. [plugins/eddb.py] */
"EDDB Journal processing disabled. See Log." = "EDDB lokikirjan käsittely ei käytössä. Katso lokitiedot.";
/* When EDDN journal handling has been killswitched [plugins/eddn.py] */
"EDDN journal handler disabled. See Log." = "EDDB lokikirjan käsittelijä ei käytössä. Katso lokitiedot.";
/* When EDSM functionality has been killswitched [plugins/edsm.py] */
"EDSM Handler disabled. See Log." = "ESDM käsittelijä ei käytössä. Katso lokitiedot.";
/* Empire rank. [stats.py] */
"Earl" = "Earl";
@@ -173,6 +182,9 @@
"Error: EDSM {MSG}" = "Virhe: EDSM {MSG}";
/* Raised when cannot contact the Companion API server. [companion.py] */
"Error: Frontier CAPI didn't respond" = "Virhe: Frontier CAPI ei vastaa.";
/* OLD: Raised when cannot contact the Companion API server. [companion.py] */
"Error: Frontier server is down" = "Virhe: Frontierin palvelin ei vastaa";
@@ -218,6 +230,12 @@
/* Section heading in settings. [prefs.py] */
"File location" = "Tiedostosijainti";
/* Failures to access Frontier CAPI endpoints [companion.py] */
"Frontier CAPI query failure" = "Frontier CAPI kyselyvirhe.";
/* Server errors from Frontier CAPI server [companion.py] */
"Frontier CAPI server error" = "Frontier CAPI palvelinvirhe.";
/* CQC rank. [stats.py] */
"Gladiator" = "Gladiator";
@@ -251,6 +269,9 @@
/* Section heading in settings. [inara.py] */
"Inara credentials" = "Inaran kirjautuminen";
/* When Inara support has been killswitched [plugins/inara.py] */
"Inara disabled. See Log." = "Inara ei käytössä. Katso lokitiedot.";
/* Settings>Plugins>Information on migrating plugins [prefs.py] */
"Information on migrating plugins" = "Tietoja lisäosien siirrosta";
+3
View File
@@ -461,6 +461,9 @@
/* Menu item. [EDMarketConnector.py] */
"Status" = "État";
/* 'Suit' label in main UI' [EDMarketConnector.py] */
"Suit" = "Combinaison";
/* Explorer rank. [stats.py] */
"Surveyor" = "Éclaireur";
+6
View File
@@ -230,6 +230,12 @@
/* Section heading in settings. [prefs.py] */
"File location" = "파일 위치";
/* Failures to access Frontier CAPI endpoints [companion.py] */
"Frontier CAPI query failure" = "Frontier CAPI 쿼리 실패";
/* Server errors from Frontier CAPI server [companion.py] */
"Frontier CAPI server error" = "Frontier CAPI 서버 에러";
/* CQC rank. [stats.py] */
"Gladiator" = "Gladiator";
+6
View File
@@ -230,6 +230,12 @@
/* Section heading in settings. [prefs.py] */
"File location" = "Położenie pliku";
/* Failures to access Frontier CAPI endpoints [companion.py] */
"Frontier CAPI query failure" = "Błąd zapytania CAPI Frontier";
/* Server errors from Frontier CAPI server [companion.py] */
"Frontier CAPI server error" = "Błąd serwera CAPI Frontier";
/* CQC rank. [stats.py] */
"Gladiator" = "Gladiator";
+6
View File
@@ -230,6 +230,12 @@
/* Section heading in settings. [prefs.py] */
"File location" = "Путь хранения файлов";
/* Failures to access Frontier CAPI endpoints [companion.py] */
"Frontier CAPI query failure" = "Неудача при запросе к Frontier CAPI";
/* Server errors from Frontier CAPI server [companion.py] */
"Frontier CAPI server error" = "Серверная ошибка Frontier CAPI";
/* CQC rank. [stats.py] */
"Gladiator" = "Гладиатор";
+6
View File
@@ -230,6 +230,12 @@
/* Section heading in settings. [prefs.py] */
"File location" = "Lokacija fajlova";
/* Failures to access Frontier CAPI endpoints [companion.py] */
"Frontier CAPI query failure" = "Frontier CAPI neuspješan upit";
/* Server errors from Frontier CAPI server [companion.py] */
"Frontier CAPI server error" = "Frontier CAPI serverska greška";
/* CQC rank. [stats.py] */
"Gladiator" = "Gladiator";
+6
View File
@@ -230,6 +230,12 @@
/* Section heading in settings. [prefs.py] */
"File location" = "Lokacija fajlova";
/* Failures to access Frontier CAPI endpoints [companion.py] */
"Frontier CAPI query failure" = "Greška pri Frontier CAPI upitu";
/* Server errors from Frontier CAPI server [companion.py] */
"Frontier CAPI server error" = "Greška na Frontier CAPI serveru";
/* CQC rank. [stats.py] */
"Gladiator" = "Gladiator";
+13
View File
@@ -566,6 +566,9 @@ Content of `state` (updated to the current journal entry):
| Field | Type | Description |
| :------------- | :-------------------------: | :-------------------------------------------------------------------------------------------------------------- |
| `GameLanguage` | `Optional[str]` | `language` value from `Fileheader` event. |
| `GameVersion` | `Optional[str]` | `version` value from `Fileheader` event. |
| `GameBuild` | `Optional[str]` | `build` value from `Fileheader` event. |
| `Captain` | `Optional[str]` | Name of the commander who's crew you're on, if any |
| `Cargo` | `dict` | Current cargo. Note that this will be totals, and any mission specific duplicates will be counted together |
| `CargoJSON` | `dict` | content of cargo.json as of last read. |
@@ -652,6 +655,16 @@ this is **NOT** the same as the return from
because CAPI data doesn't (didn't always?) have an indication of Horizons or
not.
New in version 5.0.3:
The `Suits` members have an additional key:value pair `edmcName` which is our
preferred name for display on the UI, for the in-use game language.
The "language", "gameversion" and "build" values from the "Fileheader" event
are all now stored in `state[]` fields; "GameLanguage", "GameVersion" and
"GameBuild".
##### Synthetic Events
A special "StartUp" entry is sent if EDMC is started while the game is already
+12 -12
View File
@@ -33,7 +33,7 @@ appcmdname = 'EDMC'
# <https://semver.org/#semantic-versioning-specification-semver>
# Major.Minor.Patch(-prerelease)(+buildmetadata)
# NB: Do *not* import this, use the functions appversion() and appversion_nobuild()
_static_appversion = '5.0.2'
_static_appversion = '5.0.3'
copyright = '© 2015-2019 Jonathan Harris, 2020-2021 EDCD'
update_feed = 'https://raw.githubusercontent.com/EDCD/EDMarketConnector/releases/edmarketconnector.xml'
@@ -96,20 +96,11 @@ def git_shorthash_from_head() -> str:
"""
Determine short hash for current git HEAD.
Includes -DIRTY if any changes have been made from HEAD
Includes `.DIRTY` if any changes have been made from HEAD
:return: str - None if we couldn't determine the short hash.
"""
shorthash: str = None # type: ignore
dirty = False
with contextlib.suppress(Exception):
result = subprocess.run('git diff --stat HEAD'.split(), capture_output=True)
if len(result.stdout) > 0:
dirty = True
if len(result.stderr) > 0:
logger.warning(f'Data from git on stderr:\n{str(result.stderr)}')
try:
git_cmd = subprocess.Popen('git rev-parse --short HEAD'.split(),
@@ -127,7 +118,16 @@ def git_shorthash_from_head() -> str:
logger.error(f"'{shorthash}' doesn't look like a valid git short hash, forcing to None")
shorthash = None # type: ignore
return shorthash + ('-WORKING-DIR-IS-DIRTY' if dirty else '')
if shorthash is not None:
with contextlib.suppress(Exception):
result = subprocess.run('git diff --stat HEAD'.split(), capture_output=True)
if len(result.stdout) > 0:
shorthash += '.DIRTY'
if len(result.stderr) > 0:
logger.warning(f'Data from git on stderr:\n{str(result.stderr)}')
return shorthash
def appversion() -> semantic_version.Version:
+75
View File
@@ -495,3 +495,78 @@ ship_name_map = {
'viper_mkiv': 'Viper MkIV',
'vulture': 'Vulture',
}
# Odyssey Suit Names
edmc_suit_shortnames = {
'Flight Suit': 'Flight', # EN
'Artemis Suit': 'Artemis', # EN
'Dominator Suit': 'Dominator', # EN
'Maverick Suit': 'Maverick', # EN
'Flug-Anzug': 'Flug', # DE
'Artemis-Anzug': 'Artemis', # DE
'Dominator-Anzug': 'Dominator', # DE
'Maverick-Anzug': 'Maverick', # DE
'Traje de vuelo': 'de vuelo', # ES
'Traje Artemis': 'Artemis', # ES
'Traje Dominator': 'Dominator', # ES
'Traje Maverick': 'Maverick', # ES
'Combinaison de vol': 'de vol', # FR
'Combinaison Artemis': 'Artemis', # FR
'Combinaison Dominator': 'Dominator', # FR
'Combinaison Maverick': 'Maverick', # FR
'Traje voador': 'voador', # PT-BR
# These are duplicates of the ES ones, but kept here for clarity
# 'Traje Artemis': 'Artemis', # PT-BR
# 'Traje Dominator': 'Dominator', # PT-BR
# 'Traje Maverick': 'Maverick', # PT-BR
'Летный комбинезон': 'Летный', # RU
'Комбинезон Artemis': 'Artemis', # RU
'Комбинезон Dominator': 'Dominator', # RU
'Комбинезон Maverick': 'Maverick', # RU
}
edmc_suit_symbol_localised = {
# The key here should match what's seen in Fileheader 'language', but with
# any in-file `\\` already unescaped to a single `\`.
r'English\UK': {
'flightsuit': 'Flight Suit',
'explorationsuit': 'Artemis Suit',
'tacticalsuit': 'Dominator Suit',
'utilitysuit': 'Maverick Suit',
},
r'German\DE': {
'flightsuit': 'Flug-Anzug',
'explorationsuit': 'Artemis-Anzug',
'tacticalsuit': 'Dominator-Anzug',
'utilitysuit': 'Maverick-Anzug',
},
r'French\FR': {
'flightsuit': 'Combinaison de vol',
'explorationsuit': 'Combinaison Artemis',
'tacticalsuit': 'Combinaison Dominator',
'utilitysuit': 'Combinaison Maverick',
},
r'Portuguese\BR': {
'flightsuit': 'Traje voador',
'explorationsuit': 'Traje Artemis',
'tacticalsuit': 'Traje Dominator',
'utilitysuit': 'Traje Maverick',
},
r'Russian\RU': {
'flightsuit': 'Летный комбинезон',
'explorationsuit': 'Комбинезон Artemis',
'tacticalsuit': 'Комбинезон Dominator',
'utilitysuit': 'Комбинезон Maverick',
},
r'Spanish\ES': {
'flightsuit': 'Traje de vuelo',
'explorationsuit': 'Traje Artemis',
'tacticalsuit': 'Traje Dominator',
'utilitysuit': 'Traje Maverick',
},
}
+131 -54
View File
@@ -19,6 +19,7 @@ if TYPE_CHECKING:
import util_ships
from config import config
from edmc_data import edmc_suit_shortnames, edmc_suit_symbol_localised
from EDMCLogging import get_main_logger
logger = get_main_logger()
@@ -114,6 +115,9 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
# Cmdr state shared with EDSM and plugins
# If you change anything here update PLUGINS.md documentation!
self.state: Dict = {
'GameLanguage': None, # From `Fileheader
'GameVersion': None, # From `Fileheader
'GameBuild': None, # From `Fileheader
'Captain': None, # On a crew
'Cargo': defaultdict(int),
'Credits': None,
@@ -496,13 +500,15 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
self.systemaddress = None
self.started = None
self.__init_state()
# In self.state as well, as that's what plugins get
self.state['GameLanguage'] = entry['language']
self.state['GameVersion'] = entry['gameversion']
self.state['GameBuild'] = entry['build']
elif event_type == 'Commander':
self.live = True # First event in 3.0
elif event_type == 'LoadGame':
# alpha4
# Odyssey: bool
self.cmdr = entry['Commander']
# 'Open', 'Solo', 'Group', or None for CQC (and Training - but no LoadGame event)
self.mode = entry.get('GameMode')
@@ -871,7 +877,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
{self.canonicalise(x['Name']): x['Count'] for x in clean_data}
)
elif event_type == 'BackPack':
elif event_type in ('BackPack', 'Backpack'): # WORKAROUND 4.0.0.200: BackPack becomes Backpack
# TODO: v31 doc says this is`backpack.json` ... but Howard Chalkley
# said it's `Backpack.json`
with open(join(self.currentdir, 'Backpack.json'), 'rb') as backpack: # type: ignore
@@ -978,19 +984,15 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
elif event_type == 'TransferMicroResources':
# Moving Odyssey MicroResources between ShipLocker and BackPack
# Backpack dropped as its done in BackpackChange
#
# from: 4.0.0.200 -- Locker(Old|New)Count is now a thing.
for mr in entry['Transfers']:
category = self.category(mr['Category'])
name = self.canonicalise(mr['Name'])
if mr['Direction'] == 'ToShipLocker':
self.state[category][name] += mr['Count']
self.state['BackPack'][category][name] -= mr['Count']
elif mr['Direction'] == 'ToBackpack':
self.state[category][name] -= mr['Count']
self.state['BackPack'][category][name] += mr['Count']
else:
self.state[category][name] = mr['LockerNewCount']
if mr['Direction'] not in ('ToShipLocker', 'ToBackpack'):
logger.warning(f'TransferMicroResources with unexpected Direction {mr["Direction"]=}: {mr=}')
# Paranoia check to see if anything has gone negative.
@@ -1008,9 +1010,12 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
# • Name
# • Type
# • OwnerID
for i in self.state['BackPack'][entry['Type']]:
if i == entry['Name']:
self.state['BackPack'][entry['Type']][i] += entry['Count']
# Handled by BackpackChange
# for i in self.state['BackPack'][entry['Type']]:
# if i == entry['Name']:
# self.state['BackPack'][entry['Type']][i] += entry['Count']
pass
elif event_type == 'DropItems':
# alpha4
@@ -1020,12 +1025,15 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
# • OwnerID
# • MissionID
# • Count
for i in self.state['BackPack'][entry['Type']]:
if i == entry['Name']:
self.state['BackPack'][entry['Type']][i] -= entry['Count']
# Paranoia in case we lost track
if self.state['BackPack'][entry['Type']][i] < 0:
self.state['BackPack'][entry['Type']][i] = 0
# This is handled by BackpackChange.
# for i in self.state['BackPack'][entry['Type']]:
# if i == entry['Name']:
# self.state['BackPack'][entry['Type']][i] -= entry['Count']
# # Paranoia in case we lost track
# if self.state['BackPack'][entry['Type']][i] < 0:
# self.state['BackPack'][entry['Type']][i] = 0
pass
elif event_type == 'UseConsumable':
# TODO: XXX: From v31 doc
@@ -1075,8 +1083,8 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
# "ModuleName":"wpn_s_pistol_plasma_charged",
# "ModuleName_Localised":"Manticore Tormentor" } ] }
#
suit_slotid, suitloadout_slotid = self.suitloadout_store_from_event(entry)
if not self.suit_and_loadout_setcurrent(suit_slotid, suitloadout_slotid):
suitid, suitloadout_slotid = self.suitloadout_store_from_event(entry)
if not self.suit_and_loadout_setcurrent(suitid, suitloadout_slotid):
logger.error(f"Event was: {entry}")
elif event_type == 'CreateSuitLoadout':
@@ -1091,7 +1099,10 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
# { "SlotName":"SecondaryWeapon", "SuitModuleID":1700217869872834,
# "ModuleName":"wpn_s_pistol_kinetic_sauto", "ModuleName_Localised":"Karma P-15" } ] }
#
_, _ = self.suitloadout_store_from_event(entry)
suitid, suitloadout_slotid = self.suitloadout_store_from_event(entry)
# Creation doesn't mean equipping it
# if not self.suit_and_loadout_setcurrent(suitid, suitloadout_slotid):
# logger.error(f"Event was: {entry}")
elif event_type == 'DeleteSuitLoadout':
# alpha4:
@@ -1131,10 +1142,12 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
# alpha4 :
# { "timestamp":"2021-04-29T09:03:37Z", "event":"BuySuit", "Name":"UtilitySuit_Class1",
# "Name_Localised":"Maverick Suit", "Price":150000, "SuitID":1698364934364699 }
loc_name = entry.get('Name_Localised', entry['Name'])
self.state['Suits'][entry['SuitID']] = {
'name': entry['Name'],
'locName': entry.get('Name_Localised', entry['Name']),
'id': None, # Is this an FDev ID for suit type ?
'locName': loc_name,
'edmcName': self.suit_sane_name(loc_name),
'id': None, # Is this an FDev ID for suit type ?
'suitId': entry['SuitID'],
'slots': [],
}
@@ -1581,6 +1594,46 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
logger.debug(f'Invalid journal entry:\n{line!r}\n', exc_info=ex)
return {'event': None}
def suit_sane_name(self, name: str) -> str:
"""
Given an input suit name return the best 'sane' name we can.
AS of 4.0.0.102 the Journal events are fine for a Grade 1 suit, but
anything above that has broken SuitName_Localised strings, e.g.
$TacticalSuit_Class1_Name;
Also, if there isn't a SuitName_Localised value at all we'll use the
plain SuitName which can be, e.g. tacticalsuit_class3
If the names were correct we would get 'Dominator Suit' in this instance,
however what we want to return is, e.g. 'Dominator'. As that's both
sufficient for disambiguation and more succinct.
:param name: Name that could be in any of the forms.
:return: Our sane version of this suit's name.
"""
# WORKAROUND 4.0.0.200 | 2021-05-27: Suit names above Grade 1 aren't localised
# properly by Frontier, so we do it ourselves.
# Stage 1: Is it in `$<type>_Class<X>_Name;` form ?
if m := re.fullmatch(r'(?i)^\$([^_]+)_Class([0-9]+)_Name;$', name):
n, c = m.group(1, 2)
name = n
# Stage 2: Is it in `<type>_class<x>` form ?
elif m := re.fullmatch(r'(?i)^([^_]+)_class([0-9]+)$', name):
n, c = m.group(1, 2)
name = n
# Now turn either of those into a '<type> Suit' (modulo language) form
if loc_lookup := edmc_suit_symbol_localised.get(self.state['GameLanguage']):
name = loc_lookup.get(name.lower(), name)
# WORKAROUND END
# Finally, map that to a form without the verbose ' Suit' on the end
name = edmc_suit_shortnames.get(name, name)
return name
def suitloadout_store_from_event(self, entry) -> Tuple[int, int]:
"""
Store Suit and SuitLoadout data from a journal event.
@@ -1591,45 +1644,58 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
:param entry: Journal entry - 'SwitchSuitLoadout' or 'SuitLoadout'
:return Tuple[suit_slotid, suitloadout_slotid]: The IDs we set data for.
"""
suit_slotid = self.suit_loadout_id_from_loadoutid(entry['LoadoutID'])
# Initial suit containing just the data that is then embedded in
# the loadout
new_suit = {
'name': entry['SuitName'],
'locName': entry.get('SuitName_Localised', entry['SuitName']),
'suitId': entry['SuitID'],
}
# This is the full ID from Frontier, it's not a sparse array slot id
suitid = entry['SuitID']
# Check if this looks like a suit we already have stored, so as
# to avoid 'bad' Journal localised names.
suit = self.state['Suits'].get(f"{suitid}", None)
if suit is None:
# Initial suit containing just the data that is then embedded in
# the loadout
# TODO: Attempt to map SuitName_Localised to something sane, if it
# isn't already.
suitname = entry.get('SuitName_Localised', entry['SuitName'])
edmc_suitname = self.suit_sane_name(suitname)
suit = {
'edmcName': edmc_suitname,
'locName': suitname,
'suitId': entry['SuitID'],
'name': entry['SuitName'],
}
suitloadout_slotid = self.suit_loadout_id_from_loadoutid(entry['LoadoutID'])
# Make the new loadout, in the CAPI format
new_loadout = {
'loadoutSlotId': suit_slotid,
'suit': new_suit,
'loadoutSlotId': suitloadout_slotid,
'suit': suit,
'name': entry['LoadoutName'],
'slots': self.suit_loadout_slots_array_to_dict(
entry['Modules']),
'slots': self.suit_loadout_slots_array_to_dict(entry['Modules']),
}
# Assign this loadout into our state
self.state['SuitLoadouts'][f"{new_loadout['loadoutSlotId']}"] = new_loadout
self.state['SuitLoadouts'][f"{suitloadout_slotid}"] = new_loadout
# Now add in the extra fields for new_suit to be a 'full' Suit structure
new_suit['id'] = None # Not available in 4.0.0.100 journal event
new_suit['slots'] = new_loadout['slots'] # 'slots', not 'Modules', to match CAPI
# Ensure new_suit is in self.state['Suits']
self.state['Suits'][f"{suit_slotid}"] = new_suit
suit['id'] = suit.get('id') # Not available in 4.0.0.100 journal event
suit['slots'] = new_loadout['slots'] # 'slots', not 'Modules', to match CAPI
# Ensure the suit is in self.state['Suits']
self.state['Suits'][f"{suitid}"] = suit
return suit_slotid, new_loadout['loadoutSlotId']
return suitid, suitloadout_slotid
def suit_and_loadout_setcurrent(self, suit_slotid: int, suitloadout_slotid: int) -> bool:
def suit_and_loadout_setcurrent(self, suitid: int, suitloadout_slotid: int) -> bool:
"""
Set self.state for SuitCurrent and SuitLoadoutCurrent as requested.
If the specified slots are unknown we abort and return False, else
return True.
:param suit_slotid: Numeric ID of the slot for the suit.
:param suitid: Numeric ID of the suit.
:param suitloadout_slotid: Numeric ID of the slot for the suit loadout.
:return: True if we could do this, False if not.
"""
str_suitid = f"{suit_slotid}"
str_suitid = f"{suitid}"
str_suitloadoutid = f"{suitloadout_slotid}"
if (self.state['Suits'].get(str_suitid, False)
@@ -1638,7 +1704,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
self.state['SuitLoadoutCurrent'] = self.state['SuitLoadouts'][str_suitloadoutid]
return True
logger.error(f"Tried to set a suit and suitloadout where we didn't know about both: {suit_slotid=}, "
logger.error(f"Tried to set a suit and suitloadout where we didn't know about both: {suitid=}, "
f"{str_suitloadoutid=}")
return False
@@ -1651,7 +1717,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
:param entry: Journal event dict
:return: True if passes validation, else False.
"""
# The event should have at least one of thes
# The event should have at least one of these
if 'Engineers' not in entry and 'Progress' not in entry:
logger.warning(f"EngineerProgress has neither 'Engineers' nor 'Progress': {entry=}")
return False
@@ -1687,11 +1753,22 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
return False
if 'Progress' in entry:
for e in entry['Engineers']:
for f in ('Engineer', 'EngineerID', 'Rank', 'Progress', 'RankProgress'):
if f not in e:
logger.warning(f"Engineer entry without '{f}' key: {e=} in {entry=}")
return False
# Progress is only a single Engineer, so it's not an array
# { "timestamp":"2021-05-24T17:57:52Z",
# "event":"EngineerProgress",
# "Engineer":"Felicity Farseer",
# "EngineerID":300100,
# "Progress":"Invited" }
for f in ('Engineer', 'EngineerID', 'Rank', 'Progress', 'RankProgress'):
if f not in entry:
# For some Progress there's no Rank/RankProgress yet
if f in ('Rank', 'RankProgress'):
if (progress := entry.get('Progress', None)) is not None:
if progress in ('Invited', 'Known'):
continue
logger.warning(f"Progress event without '{f}' key: {entry=}")
return False
return True
+27 -6
View File
@@ -1,9 +1,10 @@
"""CMDR Status information."""
import csv
import tkinter
import tkinter as tk
from sys import platform
from tkinter import ttk
from typing import TYPE_CHECKING, Any, AnyStr, Dict, List, NamedTuple, Optional, Sequence, cast
from typing import TYPE_CHECKING, Any, AnyStr, Callable, Dict, List, NamedTuple, Optional, Sequence, cast
import companion
import EDMCLogging
@@ -342,10 +343,11 @@ 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
# assumes things two and three are money
self.addpagerow(page, [thing[0], self.credits(int(thing[1]))], with_copy=True)
for thing in stats[3:]:
self.addpagerow(page, thing)
self.addpagerow(page, thing, with_copy=True)
ttk.Frame(page).grid(pady=5) # bottom spacer
notebook.add(page, text=_('Status')) # Status dialog title
@@ -361,7 +363,7 @@ class StatsResults(tk.Toplevel):
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]))])
self.addpagerow(page, list(ship_data[1:-1]) + [self.credits(int(ship_data[-1]))], with_copy=True)
ttk.Frame(page).grid(pady=5) # bottom spacer
notebook.add(page, text=_('Ships')) # Status dialog title
@@ -417,14 +419,16 @@ class StatsResults(tk.Toplevel):
: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)
self.addpagerow(parent, header, align=align, with_copy=False)
ttk.Separator(parent, orient=tk.HORIZONTAL).grid(columnspan=len(header), padx=10, pady=2, sticky=tk.EW)
def addpagespacer(self, parent) -> None:
"""Add a spacer to the page."""
self.addpagerow(parent, [''])
def addpagerow(self, parent: tk.Frame, content: Sequence[str], align: Optional[str] = None):
def addpagerow(
self, parent: tk.Frame, content: Sequence[str], align: Optional[str] = None, with_copy: bool = False
):
"""
Add a single row to parent.
@@ -434,7 +438,11 @@ class StatsResults(tk.Toplevel):
"""
row = -1 # To silence unbound warnings
for i in range(len(content)):
# label = HyperlinkLabel(parent, text=content[i], popup_copy=True)
label = nb.Label(parent, text=content[i])
if with_copy:
label.bind('<Button-1>', self.copy_callback(label, content[i]))
if i == 0:
label.grid(padx=10, sticky=tk.W)
row = parent.grid_size()[1]-1
@@ -449,3 +457,16 @@ class StatsResults(tk.Toplevel):
"""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
@staticmethod
def copy_callback(label: tk.Label, text_to_copy: str) -> Callable[..., None]:
"""Copy data in Label to clipboard."""
def do_copy(event: tkinter.Event) -> None:
label.clipboard_clear()
label.clipboard_append(text_to_copy)
old_bg = label['bg']
label['bg'] = 'gray49'
label.after(100, (lambda: label.configure(bg=old_bg)))
return do_copy