Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

config.py 12KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. # config.py - deals with loading configuration information.
  2. # Loads config data from a .cfg file. Also caches the compiled
  3. # data back into a .cfc file.
  4. # If you are wondering how to avoid needing .cfg files (eg,
  5. # if you are freezing Pythonwin etc) I suggest you create a
  6. # .py file, and put the config info in a docstring. Then
  7. # pass a CStringIO file (rather than a filename) to the
  8. # config manager.
  9. import glob
  10. import importlib.util
  11. import marshal
  12. import os
  13. import stat
  14. import sys
  15. import traceback
  16. import types
  17. import pywin
  18. import win32api
  19. from . import keycodes
  20. debugging = 0
  21. if debugging:
  22. import win32traceutil # Some trace statements fire before the interactive window is open.
  23. def trace(*args):
  24. sys.stderr.write(" ".join(map(str, args)) + "\n")
  25. else:
  26. trace = lambda *args: None
  27. compiled_config_version = 3
  28. def split_line(line, lineno):
  29. comment_pos = line.find("#")
  30. if comment_pos >= 0:
  31. line = line[:comment_pos]
  32. sep_pos = line.rfind("=")
  33. if sep_pos == -1:
  34. if line.strip():
  35. print("Warning: Line %d: %s is an invalid entry" % (lineno, repr(line)))
  36. return None, None
  37. return "", ""
  38. return line[:sep_pos].strip(), line[sep_pos + 1 :].strip()
  39. def get_section_header(line):
  40. # Returns the section if the line is a section header, else None
  41. if line[0] == "[":
  42. end = line.find("]")
  43. if end == -1:
  44. end = len(line)
  45. rc = line[1:end].lower()
  46. try:
  47. i = rc.index(":")
  48. return rc[:i], rc[i + 1 :]
  49. except ValueError:
  50. return rc, ""
  51. return None, None
  52. def find_config_file(f):
  53. return os.path.join(pywin.__path__[0], f + ".cfg")
  54. def find_config_files():
  55. return [
  56. os.path.split(x)[1]
  57. for x in [
  58. os.path.splitext(x)[0]
  59. for x in glob.glob(os.path.join(pywin.__path__[0], "*.cfg"))
  60. ]
  61. ]
  62. class ConfigManager:
  63. def __init__(self, f):
  64. self.filename = "unknown"
  65. self.last_error = None
  66. self.key_to_events = {}
  67. b_close = False
  68. if hasattr(f, "readline"):
  69. fp = f
  70. self.filename = "<config string>"
  71. compiled_name = None
  72. else:
  73. try:
  74. f = find_config_file(f)
  75. src_stat = os.stat(f)
  76. except os.error:
  77. self.report_error("Config file '%s' not found" % f)
  78. return
  79. self.filename = f
  80. self.basename = os.path.basename(f)
  81. trace("Loading configuration", self.basename)
  82. compiled_name = os.path.splitext(f)[0] + ".cfc"
  83. try:
  84. cf = open(compiled_name, "rb")
  85. try:
  86. ver = marshal.load(cf)
  87. ok = compiled_config_version == ver
  88. if ok:
  89. kblayoutname = marshal.load(cf)
  90. magic = marshal.load(cf)
  91. size = marshal.load(cf)
  92. mtime = marshal.load(cf)
  93. if (
  94. magic == importlib.util.MAGIC_NUMBER
  95. and win32api.GetKeyboardLayoutName() == kblayoutname
  96. and src_stat[stat.ST_MTIME] == mtime
  97. and src_stat[stat.ST_SIZE] == size
  98. ):
  99. self.cache = marshal.load(cf)
  100. trace("Configuration loaded cached", compiled_name)
  101. return # We are ready to roll!
  102. finally:
  103. cf.close()
  104. except (os.error, IOError, EOFError):
  105. pass
  106. fp = open(f)
  107. b_close = True
  108. self.cache = {}
  109. lineno = 1
  110. line = fp.readline()
  111. while line:
  112. # Skip to the next section (maybe already there!)
  113. section, subsection = get_section_header(line)
  114. while line and section is None:
  115. line = fp.readline()
  116. if not line:
  117. break
  118. lineno = lineno + 1
  119. section, subsection = get_section_header(line)
  120. if not line:
  121. break
  122. if section == "keys":
  123. line, lineno = self._load_keys(subsection, fp, lineno)
  124. elif section == "extensions":
  125. line, lineno = self._load_extensions(subsection, fp, lineno)
  126. elif section == "idle extensions":
  127. line, lineno = self._load_idle_extensions(subsection, fp, lineno)
  128. elif section == "general":
  129. line, lineno = self._load_general(subsection, fp, lineno)
  130. else:
  131. self.report_error(
  132. "Unrecognised section header '%s:%s'" % (section, subsection)
  133. )
  134. line = fp.readline()
  135. lineno = lineno + 1
  136. if b_close:
  137. fp.close()
  138. # Check critical data.
  139. if not self.cache.get("keys"):
  140. self.report_error("No keyboard definitions were loaded")
  141. if not self.last_error and compiled_name:
  142. try:
  143. cf = open(compiled_name, "wb")
  144. marshal.dump(compiled_config_version, cf)
  145. marshal.dump(win32api.GetKeyboardLayoutName(), cf)
  146. marshal.dump(importlib.util.MAGIC_NUMBER, cf)
  147. marshal.dump(src_stat[stat.ST_SIZE], cf)
  148. marshal.dump(src_stat[stat.ST_MTIME], cf)
  149. marshal.dump(self.cache, cf)
  150. cf.close()
  151. except (IOError, EOFError):
  152. pass # Ignore errors - may be read only.
  153. def configure(self, editor, subsections=None):
  154. # Execute the extension code, and find any events.
  155. # First, we "recursively" connect any we are based on.
  156. if subsections is None:
  157. subsections = []
  158. subsections = [""] + subsections
  159. general = self.get_data("general")
  160. if general:
  161. parents = general.get("based on", [])
  162. for parent in parents:
  163. trace("Configuration based on", parent, "- loading.")
  164. parent = self.__class__(parent)
  165. parent.configure(editor, subsections)
  166. if parent.last_error:
  167. self.report_error(parent.last_error)
  168. bindings = editor.bindings
  169. codeob = self.get_data("extension code")
  170. if codeob is not None:
  171. ns = {}
  172. try:
  173. exec(codeob, ns)
  174. except:
  175. traceback.print_exc()
  176. self.report_error("Executing extension code failed")
  177. ns = None
  178. if ns:
  179. num = 0
  180. for name, func in list(ns.items()):
  181. if type(func) == types.FunctionType and name[:1] != "_":
  182. bindings.bind(name, func)
  183. num = num + 1
  184. trace("Configuration Extension code loaded", num, "events")
  185. # Load the idle extensions
  186. for subsection in subsections:
  187. for ext in self.get_data("idle extensions", {}).get(subsection, []):
  188. try:
  189. editor.idle.IDLEExtension(ext)
  190. trace("Loaded IDLE extension", ext)
  191. except:
  192. self.report_error("Can not load the IDLE extension '%s'" % ext)
  193. # Now bind up the key-map (remembering a reverse map
  194. subsection_keymap = self.get_data("keys")
  195. num_bound = 0
  196. for subsection in subsections:
  197. keymap = subsection_keymap.get(subsection, {})
  198. bindings.update_keymap(keymap)
  199. num_bound = num_bound + len(keymap)
  200. trace("Configuration bound", num_bound, "keys")
  201. def get_key_binding(self, event, subsections=None):
  202. if subsections is None:
  203. subsections = []
  204. subsections = [""] + subsections
  205. subsection_keymap = self.get_data("keys")
  206. for subsection in subsections:
  207. map = self.key_to_events.get(subsection)
  208. if map is None: # Build it
  209. map = {}
  210. keymap = subsection_keymap.get(subsection, {})
  211. for key_info, map_event in list(keymap.items()):
  212. map[map_event] = key_info
  213. self.key_to_events[subsection] = map
  214. info = map.get(event)
  215. if info is not None:
  216. return keycodes.make_key_name(info[0], info[1])
  217. return None
  218. def report_error(self, msg):
  219. self.last_error = msg
  220. print("Error in %s: %s" % (self.filename, msg))
  221. def report_warning(self, msg):
  222. print("Warning in %s: %s" % (self.filename, msg))
  223. def _readline(self, fp, lineno, bStripComments=1):
  224. line = fp.readline()
  225. lineno = lineno + 1
  226. if line:
  227. bBreak = (
  228. get_section_header(line)[0] is not None
  229. ) # A new section is starting
  230. if bStripComments and not bBreak:
  231. pos = line.find("#")
  232. if pos >= 0:
  233. line = line[:pos] + "\n"
  234. else:
  235. bBreak = 1
  236. return line, lineno, bBreak
  237. def get_data(self, name, default=None):
  238. return self.cache.get(name, default)
  239. def _save_data(self, name, data):
  240. self.cache[name] = data
  241. return data
  242. def _load_general(self, sub_section, fp, lineno):
  243. map = {}
  244. while 1:
  245. line, lineno, bBreak = self._readline(fp, lineno)
  246. if bBreak:
  247. break
  248. key, val = split_line(line, lineno)
  249. if not key:
  250. continue
  251. key = key.lower()
  252. l = map.get(key, [])
  253. l.append(val)
  254. map[key] = l
  255. self._save_data("general", map)
  256. return line, lineno
  257. def _load_keys(self, sub_section, fp, lineno):
  258. # Builds a nested dictionary of
  259. # (scancode, flags) = event_name
  260. main_map = self.get_data("keys", {})
  261. map = main_map.get(sub_section, {})
  262. while 1:
  263. line, lineno, bBreak = self._readline(fp, lineno)
  264. if bBreak:
  265. break
  266. key, event = split_line(line, lineno)
  267. if not event:
  268. continue
  269. sc, flag = keycodes.parse_key_name(key)
  270. if sc is None:
  271. self.report_warning("Line %d: Invalid key name '%s'" % (lineno, key))
  272. else:
  273. map[sc, flag] = event
  274. main_map[sub_section] = map
  275. self._save_data("keys", main_map)
  276. return line, lineno
  277. def _load_extensions(self, sub_section, fp, lineno):
  278. start_lineno = lineno
  279. lines = []
  280. while 1:
  281. line, lineno, bBreak = self._readline(fp, lineno, 0)
  282. if bBreak:
  283. break
  284. lines.append(line)
  285. try:
  286. c = compile(
  287. "\n" * start_lineno + "".join(lines), # produces correct tracebacks
  288. self.filename,
  289. "exec",
  290. )
  291. self._save_data("extension code", c)
  292. except SyntaxError as details:
  293. errlineno = details.lineno + start_lineno
  294. # Should handle syntax errors better here, and offset the lineno.
  295. self.report_error(
  296. "Compiling extension code failed:\r\nFile: %s\r\nLine %d\r\n%s"
  297. % (details.filename, errlineno, details.msg)
  298. )
  299. return line, lineno
  300. def _load_idle_extensions(self, sub_section, fp, lineno):
  301. extension_map = self.get_data("idle extensions")
  302. if extension_map is None:
  303. extension_map = {}
  304. extensions = []
  305. while 1:
  306. line, lineno, bBreak = self._readline(fp, lineno)
  307. if bBreak:
  308. break
  309. line = line.strip()
  310. if line:
  311. extensions.append(line)
  312. extension_map[sub_section] = extensions
  313. self._save_data("idle extensions", extension_map)
  314. return line, lineno
  315. def test():
  316. import time
  317. start = time.clock()
  318. f = "default"
  319. cm = ConfigManager(f)
  320. map = cm.get_data("keys")
  321. took = time.clock() - start
  322. print("Loaded %s items in %.4f secs" % (len(map), took))
  323. if __name__ == "__main__":
  324. test()