tk-exec.html
001| """Tk-Exec. A new version of CJS-Exec using the Python Tk toolkit.
001|
001| Classes:
001| Application ~implements th Tk application.
001| ExecConfigFile (JConfiguration) ~implements the button configuration
001| Configuration (JConfigSet) ~implements a single 10-button configuration
001| Command (JConfigItem) ~implements a single button's command
001| LaunchDialog (Dialog) ~implements the Launch Program dialog
001|
001| Functions:
001| keypress_states (state) ~return text flags from state
001|
001| Data:
001| JConfigCommandsKey ~str: config file "commands" key
001| FileTypes ~list of filetypes for open/save dialogs
001| AboutText ~str: text for About msgbox
001| <name>Key ~settings file parameter names
001| Dflt<name> ~default settings parameters
001|
001| Commands:
001| main do_main ~start the Tk GUI app
001| test do_test ~test
001|
001| TODO! Edit Configuration dialog
001| TODO: implement File/New
001| TODO: implement File/Open...
001| TODO: implement File/Save
001| TODO: implement File/Save As...
001| TODO: implement Edit/Copy
001| TODO: implement Edit/Paste
001| """
002|
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path, getcwd
006| from datetime import datetime
007| import subprocess
008| import re
009| import tkinter as tk
010| import tkinter.ttk as ttk
011| import tkinter.filedialog as dialog
012| import tkinter.messagebox as msgbox
013| import tkinter.simpledialog as simdia
014| from logger import logger,info,debug,trace, LogFilenameTimestamp
015| from goodies import typename, KWARG, makefilename, isreallyafile, marker
016| from dates import UTC, CST
017| import jconfig as jcfg
018| import tkutil as util
019|
020| BasePath = r'C:\CJS\prj\Python\app\tk'
021| CnfgPath = path.join(BasePath, 'cfg')
022| DataPath = path.join(BasePath, 'dat')
023| ListPath = path.join(BasePath, 'out')
024| CnfgName = 'tk-exec.json'
025| CnfgEditor = r"C:\\Program Files\\Vim\\vim91\\gvim.exe"
026| Log = logger('Tk-Exec')
027| Now = datetime.now(CST())
028|
029| CMND = ''
030| ARGS = {
031|
032|
033|
034|
035| }
036| bag = {}
037|
038|
039| FileTypes = [
040| ('JSON files', '*.json'),
041| ('CNFG files', '*.cnfg'),
042| ('CJS files', '*.cjs'),
043| ("all files", "*")
044| ]
045|
046|
047| AboutText = '''\
047| "Exec" — Configurable Windows Launch Platform.
047|
047| First there were .BAT file to automate frequently
047| performed tasks. I wanted something more flexible,
047| so I wrote PerlPad in Windows C++ and the first
047| version of Exec in MS Visual BASIC. Exec no longer
047| works, but PerlPad is a frequently used tool.
047|
047| But I missed Exec and finally got around to using
047| Python's Tk and ttk modules to recreate it. Yay!
047|
047| © CJSonnack November 2025
047| '''
048|
049|
050| JConfigCommandsKey = 'commands'
051|
052|
053| class Command (jcfg.JConfigItem):
054| '''Command class. Implements a single button's command.
054|
054| A class for containing the data associated with launching
054| an application as well as text and image identifiers.
054|
054| Attributes:
054| papasan ~ExecConfigFile: our parent
054| name ~str: name of the command
054| label ~str: label for command button
054| exec ~str: executable filename
054| args ~str: arguments for app
054| wdir ~str: working directory
054| icon ~str: icon (path) for button image
054| verb ~str: windows verb (unused)
054|
054| Methods:
054| execute ~subprocess.retv: execute this command
054|
054| repr(obj) ~str: debug representation
054| str(obj) ~str: official representation
054|
054| NOTE: Might want to link the TkButton to its instance.
054| '''
055| def __init__ (self, cmd, papasan):
056| '''New ExecConfigFile.Command instance.'''
057| Log.debug(f'Command({len(cmd)}, {typename(papasan)})')
058| super().__init__(cmd, papasan)
059|
060| self.name = cmd['name']
061| self.label = cmd['label']
062| self.icon = cmd['icon']
063| self.verb = cmd['verb']
064| self.exec = self.xformer(cmd['exec'])
065| self.wdir = self.xformer(cmd['wdir'])
066| self.args = [self.xformer(arg) for arg in cmd['args']]
067|
068|
069| if self.wdir == '$args': self.wdir = self.args[0]
070|
071| def execute (self, **kwargs):
072| '''Execute this command.'''
073| Log.trace(f'Command.execute({self.label})...')
074| Log.trace(f'> exec: "{self.exec}"')
075| Log.trace(f'> args: "{self.args}"')
076| Log.trace(f'> wdir: "{self.wdir}"')
077|
078| props = dict(cwd=self.wdir)
079| retv = subprocess.Popen([self.exec]+self.args, **props)
080| Log.trace(f'= {retv}')
081| return retv
082|
083| def xformer (self, txt_in):
084| '''Transformer. Does field replacements.'''
085| txt_out = self.papasan.replace_fields(txt_in)
086| Log.trace(f'Command.xformer: {txt_in} => {txt_out}')
087| return txt_out
088|
089| def __repr__ (self):
090| return f'<{typename(self)} {self.name} @{id(self):08x}>'
091|
092| def __str__ (self):
093| return f'{self.name} "{self.label}" <{self.exec} {self.args}>'
094|
095|
096| class Configuration (jcfg.JConfigSet):
097| '''Configuration class. Implements a single 10-button configuration.
097|
097| A container class for ten Command instances. An instance takes a configuration
097| dictionary from the JSON file data and parses it to populate the instance fields.
097|
097| Attributes:
097| papasan ~ExecConfigFile: our parent
097| name ~str: name of the configuration [JSON field]
097| descrip ~str: config description [JSON field]
097| comment ~str: config comment [JSON field]
097| dtcr ~str: config created date (ctime) [JSON field]
097| dtup ~str: config updated date (ctime) [JSON field]
097| visi ~int: whether this config is visible in pick lists
097| params ~list: the ten commandments for this config
097|
097| Properties:
097| visible ~bool: whether this config is visible in pick lists
097|
097| Methods:
097| bool(obj) ~bool: True if has commands
097| len(obj) ~int: number of commands (always ten)
097| iter(obj) ~iter: iterator over commands
097| name in obj ~bool: True if name in commands
097| obj[name] ~Command: index command (get, set, del)
097| repr(obj) ~str: debug representation
097| str(obj) ~str: official representation
097|
097| '''
098| def __init__ (self, name, cfg, papasan):
099| '''New Configuration instance.'''
100| Log.debug(f'Configuration({name}, {len(cfg)}, {typename(papasan)})')
101| Log.debug()
102| super().__init__(name, cfg, papasan)
103|
104|
105| if len(cfg) == 0:
106| return
107|
108|
109| cmds = cfg[JConfigCommandsKey]
110| self.commands = [Command(cmd, papasan) for cmd in cmds]
111|
112| def __len__ (self): return len(self.commands)
113| def __iter__ (self): return iter(self.commands)
114| def __bool__ (self): return 0 < len(self.commands)
115|
116| def __getitem__ (self, ix): return self.commands[ix]
117| def __setitem__ (self, ix, param): self.commands[ix] = param
118| def __delitem__ (self, ix): del self.commands[ix]
119|
120|
121| class ExecConfigFile (jcfg.JConfiguration):
122| '''CJS-Exec program launcher configuration file class.
122|
122| Instances automagically load the JSON configuration file and process its
122| data to populate the instance attributes. The central player here is the
122| configurations dictionary containing all configurations. The instance
122| also maintains user-changable "current" configuration and can execute
122| commands 0-9 through it.
122|
122| Attributes:
122| cnfg_name ~str: name of current configuration
122| jversion ~int: "version" key from JSON file (always 1)
122| comment ~str: JSON file main comment field
122| created ~str: JSON file created date field (ctime)
122| updated ~str: JSON file updated date field (ctime)
122| configs ~dict: configurations from JSON file
122| defines ~dict: definitions from JSON file
122| images ~dict: icon and image paths from JSON file
122|
122| Properties:
122| name ~str: name of current config
122| current ~dict: current config
122| cfgskeys ~list: config keys
122| defs_keys ~list: definition keys
122|
122| Methods:
122| execute_command ~subprocess.retv: execute a command in curr config
122| get_command ~Configuration: command[ix] in the current config
122| set_configuration ~None: load a configuration by name
122| replace_fields ~str: replace tags in txt with defined text
122|
122| '''
123| NewSetType = Configuration
124|
125| def __init__ (self, cnfg_name=None, fname=CnfgName, fpath=CnfgPath):
126| '''New ExecConfigFile instance.'''
127| Log.debug(f'ExecConfigFile({cnfg_name})')
128| Log.debug(f'self.NewSetType = {typename(self.NewSetType)}')
129|
130|
131| super().__init__(cfg=cnfg_name, names='images', fname=fname, fpath=fpath)
132|
133| @property
134| def defs_keys (self): return list(self.defines)
135|
136| def get_command (self, ix):
137| '''Return command in the current configuration.'''
138| return self.current[ix]
139|
140| def execute_command (self, ix, **kwargs):
141| '''Execute a command in the current configuration.'''
142| return self.current[ix].execute(**kwargs)
143|
144| def __repr__ (self):
145| return f'<{typename(self)} {len(self)} @{id(self):08x}>'
146|
147| def __str__ (self):
148| curr = lambda k: f'[{k}]' if k == self.cnfg_name else f'{k}'
149| buf = [curr(key) for key in self.configs]
150| return f'Exec Configs: <{", ".join(buf)}>'
151|
152|
153|
154| '''Keys to settings file parameters (parameter names).'''
155| UltimateKey = 'hitch.hiker'
156| CnfgNameKey = 'curr.cnfgname'
157| CnfgFileKey = 'curr.cnfgfile'
158| LastCmndKey = 'last.cmnd.name'
159| LastArgsKey = 'last.cmnd.args'
160| LastCwdKey = 'last.cmnd.cwd'
161|
162| '''Default dictionaries for supplying default parameters.'''
163| DfltUltimate = jcfg.JConfigItem.make_dict(42, "The ultimate answer!", "But what's the question?", 'int')
164| DfltCnfgName = jcfg.JConfigItem.make_dict('default', "Last-used configuration name.", "Part of state persistence.", 'str')
165| DfltCnfgFile = jcfg.JConfigItem.make_dict('<unknown>', "Last-used configuration file.", "Part of state persistence.", 'str')
166| DfltLastCmnd = jcfg.JConfigItem.make_dict('{gvim}', "Last-used command filename.", "Part of state persistence.", 'str')
167| DfltLastArgs = jcfg.JConfigItem.make_dict('', "Last-used command arguments.", "Part of state persistence.", 'str')
168| DfltLastCwd = jcfg.JConfigItem.make_dict('', "Last-used command working dir.", "Part of state persistence.", 'str')
169|
170|
171| class AppConfigSet (jcfg.JConfigSettingsSet):
172| '''Settings class for Exec.
172|
172| Attributes:
172| config_name ~JConfigItem: Last-used configuration name
172| config_filename ~JConfigItem: Last-used configuration filename
172| last_cmnd_name ~JConfigItem: Last-used command filename
172| last_cmnd_args ~JConfigItem: Last-used command args
172| last_cmnd_cwd ~JConfigItem: Last-used command cwd
172|
172| Properties:
172| cnfgname ~str: Last-used configuration name
172| cnfgfile ~str: Last-used configuration filename
172|
172| '''
173|
174| def __init__ (self, name, params, papasan):
175| '''New AppConfigSet instance.'''
176| Log.debug(f'AppConfigSet({name}, {params}, {typename(papasan)})')
177| super().__init__(name, params, papasan)
178|
179| self.ultimate = self.getsetparam(UltimateKey , DfltUltimate)
180| self.config_name = self.getsetparam(CnfgNameKey , DfltCnfgName)
181| self.config_filename = self.getsetparam(CnfgFileKey , DfltCnfgFile)
182| self.last_cmnd_name = self.getsetparam(LastCmndKey , DfltLastCmnd)
183| self.last_cmnd_args = self.getsetparam(LastArgsKey , DfltLastArgs)
184| self.last_cmnd_cwd = self.getsetparam(LastCwdKey , DfltLastCwd)
185|
186| @property
187| def cnfgname (self): return self.config_name.value
188|
189| @property
190| def cnfgfile (self): return self.config_filename.value
191|
192| @property
193| def lastcmnd (self): return self.last_cmnd_name.value
194|
195| @property
196| def lastargs (self): return self.last_cmnd_args.value
197|
198| @property
199| def lastcwd (self): return self.last_cmnd_cwd.value
200|
201|
202| class AppSettings (jcfg.JConfigSettings):
203| '''Configuration class for GREP.'''
204|
205|
206| NewSetType = AppConfigSet
207|
208| def __init__ (self, **kwargs):
209| '''New AppSettings instance.'''
210| Log.debug(f'AppSettings()')
211| super().__init__(**kwargs)
212|
213|
214|
215| class Application:
216| '''Application class - Implements a Tk application.
216|
216| Attributes:
216| config_fpath ~str: path to configuration file (or '')
216| config_fname ~str: name of configuration file to hexdump (may include path)
216| config ~ExecConfigFile: button definitions
216| settings_path ~str: path to settings file (or '')
216| settings_name ~str: name of settings file (may include path)
216| opts ~str: name of settings configuration to use
216| settings ~JConfigSettings: application options object
216| title ~str: window title
216| root ~Tk: application window root
216| wndw ~Frame: frame for entire window
216| main ~Frame: frame for application window
216| statusbar ~Frame: frame for statusbar
216| btn[0-9X] ~Button: Command buttons 0-9 and Exit button
216| buttons ~list: contains btn0 - btn9 (not btnX)
216| lbl_status ~Label: text for statusbar
216| mbar ~Menu: the menubar
216| mbarFile ~Menu: File submenu
216| mbarEdit ~Menu: Edit submenu
216| mbarView ~Menu: View submenu
216| mbarHelp ~Menu: Help submenu
216|
216| Methods:
216| execute_command ~launch application (from button click or F# key)
216| launch_program ~launch application (user input)
216| change_config ~load a new configuration into the buttons
216| load_button_config ~set buttons configuration
216|
216| app_exit ~exit application; destory window(s)
216| app_command_# ~click Command-# Button (0-9)
216| app_keypress ~application key handler
216| update_status ~update text in statusbar
216|
216| file_new ~menu:File/New
216| file_open ~menu:File/Open...
216| file_save ~menu:File/Save
216| file_save_as ~menu:File/Save As...
216| file_reload ~menu:File/Reload JSON File
216| file_edit_json ~menu:File/Edit JSON
216| edit_copy ~menu:Edit/Copy
216| edit_paste ~menu:Edit/Paste
216| edit_config_file ~menu:Edit/Configuration File
216| view_info ~menu:View/Info
216| help_about ~menu:Help/About
216|
216| _create_widgets ~create various widgets
216| _create_menubar ~create menubar
216| '''
217| def __init__ (self, **kwargs):
218| '''New Application instance.'''
219| self.title = KWARG('title', 'Tk Exec', str, kwargs)
220| self.cfg = KWARG('cfg', '', str, kwargs)
221| self.config_fname = KWARG('fname', 'tk-exec.json', str, kwargs)
222| self.config_fpath = KWARG('fpath', CnfgPath, str, kwargs)
223| self.opts = KWARG('opts', 'default', str, kwargs)
224| self.settings_name = KWARG('sname', 'tk-exec.cnfg', str, kwargs)
225| self.settings_path = KWARG('spath', CnfgPath, str, kwargs)
226| Log.info(f'Tk-Exec.app::{str(list(kwargs.keys()))}')
227| Log.info(f'{self.cfg=}')
228| Log.debug(f'{self.config_fname=}')
229| Log.debug(f'{self.config_fpath=}')
230| Log.debug(f'{self.opts=}')
231| Log.debug(f'{self.settings_name=}')
232| Log.debug(f'{self.settings_path=}')
233| Log.debug(f'{self.title=}')
234| Log.info()
235|
236| self.settings = AppSettings(cfg=self.opts, fname=self.settings_name, fpath=self.settings_path)
237| Log.debug(f'settings: {self.settings!r}')
238| Log.debug(f'> current: {self.settings.name}')
239| Log.debug(f'> configs: {self.settings.cnfgkeys}')
240| Log.debug(f'> currcnfg: {self.settings.current!r}')
241| Log.debug(f'> parmkeys: {self.settings.current.paramkeys}')
242| Log.debug(f'> wndwpos: {self.settings.current.xpos:4d}x{self.settings.current.ypos:4d}')
243| Log.debug(f'> wndwdim: {self.settings.current.xdim:4d}x{self.settings.current.ydim:4d}')
244| Log.debug(f'> wndwmin: {self.settings.current.xmin:4d}x{self.settings.current.ymin:4d}')
245| Log.debug(f'> wndwmax: {self.settings.current.xmax:4d}x{self.settings.current.ymax:4d}')
246| Log.debug(f'> cnfgname: {self.settings.current.cnfgname}')
247| Log.debug(f'> cnfgfile: {self.settings.current.cnfgfile}')
248| Log.debug(f'> lastcmnd: {self.settings.current.lastcmnd}')
249| Log.debug(f'> lastargs: {self.settings.current.lastargs}')
250| Log.debug(f'> lastcwd: {self.settings.current.lastcwd}')
251| Log.debug()
252|
253|
254| if self.cfg:
255| Log.info(f'Commandline overrides Config-Name: {self.cfg}')
256| self.settings.current[CnfgNameKey].value = self.cfg
257| else:
258| self.cfg = self.settings.current.cnfgname
259|
260| if self.config_fname:
261| Log.info(f'Commandline overrides Config-Filename: {self.config_fname}')
262| self.filename = makefilename(self.config_fpath, self.config_fname)
263| self.settings.current[CnfgFileKey].value = self.filename
264| else:
265| self.filename = self.settings.current.cnfgfile
266| self.config_fpath = path.dirname(self.filename)
267| self.config_fname = path.basename(self.filename)
268|
269|
270| if isreallyafile(self.filename):
271| self.config= ExecConfigFile(self.cfg, fname=self.filename, fpath='')
272| Log.debug(f'Configuration: {self.config}')
273| Log.debug(f'Configuration: {self.config.name}')
274| Log.debug(f'Configuration: {self.config.cnfgkeys}')
275| Log.debug(f'Current.Config: {self.config.current}')
276| Log.debug()
277| else:
278| raise RuntimeError('No configuration file.')
279|
280|
281| self._create_widgets()
282| self._create_menubar()
283| self.load_button_config()
284| self.update_status(self.cfg, '#ffcc33')
285| Log.debug('Application initialization complete.')
286| Log.debug()
287|
288| def app_exit (self, *args):
289| '''Exit application; destory window(s).'''
290| Log.debug('Exit()')
291| maxsize = self.root.wm_maxsize()
292| minsize = self.root.wm_minsize()
293| geo = util.TkGeometry.from_string(self.root.wm_geometry())
294|
295| self.settings.current[jcfg.JConfigSettingsPosX].value = geo.xpos
296| self.settings.current[jcfg.JConfigSettingsPosY].value = geo.ypos
297| self.settings.current[jcfg.JConfigSettingsDimX].value = geo.xdim
298| self.settings.current[jcfg.JConfigSettingsDimY].value = geo.ydim
299| self.settings.current[jcfg.JConfigSettingsMaxX].value = maxsize[0]
300| self.settings.current[jcfg.JConfigSettingsMaxY].value = maxsize[1]
301| self.settings.current[jcfg.JConfigSettingsMinX].value = minsize[0]
302| self.settings.current[jcfg.JConfigSettingsMinY].value = minsize[1]
303| self.settings.current[CnfgNameKey].value = self.config.name
304|
305|
306| fn = makefilename(self.settings_path, self.settings_name)
307| self.settings.save_json_file(fn)
308|
309|
310| self.root.destroy()
311|
312| def app_test (self, *args):
313| '''For testing.'''
314| Log.trace(f'Test({list2str(args,",")})')
315|
316| def launch_program (self, *args):
317| '''Launch program from user input.'''
318| Log.debug(f'LaunchProgram()')
319|
320| cmnd = self.settings.current.lastcmnd
321| args = self.settings.current.lastargs
322| cwd = self.settings.current.lastcwd
323| dlg = LaunchDialog(self.root, cmnd,args,cwd)
324| Log.debug(f'LaunchDialog returned: {dlg.retv}')
325| if not dlg.retv:
326| return
327| Log.debug(f'Command: {dlg.cmnd}')
328| Log.debug(f'Args: {dlg.args}')
329| Log.debug(f'CWD: {dlg.cwd}')
330| Log.debug()
331| cmnd = self.config.replace_fields(dlg.cmnd)
332| args = self.config.replace_fields(dlg.args)
333| cwd = self.config.replace_fields(dlg.cwd)
334| Log.info(f'Command: {cmnd}')
335| Log.info(f'Args: {args}')
336| Log.info(f'CWD: {cwd}')
337| Log.info()
338| self.update_status(f'{cmnd} {args}')
339| retv = subprocess.Popen([cmnd, *args.split()], cwd=cwd)
340| Log.trace(f'{retv=}:{typename(retv)}')
341| Log.trace()
342|
343| self.settings.current[LastCmndKey].value = dlg.cmnd
344| self.settings.current[LastArgsKey].value = dlg.args
345| self.settings.current[LastCwdKey].value = dlg.cwd
346|
347| def execute_command (self, cmd_index):
348| '''Execute Command Handler -- used by all buttons.'''
349| Log.debug(f'ExecuteCommand({cmd_index})')
350| cmnd = self.config.get_command(cmd_index)
351| retv = self.config.execute_command(cmd_index)
352| Log.trace(f'{cmnd=!s}')
353| Log.trace(f'{retv.returncode=}')
354| Log.trace(f'{retv.args=}')
355| Log.trace()
356| self.update_status(f'{cmnd.label}')
357|
358| def change_config (self, cnfg_name):
359| '''Load a new configuration into the buttons.'''
360| Log.debug(f'ChangeConfig({cnfg_name})')
361| self.cfg = cnfg_name
362| self.config.set_configuration(self.cfg)
363| self.load_button_config()
364| self.update_status(self.cfg)
365|
366| def load_button_config (self):
367| '''Use config-name to set current buttons configuration.'''
368| Log.info(f'Load-Button-Configuration({self.config.current})')
369| Log.info()
370| for ix,cmd in enumerate(self.config.current):
371|
372| Log.info(f'{ix}: {cmd}')
373| self.buttons[ix]['text'] = f'F{ix+1} {cmd.label}'
374| Log.info()
375|
376| def update_status (self, text, color='#ffffff'):
377| '''Update the text in the statusbar.'''
378| self.lbl_status['text'] = text
379| self.lbl_status.configure(foreground=color)
380|
381| def file_new (self, *args):
382| '''New configuration. Clear all configurations!'''
383| Log.debug(f'File/New()')
384| self.txt_output.configure(state='normal')
385| self.txt_output.delete('1.0', 'end')
386| self.txt_output.configure(state='disabled')
387| self.update_status('<new>')
388|
389|
390| def file_open (self, *args):
391| '''Menu: File/Open... (JSON file).'''
392| Log.debug(f'File/Open()')
393| props = dict(
394| parent=self.root,
395| title="Select a file...",
396| filetypes=FileTypes,
397| initialdir=self.config_fpath,
398| initialfile=self.config_fname,
399| )
400| retv = dialog.askopenfile(**props)
401| Log.trace(f'{retv=}:{typename(retv)}')
402| if retv:
403| self.update_status(retv.name, '#7fffff')
404| content = retv.read()
405| Log.info(content)
406|
407|
408| def file_save (self, *args):
409| '''Menu: File/Save (JSON file).'''
410| Log.debug(f'File/Save()')
411|
412|
413|
414| def file_save_as (self, *args):
415| '''Menu: File/Save As... (JSON file).'''
416| Log.debug(f'File/SaveAs()')
417| props = dict(
418| parent=self.root,
419| title="Enter new filename...",
420| filetypes=FileTypes,
421| initialdir=self.config_fpath,
422| initialfile=self.config_fname,
423| )
424| retv = dialog.asksaveasfilename(**props)
425| Log.trace(f'{retv=}:{typename(retv)}')
426| if retv:
427| filename = retv
428| self.update_status(filename, '#ffff7f')
429|
430|
431|
432| def file_reload (self, *args):
433| '''Menu: File/Reload (JSON file).'''
434| Log.debug(f'File/Reload()')
435|
436| cnfg_name = self.config.name
437| self.config.reload()
438| self.change_config(cnfg_name)
439| self.load_button_config()
440| self.update_status(self.cfg, '#ffcc33')
441|
442| def file_edit_json (self, *args):
443| '''Menu: File/Edit JSON. Shell to GVim to edit JSON file.'''
444| Log.debug(f'File/Edit JSON()')
445| filename = self.config.cnfgfile
446| self.update_status(filename, '#ffcc33')
447| retv = subprocess.Popen([CnfgEditor, filename], cwd=BasePath)
448| Log.trace(f'{retv=}')
449|
450| def edit_copy (self, *args):
451| '''Menu: Edit/Copy handler.'''
452| Log.debug(f'Edit/Copy()')
453|
454|
455| def edit_paste (self, *args):
456| '''Menu: Edit/Paste handler.'''
457| Log.debug(f'Edit/Paste()')
458|
459|
460| def edit_config_file (self, *args):
461| '''Menu: Edit/Configuration. Edit current configuration.'''
462| Log.debug(f'Edit/Configuration()')
463|
464|
465| msgbox.showwarning('Edit Configuration', 'Not Implemented Yet! (NIY)')
466|
467| def view_info (self, *args):
468| '''Menu: View/Info message box.'''
469| Log.debug(f'View/Info()')
470| curr = self.config.current
471| buff = [
472| f'Name: {curr.name}{" (*)" if curr.visible else ""}',
473| f'Desc: {curr.descrip}',
474| f'Note: {curr.comment}',
475| '',
476| f'Created: {curr.dtcr}',
477| f'Updated: {curr.dtup}',
478| '',
479| ]
480| text = '\n'.join(buff)
481| msgbox.showinfo('Configuration Info', text)
482|
483| def help_about (self, *args):
484| '''Menu: Help/About message box.'''
485| Log.debug('Help/About()')
486| msgbox.showinfo('About Tk-Exec', AboutText)
487|
488| def help_app_info (self, *args):
489| '''Menu: Help/Info message box.'''
490| Log.debug('Help/Info()')
491|
492| msgbox.showinfo('How to use Tk-Exec', '<TBD>')
493|
494| def app_command_0 (self, *args):
495| '''Click Command-0 Button.'''
496| Log.trace(f'Command-0()')
497| self.execute_command(0)
498|
499| def app_command_1 (self, *args):
500| '''Click Command-1 Button.'''
501| Log.trace(f'Command-1()')
502| self.execute_command(1)
503|
504| def app_command_2 (self, *args):
505| '''Click Command-2 Button.'''
506| Log.trace(f'Command-2()')
507| self.execute_command(2)
508|
509| def app_command_3 (self, *args):
510| '''Click Command-3 Button.'''
511| Log.trace(f'Command-3()')
512| self.execute_command(3)
513|
514| def app_command_4 (self, *args):
515| '''Click Command-4 Button.'''
516| Log.trace(f'Command-4()')
517| self.execute_command(4)
518|
519| def app_command_5 (self, *args):
520| '''Click Command-5 Button.'''
521| Log.trace(f'Command-5()')
522| self.execute_command(5)
523|
524| def app_command_6 (self, *args):
525| '''Click Command-6 Button.'''
526| Log.trace(f'Command-6()')
527| self.execute_command(6)
528|
529| def app_command_7 (self, *args):
530| '''Click Command-7 Button.'''
531| Log.trace(f'Command-7()')
532| self.execute_command(7)
533|
534| def app_command_8 (self, *args):
535| '''Click Command-8 Button.'''
536| Log.trace(f'Command-8()')
537| self.execute_command(8)
538|
539| def app_command_9 (self, *args):
540| '''Click Command-9 Button.'''
541| Log.trace(f'Command-9()')
542| self.execute_command(9)
543|
544| def app_keypress (self, evt):
545| '''Application key handler.
545|
545| Key Bindings:
545| File/New Ctrl+N
545| File/Open Ctrl+O
545| File/Reload Ctrl+R
545| File/Save Ctrl+S
545| File/Save As Alt+S
545| File/Edit JSON Ctrl+J
545| File/Exit Alt+X
545| Edit/Copy Ctrl+C
545| Edit/Paste Ctrl+V
545| Edit/Configuration Alt+E
545| Launch Program Alt+L
545| View/Info
545| Help/About
545| Help/Info Shift+I
545|
545| '''
546| name = evt.keysym
547| code = evt.keycode
548| state = evt.state
549| flags = util.keypress_states(state)
550| Log.debug(f'app.KeyPress(<{name} {flags} [{state:08x}] ({code})>, {evt.serial})')
551|
552|
553| if evt.state & util.KEYPRESS_ALT:
554| if evt.keysym in ['E','e']:
555| self.edit_config_file()
556| return
557| if evt.keysym in ['L','l']:
558| self.launch_program()
559| return
560| if evt.keysym in ['S','s']:
561| self.file_save_as()
562| return
563| if evt.keysym in ['X','x']:
564| self.app_exit('Alt-X')
565| return
566|
567| return
568|
569|
570| if evt.state & util.KEYPRESS_CTRL:
571|
572| numkeys = ['1','2','3','4','5','6','7','8','9','0']
573| if evt.keysym in numkeys:
574| ix = numkeys.index(evt.keysym)
575| nm = self.config[ix]
576| self.change_config(nm)
577| return
578|
579| if evt.keysym in ['J','j']:
580| self.file_edit_json()
581| return
582| if evt.keysym in ['N','n']:
583| self.file_new()
584| return
585| if evt.keysym in ['O','o']:
586| self.file_open()
587| return
588| if evt.keysym in ['S','s']:
589| self.file_save()
590| return
591| if evt.keysym in ['R','r']:
592| self.file_reload()
593| return
594|
595| return
596|
597|
598| if evt.state & util.KEYPRESS_SHIFT:
599| if evt.keysym in ['I','i']:
600| self.help_app_info()
601| return
602|
603| return
604|
605|
606|
607|
608| def _create_widgets (self):
609| '''Create various widgets.'''
610| Log.info('Create Widgets...')
611|
612|
613| Log.info('Create Window...')
614| self.root = tk.Tk()
615| self.root.title(self.title)
616| self.root.geometry(self.settings.current.geometry)
617| self.root.minsize(*self.settings.current.wmin)
618| self.root.maxsize(*self.settings.current.wmax)
619|
620| self.root.bind('<Escape>' , self.app_exit)
621| self.root.bind('<F1>' , self.app_command_0)
622| self.root.bind('<F2>' , self.app_command_1)
623| self.root.bind('<F3>' , self.app_command_2)
624| self.root.bind('<F4>' , self.app_command_3)
625| self.root.bind('<F5>' , self.app_command_4)
626| self.root.bind('<F6>' , self.app_command_5)
627| self.root.bind('<F7>' , self.app_command_6)
628| self.root.bind('<F8>' , self.app_command_7)
629| self.root.bind('<F9>' , self.app_command_8)
630| self.root.bind('<F10>' , self.app_command_9)
631| self.root.bind('<KeyPress>' , self.app_keypress)
632|
633| ttk.Style().configure('Status.TLabel',
634| background='#000000', foreground='#ffffff', relief='flat',
635| font=('Segoe UI Variable',10), justify='left', ipadx=4, padding=(0,0)
636| )
637| ttk.Style().configure('Command.TButton',
638| foreground='#000000', relief='raised',
639| font=('Segoe UI Variable',10), anchor='w', ipadx=4, padding=(8,0)
640| )
641| ttk.Style().configure('Quit.TButton',
642| foreground='#000000', relief='raised',
643| font=('Segoe UI Variable',11,'bold'), ipadx=4, padding=(0,0)
644| )
645|
646|
647| self.wndw = tk.Frame(self.root, bg='#000000', relief='groove')
648| self.wndw.pack(side='top', fill='both', expand=True, padx=4, pady=4)
649|
650| self.main = tk.Frame(self.wndw, bg='#336699', relief='sunken')
651| self.main.pack(side='top', anchor='s', fill='both', expand=True, padx=2, pady=2)
652|
653| self.btn0 = ttk.Button(self.main, text="Command 0", width=30, command=self.app_command_0, style='Command.TButton')
654| self.btn1 = ttk.Button(self.main, text="Command 1", width=30, command=self.app_command_1, style='Command.TButton')
655| self.btn2 = ttk.Button(self.main, text="Command 2", width=30, command=self.app_command_2, style='Command.TButton')
656| self.btn3 = ttk.Button(self.main, text="Command 3", width=30, command=self.app_command_3, style='Command.TButton')
657| self.btn4 = ttk.Button(self.main, text="Command 4", width=30, command=self.app_command_4, style='Command.TButton')
658| self.btn5 = ttk.Button(self.main, text="Command 5", width=30, command=self.app_command_5, style='Command.TButton')
659| self.btn6 = ttk.Button(self.main, text="Command 6", width=30, command=self.app_command_6, style='Command.TButton')
660| self.btn7 = ttk.Button(self.main, text="Command 7", width=30, command=self.app_command_7, style='Command.TButton')
661| self.btn8 = ttk.Button(self.main, text="Command 8", width=30, command=self.app_command_8, style='Command.TButton')
662| self.btn9 = ttk.Button(self.main, text="Command 9", width=30, command=self.app_command_9, style='Command.TButton')
663| self.bbut = tk.Frame(self.main)
664| self.btnX = ttk.Button(self.bbut, text="Exit" , command=self.app_exit , style='Quit.TButton')
665| self.btnL = ttk.Button(self.bbut, text="Launch", command=self.launch_program, style='Quit.TButton')
666|
667| packprops = dict(side='top', fill='both', expand=True, padx=0, pady=1)
668| self.btn0.pack(**packprops)
669| self.btn1.pack(**packprops)
670| self.btn2.pack(**packprops)
671| self.btn3.pack(**packprops)
672| self.btn4.pack(**packprops)
673| self.btn5.pack(**packprops)
674| self.btn6.pack(**packprops)
675| self.btn7.pack(**packprops)
676| self.btn8.pack(**packprops)
677| self.btn9.pack(**packprops)
678|
679| self.btnX.pack(side='left', anchor='w', fill='both', expand=True, padx=0, pady=0)
680| self.btnL.pack(side='right', anchor='e', fill='both', expand=True, padx=0, pady=0)
681| self.bbut.pack(side='bottom', anchor='n', fill='both', expand=True, padx=0, pady=1)
682|
683| self.main.pack()
684| self.buttons = [self.__dict__[f'btn{ix}'] for ix in range(10)]
685| for ix,btn in enumerate(self.buttons):
686| Log.trace(f'{ix}: {btn.winfo_name()} {btn.bbox()}')
687| Log.trace()
688|
689| Log.info('Create Statusbar...')
690| self.statusbar = tk.Frame(self.root, relief='sunken', border=3)
691| self.statusbar.pack(side='bottom', anchor='n', fill='x', expand=False, padx=3, pady=3)
692| self.statusbar.configure(bg='#000000')
693|
694|
695| self.lbl_status = ttk.Label(self.statusbar, style='Status.TLabel')
696| self.lbl_status.pack(side='left', fill='x', expand=True)
697|
698| def _load_config_menu (self):
699| '''(Re-)Create the config items on the menu.'''
700| Log.debug(f'LoadConfigMenu()')
701|
702|
703| def proxy (nm):
704| '''Call selection function with an id.'''
705| return lambda: self.change_config(nm)
706|
707|
708| self.cnfg_select = tk.IntVar(value=self.config.ordinal-1)
709|
710|
711| counter = iter(range(len(self.config)))
712| for name in self.config:
713| cfg = self.config[name]
714| if not cfg.visible:
715| continue
716| ix = next(counter)
717| props = dict(
718| label=f'{ix+1}. {cfg.name}: {cfg.descrip}',
719| accelerator=(f'Ctrl+{ix+1}' if ix<10 else 'Ctrl+0'),
720| underline= 0,
721| value=ix,
722| variable=self.cnfg_select,
723| command=proxy(cfg.name),
724| )
725|
726| self.mbarView.add_radiobutton(**props)
727|
728| def _create_menubar (self):
729| '''Create menubar.'''
730| Log.info('Create Menubar...')
731|
732|
733| self.mbar = tk.Menu(self.root)
734|
735|
736| self.mbarFile = tk.Menu(self.mbar, name='fileMenu', tearoff=0)
737| self.mbarFile.add_command(label='New', underline=0, accelerator='Ctrl+N', command=self.file_new)
738| self.mbarFile.add_command(label='Open...', underline=0, accelerator='Ctrl+O', command=self.file_open)
739| self.mbarFile.add_command(label='Reload', underline=0, accelerator='Ctrl+R', command=self.file_reload)
740| self.mbarFile.add_command(label='Save', underline=0, accelerator='Ctrl+S', command=self.file_save)
741| self.mbarFile.add_command(label='Save As...', underline=5, accelerator='Alt+S', command=self.file_save_as)
742| self.mbarFile.add_separator()
743| self.mbarFile.add_command(label='Edit JSON file', underline=5, accelerator='Ctrl+J', command=self.file_edit_json)
744| self.mbarFile.add_separator()
745| self.mbarFile.add_command(label='Exit', underline=1, accelerator='Alt+Q', command=self.app_exit)
746|
747|
748| self.mbarEdit = tk.Menu(self.mbar, name='editMenu', tearoff=0)
749| self.mbarEdit.add_command(label='Copy' , underline=0, accelerator='Ctrl+C', command=self.edit_copy)
750| self.mbarEdit.add_command(label='Paste', underline=0, accelerator='Ctrl+V', command=self.edit_paste)
751| self.mbarEdit.add_separator()
752| self.mbarEdit.add_command(label='Configuration', underline=3, accelerator='F4', command=self.edit_config_file)
753|
754|
755| self.mbarView = tk.Menu(self.mbar, name='viewMenu', tearoff=0)
756| self.mbarView.add_command(label='Info', underline=0, command=self.view_info)
757| self.mbarView.add_separator()
758| self._load_config_menu()
759|
760|
761| self.mbarHelp = tk.Menu(self.mbar, name='helpMenu', tearoff=0)
762| self.mbarHelp.add_command(label='About', underline=0, command=self.help_about)
763| self.mbarHelp.add_separator()
764| self.mbarHelp.add_command(label='App Info', underline=4, accelerator='Shift+I', command=self.help_app_info)
765|
766|
767| self.mbar.add_cascade(label='File', menu=self.mbarFile, underline=0)
768| self.mbar.add_cascade(label='Edit', menu=self.mbarEdit, underline=0)
769| self.mbar.add_cascade(label='View', menu=self.mbarView, underline=0)
770| self.mbar.add_cascade(label='Help', menu=self.mbarHelp, underline=0)
771|
772|
773| self.root['menu'] = self.mbar
774|
775|
776|
777| class LaunchDialog (tk.Toplevel):
778| '''Launch Program dialog.'''
779|
780| def __init__(self, parent, cmnd, args, cwd):
781| super().__init__(parent)
782| self.title('Launch Platform')
783|
784|
785| self.cmnd = tk.StringVar(value=cmnd)
786| self.args = tk.StringVar(value=args)
787| self.cwd = tk.StringVar(value=cwd)
788| self.retv = False
789|
790|
791| self._widgets()
792| self.txt_cmnd.focus()
793|
794|
795| self.transient(parent)
796| self.protocol("WM_DELETE_WINDOW", self.quit)
797| self.withdraw()
798| self.update_idletasks()
799|
800|
801| x = parent.winfo_rootx() + 20
802| y = parent.winfo_rooty() + 10
803| self.geometry(f"+{x}+{y}")
804|
805| self.deiconify()
806| self.grab_set()
807|
808|
809| self.wait_window(self)
810|
811| def okay (self):
812|
813| cmnd = self.cmnd.get().strip()
814| if not cmnd:
815| msgbox.showerror("Invalid Input", "Command cannot be empty.")
816| return
817|
818| self.cmnd = self.cmnd.get().strip()
819| self.args = self.args.get().strip()
820| self.cwd = self.cwd.get().strip()
821| self.retv = True
822| self.quit()
823|
824| def quit (self):
825| self.grab_release()
826| self.destroy()
827|
828| def _widgets (self):
829| """Create dialog body."""
830| Log.debug('LaunchDialog._widgets()')
831| self.wndw = tk.Frame(self, relief='solid')
832| self.wndw.pack(fill='both', expand=True, padx=2, pady=2)
833|
834| self.main = tk.Frame(self.wndw, relief='sunken')
835| self.btns = tk.Frame(self.wndw, relief='solid')
836|
837| self.main.pack(side='top', fill='x', padx=2, pady=2)
838| self.btns.pack(side='bottom', fill='x', padx=2, pady=2)
839|
840| ttk.Style().configure('my.TLabel',
841| font=('Segoe UI Variable',8,'bold'), justify='left',
842| relief='flat', ipadx=4, padding=(0,0)
843| )
844| self.lbl_cmnd = ttk.Label(self.main, style='my.TLabel', text="Command:")
845| self.lbl_args = ttk.Label(self.main, style='my.TLabel', text="Args:")
846| self.lbl_cwd = ttk.Label(self.main, style='my.TLabel', text="Path:")
847| self.txt_cmnd = ttk.Entry(self.main, textvariable=self.cmnd, width=50)
848| self.txt_args = ttk.Entry(self.main, textvariable=self.args, width=50)
849| self.txt_cwd = ttk.Entry(self.main, textvariable=self.cwd , width=50)
850|
851| self.lbl_cmnd.grid(row=0, column=0, padx=(9,10), pady=(1,3), sticky='w')
852| self.lbl_args.grid(row=1, column=0, padx=(9,10), pady=(1,3), sticky='w')
853| self.lbl_cwd .grid(row=2, column=0, padx=(9,10), pady=(1,3), sticky='w')
854| self.txt_cmnd.grid(row=0, column=1, padx=(5,25), pady=(1,3))
855| self.txt_args.grid(row=1, column=1, padx=(5,25), pady=(1,3))
856| self.txt_cwd .grid(row=2, column=1, padx=(5,25), pady=(1,3))
857|
858| self.btn_quit = tk.Button(self.btns, text="Cancel", command=self.quit)
859| self.btn_quit.pack(side='right', ipadx=8)
860|
861| self.btn_okay = tk.Button(self.btns, text="OK", command=self.okay)
862| self.btn_okay.pack(side='right', ipadx=8)
863|
864|
865|
866| def do_main (**kwargs):
867| '''CMND: Tk Exec FLP -- Flexible Launch Platform.'''
868| flag = KWARG('flag', 1, int, kwargs)
869| Log.info(f'main:: {list(kwargs.keys())}')
870| Log.debug(f'{flag=}')
871| Log.info()
872|
873|
874| app = Application(**kwargs)
875| bag['app'] = app
876|
877|
878| if flag:
879| app.root.mainloop()
880|
881| Log.info()
882| return 'Done'
883|
884|
885| def do_test (**kwargs):
886| '''CMND: Do a test.'''
887| fpath = KWARG('fpath', BasePath, str, kwargs)
888| fname = KWARG('fname', 'test.out', str, kwargs)
889| cnfg_name = KWARG('cfg', 'main', str, kwargs)
890| flag = KWARG('flag', 1, int, kwargs)
891| Log.info(f'test:: {list(kwargs.keys())}' )
892| Log.debug(f'{fpath=}')
893| Log.debug(f'{fname=}')
894| Log.debug(f'{cnfg_name=}')
895| Log.debug(f'{flag=}')
896| Log.info()
897|
898| cfg = ExecConfigFile(cnfg_name)
899| bag['cfg'] = cfg
900|
901| Log.info('Current Configuration:')
902| Log.info(f'> {cfg.current!s}')
903| Log.info(f'> {cfg.current!r}')
904| Log.info(f'> Name: {cfg.name}')
905| Log.info(f'> Size: {len(cfg.current)}')
906| Log.info()
907|
908| Log.info('Current Configuration Parameters:')
909| for ix,param in enumerate(cfg.current, start=1):
910| Log.info(f'{ix:2d}: {param!s} {param!r}')
911| Log.info()
912|
913| Log.info()
914| return 'Done'
915|
916| def dispatch (cmd, **kwargs):
917| '''Dispatch to a module function based on CMD.'''
918| Log.info(f'CMD: {cmd}')
919| for kw in kwargs:
920| Log.debug(f'argument[{kw}]: {kwargs[kw]}')
921| Log.info()
922| if cmd == 'main': return do_main(**kwargs)
923| if cmd == 'test': return do_test(**kwargs)
924| return 'Nothing to do!'
925|
926| if __name__ == '__main__':
927| print(f'autorun: {argv[0]}')
928| Log.start(path.join(BasePath,'tk-exec.log'))
929|
930| Log.level(info())
931| Log.info(argv[0])
932| Log.info()
933| cmd = argv[1] if 1 < len(argv) else CMND
934| kwargs = ARGS
935| for a in argv[2:]:
936| nv = a.split('=', 1)
937| kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
938| Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
939| try:
940| print(f'CMD: {cmd}')
941| print()
942| obj = dispatch(cmd, **kwargs)
943| if 'app' in bag: app=bag['app']
944| print()
945| print(obj)
946| Log.info()
947| Log.info(obj)
948| except:
949| etype, evalue, tb = exc_info()
950| ts = extract_tb(tb)
951| Log.error()
952| Log.error(f'{etype.__name__}: {evalue!s}')
953| Log.error()
954| for t in ts[-5:]:
955| Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
956| Log.error(f' {t[3]}')
957| Log.error()
958| raise
959| finally:
960| Log.end()
961|
962| '''eof'''
963|