diff --git a/.github/workflows/push-checks.yml b/.github/workflows/push-checks.yml index ba8367c7..b6ad01a5 100644 --- a/.github/workflows/push-checks.yml +++ b/.github/workflows/push-checks.yml @@ -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 <" + + 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__: diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 0607afaa..aba22e7b 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -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` diff --git a/PLUGINS.md b/PLUGINS.md index 00d48155..9f73df7f 100644 --- a/PLUGINS.md +++ b/PLUGINS.md @@ -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 diff --git a/config.py b/config.py index e60ff1cd..41d56f3f 100644 --- a/config.py +++ b/config.py @@ -13,7 +13,7 @@ appcmdname = 'EDMC' # appversion **MUST** follow Semantic Versioning rules: # # 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'\\;') diff --git a/dashboard.py b/dashboard.py index 43ac67a7..4259dccb 100644 --- a/dashboard.py +++ b/dashboard.py @@ -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('<>', when="tail") - except: - if __debug__: print_exc() + + except Exception: + logger.exception('Reading Status.json') # singleton dashboard = Dashboard() diff --git a/hotkey.py b/hotkey.py index 8ee8762d..9b261ccc 100644 --- a/hotkey.py +++ b/hotkey.py @@ -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('<>', 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('<>', when="tail") + if not config.shutting_down: + self.root.event_generate('<>', when="tail") else: # Pass the key on UnregisterHotKey(None, 1) diff --git a/monitor.py b/monitor.py index 63c4e25a..f8d4a201 100644 --- a/monitor.py +++ b/monitor.py @@ -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('<>', when="tail") + if not config.shutting_down: + self.root.event_generate('<>', 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('<>', when="tail") + if not config.shutting_down: + self.root.event_generate('<>', 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() diff --git a/plug.py b/plug.py index dd960704..755fec1c 100644 --- a/plug.py +++ b/plug.py @@ -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('<>', when="tail") diff --git a/plugins/edsm.py b/plugins/edsm.py index 80c0077a..e9fbd46c 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -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('<>', when="tail") + + if not config.shutting_down: + # calls update_status in main thread + this.system_link.event_generate('<>', when="tail") if r['msgnum'] // 100 != 1: logger.warning(f'EDSM event with not-1xx status:\n{r["msgnum"]}\n{r["msg"]}\n' diff --git a/plugins/inara.py b/plugins/inara.py index 4b61322c..ac5d53f5 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -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('<>', when="tail") + + if not config.shutting_down: + # calls update_location in main thread + this.system_link.event_generate('<>', when="tail") elif data_event['eventName'] in ['addCommanderShip', 'setCommanderShip']: this.lastship = reply_event.get('eventData', {}) - # calls update_ship in main thread - this.system_link.event_generate('<>', when="tail") + + if not config.shutting_down: + # calls update_ship in main thread + this.system_link.event_generate('<>', when="tail") return True # regardless of errors above, we DID manage to send it, therefore inform our caller as such diff --git a/prefs.py b/prefs.py index 95612e6a..e9c3afab 100644 --- a/prefs.py +++ b/prefs.py @@ -1157,4 +1157,5 @@ class PreferencesDialog(tk.Toplevel): except Exception: AXIsProcessTrustedWithOptions({kAXTrustedCheckOptionPrompt: True}) - self.parent.event_generate('<>', when="tail") + if not config.shutting_down: + self.parent.event_generate('<>', when="tail") diff --git a/protocol.py b/protocol.py index 49345643..408b3082 100644 --- a/protocol.py +++ b/protocol.py @@ -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('<>', when="tail") + + if not config.shutting_down: + self.master.event_generate('<>', when="tail") if sys.platform == 'darwin' and getattr(sys, 'frozen', False): diff --git a/requirements-dev.txt b/requirements-dev.txt index b50ae664..e2ea8f11 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -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. diff --git a/requirements.txt b/requirements.txt index bf29adc9..7f6952ba 100644 --- a/requirements.txt +++ b/requirements.txt @@ -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 diff --git a/update.py b/update.py index c234dfc9..de7eb8cd 100644 --- a/update.py +++ b/update.py @@ -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('<>', when="tail") + if not config.shutting_down: + self.root.event_generate('<>', when="tail") def use_internal(self) -> bool: """ @@ -208,4 +209,4 @@ class Updater(object): :return: None """ - pass \ No newline at end of file + pass