jconfig.html
001| """JSON Configuration File.
001|
001| While these classes actually work, they're intended to be subclassed for specific
001| configuration files based on this model.
001|
001| Classes:
001| JConfiguration
001| JConfigSet
001| JConfigItem
001|
001| JConfigSettingsItem
001| JConfigSettingsSet
001| JConfigSettings
001|
001| JSON Format:
001| "comment" : str
001| "date-created" : str
001| "date-updated" : str
001| "defines" : { <tagname> : [ <label> : <replacement-text>, ... ] }
001| "configs" : { <cfgname> : { <configuration> }, ... }
001|
001| <configuration> :=
001| "description" : str
001| "comment" : str
001| "date-created" : str
001| "date-updated" : str
001| "visible" : int [0|1]
001| "parameters": { <name>: {"value":*, "description":str, "comment":str}, ... }
001|
001| Settings files are same but with "settings" instead of "parameters":
001| "settings": { <name>: { <name>:<value>, ... }
001|
001| TODO: integer indexing of configs and params/settings
001| """
002|
003| from sys import argv
004| from os import path
005| from datetime import datetime
006| import re
007| import json
008| from logger import logger,trace
009| from goodies import typename, KWARG
010|
011| Log = logger('JConfig')
012| Now = datetime.now()
013|
014|
015| JsonIndent = 2
016|
017| '''JConfig JSON files need to use these keys!'''
018| JConfigDefinesKey = 'defines'
019| JConfigConfigsKey = 'configs'
020| JConfigParamsKey = 'parameters'
021| JConfigDateCreKey = 'date-created'
022| JConfigDateUpdKey = 'date-updated'
023| JConfigDescripKey = 'description'
024| JConfigCommentKey = 'comment'
025| JConfigValueKey = 'value'
026| JConfigDTypeKey = 'dtype'
027| JConfigVisibleKey = 'visible'
028|
029|
030| class JConfigItem:
031| '''JSON File Basic Configuration Item class.
031|
031| An instance takes a configuration dictionary (from the JSON file data)
031| and parses it to populate some basic instance fields.
031|
031| Attributes:
031| papasan ~JConfiguration: our parent
031| name ~str: name of the configuration [JSON field]
031| descrip ~str: config description [JSON field]
031| comment ~str: config comment [JSON field]
031|
031| Properties:
031| json_dict ~str: JSON version of parameter (for saving)
031|
031| Methods:
031| replace_fields ~delegates to same in papasan
031|
031| '''
032| @staticmethod
033| def make_dict (value='<NULL>', descr='(no description)', comment='(no comment)', dtype='str'):
034| '''Return a params dictionary given the four parameter datums.'''
035| return {JConfigDescripKey:descr,JConfigCommentKey:comment,JConfigValueKey:value,JConfigDTypeKey:dtype}
036|
037| def __init__ (self, params, papasan):
038| '''New JConfigItem instance.'''
039| Log.debug(f'JConfigItem(len={len(params)}, {typename(papasan)})')
040|
041| self.papasan = papasan
042| self.descrip = '(no description)'
043| self.comment = '(no comment)'
044| self.value = '<NULL>'
045| self.dtype = 'str'
046|
047| if JConfigDescripKey in params: self.descrip = params[JConfigDescripKey]
048| if JConfigCommentKey in params: self.comment = params[JConfigCommentKey]
049| if JConfigValueKey in params: self.value = params[JConfigValueKey]
050| if JConfigDTypeKey in params: self.dtype = params[JConfigDTypeKey]
051|
052| Log.trace(f'Item: {self.value} <{self.dtype}> "{self.descrip}"')
053|
054| def replace_fields (self, txt, maxtry=10):
055| '''Replace fields. Delegated to containing JConfiguration.'''
056| return self.papasan.replace_fields(txt, maxtry=maxtry)
057|
058| @property
059| def json_dict (self):
060| '''Return a JSON saveable dictionary.'''
061| return JConfigItem.make_dict(self.value, self.descrip, self.comment, self.dtype)
062|
063| def __repr__ (self):
064| return f'<{typename(self)} {self.value} @{id(self):08x}>'
065|
066| def __str__ (self):
067| return f'{self.value} <self.dtype> "{self.descrip}"'
068|
069|
070| class JConfigSet:
071| '''Basic JSON File Configuration Set class.
071|
071| An instance takes a single configuration dictionary from the JSON file data
071| and parses it to populate its instance fields.
071|
071| Class Attributes:
071| NewItemType ~JConfigItem: type for making a configuration item
071|
071| Attributes:
071| papasan ~JConfiguration: our parent
071| name ~str: name of the configuration [JSON field]
071| descrip ~str: config description [JSON field]
071| comment ~str: config comment [JSON field]
071| dtcr ~str: config created date (ctime) [JSON field]
071| dtup ~str: config updated date (ctime) [JSON field]
071| visi ~int: whether this config is visible in pick lists
071| params ~list[JConfigItem]: parameters in this config set
071|
071| Properties:
071| visible ~bool: whether this config is visible in pick lists
071| paramkeys ~list[str]: list of parameter names
071| json_dict ~str: JSON version of parameter (for saving)
071|
071| Methods:
071| getparam ~get parameter (return default if doesn't exist)
071| getsetparam ~get parameter (set to default if doesn't exist)
071|
071| obj[name/ix] ~JConfigItem: index command (get, set, del)
071| name in obj ~bool: True if name in commands
071| len(obj) ~int: number of commands (always ten)
071| iter(obj) ~iter: iterator over commands
071| bool(obj) ~bool: True if has commands
071| str(obj) ~str: official representation
071| repr(obj) ~str: debug representation
071|
071| '''
072| NewItemType = JConfigItem
073|
074| def __init__ (self, name, paramset, papasan):
075| '''New JConfigSet instance.'''
076| Log.debug(f'JConfigSet({name}, {len(paramset)}, {typename(papasan)})')
077| Log.debug()
078|
079| self.papasan = papasan
080| self.name = name
081| self.descrip = '(no description)'
082| self.comment = '(no comment)'
083| self.dtcr = Now.ctime()
084| self.dtup = Now.ctime()
085| self.visi = 1
086| self.params = {}
087|
088| if JConfigDescripKey in paramset: self.descrip = paramset[JConfigDescripKey]
089| if JConfigCommentKey in paramset: self.comment = paramset[JConfigCommentKey]
090| if JConfigDateCreKey in paramset: self.dtcr = paramset[JConfigDateCreKey]
091| if JConfigDateUpdKey in paramset: self.dtup = paramset[JConfigDateUpdKey]
092| if JConfigVisibleKey in paramset: self.visi = paramset[JConfigVisibleKey]
093|
094|
095| if JConfigParamsKey in paramset:
096| pd = paramset[JConfigParamsKey]
097| self.params = {n:type(self).NewItemType(pd[n], papasan) for n in pd}
098| Log.trace()
099|
100|
101| def getparam (self, name, dflt):
102| '''Get parameter (return default if doesn't exist).'''
103| if name in self.params:
104| return self.params[name]
105| return dflt
106|
107| def getsetparam (self, name, dflt):
108| '''Get parameter (set to default if doesn't exist).'''
109| if name not in self.params:
110| self.params[name] = JConfigItem(dflt,self.papasan)
111| return self.params[name]
112|
113| @property
114| def visible (self): return True if self.visi else False
115|
116| @property
117| def paramkeys (self): return list(self.params)
118|
119| @property
120| def json_dict (self):
121| '''Return a JSON saveable dictionary.'''
122| return {
123| JConfigDescripKey: self.descrip,
124| JConfigCommentKey: self.comment,
125| JConfigDateCreKey: self.dtcr,
126| JConfigDateUpdKey: self.dtup,
127| JConfigVisibleKey: self.visi,
128| JConfigParamsKey: {n:p.json_dict for n,p in self.params.items() if isinstance(p,JConfigItem)}
129| }
130|
131| def __len__ (self): return len(self.params)
132| def __iter__ (self): return iter(self.params)
133| def __bool__ (self): return 0 < len(self.params)
134|
135| def __getitem__ (self, which):
136| '''Get a parameter by name (or index). Won't raise IndexError.'''
137|
138| if isinstance(which,int):
139| which = self._index_to_name(which)
140|
141| return self.params[which] if which in self.params else None
142|
143| def __setitem__ (self, which, param):
144| '''Set a parameter by name (or index). NOTE: SILENTLY IGNORES INVALID INDEXES.'''
145|
146| if isinstance(which,int):
147| which = self._index_to_name(which)
148|
149| self.params[which] = param
150|
151| def __delitem__ (self, which):
152| '''Delete a parameter by name (or index). NOTE: SILENTLY IGNORES INVALID INDEXES.'''
153|
154| if isinstance(which,int):
155| which = self._index_to_name(which)
156|
157| del self.params[which]
158|
159| def _index_to_name (self, ix):
160| '''Convert an integer index to a parameter name.'''
161| names = list(self.params.keys())
162| return names[ix] if ix < len(names) else '#NoSuchParameter#'
163|
164| def __repr__ (self):
165| return f'<{typename(self)} {len(self)} @{id(self):08x}>'
166|
167| def __str__ (self):
168| vis = '*' if self.visi else '-'
169| return f'{self.name}: {self.descrip} ({vis}) {self.dtup}'
170|
171|
172|
173| class JConfiguration:
174| '''Basic JSON File Configuration class.
174|
174| Instances automagically load the JSON configuration file and process its
174| data to populate the instance attributes. The central player here is the
174| configurations dictionary containing all configurations. The instance
174| also maintains user-changable "current" configuration.
174|
174| Class Attributes:
174| NewSetType ~JConfigSet: type for making a configuration set
174|
174| Attributes:
174| cnfg_name ~str: name of current configuration
174| cnfg_index ~int: index of current configuration
174| curr_cnfg ~JConfigSet: current configuration
174| file_path ~str: path to config file (or None or '')
174| file_name ~str: name of config file (can contain path if not file_path)
174| cnfg_file ~str: full path and name of config file (generated)
174| tag_regex ~str: regular expression for tag replacement
174| name_list ~str: CSV list of dictionaries to look for
174| noinit ~int: if true, don't try to read JSON file
174| tag_re ~re: compiled regular expression for tag replacement
174| jversion ~int: "version" key from JSON file (always 1)
174| comment ~str: JSON file main comment field
174| created ~str: JSON file created date field (ctime)
174| updated ~str: JSON file updated date field (ctime)
174| defines ~keys: tagnames; values: (name, text) tuples
174| configs ~keys: cfgnames; values: JConfigSet objects
174|
174| Properties:
174| name ~str: name of current config
174| current ~dict: current config
174| cnfgkeys ~list: config keys
174| cnfgfile ~str:full path and name of config file
174| fname ~str:filename of config file
174| fpath ~str:pathname of config file
174|
174| Methods:
174| get_command ~JConfigSet: command[ix] in the current config
174| replace_fields ~str: replace tags with defined tex
174| set_configuration ~None: load a configuration by name
174| reload ~None: reload the JSON file
174| json_dict ~str: JSON version of parameter (for saving)
174| save_json_file ~None: save the JSON file
174|
174| obj[name/ix] ~JConfigSet: index config (get, set, del)
174| name in obj ~bool: True if name in configs
174| len(obj) ~int: number of configurations
174| iter(obj) ~iter: iterator over configurations
174| bool(obj) ~bool: True if has configurations
174| str(obj) ~str: official representation
174| repr(obj) ~str: debug representation
174|
174| '''
175| NewSetType = JConfigSet
176|
177| @classmethod
178| def get_blank_config (cls, **kwargs):
179| Log.trace(f'JConfiguration::GetBlankConfig({cls.__name__})')
180| obj = cls(noinitialize=1, **kwargs)
181| return obj
182|
183| def __init__ (self, **kwargs):
184| '''New JConfiguration instance.
184|
184| Keyword Arguments:
184| cfg ~name of configuration to make current after loading
184| fpath ~path to config file (or None or '')
184| fname ~name of config file (can contain path if not file_path)
184| re ~regular expression for tag replacement
184| names ~CSV list of dictionary names to load
184|
184| The new instance loads the JSON file and extracts these top-level fields:
184| version ~required JSON key; always 1
184| comment ~comment text applying to entire file
184| date-created ~date file was created (ctime string)
184| date-updated ~date file last updated (ctim string)
184|
184| The instance also loads two dictionaries from the JSON text:
184| defines ~definitions from JSON file
184| configs ~configurations from JSON file
184|
184| '''
185| self.cnfg_name = kwargs['cfg'] if 'cfg' in kwargs else None
186|
187| self.file_path = KWARG('fpath', '', str, kwargs)
188| self.file_name = KWARG('fname', '', str, kwargs)
189| self.tag_regex = KWARG('re', r'\{([0-9\.\:A-Za-z]+)\}', str, kwargs)
190| self.name_list = KWARG('names', None, str, kwargs)
191| self.noinit = KWARG('noinitialize', 0, int, kwargs)
192| Log.debug(f'JConfiguration()')
193| Log.debug(f'{self.cnfg_name=}')
194| Log.debug(f'{self.file_path=}')
195| Log.debug(f'{self.file_name=}')
196| Log.debug(f'{self.tag_regex=}')
197| Log.debug(f'{self.name_list=}')
198| Log.debug(f'{self.noinit=}')
199| Log.debug()
200| self.cnfg_file = path.join(self.file_path,self.file_name) if self.file_path else self.file_name
201|
202|
203| self.jversion = 1
204| self.comment = 'New Configuration File.'
205| self.created = Now.ctime()
206| self.updated = Now.ctime()
207| self.tag_re = re.compile(self.tag_regex)
208|
209|
210|
211| self.defines = {}
212| self.configs = {'default':type(self).NewSetType('default',{},self)}
213| self.curr_cnfg = self.configs['default']
214| self.curr_index = 0
215|
216|
217| if (self.name_list is not None) and (0 < len(self.name_list)):
218| for name in self.name_list.split(','):
219| setattr(self, name, {})
220|
221|
222|
223| if not self.noinit:
224| self._initialize()
225|
226|
227| @property
228| def name (self): return self.cnfg_name
229|
230| @property
231| def ordinal (self): return self.cnfg_index
232|
233| @property
234| def current (self): return self.curr_cnfg
235|
236| @property
237| def cnfgkeys (self): return list(self.configs)
238|
239| @property
240| def cnfgfile (self): return self.cnfg_file
241|
242| @property
243| def fname (self): return self.file_name
244|
245| @property
246| def fpath (self): return self.file_path
247|
248| def replace_fields (self, txt, maxtry=10):
249| '''Replace tags in txt with defined text.'''
250|
251| tmp = str(txt)
252|
253|
254| for ix in range(maxtry):
255|
256|
257| res = self.tag_re.search(tmp)
258|
259|
260| if res is None:
261| return tmp
262|
263|
264| start,end = res.span()
265| code = res.groups()[0]
266|
267|
268| if code not in self.defines:
269|
270|
271| break
272|
273|
274| repl = self.defines[code][1]
275|
276|
277| tmp = f'{tmp[:start]}{repl}{tmp[end:]}'
278|
279| Log.trace(f'{txt} => {tmp}')
280| return tmp
281|
282| def set_configuration (self, cnfg_name=None, dflt_name=None):
283| '''Load a configuration. Loads "main" or "default" if name is None.'''
284| Log.debug(f'JConfiguration::SetConfiguration({cnfg_name}, {dflt_name})')
285|
286|
287| if (cnfg_name is None) or (len(cnfg_name) == 0):
288|
289| if (dflt_name is not None) and (dflt_name in self):
290| self.cnfg_name = dflt_name
291|
292|
293| elif 'default' in self:
294| self.cnfg_name = 'default'
295|
296|
297| elif 'standard' in self:
298| self.cnfg_name = 'standard'
299|
300|
301| elif 'main' in self:
302| self.cnfg_name = 'main'
303|
304|
305| elif '_' in self:
306| self.cnfg_name = '_'
307|
308|
309| elif '*' in self:
310| self.cnfg_name = '*'
311|
312|
313| else:
314| raise RuntimeError('Unable to find to find a configuration.')
315|
316|
317| else:
318|
319| if cnfg_name not in self:
320| raise RuntimeError(f'Unable to find "{cnfg_name}" configuration.')
321|
322| self.cnfg_name = cnfg_name
323|
324|
325| self.curr_cnfg = self.configs[self.cnfg_name]
326| self.cnfg_index = list(self.configs).index(self.cnfg_name)
327| Log.trace(f'{typename(self)}:CurrentConfig: {self.curr_cnfg.name}')
328| Log.trace()
329|
330| def reload (self, cnfg_name=None):
331| '''Reload the JSON file.'''
332| Log.debug(f'JConfiguration::Reload({cnfg_name})')
333| self._initialize()
334| self.set_configuration(self.cnfg_name)
335|
336| def save_json_file (self, filename):
337| '''Save data to a JSON file.'''
338| Log.debug(f'JConfiguration::SaveFile({filename})')
339| data = self.json_dict
340|
341|
342|
343| if JConfigDateUpdKey in data:
344| data[JConfigDateUpdKey] = datetime.now().ctime()
345|
346|
347| try:
348| fp = open(filename, mode='w', encoding='utf8')
349| json.dump(data, fp, indent=JsonIndent, separators=(',',':'), sort_keys=False)
350| except Exception as e:
351| Log.error()
352| Log.error(e)
353| Log.error('Unable to save JSON file.')
354| Log.error()
355| raise
356| finally:
357| fp.close()
358|
359| @property
360| def json_dict (self):
361| '''Return a JSON saveable dictionary.'''
362|
363| tmp = {
364| 'version': 1,
365| JConfigCommentKey: self.comment,
366| JConfigDateCreKey: self.created,
367| JConfigDateUpdKey: self.updated,
368| JConfigDefinesKey: {n:t for n,t in self.defines.items()},
369| JConfigConfigsKey: {n:cfg.json_dict for n,cfg in self.configs.items()},
370| }
371| if (self.name_list is not None) and (0 < len(self.name_list)):
372| for name in self.name_list.split(','):
373| tmp[name] = getattr(self, name)
374| return tmp
375|
376| def _initialize (self):
377| '''Load JSON file and populate attributes.'''
378| fin = {}
379|
380|
381| if path.exists(self.cnfg_file) and path.isfile(self.cnfg_file):
382| fp = open(self.cnfg_file, mode='rb')
383| try:
384| fin = json.load(fp)
385| except Exception as e:
386| Log.error()
387| Log.error('Unable to load JSON file.')
388| Log.error(e)
389| Log.warn()
390| Log.warn('Continuing with defaults...')
391| Log.warn()
392| finally:
393| fp.close()
394| else:
395| Log.warn()
396| Log.warn('The specificed JSON file does not exist:')
397| Log.warn(self.cnfg_file)
398| Log.warn()
399| Log.warn('Continuing with defaults...')
400| Log.warn()
401|
402|
403| if 'version' in fin: self.jversion = fin['version']
404| if JConfigCommentKey in fin: self.comment = fin[JConfigCommentKey]
405| if JConfigDateCreKey in fin: self.created = fin[JConfigDateCreKey]
406| if JConfigDateUpdKey in fin: self.updated = fin[JConfigDateUpdKey]
407|
408|
409| if JConfigDefinesKey in fin:
410| defs_dict = fin[JConfigDefinesKey]
411| Log.trace('Loading definitions...')
412|
413|
414| for name in defs_dict:
415| label,text = defs_dict[name]
416| self.defines[name] = (label, text)
417| Log.trace(f'definition[{name}]: {label} = "{text}"')
418| Log.trace()
419|
420|
421| if JConfigConfigsKey in fin:
422| cfgs_dict = fin[JConfigConfigsKey]
423| Log.trace('Loading configurations (using {typename(type(self).NewSetType)})...')
424| Log.trace()
425|
426|
427| for name in cfgs_dict:
428| cfg = cfgs_dict[name]
429| cfgset = type(self).NewSetType(name, cfg, self)
430| self.configs[name] = cfgset
431| Log.trace(f'configuration[{name}]: {self.configs[name]}')
432| Log.trace()
433|
434|
435| if (self.name_list is not None) and (0 < len(self.name_list)):
436| Log.trace('Loading named dictionaries...')
437|
438| for name in self.name_list.split(','):
439| Log.trace(f'dictionary: {name}')
440| if name in fin:
441| data = fin[name]
442| setattr(self, name, data)
443| Log.trace(f'> installed: {name}')
444| else:
445| Log.trace(f'> named dictionary "{name}" not found')
446| Log.trace()
447|
448|
449| self.set_configuration(self.cnfg_name)
450|
451| def __len__ (self): return len(self.configs)
452| def __iter__ (self): return iter(self.configs)
453| def __contains__ (self, which): return (which in self.configs)
454| def __bool__ (self): return (0 < len(self.configs))
455|
456| def __getitem__ (self, which):
457| '''Get a configuration by name (or index).'''
458|
459| if isinstance(which,int):
460| which = self._index_to_name(which)
461|
462| return self.configs[which] if which in self.configs else None
463|
464| def __setitem__ (self, which, config):
465| '''Set a configuration by name (or index). NOTE: SILENTLY IGNORES INVALID INDEXES.'''
466|
467| if isinstance(which,int):
468| which = self._index_to_name(which)
469| self.configs[which] = config
470|
471| def __delitem__ (self, which):
472| '''Delete a configuration by name (or index). NOTE: SILENTLY IGNORES INVALID INDEXES.'''
473|
474| if isinstance(which,int):
475| which = self._index_to_name(which)
476| del self.configs[which]
477|
478| def _index_to_name (self, ix):
479| '''Convert an integer index to a configuration name.'''
480| names = list(self.configs.keys())
481| return names[ix] if ix < len(names) else '#NoSuchConfiguration#'
482|
483| def __repr__ (self):
484| return f'<{typename(self)} {len(self)} @{id(self):08x}>'
485|
486| def __str__ (self):
487| curr = lambda k: f'[{k}]' if k == self.cnfg_name else f'{k}'
488| buf = [curr(key) for key in self.configs]
489| return f'JConfigs: <{", ".join(buf)}>'
490|
491|
492|
493| JConfigSettingsPosX = "window.ulc.x"
494| JConfigSettingsPosY = "window.ulc.y"
495| JConfigSettingsDimX = "window.dim.x"
496| JConfigSettingsDimY = "window.dim.y"
497| JConfigSettingsMaxX = "window.max.x"
498| JConfigSettingsMaxY = "window.max.y"
499| JConfigSettingsMinX = "window.min.x"
500| JConfigSettingsMinY = "window.min.y"
501|
502| DfltWndwPosX = JConfigItem.make_dict( 200, 'App window screen X coordinate.', 'To save/restore window position.', 'int')
503| DfltWndwPosY = JConfigItem.make_dict( 100, 'App window screen Y coordinate.', 'To save/restore window position.', 'int')
504| DfltWndwDimX = JConfigItem.make_dict( 800, 'App window initial width.' , 'To save/restore window dimensions.', 'int')
505| DfltWndwDimY = JConfigItem.make_dict( 600, 'App window initial height.', 'To save/restore window dimensions.', 'int')
506| DfltWndwMaxX = JConfigItem.make_dict(2500, 'App window maximum width.' , 'To save/restore window limits.', 'int')
507| DfltWndwMaxY = JConfigItem.make_dict(2000, 'App window maximum height.', 'To save/restore window limits.', 'int')
508| DfltWndwMinX = JConfigItem.make_dict( 480, 'App window minumum width.' , 'To save/restore window limits.', 'int')
509| DfltWndwMinY = JConfigItem.make_dict( 330, 'App window minumum height.', 'To save/restore window limits.', 'int')
510|
511|
512| class JConfigSettingsSet (JConfigSet):
513| '''Basic JSON File Settings Set class.
513|
513| Properties:
513| geometry ~str: tk geometry string
513| wdim,xdim,ydim ~int: initial window dimensions
513| wmin,xmin,ymin ~int: minimum window dimensions
513| wmax,xmax,ymax ~maximum window dimensions
513| wpos,xpos,ypos ~window location on screen
513|
513| Methods:
513| ?
513|
513| '''
514| def __init__ (self, name, cfg, papasan):
515| '''New JConfigSettingsSet instance.'''
516| Log.debug(f'JConfigSettingsSet({name}, {len(cfg)}, {typename(papasan)})')
517| super().__init__(name, cfg, papasan)
518|
519| self.wdw_pos_x = self.getsetparam(JConfigSettingsPosX, DfltWndwPosX)
520| self.wdw_pos_y = self.getsetparam(JConfigSettingsPosY, DfltWndwPosY)
521| self.wdw_dim_x = self.getsetparam(JConfigSettingsDimX, DfltWndwDimX)
522| self.wdw_dim_y = self.getsetparam(JConfigSettingsDimY, DfltWndwDimY)
523| self.wdw_max_x = self.getsetparam(JConfigSettingsMaxX, DfltWndwMaxX)
524| self.wdw_max_y = self.getsetparam(JConfigSettingsMaxY, DfltWndwMaxY)
525| self.wdw_min_x = self.getsetparam(JConfigSettingsMinX, DfltWndwMinX)
526| self.wdw_min_y = self.getsetparam(JConfigSettingsMinY, DfltWndwMinY)
527|
528|
529| @property
530| def xpos (self): return self.wdw_pos_x.value
531|
532| @property
533| def ypos (self): return self.wdw_pos_y.value
534|
535| @property
536| def wpos (self): return (self.wdw_pos_x.value, self.wdw_pos_y.value)
537|
538| @property
539| def xdim (self): return self.wdw_dim_x.value
540|
541| @property
542| def ydim (self): return self.wdw_dim_y.value
543|
544| @property
545| def wdim (self): return (self.wdw_dim_x.value, self.wdw_dim_y.value)
546|
547| @property
548| def geometry (self):
549| return f'{self.xdim}x{self.ydim}+{self.xpos}+{self.ypos}'
550|
551| @property
552| def xmax (self): return self.wdw_max_x.value
553|
554| @property
555| def ymax (self): return self.wdw_max_y.value
556|
557| @property
558| def wmax (self): return (self.wdw_max_x.value, self.wdw_max_y.value)
559|
560| @property
561| def xmin (self): return self.wdw_min_x.value
562|
563| @property
564| def ymin (self): return self.wdw_min_y.value
565|
566| @property
567| def wmin (self): return (self.wdw_min_x.value, self.wdw_min_y.value)
568|
569|
570|
571| class JConfigSettings (JConfiguration):
572| '''Basic JSON File Settings class.
572|
572| Overrides JConfiguration to implement an application settings class
572| for storing and restoring application settings.
572|
572| Class Attributes:
572| NewSetType ~JConfigSettingsSet: type for making a settings set
572|
572| '''
573| NewSetType = JConfigSettingsSet
574|
575| def __init__ (self, **kwargs):
576| '''New JConfigSettings instance.'''
577| Log.debug(f'JConfigSettings()')
578| super().__init__(**kwargs)
579|
580|
581| if 0 < len(self):
582|
583| if 0 < len(self.current):
584|
585| return
586|
587| raise RuntimeError("Didn't expect zero params!")
588|
589| raise RuntimeError("Didn't expect zero config groups!")
590|
591|
592|
593| def print_and_log (text=''):
594| '''Print to screen and to log.'''
595| print(text)
596| Log.info(text)
597|
598|
599| def do_demo_jsettings ():
600| cfg = JConfigSettings(fname='tk-hexd.cnfg', fpath=r'C:\CJS\prj\Python\ws\tk\cfg')
601| print_and_log('Settings:')
602| print_and_log(f'{cfg.cnfgfile}')
603| print_and_log(f'{cfg!s}')
604| print_and_log(f'{cfg!r}')
605| print_and_log()
606| print_and_log('Current Settings:')
607| print_and_log(f'> {cfg.current!s}')
608| print_and_log(f'> {cfg.current!r}')
609| print_and_log(f'> Name: {cfg.name}')
610| print_and_log(f'> Keys: {cfg.cnfgkeys}')
611| print_and_log(f'> Size: {len(cfg.current)}')
612| print_and_log(f'> PKeys: {cfg.current.paramkeys}')
613| if 0 < len(cfg.current.paramkeys):
614| key = cfg.current.paramkeys[0]
615| print_and_log(f'> {cfg.current[key]}')
616| print_and_log(f'> {typename(cfg.current[key])}')
617| print_and_log()
618| print_and_log('Current Configuration Parameters:')
619| for ix,param in enumerate(cfg.current, start=1):
620| print_and_log(f'[{ix:2d}] {param}: {cfg.current[param]}')
621| print_and_log()
622| return cfg
623|
624| def do_demo_jconfig ():
625| cfg = JConfiguration(cfg='default', names='locations', fname=r'C:\CJS\prj\Python\ws\tk\cfg\jconfig.json')
626| print_and_log('Configuration:')
627| print_and_log(f'{cfg.cnfgfile}')
628| print_and_log(f'{cfg!s}')
629| print_and_log(f'{cfg!r}')
630| print_and_log()
631| print_and_log('Current Configuration:')
632| print_and_log(f'> {cfg.current!s}')
633| print_and_log(f'> {cfg.current!r}')
634| print_and_log(f'> Name: {cfg.name}')
635| print_and_log(f'> Keys: {cfg.cnfgkeys}')
636| print_and_log(f'> Size: {len(cfg.current)}')
637| print_and_log(f'> PKeys: {cfg.current.paramkeys}')
638| if 0 < len(cfg.current.paramkeys):
639| key = cfg.current.paramkeys[0]
640| print_and_log(f'> {cfg.current[key]}')
641| print_and_log(f'> {typename(cfg.current[key])}')
642| print_and_log()
643| print_and_log('Current Configuration Parameters:')
644| for ix,param in enumerate(cfg.current, start=1):
645| print_and_log(f'{ix:2d}: {param} = {cfg.current[param]}')
646| print_and_log()
647| if hasattr(cfg, 'locations'):
648| print_and_log('Locations:')
649| for ix,loc in enumerate(cfg.locations, start=1):
650| print_and_log(f'{ix:2d}: {loc} {cfg.locations[loc]}')
651| print_and_log()
652| print_and_log()
653| return cfg
654|
655| def do_test_blank ():
656| cfg = JConfiguration.get_blank_config()
657| print_and_log(cfg)
658| print_and_log(cfg.current)
659| print_and_log(cfg.current.paramkeys)
660| Log.info(cfg)
661| return cfg
662|
663| if __name__ == '__main__':
664| print(f'autorun: {argv[0]}')
665| print()
666| Log.start(r'C:\CJS\prj\Python\ws\tk\jconfig.log')
667| Log.level(trace())
668| Log.info(f'autorun: {argv[0]}')
669| Log.info()
670| try:
671| cfg = do_demo_jsettings()
672| print_and_log(f'Settings demo returned:')
673| print_and_log(f'> {cfg}')
674| print_and_log()
675| print_and_log()
676| cfg = do_demo_jconfig()
677| print_and_log(f'Configuration demo returned:')
678| print_and_log(f'> {cfg}')
679| print_and_log()
680| print_and_log()
681|
682|
683|
684|
685|
686| cfg.save_json_file(r'C:\CJS\prj\Python\ws\tk\test.json')
687| print_and_log()
688| print_and_log()
689| except Exception as e:
690| Log.error(e)
691| raise
692| finally:
693| Log.end()
694| print()
695|
696| '''eof'''
697|