mirror of
https://github.com/EDCD/EDMarketConnector.git
synced 2026-12-02 03:45:25 +03:00
Merge branch 'release-4.1.6' into releases
This commit is contained in:
commit
97192633b0
17 files changed
+278
-68
No files matched your search
@@ -9,7 +9,7 @@ name: Push-Checks
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ develop ]
|
||||
branches: [ main ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -27,27 +27,15 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install flake8 pytest
|
||||
pip install flake8 pytest wheel
|
||||
if [ -f requirements-dev.txt ]; then pip install -r requirements-dev.txt; fi
|
||||
- name: Lint with flake8
|
||||
env:
|
||||
ROOT_SHA: ${{github.base_ref}}
|
||||
|
||||
run: |
|
||||
DATA=$(python3 <<EOF
|
||||
import json
|
||||
import os
|
||||
with open(os.getenv('GITHUB_EVENT_PATH')) as f:
|
||||
data = json.load(f)
|
||||
|
||||
typ = os.getenv('GITHUB_EVENT_NAME')
|
||||
|
||||
if 'pull_request' in typ:
|
||||
print(data['base']['ref'])
|
||||
elif 'push' in typ:
|
||||
print(data['before'])
|
||||
EOF
|
||||
)
|
||||
DATA=$(jq --raw-output .before $GITHUB_EVENT_PATH)
|
||||
|
||||
# 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
|
||||
|
||||
@@ -1,6 +1,54 @@
|
||||
This is the master changelog for Elite Dangerous Market Connector. Entries are in reverse chronological order (latest first).
|
||||
---
|
||||
|
||||
Release 4.1.6
|
||||
===
|
||||
|
||||
We might have finally found the cause of the application hangs during shutdown.
|
||||
Note that this became easier to track down due to the downtime
|
||||
for migration of www.edsm.net around 2021-01-11. Before these fixes EDSM's
|
||||
API not being available would cause an EDMC hang on shutdown.
|
||||
|
||||
* We've applied extra paranoia to some of the application shutdown code to
|
||||
ensure we're not still trying to handle journal events during this sequence.
|
||||
|
||||
We also re-ordered the shutdown sequence, which might help avoid the shutdown
|
||||
hang.
|
||||
|
||||
If you encounter a shutdown hang then please add a comment and log files to
|
||||
[Application can leave a zombie process on shutdown #678](https://github.com/EDCD/EDMarketConnector/issues/678)
|
||||
to help us track down the cause and fix it.
|
||||
|
||||
* We now avoid making Tk event_generate() calls whilst the appliction is
|
||||
shutting down.
|
||||
|
||||
* Plugins should actively avoid making any sort of Tk event_generate() call
|
||||
during application shutdown.
|
||||
|
||||
This means using `if not config.shutting_down:` to gate any code in worker
|
||||
threads that might attempt this. Also, be sure you're not attempting such
|
||||
in your `plugin_stop()` function.
|
||||
|
||||
See plugins/edsm.py and plugins/inara.py for example of the usage.
|
||||
|
||||
* Any use of `plug.show_error()` won't actually change the UI status line
|
||||
during shutdown, but the text you tried to show will be logged instead.
|
||||
|
||||
* Cargo tracking will now correctly count all instances of the same type of
|
||||
cargo for different missions. Previously it only counted the cargo for
|
||||
the last mission requiring that cargo type, as found in Cargo.json.
|
||||
|
||||
* The loaded contents of Cargo.json can now be found in `monitor.state['CargoJSON']`.
|
||||
`monitor.state` is what is passed to plugins as `state` in the
|
||||
`journal_entry()` call.
|
||||
|
||||
* Our logging code should now cope with logging from a property.
|
||||
|
||||
* Logging from any name-mangled method should now work properly.
|
||||
|
||||
* Miscellaneous updates to PLUGINS.md - mostly to clarify some things.
|
||||
|
||||
|
||||
Release 4.1.5
|
||||
===
|
||||
|
||||
|
||||
+30
-5
@@ -309,14 +309,39 @@ class EDMCContextFilter(logging.Filter):
|
||||
|
||||
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
|
||||
if name.startswith("__") and not name.endswith("__"):
|
||||
name = f'_{frame_class.__class__.__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 = getattr(frame_class, name, None)
|
||||
if fn and fn.__qualname__:
|
||||
caller_qualname = fn.__qualname__
|
||||
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)"
|
||||
|
||||
else:
|
||||
caller_qualname = f"<property {name} on {class_name}>"
|
||||
|
||||
elif fn.__qualname__:
|
||||
caller_qualname = fn.__qualname__
|
||||
|
||||
# Find containing class name(s) of caller, if any
|
||||
if frame_class.__class__ and frame_class.__class__.__qualname__:
|
||||
|
||||
+30
-9
@@ -743,6 +743,10 @@ class AppWindow(object):
|
||||
'FlightCon': _('Helm'), # Multicrew role
|
||||
}.get(role, role)
|
||||
|
||||
if monitor.thread is None:
|
||||
logger.debug('monitor.thread is None, assuming shutdown and returning')
|
||||
return
|
||||
|
||||
while True:
|
||||
entry = monitor.get_entry()
|
||||
if not entry:
|
||||
@@ -1055,6 +1059,8 @@ class AppWindow(object):
|
||||
self.status['text'] = str(e)
|
||||
|
||||
def onexit(self, event=None):
|
||||
config.set_shutdown() # Signal we're in shutdown now.
|
||||
|
||||
# http://core.tcl.tk/tk/tktview/c84f660833546b1b84e7
|
||||
if platform != 'darwin' or self.w.winfo_rooty() > 0:
|
||||
x, y = self.w.geometry().split('+')[1:3] # e.g. '212x170+2881+1267'
|
||||
@@ -1065,27 +1071,36 @@ class AppWindow(object):
|
||||
self.w.update_idletasks()
|
||||
logger.info('Starting shutdown procedures...')
|
||||
|
||||
logger.info('Closing protocol handler...')
|
||||
protocolhandler.close()
|
||||
# First so it doesn't interrupt us
|
||||
logger.info('Closing update checker...')
|
||||
self.updater.close()
|
||||
|
||||
# Earlier than anything else so plugin code can't interfere *and* it
|
||||
# won't still be running in a manner that might rely on something
|
||||
# we'd otherwise have already stopped.
|
||||
logger.info('Notifying plugins to stop...')
|
||||
plug.notify_stop()
|
||||
|
||||
# Handling of application hotkeys now so the user can't possible cause
|
||||
# an issue via triggering one.
|
||||
logger.info('Unregistering hotkey manager...')
|
||||
hotkeymgr.unregister()
|
||||
|
||||
# Now the main programmatic input methods
|
||||
logger.info('Closing dashboard...')
|
||||
dashboard.close()
|
||||
|
||||
logger.info('Closing journal monitor...')
|
||||
monitor.close()
|
||||
|
||||
logger.info('Notifying plugins to stop...')
|
||||
plug.notify_stop()
|
||||
|
||||
logger.info('Closing update checker...')
|
||||
self.updater.close()
|
||||
# Frontier auth/CAPI handling
|
||||
logger.info('Closing protocol handler...')
|
||||
protocolhandler.close()
|
||||
|
||||
logger.info('Closing Frontier CAPI sessions...')
|
||||
companion.session.close()
|
||||
|
||||
# Now anything else.
|
||||
logger.info('Closing config...')
|
||||
config.close()
|
||||
|
||||
@@ -1238,7 +1253,6 @@ executable: {sys.executable}
|
||||
sys.path: {sys.path}'''
|
||||
)
|
||||
|
||||
|
||||
# We prefer a UTF-8 encoding gets set, but older Windows versions have
|
||||
# issues with this. From Windows 10 1903 onwards we can rely on the
|
||||
# manifest ActiveCodePage to set this, but that is silently ignored on
|
||||
@@ -1287,7 +1301,8 @@ sys.path: {sys.path}'''
|
||||
logger.exception(f"Could not set LC_ALL to ('{locale_startup[0]}', 'UTF_8')")
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Exception other than locale.Error on setting LC_ALL=('{locale_startup[0]}', 'UTF_8')")
|
||||
logger.exception(
|
||||
f"Exception other than locale.Error on setting LC_ALL=('{locale_startup[0]}', 'UTF_8')")
|
||||
|
||||
else:
|
||||
log_locale('After switching to UTF-8 encoding (same language)')
|
||||
@@ -1303,10 +1318,16 @@ sys.path: {sys.path}'''
|
||||
def __init__(self):
|
||||
logger.debug('A call from A.B.__init__')
|
||||
self.__test()
|
||||
_ = self.test_prop
|
||||
|
||||
def __test(self):
|
||||
logger.debug("A call from A.B.__test")
|
||||
|
||||
@property
|
||||
def test_prop(self):
|
||||
logger.debug("test log from property")
|
||||
return "Test property is testy"
|
||||
|
||||
# abinit = A.B()
|
||||
|
||||
# Plain, not via `logger`
|
||||
|
||||
+22
-3
@@ -225,6 +225,11 @@ with core EDMC or other plugins.**
|
||||
Use `numberFromString()` from EDMC's `l10n.Locale` object to parse input
|
||||
numbers in a locale-independent way.
|
||||
|
||||
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
|
||||
@@ -392,7 +397,8 @@ Content of `state` (updated to the current journal entry):
|
||||
| Field | Type | Description |
|
||||
| :------------- | :-------------------------: | :-------------------------------------------------------------------------------------------------------------- |
|
||||
| `Captian` | `Optional[str]` | Name of the commander who's crew you're on, if any |
|
||||
| `Cargo` | `dict` | Current cargo |
|
||||
| `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. |
|
||||
| `Credits` | `int` | Current credits balance |
|
||||
| `FID` | `str` | Frontier commander ID |
|
||||
| `Loan` | `Optional[int]` | Current loan amount, if any |
|
||||
@@ -418,8 +424,16 @@ 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.
|
||||
|
||||
Similarly, a special "ShutDown" entry is sent when the game is quitted while
|
||||
EDMC is running. This event is not sent when EDMC is running on a different
|
||||
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.
|
||||
Note that this is distinct in (letter) case from the "Shutdown" event that
|
||||
the game itself writes to the Journal when you exit normally. If you want to
|
||||
react to either in your plugin code then either compare in a case insensitive
|
||||
manner or check for both. The difference in case allows you to differentiate
|
||||
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
|
||||
@@ -443,6 +457,11 @@ typically about once a second when in orbital flight.
|
||||
|
||||
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.
|
||||
|
||||
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
|
||||
|
||||
#### Getting Commander Data
|
||||
|
||||
```python
|
||||
|
||||
@@ -13,7 +13,7 @@ appcmdname = 'EDMC'
|
||||
# appversion **MUST** follow Semantic Versioning rules:
|
||||
# <https://semver.org/#semantic-versioning-specification-semver>
|
||||
# Major.Minor.Patch(-prerelease)(+buildmetadata)
|
||||
appversion = '4.1.5' #-rc1+a872b5f'
|
||||
appversion = '4.1.6' #-rc1+a872b5f'
|
||||
# For some things we want appversion without (possible) +build metadata
|
||||
appversion_nobuild = str(semantic_version.Version(appversion).truncate('prerelease'))
|
||||
copyright = u'© 2015-2019 Jonathan Harris, 2020 EDCD'
|
||||
@@ -117,6 +117,8 @@ class Config(object):
|
||||
if platform=='darwin':
|
||||
|
||||
def __init__(self):
|
||||
self.__in_shutdown = False # Is the application currently shutting down ?
|
||||
|
||||
self.app_dir = join(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], appname)
|
||||
if not isdir(self.app_dir):
|
||||
mkdir(self.app_dir)
|
||||
@@ -177,9 +179,17 @@ class Config(object):
|
||||
self.save()
|
||||
self.defaults = None
|
||||
|
||||
def set_shutdown(self):
|
||||
self.__in_shutdown = True
|
||||
|
||||
@property
|
||||
def shutting_down(self) -> bool:
|
||||
return self.__in_shutdown
|
||||
|
||||
elif platform=='win32':
|
||||
|
||||
def __init__(self):
|
||||
self.__in_shutdown = False # Is the application currently shutting down ?
|
||||
|
||||
self.app_dir = join(KnownFolderPath(FOLDERID_LocalAppData), appname)
|
||||
if not isdir(self.app_dir):
|
||||
@@ -268,11 +278,19 @@ class Config(object):
|
||||
RegCloseKey(self.hkey)
|
||||
self.hkey = None
|
||||
|
||||
def set_shutdown(self):
|
||||
self.__in_shutdown = True
|
||||
|
||||
@property
|
||||
def shutting_down(self) -> bool:
|
||||
return self.__in_shutdown
|
||||
|
||||
elif platform=='linux':
|
||||
|
||||
SECTION = 'config'
|
||||
|
||||
def __init__(self):
|
||||
self.__in_shutdown = False # Is the application currently shutting down ?
|
||||
|
||||
# http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
|
||||
self.app_dir = join(getenv('XDG_DATA_HOME', expanduser('~/.local/share')), appname)
|
||||
@@ -346,6 +364,13 @@ class Config(object):
|
||||
self.save()
|
||||
self.config = None
|
||||
|
||||
def set_shutdown(self):
|
||||
self.__in_shutdown = True
|
||||
|
||||
@property
|
||||
def shutting_down(self) -> bool:
|
||||
return self.__in_shutdown
|
||||
|
||||
def _escape(self, val):
|
||||
return str(val).replace(u'\\', u'\\\\').replace(u'\n', u'\\n').replace(u';', u'\\;')
|
||||
|
||||
|
||||
+14
-11
@@ -1,16 +1,13 @@
|
||||
import json
|
||||
from calendar import timegm
|
||||
from operator import itemgetter
|
||||
from os import listdir
|
||||
from os.path import isdir, isfile, join, getsize
|
||||
from sys import platform
|
||||
import time
|
||||
|
||||
if __debug__:
|
||||
from traceback import print_exc
|
||||
|
||||
from config import config
|
||||
from EDMCLogging import get_main_logger
|
||||
|
||||
logger = get_main_logger()
|
||||
|
||||
if platform=='darwin':
|
||||
from watchdog.observers import Observer
|
||||
@@ -67,8 +64,10 @@ class Dashboard(FileSystemEventHandler):
|
||||
if not self.observed and not polling:
|
||||
self.observed = self.observer.schedule(self, self.currentdir)
|
||||
|
||||
if __debug__:
|
||||
print('%s Dashboard "%s"' % (polling and 'Polling' or 'Monitoring', self.currentdir))
|
||||
if polling:
|
||||
logger.debug(f'Polling Dashboard "{self.currentdir}"')
|
||||
else:
|
||||
logger.debug(f'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
|
||||
@@ -78,8 +77,8 @@ class Dashboard(FileSystemEventHandler):
|
||||
return True
|
||||
|
||||
def stop(self):
|
||||
if __debug__:
|
||||
print('Stopping monitoring Dashboard')
|
||||
logger.debug('Stopping monitoring Dashboard')
|
||||
|
||||
self.currentdir = None
|
||||
if self.observed:
|
||||
self.observed = None
|
||||
@@ -116,6 +115,9 @@ class Dashboard(FileSystemEventHandler):
|
||||
|
||||
# Can be called either in watchdog thread or, if polling, in main thread.
|
||||
def process(self, logfile=None):
|
||||
if config.shutting_down:
|
||||
return
|
||||
|
||||
try:
|
||||
with open(join(self.currentdir, 'Status.json'), 'rb') as h:
|
||||
data = h.read().strip()
|
||||
@@ -127,8 +129,9 @@ class Dashboard(FileSystemEventHandler):
|
||||
self.status != entry):
|
||||
self.status = entry
|
||||
self.root.event_generate('<<DashboardEvent>>', when="tail")
|
||||
except:
|
||||
if __debug__: print_exc()
|
||||
|
||||
except Exception:
|
||||
logger.exception('Reading Status.json')
|
||||
|
||||
# singleton
|
||||
dashboard = Dashboard()
|
||||
@@ -92,11 +92,15 @@ if platform == 'darwin':
|
||||
self.observer = NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSKeyDownMask, self._handler)
|
||||
|
||||
def _poll(self):
|
||||
if config.shutting_down:
|
||||
return
|
||||
|
||||
# No way of signalling to Tkinter from within the callback handler block that doesn't
|
||||
# cause Python to crash, so poll.
|
||||
if self.activated:
|
||||
self.activated = False
|
||||
self.root.event_generate('<<Invoke>>', when="tail")
|
||||
|
||||
if self.keycode or self.modifiers:
|
||||
self.root.after(HotkeyMgr.POLL, self._poll)
|
||||
|
||||
@@ -123,6 +127,9 @@ if platform == 'darwin':
|
||||
self.acquire_state = HotkeyMgr.ACQUIRE_INACTIVE
|
||||
|
||||
def _acquire_poll(self):
|
||||
if config.shutting_down:
|
||||
return
|
||||
|
||||
# No way of signalling to Tkinter from within the monkey-patched event handler that doesn't
|
||||
# cause Python to crash, so poll.
|
||||
if self.acquire_state:
|
||||
@@ -316,7 +323,8 @@ elif platform == 'win32':
|
||||
while GetMessage(ctypes.byref(msg), None, 0, 0) != 0:
|
||||
if msg.message == WM_HOTKEY:
|
||||
if config.getint('hotkey_always') or WindowTitle(GetForegroundWindow()).startswith('Elite - Dangerous'):
|
||||
self.root.event_generate('<<Invoke>>', when="tail")
|
||||
if not config.shutting_down:
|
||||
self.root.event_generate('<<Invoke>>', when="tail")
|
||||
else:
|
||||
# Pass the key on
|
||||
UnregisterHotKey(None, 1)
|
||||
|
||||
+59
-7
@@ -7,7 +7,7 @@ from os.path import basename, expanduser, isdir, join
|
||||
from sys import platform
|
||||
from time import gmtime, localtime, sleep, strftime, strptime, time
|
||||
from calendar import timegm
|
||||
from typing import Any, Optional, OrderedDict as OrderedDictT, Tuple, TYPE_CHECKING, Union
|
||||
from typing import Any, List, MutableMapping, Optional, OrderedDict as OrderedDictT, Tuple, TYPE_CHECKING, Union
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import tkinter
|
||||
@@ -118,6 +118,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
|
||||
'ModulesValue': None,
|
||||
'Rebuy': None,
|
||||
'Modules': None,
|
||||
'CargoJSON': None, # The raw data from the last time cargo.json was read
|
||||
}
|
||||
|
||||
def start(self, root: 'tkinter.Tk'):
|
||||
@@ -186,8 +187,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
|
||||
return True
|
||||
|
||||
def stop(self):
|
||||
if __debug__:
|
||||
print('Stopping monitoring Journal')
|
||||
logger.debug('Stopping monitoring Journal')
|
||||
|
||||
self.currentdir = None
|
||||
self.version = None
|
||||
@@ -326,13 +326,19 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
|
||||
loghandle.seek(0, SEEK_END) # required to make macOS notice log change over SMB
|
||||
loghandle.seek(log_pos, SEEK_SET) # reset EOF flag # TODO: log_pos reported as possibly unbound
|
||||
for line in loghandle:
|
||||
# Paranoia check to see if we're shutting down
|
||||
if threading.current_thread() != self.thread:
|
||||
logger.info("We're not meant to be running, exiting...")
|
||||
return # Terminate
|
||||
|
||||
if b'"event":"Location"' in line:
|
||||
logger.trace('Found "Location" event, appending to event_queue')
|
||||
|
||||
self.event_queue.append(line)
|
||||
|
||||
if self.event_queue:
|
||||
self.root.event_generate('<<JournalEvent>>', when="tail")
|
||||
if not config.shutting_down:
|
||||
self.root.event_generate('<<JournalEvent>>', when="tail")
|
||||
|
||||
log_pos = loghandle.tell()
|
||||
|
||||
@@ -350,7 +356,9 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
|
||||
'{{ "timestamp":"{}", "event":"ShutDown" }}'.format(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime()))
|
||||
)
|
||||
|
||||
self.root.event_generate('<<JournalEvent>>', when="tail")
|
||||
if not config.shutting_down:
|
||||
self.root.event_generate('<<JournalEvent>>', when="tail")
|
||||
|
||||
self.game_was_running = False
|
||||
|
||||
else:
|
||||
@@ -363,7 +371,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
|
||||
|
||||
try:
|
||||
# Preserve property order because why not?
|
||||
entry: OrderedDictT[str, Any] = json.loads(line, object_pairs_hook=OrderedDict)
|
||||
entry: MutableMapping[str, Any] = json.loads(line, object_pairs_hook=OrderedDict)
|
||||
entry['timestamp'] # we expect this to exist # TODO: replace with assert? or an if key in check
|
||||
|
||||
event_type = entry['event']
|
||||
@@ -608,8 +616,11 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
|
||||
if 'Inventory' not in entry:
|
||||
with open(join(self.currentdir, 'Cargo.json'), 'rb') as h: # type: ignore
|
||||
entry = json.load(h, object_pairs_hook=OrderedDict) # Preserve property order because why not?
|
||||
self.state['CargoJSON'] = entry
|
||||
|
||||
self.state['Cargo'].update({self.canonicalise(x['Name']): x['Count'] for x in entry['Inventory']})
|
||||
clean = self.coalesce_cargo(entry['Inventory'])
|
||||
|
||||
self.state['Cargo'].update({self.canonicalise(x['Name']): x['Count'] for x in clean})
|
||||
|
||||
elif event_type in ('CollectCargo', 'MarketBuy', 'BuyDrones', 'MiningRefined'):
|
||||
commodity = self.canonicalise(entry['Type'])
|
||||
@@ -819,6 +830,10 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
|
||||
|
||||
:return: dict representing the event
|
||||
"""
|
||||
if self.thread is None:
|
||||
logger.debug('Called whilst self.thread is None, returning')
|
||||
return None
|
||||
|
||||
if not self.event_queue:
|
||||
logger.debug('Called with no event_queue')
|
||||
return None
|
||||
@@ -966,6 +981,43 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below
|
||||
with open(filename, 'wt') as h:
|
||||
h.write(string)
|
||||
|
||||
def coalesce_cargo(self, raw_cargo: List[MutableMapping[str, Any]]) -> List[MutableMapping[str, Any]]:
|
||||
"""
|
||||
Coalesce multiple entries of the same cargo into one.
|
||||
|
||||
This exists due to the fact that a user can accept multiple missions that all require the same cargo. On the ED
|
||||
side, this is represented as multiple entries in the `Inventory` List with the same names etc. Just a differing
|
||||
MissionID. We (as in EDMC Core) dont want to support the multiple mission IDs, but DO want to have correct cargo
|
||||
counts. Thus, we reduce all existing cargo down to one total.
|
||||
>>> test = [
|
||||
... { "Name":"basicmedicines", "Name_Localised":"BM", "MissionID":684359162, "Count":147, "Stolen":0 },
|
||||
... { "Name":"survivalequipment", "Name_Localised":"SE", "MissionID":684358939, "Count":147, "Stolen":0 },
|
||||
... { "Name":"survivalequipment", "Name_Localised":"SE", "MissionID":684359344, "Count":36, "Stolen":0 }
|
||||
... ]
|
||||
>>> EDLogs().coalesce_cargo(test) # doctest: +NORMALIZE_WHITESPACE
|
||||
[{'Name': 'basicmedicines', 'Name_Localised': 'BM', 'MissionID': 684359162, 'Count': 147, 'Stolen': 0},
|
||||
{'Name': 'survivalequipment', 'Name_Localised': 'SE', 'MissionID': 684358939, 'Count': 183, 'Stolen': 0}]
|
||||
|
||||
:param raw_cargo: Raw cargo data (usually from Cargo.json)
|
||||
:return: Coalesced data
|
||||
"""
|
||||
# self.state['Cargo'].update({self.canonicalise(x['Name']): x['Count'] for x in entry['Inventory']})
|
||||
out: List[MutableMapping[str, Any]] = []
|
||||
for inventory_item in raw_cargo:
|
||||
if not any(self.canonicalise(x['Name']) == self.canonicalise(inventory_item['Name']) for x in out):
|
||||
out.append(dict(inventory_item))
|
||||
continue
|
||||
|
||||
# We've seen this before, update that count
|
||||
x = list(filter(lambda x: self.canonicalise(x['Name']) == self.canonicalise(inventory_item['Name']), out))
|
||||
|
||||
if len(x) != 1:
|
||||
logger.debug(f'Unexpected number of items: {len(x)} where 1 was expected. {x}')
|
||||
|
||||
x[0]['Count'] += inventory_item['Count']
|
||||
|
||||
return out
|
||||
|
||||
|
||||
# singleton
|
||||
monitor = EDLogs()
|
||||
@@ -251,10 +251,14 @@ def notify_stop():
|
||||
plugin_stop = plugin._get_func('plugin_stop')
|
||||
if plugin_stop:
|
||||
try:
|
||||
logger.info(f'Asking plugin "{plugin.name}" to stop...')
|
||||
newerror = plugin_stop()
|
||||
error = error or newerror
|
||||
except Exception as e:
|
||||
logger.exception(f'Plugin "{plugin.name}" failed')
|
||||
|
||||
logger.info('Done')
|
||||
|
||||
return error
|
||||
|
||||
|
||||
@@ -362,9 +366,16 @@ def notify_newdata(data, is_beta):
|
||||
def show_error(err):
|
||||
"""
|
||||
Display an error message in the status line of the main window.
|
||||
|
||||
Will be NOP during shutdown to avoid Tk hang.
|
||||
:param err:
|
||||
.. versionadded:: 2.3.7
|
||||
"""
|
||||
|
||||
if config.shutting_down:
|
||||
logger.info(f'Called during shutdown: "{str(err)}"')
|
||||
return
|
||||
|
||||
if err and last_error['root']:
|
||||
last_error['msg'] = str(err)
|
||||
last_error['root'].event_generate('<<PluginError>>', when="tail")
|
||||
+4
-2
@@ -598,8 +598,10 @@ 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
|
||||
this.system_link.event_generate('<<EDSMStatus>>', when="tail")
|
||||
|
||||
if not config.shutting_down:
|
||||
# calls update_status in main thread
|
||||
this.system_link.event_generate('<<EDSMStatus>>', when="tail")
|
||||
|
||||
if r['msgnum'] // 100 != 1:
|
||||
logger.warning(f'EDSM event with not-1xx status:\n{r["msgnum"]}\n{r["msg"]}\n'
|
||||
|
||||
+8
-4
@@ -1290,13 +1290,17 @@ def send_data(url: str, data: Mapping[str, Any]) -> bool:
|
||||
'setCommanderTravelLocation'
|
||||
):
|
||||
this.lastlocation = reply_event.get('eventData', {})
|
||||
# calls update_location in main thread
|
||||
this.system_link.event_generate('<<InaraLocation>>', when="tail")
|
||||
|
||||
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
|
||||
this.system_link.event_generate('<<InaraShip>>', when="tail")
|
||||
|
||||
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
|
||||
|
||||
|
||||
@@ -1157,4 +1157,5 @@ class PreferencesDialog(tk.Toplevel):
|
||||
except Exception:
|
||||
AXIsProcessTrustedWithOptions({kAXTrustedCheckOptionPrompt: True})
|
||||
|
||||
self.parent.event_generate('<<Quit>>', when="tail")
|
||||
if not config.shutting_down:
|
||||
self.parent.event_generate('<<Quit>>', when="tail")
|
||||
+4
-2
@@ -5,7 +5,7 @@ import threading
|
||||
import urllib.request, urllib.error, urllib.parse
|
||||
import sys
|
||||
|
||||
from config import appname
|
||||
from config import appname, config
|
||||
|
||||
|
||||
if sys.platform == 'win32':
|
||||
@@ -32,7 +32,9 @@ class GenericProtocolHandler(object):
|
||||
|
||||
def event(self, url):
|
||||
self.lastpayload = url
|
||||
self.master.event_generate('<<CompanionAuthEvent>>', when="tail")
|
||||
|
||||
if not config.shutting_down:
|
||||
self.master.event_generate('<<CompanionAuthEvent>>', when="tail")
|
||||
|
||||
|
||||
if sys.platform == 'darwin' and getattr(sys, 'frozen', False):
|
||||
|
||||
@@ -17,7 +17,7 @@ pep8-naming==0.11.1
|
||||
autopep8==1.5.4
|
||||
|
||||
# HTML changelogs
|
||||
grip>=4.5.2
|
||||
grip==4.5.2
|
||||
|
||||
# Packaging
|
||||
# We only need py2exe on windows.
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
certifi==2019.9.11
|
||||
requests>=2.11.1
|
||||
watchdog>=0.8.3
|
||||
requests==2.25.1
|
||||
watchdog==0.10.3
|
||||
# argh==0.26.2 watchdog dep
|
||||
# pyyaml==5.3.1 watchdog dep
|
||||
semantic-version==2.8.5
|
||||
@@ -9,7 +9,7 @@ if TYPE_CHECKING:
|
||||
import tkinter as tk
|
||||
|
||||
# ensure registry is set up on Windows before we start
|
||||
from config import appname, appversion, appversion_nobuild, update_feed
|
||||
from config import appname, appversion, appversion_nobuild, config, update_feed
|
||||
|
||||
class EDMCVersion(object):
|
||||
"""
|
||||
@@ -40,7 +40,8 @@ class Updater(object):
|
||||
Receive (Win)Sparkle shutdown request and send it to parent.
|
||||
:rtype: None
|
||||
"""
|
||||
self.root.event_generate('<<Quit>>', when="tail")
|
||||
if not config.shutting_down:
|
||||
self.root.event_generate('<<Quit>>', when="tail")
|
||||
|
||||
def use_internal(self) -> bool:
|
||||
"""
|
||||
@@ -208,4 +209,4 @@ class Updater(object):
|
||||
|
||||
:return: None
|
||||
"""
|
||||
pass
|
||||
pass
|
||||
Reference in new issue
Block a user