diff --git a/EDMC.py b/EDMC.py index 04701313..55a1a3fd 100755 --- a/EDMC.py +++ b/EDMC.py @@ -189,7 +189,7 @@ 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', str(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 +215,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', []) if args.p in cmdrs: idx = cmdrs.index(args.p) @@ -231,7 +231,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', []) if monitor.cmdr not in cmdrs: raise companion.CredentialsError() diff --git a/EDMCLogging.py b/EDMCLogging.py index 8445a9fe..068d7225 100644 --- a/EDMCLogging.py +++ b/EDMCLogging.py @@ -473,7 +473,7 @@ def get_main_logger() -> 'LoggerMixin': # Singleton -loglevel = config.get('loglevel') +loglevel = config.get_str('loglevel') if not loglevel: loglevel = logging.INFO diff --git a/commodity.py b/commodity.py index fec7d2b7..1ee86055 100644 --- a/commodity.py +++ b/commodity.py @@ -20,7 +20,7 @@ bracketmap = { def export(data, kind=COMMODITY_DEFAULT, filename=None): - querytime = config.getint('querytime') or int(time.time()) + querytime = config.get_int('querytime') or int(time.time()) if not filename: filename = '{system}.{starport}.{time}.{kind}'.format( @@ -29,7 +29,7 @@ def export(data, kind=COMMODITY_DEFAULT, filename=None): time=time.strftime('%Y-%m-%dT%H.%M.%S', time.localtime(querytime)), kind='csv' ) - filename = join(config.get('outdir'), filename) + filename = join(config.get_str('outdir'), filename) if kind == COMMODITY_CSV: sep = ';' # BUG: for fixing later after cleanup diff --git a/companion.py b/companion.py index 7d6bbe36..36639f3f 100644 --- a/companion.py +++ b/companion.py @@ -40,7 +40,6 @@ 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) @@ -286,13 +285,13 @@ class Auth(object): logger.debug(f'Trying for "{self.cmdr}"') self.verifier = None - cmdrs = cast(List[str], config.get('cmdrs')) + cmdrs = cast(List[str], config.get_list('cmdrs', [])) logger.debug(f'Cmdrs: {cmdrs}') idx = cmdrs.index(self.cmdr) logger.debug(f'idx = {idx}') - tokens = config.get('fdev_apikeys') or [] + tokens = cast('List[str]', config.get_list('fdev_apikeys', [])) tokens = tokens + [''] * (len(cmdrs) - len(tokens)) if tokens[idx]: logger.debug('We have a refresh token for that idx') @@ -376,9 +375,9 @@ class Auth(object): data = r.json() if r.status_code == requests.codes.ok: logger.info(f'Frontier CAPI Auth: New token for \"{self.cmdr}\"') - cmdrs = cast(List[str], config.get('cmdrs')) + cmdrs = cast(List[str], config.get_list('cmdrs', [])) idx = cmdrs.index(self.cmdr) - tokens = config.get('fdev_apikeys') or [] + tokens = cast(List[str], config.get_list('fdev_apikeys', [])) tokens = tokens + [''] * (len(cmdrs) - len(tokens)) tokens[idx] = data.get('refresh_token', '') config.set('fdev_apikeys', tokens) @@ -405,9 +404,9 @@ class Auth(object): def invalidate(cmdr: str) -> None: """Invalidate Refresh Token for specified Commander.""" logger.info(f'Frontier CAPI Auth: Invalidated token for "{cmdr}"') - cmdrs = cast(List[str], config.get('cmdrs')) + cmdrs = cast(List[str], config.get_list('cmdrs', [])) idx = cmdrs.index(cmdr) - tokens = cast(List[str], config.get('fdev_apikeys') or []) + tokens = cast(List[str], config.get_list('fdev_apikeys', [])) tokens = tokens + [''] * (len(cmdrs) - len(tokens)) tokens[idx] = '' config.set('fdev_apikeys', tokens) diff --git a/dashboard.py b/dashboard.py index 7fef3a9f..530e4b3b 100644 --- a/dashboard.py +++ b/dashboard.py @@ -41,7 +41,7 @@ class Dashboard(FileSystemEventHandler): self.root = root self.session_start = started - logdir = config.get('journaldir') or config.default_journal_dir + logdir = config.get_str('journaldir', str(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() diff --git a/docs/examples/click_counter/load.py b/docs/examples/click_counter/load.py index 02403f2f..ff9b449d 100644 --- a/docs/examples/click_counter/load.py +++ b/docs/examples/click_counter/load.py @@ -26,7 +26,7 @@ class ClickCounter: def __init__(self) -> None: # Be sure to use names that wont collide in our config variables - self.click_count: Optional[tk.StringVar] = tk.StringVar(value=str(config.getint('click_counter_count'))) + self.click_count: Optional[tk.StringVar] = tk.StringVar(value=str(config.get_int('click_counter_count'))) logger.info("ClickCounter instantiated") def on_load(self) -> str: diff --git a/edshipyard.py b/edshipyard.py index f3ce48a4..dd80ffda 100644 --- a/edshipyard.py +++ b/edshipyard.py @@ -74,7 +74,7 @@ def export(data, filename=None): return ret + ' ' - querytime = config.getint('querytime') or int(time.time()) + querytime = config.get_int('querytime') or int(time.time()) loadout = defaultdict(list) mass = 0.0 @@ -199,14 +199,14 @@ def export(data, filename=None): # Look for last ship of this type ship = companion.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 open(join(config.get_str('outdir'), oldfiles[-1]), 'rU') as h: if h.read() == string: return # same as last time - don't write # Write - filename = join(config.get('outdir'), '{}.{}.txt'.format( + filename = join(config.get_str('outdir'), '{}.{}.txt'.format( ship, time.strftime('%Y-%m-%dT%H.%M.%S', time.localtime(querytime))) ) diff --git a/hotkey.py b/hotkey.py index 966975a4..5165e0b9 100644 --- a/hotkey.py +++ b/hotkey.py @@ -113,7 +113,7 @@ if platform == 'darwin': def _handler(self, event): # use event.charactersIgnoringModifiers to handle composing characters like Alt-e if (event.modifierFlags() & HotkeyMgr.MODIFIERMASK) == self.modifiers and ord(event.charactersIgnoringModifiers()[0]) == self.keycode: - if config.getint('hotkey_always'): + if config.get_int('hotkey_always'): self.activated = True else: # Only trigger if game client is front process front = NSWorkspace.sharedWorkspace().frontmostApplication() @@ -347,7 +347,7 @@ elif platform == 'win32': logger.debug('WM_HOTKEY') if ( - config.getint('hotkey_always') + config.get_int('hotkey_always') or WindowTitle(GetForegroundWindow()).startswith('Elite - Dangerous') ): logger.debug('Sending event <>') diff --git a/loadout.py b/loadout.py index 6814c18f..85c4f0f8 100644 --- a/loadout.py +++ b/loadout.py @@ -22,15 +22,15 @@ def export(data, filename=None): # Look for last ship of this type ship = companion.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') or 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) diff --git a/monitor.py b/monitor.py index 94486d6e..637bcb95 100644 --- a/monitor.py +++ b/monitor.py @@ -129,7 +129,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below """Start journal monitoring.""" logger.debug('Begin...') self.root = root - journal_dir = config.get('journaldir') or config.default_journal_dir + journal_dir = config.get_str('journaldir', str(config.default_journal_dir)) if journal_dir is None: logger.debug('journal_dir was None, setting ""') @@ -169,7 +169,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below # File system events are unreliable/non-existent over network drives on Linux. # We can't easily tell whether a path points to a network drive, so assume # any non-standard logdir might be on a network drive and poll instead. - polling = bool(config.get('journaldir')) and platform != 'win32' + polling = bool(config.get_str('journaldir')) and platform != 'win32' if not polling and not self.observer: logger.debug('Not polling, no observer, starting an observer...') self.observer = Observer() @@ -1023,29 +1023,15 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below ship = ship_file_name(self.state['ShipName'], self.state['ShipType']) regexp = re.compile(re.escape(ship) + r'\.\d{4}\-\d\d\-\d\dT\d\d\.\d\d\.\d\d\.txt') - oldfiles = sorted((x for x in listdir(config.get('outdir')) if regexp.match(x))) # type: ignore + oldfiles = sorted((x for x in listdir(config.get_str('outdir')) if regexp.match(x))) # type: ignore if oldfiles: - try: - with open(join(config.get('outdir'), oldfiles[-1]), 'rU', encoding='utf-8') as h: # type: ignore - if h.read() == string: - return # same as last time - don't write - - except UnicodeError: - logger.exception("UnicodeError reading old ship loadout with utf-8 encoding, trying without...") - try: - with open(join(config.get('outdir'), oldfiles[-1]), 'rU') as h: # type: ignore - if h.read() == string: - return # same as last time - don't write - - except OSError: - logger.exception("OSError reading old ship loadout default encoding.") - - except OSError: - logger.exception("OSError reading old ship loadout with default encoding") + with open(join(config.get_str('outdir'), oldfiles[-1]), 'rU') as h: # type: ignore + if h.read() == string: + return # same as last time - don't write # Write filename = join( # type: ignore - config.get('outdir'), '{}.{}.txt'.format(ship, strftime('%Y-%m-%dT%H.%M.%S', localtime(time()))) + config.get_str('outdir'), '{}.{}.txt'.format(ship, strftime('%Y-%m-%dT%H.%M.%S', localtime(time()))) ) try: diff --git a/outfitting.py b/outfitting.py index 061cb4f3..1670f06b 100644 --- a/outfitting.py +++ b/outfitting.py @@ -509,7 +509,7 @@ def lookup(module, ship_map, entitled=False): def export(data, filename): - querytime = config.getint('querytime') or int(time.time()) + querytime = config.get_int('querytime') or int(time.time()) assert data['lastSystem'].get('name') assert data['lastStarport'].get('name') diff --git a/plugins/coriolis.py b/plugins/coriolis.py index 21077886..36ccde27 100644 --- a/plugins/coriolis.py +++ b/plugins/coriolis.py @@ -8,7 +8,7 @@ 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') diff --git a/plugins/eddb.py b/plugins/eddb.py index f61ae017..12ebc8ed 100644 --- a/plugins/eddb.py +++ b/plugins/eddb.py @@ -104,14 +104,14 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): 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: @@ -139,13 +139,13 @@ def cmdr_data(data: CAPIData, 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 config.get_str('station_provider') == 'eddb': if data['commander']['docked']: this.station_link['text'] = this.station diff --git a/plugins/eddn.py b/plugins/eddn.py index 243b6beb..8faed4fd 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -305,7 +305,7 @@ Msg:\n{msg}''' data['lastStarport'].get('economies', {}), data['lastStarport']['modules'], data['lastStarport']['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 @@ -348,7 +348,7 @@ Msg:\n{msg}''' data['lastStarport'].get('economies', {}), data['lastStarport']['modules'], ships - ) + ) shipyard: List[Mapping[str, Any]] = sorted( itertools.chain( @@ -495,7 +495,7 @@ Msg:\n{msg}''' 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 @@ -531,11 +531,11 @@ def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: 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) @@ -587,7 +587,7 @@ def prefsvarchanged(event=None) -> None: def prefs_changed(cmdr: str, is_beta: bool) -> None: 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) @@ -645,7 +645,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)): @@ -719,7 +719,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 @@ -728,7 +728,7 @@ 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' + path = pathlib.Path(str(config.get_str('journaldir') or config.default_journal_dir)) / f'{entry["event"]}.json' with path.open('rb') as f: entry = json.load(f) if entry['event'] == 'Market': @@ -750,7 +750,7 @@ def journal_entry( # noqa: C901 def cmdr_data(data: CAPIData, is_beta: bool) -> Optional[str]: - if data['commander'].get('docked') and config.getint('output') & config.OUT_MKT_EDDN: + if data['commander'].get('docked') and config.get_int('output') & config.OUT_MKT_EDDN: try: if this.marketId != data['lastStarport']['id']: this.commodities = this.outfitting = this.shipyard = None diff --git a/plugins/edsm.py b/plugins/edsm.py index ce2b40b3..1fd43a60 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -15,7 +15,7 @@ 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 @@ -124,20 +124,20 @@ 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') or '']) + config.set('edsm_apikeys', [config.get_str('edsm_apikey') or '']) config.delete('edsm_cmdrname') config.delete('edsm_apikey') - if config.getint('output') & 256: + if config.get_int('output') & 256: # Migrate <= 2.34 setting config.set('edsm_out', 1) @@ -189,7 +189,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 ) @@ -289,9 +289,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', []) + usernames: List[str] = config.get_list('edsm_usernames', []) + apikeys: List[str] = config.get_list('edsm_apikeys', []) + if cmdr in cmdrs: idx = cmdrs.index(cmdr) usernames.extend([''] * (1 + idx - len(usernames))) @@ -319,15 +320,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 @@ -364,7 +365,7 @@ entry: {entry!r}''' this.station = None this.station_marketid = None - if config.get('station_provider') == 'EDSM': + if config.get_str('station_provider') == 'EDSM': to_set = this.station if not this.station: if this.system_population and this.system_population > 0: @@ -410,7 +411,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 @@ -460,13 +461,13 @@ def cmdr_data(data: CAPIData, 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 config.get_str('station_provider') == 'EDSM': if data['commander']['docked']: this.station_link['text'] = this.station diff --git a/plugins/inara.py b/plugins/inara.py index 5abcf2ec..92d3d661 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -209,7 +209,7 @@ def plugin_prefs(parent: tk.Tk, cmdr: str, is_beta: bool) -> tk.Frame: 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 - 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 ) @@ -271,14 +271,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', []) + apikeys = config.get_list('inara_apikeys', []) if cmdr in cmdrs: idx = cmdrs.index(cmdr) apikeys.extend([''] * (1 + idx - len(apikeys))) @@ -309,9 +309,9 @@ 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', []) + if cmdr in cmdrs and config.get_list('inara_apikeys'): + return config.get_list('inara_apikeys')[cmdrs.index(cmdr)] else: return None @@ -377,7 +377,7 @@ def journal_entry( this.station = None this.station_marketid = None - if config.getint('inara_out') and not is_beta and not this.multicrew and credentials(cmdr): + 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 @@ -1018,13 +1018,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: @@ -1053,13 +1053,13 @@ def cmdr_data(data: CAPIData, 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 config.get_str('station_provider') == 'Inara': if data['commander']['docked']: this.station_link['text'] = this.station @@ -1073,7 +1073,7 @@ def cmdr_data(data: CAPIData, 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( Credentials(this.cmdr, this.FID, str(credentials(this.cmdr))), diff --git a/prefs.py b/prefs.py index e9c3afab..7bfb697c 100644 --- a/prefs.py +++ b/prefs.py @@ -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 @@ -326,11 +326,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 +376,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 +407,7 @@ 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 '')) + self.logdir.set(str(config.get_str('journaldir') or config.default_journal_dir or '')) self.logdir_entry = nb.Entry(config_frame, takefocus=False) # Location of the new Journal file in E:D 2.2 @@ -431,7 +431,7 @@ class PreferencesDialog(tk.Toplevel): 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 +439,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 +509,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 +531,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', '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 +543,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 +554,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 +571,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 +599,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 +628,10 @@ 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.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 +715,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 @@ -897,7 +897,7 @@ 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() @@ -1084,7 +1084,7 @@ class PreferencesDialog(tk.Toplevel): (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( @@ -1113,7 +1113,7 @@ 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') or None) # type: ignore # This sets self in weird ways. config.set('ui_scale', self.ui_scale.get()) config.set('always_ontop', self.always_ontop.get()) @@ -1136,7 +1136,7 @@ class PreferencesDialog(tk.Toplevel): self.after_cancel(self.cmdrchanged_alarm) self.cmdrchanged_alarm = None - self.parent.wm_attributes('-topmost', 1 if config.getint('always_ontop') else 0) + self.parent.wm_attributes('-topmost', 1 if config.get_int('always_ontop') else 0) self.destroy() if platform == 'darwin': diff --git a/shipyard.py b/shipyard.py index fe31d33e..ba25a55c 100644 --- a/shipyard.py +++ b/shipyard.py @@ -8,7 +8,7 @@ from config import config def export(data, filename): - querytime = config.getint('querytime') or int(time.time()) + querytime = config.get_int('querytime', int(time.time())) assert data['lastSystem'].get('name') assert data['lastStarport'].get('name') diff --git a/td.py b/td.py index ba4e5465..956371e2 100644 --- a/td.py +++ b/td.py @@ -22,9 +22,9 @@ stockbracketmap = { 0: '-', def export(data): - querytime = config.getint('querytime') or int(time.time()) + querytime = config.get_int('querytime', 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')) diff --git a/theme.py b/theme.py index d56b7798..26cff4f3 100644 --- a/theme.py +++ b/theme.py @@ -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