Skip to content

Commit 0e6e95f

Browse files
authored
Dr16issues, some progress (#63)
* entered getUnimacroGrammarsDirectory, and a lot of tidying up in natlinkstatus.py * the buttonclicktest.py shows the bug when natlink.playEvents is called.
1 parent 0e07c86 commit 0e6e95f

File tree

4 files changed

+182
-152
lines changed

4 files changed

+182
-152
lines changed

src/natlinkcore/configure/natlinkconfigfunctions.py

Lines changed: 41 additions & 116 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
# Quintijn Hoogenboom, January 2008 (...), August 2022
99
#
1010

11-
#pylint:disable=C0302, W0702, R0904, C0116, W0613, R0914, R0912, C0415, W0611
11+
#pylint:disable=C0302, W0702, R0904, C0116, W0613, R0914, R0912
1212
"""With the functions in this module Natlink can be configured.
1313
1414
These functions are called in different ways:
@@ -57,13 +57,6 @@ def get_check_config_locations(self):
5757
"""
5858
config_path, fallback_path = loader.config_locations()
5959

60-
if isfile(config_path):
61-
with open(config_path, 'r', encoding='utf-8') as fp:
62-
text = fp.read().strip()
63-
if not text:
64-
print(f'empty natlink.ini file: "{config_path}",\n\tremove, and go back to default')
65-
os.remove(config_path)
66-
6760
if not isfile(config_path):
6861
config_dir = Path(config_path).parent
6962
if not config_dir.is_dir():
@@ -75,43 +68,7 @@ def check_config(self):
7568
"""check config_file for possibly unwanted settings
7669
"""
7770
self.config_remove(section='directories', option='default_config')
78-
keys = self.config_get('directories')
79-
80-
## check vocola:
81-
if 'vocoladirectory' in keys and 'vocolagrammarsdirectory' in keys:
82-
try:
83-
import vocola2
84-
except ImportError:
85-
# vocola has been gone, remove:
86-
self.disable_vocola()
87-
self.config_remove('vocola', 'vocolauserdirectory')
88-
else:
89-
## just to be sure:
90-
self.config_remove('vocola', 'vocolauserdirectory')
91-
self.config_remove('directories', 'vocoladirectory')
92-
self.config_remove('directories', 'vocolagrammarsdirectory')
9371

94-
if 'unimacrodirectory' in keys and 'unimacrogrammarsdirectory' in keys:
95-
try:
96-
import unimacro
97-
except ImportError:
98-
# unimacro has been gone, remove:
99-
self.disable_unimacro()
100-
self.config_remove('unimacro', 'unimacrouserdirectory')
101-
else:
102-
## just to be sure:
103-
self.config_remove('unimacro', 'unimacrouserdirectory')
104-
self.config_remove('directories', 'unimacrodirectory')
105-
self.config_remove('directories', 'unimacrogrammarsdirectory')
106-
107-
108-
if 'dragonflyuserdirectory' in keys:
109-
try:
110-
import dragonfly
111-
except ImportError:
112-
# dragonfly has been gone, remove:
113-
self.disable_dragonfly()
114-
11572
def getConfig(self):
11673
"""return the config instance
11774
"""
@@ -122,16 +79,14 @@ def getConfig(self):
12279
self.config_encoding = rwfile.encoding
12380
return _config
12481

125-
def config_get(self, section, option=None):
126-
"""get the section keys or a setting from the natlink ini file
82+
def config_get(self, section, option):
83+
"""set a setting into the natlink ini file
12784
12885
"""
129-
if option:
130-
try:
131-
return self.Config.get(section, option)
132-
except (configparser.NoSectionError, configparser.NoOptionError):
133-
return None
134-
return self.Config.options(section)
86+
try:
87+
return self.Config.get(section, option)
88+
except (configparser.NoSectionError, configparser.NoOptionError):
89+
return None
13590

13691
def config_set(self, section, option, value):
13792
"""set a setting into an inifile (possibly other than natlink.ini)
@@ -152,7 +107,7 @@ def config_set(self, section, option, value):
152107
value = str(value)
153108
self.Config.set(section, option, str(value))
154109
self.config_write()
155-
self.status.__init__()
110+
self.status = natlinkstatus.NatlinkStatus()
156111
return True
157112

158113
def config_write(self):
@@ -180,7 +135,7 @@ def config_remove(self, section, option):
180135
if section not in ['directories', 'settings', 'userenglish-directories', 'userspanish-directories']:
181136
self.Config.remove_section(section)
182137
self.config_write()
183-
self.status.__init__()
138+
self.status = natlinkstatus.NatlinkStatus()
184139

185140
# def setUserDirectory(self, arg):
186141
# self.setDirectory('UserDirectory', arg)
@@ -200,7 +155,7 @@ def setDirectory(self, option, dir_path, section=None):
200155
print('No valid directory specified')
201156
return
202157

203-
dir_path = dir_path.strip().replace('/', '\\')
158+
dir_path = dir_path.strip()
204159
directory = createIfNotThere(dir_path, level_up=1)
205160
if not (directory and Path(directory).is_dir()):
206161
if directory is False:
@@ -284,26 +239,32 @@ def clearFile(self, option, section):
284239

285240
def setLogging(self, logginglevel):
286241
"""Sets the natlink logging output
287-
logginglevel (str) -- CRITICAL, FATAL, ERROR, WARNING, INFO, DEBUG
288-
289-
This one is used in the natlinkconfig_gui
242+
logginglevel (str) -- Critical, Fatal, Error, Warning, Info, Debug
290243
"""
291-
key = 'log_level'
292-
section = 'settings'
293-
value = logginglevel.upper()
294-
old_value = self.config_get(section, key)
244+
# Config.py handles log level str upper formatting from ini
245+
value = logginglevel.title()
246+
old_value = self.config_get('settings', "log_level")
295247
if old_value == value:
296248
print(f'setLogging, setting is already "{old_value}"')
297249
return True
298-
if value in ["CRITICAL", "FATAL", "ERROR", "WARNING", "INFO", "DEBUG"]:
250+
if value in ["Critical", "Fatal", "Error", "Warning", "Info", "Debug"]:
299251
print(f'setLogging, setting logging to: "{value}"')
300-
self.config_set(section, key, value)
252+
self.config_set('settings', "log_level", value)
301253
if old_value is not None:
302-
self.config_set('previous settings', key, old_value)
254+
self.config_set('previous settings', "log_level", old_value)
303255
return True
304-
print(f'Invalid value for setLogging: "{value}"')
305256
return False
306257

258+
def disableDebugOutput(self):
259+
"""disables the Natlink debug output
260+
"""
261+
key = 'log_level'
262+
# section = 'settings'
263+
old_value = self.config_get('previous settings', key)
264+
if old_value:
265+
self.config_set('settings', key, old_value)
266+
self.config_set('settings', key, 'INFO')
267+
307268
def enable_unimacro(self, arg):
308269
unimacro_user_dir = self.status.getUnimacroUserDirectory()
309270
if unimacro_user_dir and isdir(unimacro_user_dir):
@@ -313,7 +274,7 @@ def enable_unimacro(self, arg):
313274

314275
uni_dir = self.status.getUnimacroDirectory()
315276
if uni_dir:
316-
print('==== install and/or update unimacro====\n')
277+
print('==== instal and/or update unimacro====\n')
317278
try:
318279
subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "unimacro"])
319280
except subprocess.CalledProcessError:
@@ -359,7 +320,7 @@ def enable_vocola(self, arg):
359320

360321
voc_dir = self.status.getVocolaDirectory()
361322
if voc_dir:
362-
print('==== install and/or update vocola2====\n')
323+
print('==== instal and/or update vocola2====\n')
363324
try:
364325
subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "vocola2"])
365326
except subprocess.CalledProcessError:
@@ -394,41 +355,6 @@ def disable_vocola(self, arg=None):
394355
self.config_remove('directories', 'vocola')
395356
self.config_remove('directories', 'vocoladirectory') #could still be there...
396357

397-
def enable_dragonfly(self, arg):
398-
"""enable dragonfly, by setting arg (prompting if False), and other settings
399-
"""
400-
key = 'dragonflyuserdirectory'
401-
dragonfly_user_dir = self.status.getDragonflyUserDirectory()
402-
if dragonfly_user_dir and isdir(dragonfly_user_dir):
403-
print(f'dragonflyUserDirectory is already defined: "{dragonfly_user_dir}"\n\tto change, first clear (option "D") and then set again')
404-
print('\nWhen you want to upgrade dragonfly (dragonfly2), also first clear ("D"), then choose this option ("d") again.\n')
405-
return
406-
407-
dfl_prev_dir = self.config_get('previous settings', key)
408-
if dfl_prev_dir:
409-
410-
print('==== install and/or update dragonfly2====\n')
411-
try:
412-
subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "dragonfly2"])
413-
except subprocess.CalledProcessError:
414-
print('====\ncould not pip install --upgrade dragonfly2\n====\n')
415-
return
416-
else:
417-
try:
418-
subprocess.check_call([sys.executable, "-m", "pip", "install", "dragonfly2"])
419-
except subprocess.CalledProcessError:
420-
print('====\ncould not pip install dragonfly2\n====\n')
421-
return
422-
self.status.refresh() # refresh status
423-
424-
self.setDirectory(key, arg)
425-
426-
def disable_dragonfly(self, arg=None):
427-
"""disable dragonfly, arg not needed/used
428-
"""
429-
key = 'dragonflyuserdirectory'
430-
self.clearDirectory(key)
431-
432358
def copyUnimacroIncludeFile(self):
433359
"""copy Unimacro include file into Vocola user directory
434360
@@ -525,20 +451,20 @@ def includeUnimacroVchLineInVocolaFiles(self, subDirectory=None):
525451
changed = 0
526452
correct = 0
527453
Output = []
528-
rwfile = readwritefile.ReadWriteFile()
529-
lines = rwfile.readAnything(F).split('\n')
530-
for line in lines:
454+
for line in open(F, 'r'):
531455
if line.strip() == includeLine.strip():
532456
correct = 1
533-
if line.strip() in oldIncludeLines:
534-
changed = 1
535-
continue
536-
Output.append(line)
457+
for oldLine in oldIncludeLines:
458+
if line.strip() == oldLine:
459+
changed = 1
460+
break
461+
else:
462+
Output.append(line)
537463
if changed or not correct:
538464
# changes were made:
539465
if not correct:
540466
Output.insert(0, includeLine)
541-
rwfile.writeAnything(F, Output)
467+
open(F, 'w').write(''.join(Output))
542468
nFiles += 1
543469
elif len(f) == 3 and os.path.isdir(F):
544470
# subdirectory, recursive
@@ -584,10 +510,7 @@ def removeUnimacroVchLineInVocolaFiles(self, subDirectory=None):
584510
if f.endswith(".vcl"):
585511
changed = 0
586512
Output = []
587-
rwfile = readwritefile.ReadWriteFile()
588-
lines = rwfile.readAnything(F).split('\n')
589-
590-
for line in lines:
513+
for line in open(F, 'r'):
591514
for oldLine in oldIncludeLines:
592515
if line.strip() == oldLine:
593516
changed = 1
@@ -596,10 +519,11 @@ def removeUnimacroVchLineInVocolaFiles(self, subDirectory=None):
596519
Output.append(line)
597520
if changed:
598521
# had break, so changes were made:
599-
rwfile.writeAnything(F, Output)
522+
open(F, 'w').write(''.join(Output))
600523
nFiles += 1
601524
elif len(f) == 3 and os.path.isdir(F):
602525
self.removeUnimacroVchLineInVocolaFiles(F)
526+
self.disableVocolaTakesUnimacroActions()
603527
mess = f'removed include lines from {nFiles} files in {toFolder}'
604528
print(mess)
605529

@@ -749,3 +673,4 @@ def createIfNotThere(path_name, level_up=None):
749673
_home_path = _nc.home_path
750674
_natlinkconfig_path = _nc.natlinkconfig_path
751675
print(f'natlinkconfig_path: {_natlinkconfig_path}')
676+
pass

src/natlinkcore/natlinkpydebug.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
"""
2+
code to help with debugging including:
3+
- enable python debuggers to attach.
4+
currently on DAP debuggers are supported.
5+
https://microsoft.github.io/debug-adapter-protocol/
6+
There are several, Microsoft Visual Studio COde is known to work.
7+
There are several, Microsoft Visual Studio COde is known to work.
8+
9+
If you know how to add support for another debugger please add it.
10+
11+
Written by Doug Ransom, 2021
12+
"""
13+
#pylint:disable=C0116, W0703
14+
import os
15+
import debugpy
16+
from natlinkcore import natlinkstatus
17+
18+
__status = natlinkstatus.NatlinkStatus()
19+
__natLinkPythonDebugPortEnviornmentVar= "NatlinkPyDebugPort"
20+
__natLinkPythonDebugOnStartupVar="NatlinkPyDebugStartup"
21+
22+
__pyDefaultPythonExecutor = "python.exe"
23+
__debug_started=False
24+
default_debugpy_port=7474
25+
__debugpy_debug_port=default_debugpy_port
26+
__debugger="not configured"
27+
dap="DAP"
28+
29+
#bring a couple functions from DAP and export from our namespace
30+
dap_is_client_connected=debugpy.is_client_connected
31+
dap_breakpoint = debugpy.breakpoint
32+
33+
def dap_info():
34+
return f"""
35+
Debugger: {__debugger} DAP Port:{__debugpy_debug_port} IsClientConnected: {dap_is_client_connected()} Default DAP Port {default_debugpy_port}
36+
Debug Started:{__debug_started}
37+
"""
38+
39+
def start_dap():
40+
#pylint:disable=W0603
41+
global __debug_started,__debugpy_debug_port,__debugger
42+
if __debug_started:
43+
print(f"DAP already started with debugpy for port {__debugpy_debug_port}")
44+
return
45+
try:
46+
47+
if __natLinkPythonDebugPortEnviornmentVar in os.environ:
48+
natLinkPythonPortStringVal = os.environ[__natLinkPythonDebugPortEnviornmentVar]
49+
__debugpy_debug_port = int(natLinkPythonPortStringVal)
50+
print(f"Starting debugpy on port {natLinkPythonPortStringVal}")
51+
52+
python_exec = __pyDefaultPythonExecutor #for now, only the python in system path can be used for natlink and this module
53+
print(f"Python Executable (required for debugging): '{python_exec}'")
54+
debugpy.configure(python=f"{python_exec}")
55+
debugpy.listen(__debugpy_debug_port)
56+
print(f"debugpy listening on port {__debugpy_debug_port}")
57+
__debug_started = True
58+
__debugger = dap
59+
60+
if __natLinkPythonDebugOnStartupVar in os.environ:
61+
dos_str=os.environ[__natLinkPythonDebugOnStartupVar]
62+
dos=len(dos_str)==1 and dos_str in "YyTt"
63+
64+
if dos:
65+
print(f"Waiting for DAP debugger to attach now as {__natLinkPythonDebugOnStartupVar} is set to {dos_str}")
66+
debugpy.wait_for_client()
67+
68+
69+
except Exception as ee:
70+
print(f"""
71+
Exception {ee} while starting debug. Possible cause is incorrect python executable specified {python_exec}
72+
""" )
73+
74+
def debug_check_on_startup():
75+
#pylint:disable=W0603
76+
global __debug_started,__debugpy_debug_port,__debugger
77+
debug_instructions = f"{__status.getCoreDirectory()}\\debugging python instructions.docx"
78+
print(f"Instructions for attaching a python debugger are in {debug_instructions} ")
79+
if __natLinkPythonDebugPortEnviornmentVar in os.environ:
80+
start_dap()
81+
82+
83+
84+
85+
86+

0 commit comments

Comments
 (0)